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.
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:where 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:This formula looks good, however, it can be simplified further. Let's take a closer look at binary representation of numbers , and their number of ones.
Because of how binary addition works, first bit will always flip:and -th bit flips only if all bits from to are :Let's define such that Now we can notice that only bits from to will flip. Moreover, bit will flip from to and all bits from to will flip from to . Also notice that is the number of trailing bits in .
So now we can simplify the formula: comes from flipping the -th bit and from flipping all bits from to .
After plugging this into the formula, we get: