# Merkle tree sorting leaves and pairs

I am implementing a Merkle tree and am considering using either of the two options.

The first one is sorting only by leaves. This one makes sense to me since you would like to have the same input every time you are constructing a tree from the data, that might not arrive sorted by default.

       CAB
/    \
CA     \
/    \    \
C     A     B
/  \  /  \  /  \
1  2  3  4  5  6


The second one is sorting by leaves and pairs, which means that after sorting the leaves, you also sort all the pairs after hashing them, however I'm not entirely sure about the benefits of this implementation (if any).

       ACB
/    \
AC     \
/    \    \
C     A     B
/  \  /  \  /  \
1  2  3  4  5  6


I have seen these implementations of Merkle trees in the past but am not sure about their benefits. So why choose one over the other?

• Are your sure this is the Merkle-Tree also known as the Hash tree. – kelalaka Jul 31 '20 at 18:50
• @kelalaka yes, both are variants of Merkle-Trees – Alko Aug 3 '20 at 8:25

The first method is the standard one that I've seen.

I'm not clear on what the purpose of the second method would be, or even exactly how it works. It's not something I've seen before.

I'd suggest you use the first method by default, and if you encounter a situation where it is insufficient or has some problems, post a question asking about the specific requirements you have in that situation.

• Hey, thanks. The difference is that instead of just the leaves it also sorts the node hash pairs, before hashing them. The purpouse of using this method is also unclear to me. – Alko Jul 29 '20 at 9:35
• I think Amazon QLDB uses this approach. – Alko Jul 29 '20 at 9:42

A bit late to the party, but the second approach can be useful to simplify the merkle-path. When hashing a pair, it's required to know if the leaf is on the left or right side of the pair. This can become quite complex, for example, when implementing multi-leaf inclusion proofs. By sorting the pairs before hashing, it doesn't matter which side the leaf actually has in the pair, as you're applying the same rule every time. Pretty neat solution in my opinion.