“Improved” Patricia trie

How we can improve it? The best answer is in Ethereum wiki, I won’t be able to explain better, so I will cite it below 💅💅💅.

The holy answer.

Finally, chose one 💆💆💆.

I have been mentioned about leaf node and extension node in Episode 1+, but we don’t know what they are. We met some situations that make our trie become degraded and those are the long paths without branch (no divergent path).

For example: 56f0 , to get horse value, you need to descend too many empty-value nodes.

But, these lead to 2 sub-problems.

No divergent path points to a data at the end. For example: 56f0 . No divergent path is branched in the middle. For example: cab of {cabe, cab8} .

To solve the first one they introduced leaf node and solve the second one they introduced extension node. They are nodes in form of an array with 2 elements, the first element is partialPath that helps to reduce empty-value node, the second one contains value that is data if leaf or merkleHash if extension .

Using leaf node.

hashE now becomes a leaf node, to get value of 56f0 path we can do like:

Getting element with index 5 of rootHash and the value is hashE . Because hashE may be a leaf or extension node, we have to compare the rest of path (remainder) to partialPath of hashE . Remainder is 6f0 and partialPath is 6f0 (they are the same), so this node is leaf node. We return data field and result is horse .

Using leaf node and extension node.

hashB now becomes a extension node. For example, getting data of cab8 path:

Getting element indexed by c of rootHash , value is hashB . We can see hashB is a node as an array with 2 values, so we keep comparing remainder with partialPath to know which one node is. Remainder is ab8 and partialPath is ab , it means node is extension node. We remove partialPath from the current rest of path and we get the new rest of path is 8 and the next hash is hashJ . Finding node corresponding with hashJ , getting element indexed by 8 and the value is hashK . Remainder is empty now. Finding hashK and we are received a node with empty partialPath (leaf node because remainder is equal to partialPath ), return dog .

In addition, we can see hashD , hashK and hashL are leaf nodes as well. And actually, our trie is still not optimized completely.

Optimized trie.

Now, this trie seems to be optimized fully by leaf node and extension node.

Two examples above help us understand why and how Patricia trie was built and improved. Now we will complete it and get final Patricia trie which is used by Ethereum. 🚀🚀🚀

Patricia trie

Some additional rules:

Every partialPath will be HP encoded before hand. Every elements in a node will be RLP encoded. Value (Node) will be RLP encoded before stored down.