I've read and watch about merkle trees but can't figure out how to implement is_present(element) method. Explainations and links are accepted.
Asked
Active
Viewed 2,360 times
1 Answers
7
I've read and watch about merkle trees but can't figure out how to implement is_present(element) method.
- Put the entire contents of the merkle tree in an array.
- Check that the result of hashing all of the elements equals the root of the merkle tree. (If not, this is not the correct merkle tree.)
- Check if the element is in the array.
This takes O(n) time and space, where n is the number of elements in the merkle tree.
Proving that to another node
You can create a proof that a particular element is in a tree. This proof takes O(log n) space to store, and O(log n) time to verify, but still takes O(n) time to construct.
Construction:
- Run through steps 1-3 above.
- Start with the element you want to prove the presence of. Add it to the result list.
- Find its buddy. In other words, find the hash that it would be hashed with to form the merkle branch containing both. Add it to the result list.
- Repeat 2 through 3 until you get to the merkle root, which has no buddy.
- The resulting list is your proof.
Verification:
- Start with the first item in the list. Verify that it's the one you're trying to prove the presence of. Set A to this.
- Hash it with the second item, with it either first or second depending on where the original item is in the merkle tree. Set A to this hash.
- Repeat 2 with the next item until you run out of items.
- Verify that A equals the merkle root.
If the merkle tree is in sorted order, you can also create a proof that an element is not in the merkle tree. It works in a similar way, except that you find the two elements that would have been the neighboring elements. Then, you prove that both are in the tree, and that they are next to each other.
Nick ODell
- 29,184
- 11
- 69
- 129
-
for me the most tricky part is finding "buddy". Can you explain how to find it? – ka4eli Nov 06 '16 at 08:32
-
4A tl;dr: you don't check whether something is present in a Merkle tree. You ask the party who claims that something is in it to prove to you instead. – Pieter Wuille Nov 06 '16 at 21:19
-
Why would `hash(hash(A, B), hash(C, D)) == hash(A, B, C, D) `? – Zaz Jun 16 '23 at 00:20
-
@Zaz It doesn't. – Nick ODell Jun 16 '23 at 00:21
-
Then why would the hash of the array equal the root of the Merkle tree? – Zaz Jun 21 '23 at 17:45