Ethereum Trie (py-trie)

3.1.0 · active · verified Thu Apr 16

The `trie` library is a Python implementation of the Ethereum Trie (specifically, the Hexary Trie) data structure. It provides tools for interacting with the Merkelized Patricia Trie, which is fundamental to Ethereum's state, transaction, and receipt storage. As of its current version 3.1.0, it remains an active project maintained by the Ethereum Foundation, with a release cadence tied to ongoing Ethereum development and needs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic usage of `HexaryTrie` by initializing it with an in-memory dictionary acting as a database, inserting and retrieving byte string key-value pairs, and checking for key existence. In a real-world Ethereum context, the `db` parameter would typically be a more robust, persistent database backend.

from trie import HexaryTrie

# A simple in-memory dict for demonstration. For production, use a persistent database.
db = {}

t = HexaryTrie(db=db)

# The root hash of an empty trie
print(f"Initial root hash: {t.root_hash.hex()}")

# Insert some key-value pairs (keys and values must be bytes)
t.set(b'dog', b'puppy')
t.set(b'do', b'remi')
t.set(b'cat', b'kitten')

print(f"Root hash after inserts: {t.root_hash.hex()}")

# Retrieve values
print(f"Value for 'dog': {t.get(b'dog')}")
print(f"Value for 'cat': {t.get(b'cat')}")

# Check for key existence
print(f"'dog' in trie: {b'dog' in t}")
print(f"'fish' in trie: {b'fish' in t}")

# Delete a key
t.delete(b'dog')
print(f"'dog' in trie after deletion: {b'dog' in t}")
print(f"Root hash after deletion: {t.root_hash.hex()}")

view raw JSON →