|

Merkle Mountain Range (MMR)

|
Visualizer

Append function

The append function is used to add a new leaf to the MMR. The new leaf is added to the right of the last leaf in the MMR. Appending a new leaf might require creating some amount of new nodes. This is because MMR can contain at most one tree of each height, so if the last tree is a single node, appending a new leaf without creating other nodes would result in two trees of height 0.

15
7
3
1
2
6
4
5
14
10
8
9
13
11
12
22
18
16
17
21
19
20

For example above, we have an MMR with 11 leaves. Appending a new node (20) would require nodes 21 and 22 to be created, because trees of size 0 and 1 already exist.

Now let's see how to calculate how many new nodes will be created besides the new leaf.

As we mentioned in leaf count to MMR size article, we can calculate number of nodes in MMR using the following formula:2ncount_ones(n)2 \cdot n - \operatorname{count\_ones}(n)where nn is the number of leaves in the MMR.

To calculate how many new nodes will be created, we can subtract the number of nodes in the MMR before appending the new leaf from the number of nodes in the MMR after appending the new leaf:2(n+1)count_ones(n+1)(2ncount_ones(n)=2+count_ones(n)count_ones(n+1)2 \cdot (n+1) - \operatorname{count\_ones}(n+1) - (2 \cdot n - \operatorname{count\_ones}(n) = 2 + \operatorname{count\_ones}(n) - \operatorname{count\_ones}(n+1)This formula looks good, however, it can be simplified further. Let's take a closer look at binary representation of numbers nn, n+1n+1 and their number of ones.

aka_k\ldotsa3a_3a2a_2a1a_1a0a_0++00\ldots00000011
bkb_k\ldotsb3b_3b2b_2b1b_1b0b_0

Because of how binary addition works, first bit will always flip:b0=1a0b_0 = 1 - a_0and ii-th bit flips only if all bits from 00 to i1i-1 are 11:bi={1aiif   j<iaj=1aiotherwiseb_i = \begin{cases} 1-a_i & \text{if $\; \forall_{j<i} \, a_j=1$} \\ a_i & \text{otherwise} \end{cases}Let's define tt such that at=0 and i<tai=1a_t = 0 \text{ and } \forall_{i<t} a_i = 1Now we can notice that only bits from 00 to tt will flip. Moreover, bit tt will flip from 00 to 11 and all bits from 00 to t1t-1 will flip from 11 to 00. Also notice that tt is the number of trailing 11 bits in nn.

So now we can simplify the formula:count_ones(n+1)count_ones(n)=1trailing_ones(n)\operatorname{count\_ones}(n+1) - \operatorname{count\_ones}(n) = 1 - \operatorname{trailing\_ones}(n)+1+1 comes from flipping the tt-th bit and count_ones(n)-\operatorname{count\_ones}(n) from flipping all bits from 00 to t1t-1.

After plugging this into the formula, we get:2(1trailing_ones(n))=1+trailing_ones(n)2 - (1 - \operatorname{trailing\_ones}(n)) = 1 + \operatorname{trailing\_ones(n)}

© 2024 Herodotus Dev Ltd. All rights reserved.
Powered by