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.
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.
- 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.
- 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.