# Algorithm of checking whether an element is present in a merkle tree

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.

1. Put the entire contents of the merkle tree in an array.
2. 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.)
3. 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:

1. Run through steps 1-3 above.
2. Start with the element you want to prove the presence of. Add it to the result list.
3. 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.
4. Repeat 2 through 3 until you get to the merkle root, which has no buddy.
5. The resulting list is your proof.

Verification:

1. 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.
2. 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.
3. Repeat 2 with the next item until you run out of items.
4. 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.

• for me the most tricky part is finding "buddy". Can you explain how to find it? Nov 6 '16 at 8:32
• A 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. Nov 6 '16 at 21:19