I am trying to create a HexaryTrie from the database that the trie writes to.

Here is my Code:

from trie import (

db = {}
trie1 = HexaryTrie(db)

trie1[b'deadbeef'] = b'deadbeef'

trie2 = HexaryTrie(db)

# ^ these print different root hashes :(

I saw in py-trie, that the HexaryTrie constructor is:

def __init__(self, db, root_hash=BLANK_NODE_HASH, prune=False):
    self.db = db
    self.root_hash = root_hash
    self.is_pruning = prune

Is there a way to use the db that is being created to "re"-create the trie?

Thank you in advance :)

1 Answer 1


Is there a way to use the db that is being created to "re"-create the trie?

Yes, with one missing piece.

A HexaryTrie instance keeps track of its current root hash as it updates. But if you load a fresh trie from the database, you have to tell it which root hash to bootstrap from.

So, set up your initial data:

db = {}
trie1 = HexaryTrie(db)

trie1[b'deadbeef'] = b'deadbeef'

Recreate the original problem:

trie2 = HexaryTrie(db)
# because this doesn't have a root hash to look up the nodes, this
# returns empty data. Side note: I wish it raised a KeyError here...
assert trie2[b'deadbeef'] == b''

To look up the data successfully, you can change the root hash at runtime:

trie2.root_hash = trie1.root_hash
# The trie can now find the desired data:
assert trie2[b'deadbeef'] == b'deadbeef'

Alternatively, create the trie with the correct root hash:

trie3 = HexaryTrie(db, root_hash=trie1.root_hash)
assert trie3[b'deadbeef'] == b'deadbeef'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.