ethereum.frontier.trie
State Trie ^^^^^^^^^^
.. contents:: Table of Contents :backlinks: none :local:
Introduction
The state trie is the structure responsible for storing
.fork_types.Account
objects.
EMPTY_TRIE_ROOT
53 | EMPTY_TRIE_ROOT = Root( |
---|---|
54 | hex_to_bytes( |
55 | "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" |
56 | ) |
57 | ) |
Node
59 | Node = Union[Account, Bytes, Transaction, Receipt, Uint, U256, None] |
---|
K
60 | K = TypeVar("K", bound=Bytes) |
---|
V
61 | V = TypeVar( |
---|---|
62 | "V", |
63 | Optional[Account], |
64 | Optional[Bytes], |
65 | Bytes, |
66 | Optional[Transaction], |
67 | Optional[Receipt], |
68 | Uint, |
69 | U256, |
70 | ) |
LeafNode
Leaf node in the Merkle Trie
73 | @slotted_freezable |
---|
74 | @dataclass |
---|
class LeafNode:
rest_of_key
78 | rest_of_key: Bytes |
---|
value
79 | value: rlp.Extended |
---|
ExtensionNode
Extension node in the Merkle Trie
82 | @slotted_freezable |
---|
83 | @dataclass |
---|
class ExtensionNode:
key_segment
87 | key_segment: Bytes |
---|
subnode
88 | subnode: rlp.Extended |
---|
BranchNode
Branch node in the Merkle Trie
91 | @slotted_freezable |
---|
92 | @dataclass |
---|
class BranchNode:
subnodes
96 | subnodes: List[rlp.Extended] |
---|
value
97 | value: rlp.Extended |
---|
InternalNode
100 | InternalNode = Union[LeafNode, ExtensionNode, BranchNode] |
---|
encode_internal_node
Encodes a Merkle Trie node into its RLP form. The RLP will then be
serialized into a Bytes
and hashed unless it is less that 32 bytes
when serialized.
This function also accepts None
, representing the absence of a node,
which is encoded to b""
.
Parameters
node : Optional[InternalNode] The node to encode.
Returns
encoded : rlp.RLP
The node encoded as RLP.
def encode_internal_node(node: Optional[InternalNode]) -> ethereum.rlp.Extended:
104 | """ |
---|---|
105 | Encodes a Merkle Trie node into its RLP form. The RLP will then be |
106 | serialized into a `Bytes` and hashed unless it is less that 32 bytes |
107 | when serialized. |
108 |
|
109 | This function also accepts `None`, representing the absence of a node, |
110 | which is encoded to `b""`. |
111 |
|
112 | Parameters |
113 | ---------- |
114 | node : Optional[InternalNode] |
115 | The node to encode. |
116 |
|
117 | Returns |
118 | ------- |
119 | encoded : `rlp.RLP` |
120 | The node encoded as RLP. |
121 | """ |
122 | unencoded: rlp.Extended |
123 | if node is None: |
124 | unencoded = b"" |
125 | elif isinstance(node, LeafNode): |
126 | unencoded = ( |
127 | nibble_list_to_compact(node.rest_of_key, True), |
128 | node.value, |
129 | ) |
130 | elif isinstance(node, ExtensionNode): |
131 | unencoded = ( |
132 | nibble_list_to_compact(node.key_segment, False), |
133 | node.subnode, |
134 | ) |
135 | elif isinstance(node, BranchNode): |
136 | unencoded = node.subnodes + [node.value] |
137 | else: |
138 | raise AssertionError(f"Invalid internal node type {type(node)}!") |
139 | |
140 | encoded = rlp.encode(unencoded) |
141 | if len(encoded) < 32: |
142 | return unencoded |
143 | else: |
144 | return keccak256(encoded) |
encode_node
Encode a Node for storage in the Merkle Trie.
Currently mostly an unimplemented stub.
def encode_node(node: Node, storage_root: Optional[Bytes]) -> Bytes:
148 | """ |
---|---|
149 | Encode a Node for storage in the Merkle Trie. |
150 |
|
151 | Currently mostly an unimplemented stub. |
152 | """ |
153 | if isinstance(node, Account): |
154 | assert storage_root is not None |
155 | return encode_account(node, storage_root) |
156 | elif isinstance(node, (Transaction, Receipt, U256)): |
157 | return rlp.encode(node) |
158 | elif isinstance(node, Bytes): |
159 | return node |
160 | else: |
161 | raise AssertionError( |
162 | f"encoding for {type(node)} is not currently implemented" |
163 | ) |
Trie
The Merkle Trie.
166 | @dataclass |
---|
class Trie:
secured
172 | secured: bool |
---|
default
173 | default: V |
---|
_data
174 | _data: Dict[K, V] = field(default_factory=dict) |
---|
copy_trie
Create a copy of trie
. Since only frozen objects may be stored in tries,
the contents are reused.
Parameters
trie: Trie
Trie to copy.
Returns
new_trie : Trie[K, V]
A copy of the trie.
def copy_trie(trie: Trie[K, V]) -> Trie[K, V]:
178 | """ |
---|---|
179 | Create a copy of `trie`. Since only frozen objects may be stored in tries, |
180 | the contents are reused. |
181 |
|
182 | Parameters |
183 | ---------- |
184 | trie: `Trie` |
185 | Trie to copy. |
186 |
|
187 | Returns |
188 | ------- |
189 | new_trie : `Trie[K, V]` |
190 | A copy of the trie. |
191 | """ |
192 | return Trie(trie.secured, trie.default, copy.copy(trie._data)) |
trie_set
Stores an item in a Merkle Trie.
This method deletes the key if value == trie.default
, because the Merkle
Trie represents the default value by omitting it from the trie.
Parameters
trie: Trie
Trie to store in.
key : Bytes
Key to lookup.
value : V
Node to insert at key
.
def trie_set(trie: Trie[K, V], key: K, value: V) -> None:
196 | """ |
---|---|
197 | Stores an item in a Merkle Trie. |
198 |
|
199 | This method deletes the key if `value == trie.default`, because the Merkle |
200 | Trie represents the default value by omitting it from the trie. |
201 |
|
202 | Parameters |
203 | ---------- |
204 | trie: `Trie` |
205 | Trie to store in. |
206 | key : `Bytes` |
207 | Key to lookup. |
208 | value : `V` |
209 | Node to insert at `key`. |
210 | """ |
211 | if value == trie.default: |
212 | if key in trie._data: |
213 | del trie._data[key] |
214 | else: |
215 | trie._data[key] = value |
trie_get
Gets an item from the Merkle Trie.
This method returns trie.default
if the key is missing.
Parameters
trie: Trie to lookup in. key : Key to lookup.
Returns
node : V
Node at key
in the trie.
def trie_get(trie: Trie[K, V], key: K) -> V:
219 | """ |
---|---|
220 | Gets an item from the Merkle Trie. |
221 |
|
222 | This method returns `trie.default` if the key is missing. |
223 |
|
224 | Parameters |
225 | ---------- |
226 | trie: |
227 | Trie to lookup in. |
228 | key : |
229 | Key to lookup. |
230 |
|
231 | Returns |
232 | ------- |
233 | node : `V` |
234 | Node at `key` in the trie. |
235 | """ |
236 | return trie._data.get(key, trie.default) |
common_prefix_length
Find the longest common prefix of two sequences.
def common_prefix_length(a: Sequence, b: Sequence) -> int:
240 | """ |
---|---|
241 | Find the longest common prefix of two sequences. |
242 | """ |
243 | for i in range(len(a)): |
244 | if i >= len(b) or a[i] != b[i]: |
245 | return i |
246 | return len(a) |
nibble_list_to_compact
Compresses nibble-list into a standard byte array with a flag.
A nibble-list is a list of byte values no greater than 15
. The flag is
encoded in high nibble of the highest byte. The flag nibble can be broken
down into two two-bit flags.
Highest nibble::
+---+---+----------+--------+
| _ | _ | is_leaf | parity |
+---+---+----------+--------+
3 2 1 0
The lowest bit of the nibble encodes the parity of the length of the
remaining nibbles -- 0
when even and 1
when odd. The second lowest bit
is used to distinguish leaf and extension nodes. The other two bits are not
used.
Parameters
x : Array of nibbles. is_leaf : True if this is part of a leaf node, or false if it is an extension node.
Returns
compressed : bytearray
Compact byte array.
def nibble_list_to_compact(x: Bytes, is_leaf: bool) -> Bytes:
250 | """ |
---|---|
251 | Compresses nibble-list into a standard byte array with a flag. |
252 |
|
253 | A nibble-list is a list of byte values no greater than `15`. The flag is |
254 | encoded in high nibble of the highest byte. The flag nibble can be broken |
255 | down into two two-bit flags. |
256 |
|
257 | Highest nibble:: |
258 |
|
259 | +---+---+----------+--------+ |
260 | | _ | _ | is_leaf | parity | |
261 | +---+---+----------+--------+ |
262 | 3 2 1 0 |
263 |
|
264 |
|
265 | The lowest bit of the nibble encodes the parity of the length of the |
266 | remaining nibbles -- `0` when even and `1` when odd. The second lowest bit |
267 | is used to distinguish leaf and extension nodes. The other two bits are not |
268 | used. |
269 |
|
270 | Parameters |
271 | ---------- |
272 | x : |
273 | Array of nibbles. |
274 | is_leaf : |
275 | True if this is part of a leaf node, or false if it is an extension |
276 | node. |
277 |
|
278 | Returns |
279 | ------- |
280 | compressed : `bytearray` |
281 | Compact byte array. |
282 | """ |
283 | compact = bytearray() |
284 | |
285 | if len(x) % 2 == 0: # ie even length |
286 | compact.append(16 * (2 * is_leaf)) |
287 | for i in range(0, len(x), 2): |
288 | compact.append(16 * x[i] + x[i + 1]) |
289 | else: |
290 | compact.append(16 * ((2 * is_leaf) + 1) + x[0]) |
291 | for i in range(1, len(x), 2): |
292 | compact.append(16 * x[i] + x[i + 1]) |
293 | |
294 | return Bytes(compact) |
bytes_to_nibble_list
Converts a Bytes
into to a sequence of nibbles (bytes with value < 16).
Parameters
bytes_:
The Bytes
to convert.
Returns
nibble_list : Bytes
The Bytes
in nibble-list format.
def bytes_to_nibble_list(bytes_: Bytes) -> Bytes:
298 | """ |
---|---|
299 | Converts a `Bytes` into to a sequence of nibbles (bytes with value < 16). |
300 |
|
301 | Parameters |
302 | ---------- |
303 | bytes_: |
304 | The `Bytes` to convert. |
305 |
|
306 | Returns |
307 | ------- |
308 | nibble_list : `Bytes` |
309 | The `Bytes` in nibble-list format. |
310 | """ |
311 | nibble_list = bytearray(2 * len(bytes_)) |
312 | for byte_index, byte in enumerate(bytes_): |
313 | nibble_list[byte_index * 2] = (byte & 0xF0) >> 4 |
314 | nibble_list[byte_index * 2 + 1] = byte & 0x0F |
315 | return Bytes(nibble_list) |
_prepare_trie
Prepares the trie for root calculation. Removes values that are empty,
hashes the keys (if secured == True
) and encodes all the nodes.
Parameters
trie :
The Trie
to prepare.
get_storage_root :
Function to get the storage root of an account. Needed to encode
Account
objects.
Returns
out : Mapping[ethereum.base_types.Bytes, Node]
Object with keys mapped to nibble-byte form.
def _prepare_trie(trie: Trie[K, V], get_storage_root: Optional[Callable[[Address], Root]]) -> Mapping[Bytes, Bytes]:
322 | """ |
---|---|
323 | Prepares the trie for root calculation. Removes values that are empty, |
324 | hashes the keys (if `secured == True`) and encodes all the nodes. |
325 |
|
326 | Parameters |
327 | ---------- |
328 | trie : |
329 | The `Trie` to prepare. |
330 | get_storage_root : |
331 | Function to get the storage root of an account. Needed to encode |
332 | `Account` objects. |
333 |
|
334 | Returns |
335 | ------- |
336 | out : `Mapping[ethereum.base_types.Bytes, Node]` |
337 | Object with keys mapped to nibble-byte form. |
338 | """ |
339 | mapped: MutableMapping[Bytes, Bytes] = {} |
340 | |
341 | for preimage, value in trie._data.items(): |
342 | if isinstance(value, Account): |
343 | assert get_storage_root is not None |
344 | address = Address(preimage) |
345 | encoded_value = encode_node(value, get_storage_root(address)) |
346 | else: |
347 | encoded_value = encode_node(value) |
348 | if encoded_value == b"": |
349 | raise AssertionError |
350 | key: Bytes |
351 | if trie.secured: |
352 | # "secure" tries hash keys once before construction |
353 | key = keccak256(preimage) |
354 | else: |
355 | key = preimage |
356 | mapped[bytes_to_nibble_list(key)] = encoded_value |
357 | |
358 | return mapped |
root
Computes the root of a modified merkle patricia trie (MPT).
Parameters
trie :
Trie
to get the root of.
get_storage_root :
Function to get the storage root of an account. Needed to encode
Account
objects.
Returns
root : .fork_types.Root
MPT root of the underlying key-value pairs.
def root(trie: Trie[K, V], get_storage_root: Optional[Callable[[Address], Root]]) -> Root:
365 | """ |
---|---|
366 | Computes the root of a modified merkle patricia trie (MPT). |
367 |
|
368 | Parameters |
369 | ---------- |
370 | trie : |
371 | `Trie` to get the root of. |
372 | get_storage_root : |
373 | Function to get the storage root of an account. Needed to encode |
374 | `Account` objects. |
375 |
|
376 |
|
377 | Returns |
378 | ------- |
379 | root : `.fork_types.Root` |
380 | MPT root of the underlying key-value pairs. |
381 | """ |
382 | obj = _prepare_trie(trie, get_storage_root) |
383 | |
384 | root_node = encode_internal_node(patricialize(obj, Uint(0))) |
385 | if len(rlp.encode(root_node)) < 32: |
386 | return keccak256(rlp.encode(root_node)) |
387 | else: |
388 | assert isinstance(root_node, Bytes) |
389 | return Root(root_node) |
patricialize
Structural composition function.
Used to recursively patricialize and merkleize a dictionary. Includes memoization of the tree structure and hashes.
Parameters
obj : Underlying trie key-value pairs, with keys in nibble-list format. level : Current trie level.
Returns
node : ethereum.base_types.Bytes
Root node of obj
.
def patricialize(obj: Mapping[Bytes, Bytes], level: Uint) -> Optional[InternalNode]:
395 | """ |
---|---|
396 | Structural composition function. |
397 |
|
398 | Used to recursively patricialize and merkleize a dictionary. Includes |
399 | memoization of the tree structure and hashes. |
400 |
|
401 | Parameters |
402 | ---------- |
403 | obj : |
404 | Underlying trie key-value pairs, with keys in nibble-list format. |
405 | level : |
406 | Current trie level. |
407 |
|
408 | Returns |
409 | ------- |
410 | node : `ethereum.base_types.Bytes` |
411 | Root node of `obj`. |
412 | """ |
413 | if len(obj) == 0: |
414 | return None |
415 | |
416 | arbitrary_key = next(iter(obj)) |
417 | |
418 | # if leaf node |
419 | if len(obj) == 1: |
420 | leaf = LeafNode(arbitrary_key[level:], obj[arbitrary_key]) |
421 | return leaf |
422 | |
423 | # prepare for extension node check by finding max j such that all keys in |
424 | # obj have the same key[i:j] |
425 | substring = arbitrary_key[level:] |
426 | prefix_length = len(substring) |
427 | for key in obj: |
428 | prefix_length = min( |
429 | prefix_length, common_prefix_length(substring, key[level:]) |
430 | ) |
431 |
|
432 | # finished searching, found another key at the current level |
433 | if prefix_length == 0: |
434 | break |
435 | |
436 | # if extension node |
437 | if prefix_length > 0: |
438 | prefix = arbitrary_key[level : level + prefix_length] |
439 | return ExtensionNode( |
440 | prefix, |
441 | encode_internal_node(patricialize(obj, level + prefix_length)), |
442 | ) |
443 | |
444 | branches: List[MutableMapping[Bytes, Bytes]] = [] |
445 | for _ in range(16): |
446 | branches.append({}) |
447 | value = b"" |
448 | for key in obj: |
449 | if len(key) == level: |
450 | # shouldn't ever have an account or receipt in an internal node |
451 | if isinstance(obj[key], (Account, Receipt, Uint)): |
452 | raise AssertionError |
453 | value = obj[key] |
454 | else: |
455 | branches[key[level]][key] = obj[key] |
456 | |
457 | return BranchNode( |
458 | [ |
459 | encode_internal_node(patricialize(branches[k], level + 1)) |
460 | for k in range(16) |
461 | ], |
462 | value, |
463 | ) |