trie

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2020 License: Apache-2.0 Imports: 18 Imported by: 9

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrAlreadyProcessed = errors.New("already processed")

ErrAlreadyProcessed is returned by the trie sync when it's requested to process a node it already processed previously.

View Source
var ErrNotRequested = errors.New("not requested")

ErrNotRequested is returned by the trie sync when it's requested to process a node it did not request.

Functions

func CacheMisses

func CacheMisses() int64

CacheMisses retrieves a global counter measuring the number of cache misses the trie had since process startup. This isn't useful for anything apart from trie debugging purpose

func CacheUnloads

func CacheUnloads() int64

CacheUnloads retrieves a global counter measuring the number of cache uploads the trie did since process startup. This isn't useful for anything apart from trie debugging purpose

func VerifyProof

func VerifyProof(rootHash common.Hash, key []byte, proofDb DatabaseReader) (value []byte, nodes int, err error)

VerifyProof checks merkle proofs. The given proof must contain the value for key in a trie with the given root hash. VerifyProof returns an error if the proof contains invalid trie nodes or the wrong value.

Types

type Database

type Database struct {
	// contains filtered or unexported fields
}

Database is an intermediate write layer between the trie data structures and the disk database. The aim is to accumulate trie writes in-memory and only periodically flush a couple tries to disk, garbage collecting the remainder.

func NewDatabase

func NewDatabase(diskdb ethdb.Database) *Database

NewDatabase creates a new trie database to store ephemeral trie content before its written out to disk or garbage collected. No read cache is created, so all data retrievals will hit the underlying disk database.

func NewDatabaseWithCache

func NewDatabaseWithCache(diskdb ethdb.Database, cache int) *Database

NewDatabaseWithCache creates a new trie database to store ephemeral trie content before its written out to disk or garbage collected. It also acts as a read cache for nodes loaded from disk.

func (*Database) Cap

func (db *Database) Cap(limit common.StorageSize) error

Cap iteratively flushed old but still referenced trie nodes until the total memory usage goes below the given threshold

func (*Database) Commit

func (db *Database) Commit(node common.Hash, report bool) error

Commit iterates over all the children of a particular node, writes them out to disk, forcefully tearing down all references in both directions.

As a side effect, all pre-images accumulated up to this point are also written

func (*Database) Dereference

func (db *Database) Dereference(root common.Hash)

Dereference removes an existing reference from a root node The function calls the dereference function and do the metrics calculation

func (*Database) DiskDB

func (db *Database) DiskDB() DatabaseReader

DiskDB retrieves the persistent storage backing the trie database.

func (*Database) InsertBlob

func (db *Database) InsertBlob(hash common.Hash, blob []byte)

InsertBlob writes a new reference tracked blob to the memory database if it's yet unknown. This method should only be used for non-trie nodes that require reference counting, since trie nodes are garbage collected directly through their embedded children.

func (*Database) Node

func (db *Database) Node(hash common.Hash) ([]byte, error)

Node retrieves an encoded cached trie node from memory. If it cannot be found cached, the method queries the persistent database for the content. The returned node is rlp encoded.

func (*Database) Nodes

func (db *Database) Nodes() []common.Hash

Nodes retrieves the hashes of all the nodes cached within the memory database. This method is extremely expensive and should only be used to validate internal states in test code.

func (*Database) Reference

func (db *Database) Reference(child common.Hash, parent common.Hash)

Reference adds a new reference from a parent node to a child node

func (*Database) Size

Size returns the current storage size of the memory cache in front of the persistent database layer

type DatabaseReader

type DatabaseReader interface {
	// Get retrieves the value associated with key from the database.
	Get(key []byte) (value []byte, err error)

	// Has retrieves whether a key is present in the database.
	Has(key []byte) (bool, error)
}

DatabaseReader wraps the Get and Has method of a backing store for the trie.

type Iterator

type Iterator struct {
	Key   []byte // Current data key on which the iterator is positioned on
	Value []byte // Current data value on which the iterator is positioned on
	Err   error
	// contains filtered or unexported fields
}

Iterator is a key-value trie iterator that traverses a Trie.

func NewIterator

func NewIterator(it NodeIterator) *Iterator

NewIterator creates a new key-value iterator from a node iterator

func (*Iterator) Next

func (it *Iterator) Next() bool

Next moves the iterator forward one key-value entry. If there is no more entries, return false, else return true. This is the function to be used directly by the upper level codes.

func (*Iterator) Prove

func (it *Iterator) Prove() [][]byte

Prove generates the Merkle proof for the leaf node the iterator is currently positioned on.

type LeafCallback

type LeafCallback func(leaf []byte, parent common.Hash) error

LeafCallback is a callback type invoked when a trie operation reaches a leaf node. It's used by state sync and commit to allow handling external references between account and storage tries.

type MissingNodeError

type MissingNodeError struct {
	NodeHash common.Hash // hash of the missing node
	Path     []byte      // hex-encoded path to the missing node
}

MissingNodeError is returned by the trie functions (TryGet, TryUpdate, TryDelete) in the case where a trie node is not present in the local database. It contains information necessary for retrieving the missing node.

func (*MissingNodeError) Error

func (err *MissingNodeError) Error() string

type NodeIterator

type NodeIterator interface {
	// Next moves the iterator to the next node. If the parameter is false, any child
	// nodes will be skipped.
	Next(bool) bool

	// Error returns the error status of the iterator
	Error() error

	// Hash returns the hash of the current node
	Hash() common.Hash

	// Parent returns the hash of the parent of the current node. The hash may be the
	// one grandparent if the immediate parent is an internal node with no hash.
	Parent() common.Hash

	// Path returns the hex-encoded path to the current node.
	// Callers must not retain reference to the return value after Calling Next.
	// For leaf nodes, the last element of the path is the 'terminator symbol' 0x10.
	Path() []byte

	// Leaf returns true iff the current node is a leaf node.
	Leaf() bool

	// LeafKey returns the key of the leaf. The method panics if the iterator is not
	// positioned at a leaf. Callers must not retain references to the value after
	// calling Next.
	LeafKey() []byte

	// LeafBlob returns the content of the leaf. The method panics if the iterator is
	// not positioned at a leaf. Callers must not retain references to the value after
	// calling Next
	LeafBlob() []byte

	// LeafProof returns the Merkle proof of the leaf. The method panics if the
	// iterator is not positioned at a leaf. Callers must not retain references to
	// the value after calling Next.
	LeafProof() [][]byte
}

NodeIterator is an iterator to traverse the trie pre-order

Example
trie := newTrieWithData(testData)
trie.Commit(nil)

it := NewIterator(trie.NodeIterator(nil))
for it.Next() {
	fmt.Printf("Got key value pair: %s -> %s\n", it.Key, it.Value)
}
Output:

Got key value pair: doge -> coin
Got key value pair: dog -> puppy
Got key value pair: do -> verb
Got key value pair: ether -> wookiedoo
Got key value pair: horse -> stallion
Got key value pair: shaman -> horse
Got key value pair: somethingveryoddindeedthis is -> myothernodedata

func NewDifferenceIterator

func NewDifferenceIterator(a, b NodeIterator) (NodeIterator, *int)

NewDifferenceIterator constructs a NodeIterator that iterates over elements in b that are not in a. Returns the iterator, and a pointer to an integer recording the number of nodes seen.

func NewUnionIterator

func NewUnionIterator(iters []NodeIterator) (NodeIterator, *int)

NewUnionIterator contracts a NodeIterator that iterates over element in the union of the provided NodeIterators. Returns the iterator, and a pointer to an integer recording the number of nodes visited.

type SecureTrie

type SecureTrie struct {
	// contains filtered or unexported fields
}

SecureTrie wraps a trie with key hashing. In a secure trie, all access operations hash the key using keccak256. This prevents calling code from creating long chains of nodes that increase the access time.

Contrary to a regular trie, a SecureTrie can only be created with New and must have an attached database. The database also stores the preimage of each key.

SecureTrie is not safe for concurrent use.

Example

SecureTrie has almost the same behaviour as Trie

triedb := NewDatabase(ethdb.NewMemDatabase())
trie, _ := NewSecure(common.Hash{}, triedb, 0)
for _, entry := range testData {
	trie.Update([]byte(entry.k), []byte(entry.v))
}

// Insert
trie.Update([]byte("does"), []byte("good"))

// Get
val := trie.Get([]byte("does"))
fmt.Printf("Retrieved key value pair: %s -> %s\n", "does", string(val))

// Delete
trie.Delete([]byte("does"))
if val := trie.Get([]byte("does")); val == nil {
	fmt.Printf("Successfully deleted the key \"does\"\n")
}

// Commit
hash, err := trie.Commit(nil)
if err != nil {
	fmt.Println("Commit return an error:", err.Error())
	return
}

// Create a new trie same as the original trie
newTrie, err := NewSecure(hash, triedb, 0)
if err != nil {
	fmt.Println(err.Error())
}
val = newTrie.Get([]byte("dog"))
fmt.Printf("Retrieved from new trie: %s -> %s", "dog", val)
Output:

Retrieved key value pair: does -> good
Successfully deleted the key "does"
Retrieved from new trie: dog -> puppy

func NewSecure

func NewSecure(root common.Hash, db *Database, cachelimit uint16) (*SecureTrie, error)

NewSecure creates a trie with an existing root node from a backing database and optional intermediate in-memory node pool.

If root is the zero hash or the sha3 hash of an empty string, the trie is initially empty. Otherwise, New will panic if db is nil and returns MissingNodeError if the root node cannot be found.

Accessing the trie loads nodes from the database and node pool on demand. Loaded nodes are kept around until their 'cache generation' expires. A new cache generation is created by each call to Commit. cachelimit sets the number of past cache generations to keep.

func (*SecureTrie) Commit

func (t *SecureTrie) Commit(onleaf LeafCallback) (root common.Hash, err error)

Commit writes all nodes and the secure hash pre-image to the trie's database. Nodes are stroed with their sha3 hash as the key.

Committing flushes nodes from memory. Subsequent Get calls will load nodes from the database.

func (*SecureTrie) Copy

func (t *SecureTrie) Copy() *SecureTrie

Copy returns a copy of SecureTrie.

func (*SecureTrie) Delete

func (t *SecureTrie) Delete(key []byte)

Delete removes any existing value for key from the trie.

func (*SecureTrie) Get

func (t *SecureTrie) Get(key []byte) []byte

Get returns the value for key stored in the trie. The value bytes must not be modified by the caller.

func (*SecureTrie) GetKey

func (t *SecureTrie) GetKey(shaKey []byte) []byte

GetKey returns the sha3 preimage of a hashed key that was previously used to store a value

func (*SecureTrie) Hash

func (t *SecureTrie) Hash() common.Hash

Hash returns the root hash of SecureTrie. It does not write to the database and can be used even if the trie doesn't have one.

func (*SecureTrie) NodeIterator

func (t *SecureTrie) NodeIterator(start []byte) NodeIterator

NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration starts at the key after the given start key.

func (*SecureTrie) Prove

func (t *SecureTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error

Prove constructs a merkle proof for key. The result contains all encoded nodes on the path to the value at key. The value itself is also included in the last node and can be retrieved by verifying the proof.

If the trie does not contain a value for key, the returned proof contains all nodes of the longest existing prefix of the key (at least the root node), ending with the node that proves the absence of the key.

func (*SecureTrie) TryDelete

func (t *SecureTrie) TryDelete(key []byte) error

TryDelete removes any existing value for key from the trie. If a node was not found in the database, a MissingNodeError is returned.

func (*SecureTrie) TryGet

func (t *SecureTrie) TryGet(key []byte) ([]byte, error)

TryGet returns the value for key stored in the trie. the value bytes must no be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*SecureTrie) TryUpdate

func (t *SecureTrie) TryUpdate(key, value []byte) error

TryUpdate associates key with value in the trie. Subsequent calls to Get will return value. If value has zero length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

If a node was not found in the database, a MissingNodeError is returned.

func (*SecureTrie) Update

func (t *SecureTrie) Update(key, value []byte)

Update associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil

The value bytes must not be modified by the caller while they are stored in the trie

type Sync

type Sync struct {
	// contains filtered or unexported fields
}

Sync is the main state of trie synchronisation scheduler, which provides yet unknown trie hashes to retrieve, accepts node data associated with said hashes and reconstructs the trie step by step until all is done.

Example
// Create a random trie to copy
srcDb, srcTrie, _ := makeTestTrie()

// Create a destination trie and sync with the scheduler
diskdb := ethdb.NewMemDatabase()
sched := NewSync(srcTrie.Hash(), diskdb, nil)

queue := append([]common.Hash{}, sched.Missing(1)...)
for len(queue) > 0 {
	results := make([]SyncResult, len(queue))
	for i, hash := range queue {
		data, err := srcDb.Node(hash)
		if err != nil {
			fmt.Printf("failed to retrieve node data for %x: %v\n", hash, err)
		}
		results[i] = SyncResult{hash, data}
	}
	if _, index, err := sched.Process(results); err != nil {
		fmt.Printf("failed to process result #%d: %v\n", index, err)
	}
	if index, err := sched.Commit(diskdb); err != nil {
		fmt.Printf("failed to commit data #%d: %v\n", index, err)
	}
	queue = append(queue[:0], sched.Missing(1)...)
}
Output:

func NewSync

func NewSync(root common.Hash, database DatabaseReader, callback LeafCallback) *Sync

NewSync creates a new trie data download scheduler

func (*Sync) AddRawEntry

func (s *Sync) AddRawEntry(hash common.Hash, depth int, parent common.Hash)

AddRawEntry schedules the direct retrieval of a state entry that should not be interpreted as a trie node, but rather accepted and stored into the database as is. This method's goal is to support misc state metadata retrievals (e.g. contract code)

func (*Sync) AddSubTrie

func (s *Sync) AddSubTrie(root common.Hash, depth int, parent common.Hash, callback LeafCallback)

AddSubTrie registers a new trie to the sync code, rooted at the designated parent.

func (*Sync) Commit

func (s *Sync) Commit(dbw ethdb.Putter) (int, error)

Commit flushes the data stored in the internal membatch out to persistent storage, returning the number of items written and any occurred error.

func (*Sync) Missing

func (s *Sync) Missing(max int) []common.Hash

Missing retrieves the known missing nodes from the trie for retrieval.

func (*Sync) Pending

func (s *Sync) Pending() int

Pending returns the number of state entries currently pending for download.

func (*Sync) Process

func (s *Sync) Process(results []SyncResult) (bool, int, error)

Process injects a batch of retrieved trie nodes data, returning if something was committed to the database and also the index of an entry if processing of it failed.

type SyncResult

type SyncResult struct {
	Hash common.Hash // Hash of the originally unknown trie node
	Data []byte      // Data content of the retrieved node
}

SyncResult is a simple list to return missing nodes along with their request hashes.

type Trie

type Trie struct {
	// contains filtered or unexported fields
}

Trie is a Merkle Patricia Trie. The zero value is an empty trie with no database. Use New to create a trie that sits on top of a database

Trie is not safe for concurrent use.

func New

func New(root common.Hash, db *Database) (*Trie, error)

New creates a trie with an existing root node from db.

If root is the zero hash or the sha3 hash of an empty string, the trie is initially empty and does not require a database. Otherwise, New will panic if db is nil and returns a MissingNodeError if root does not exist in the database. Accessing the trie loads nodes from db on demand.

func NewTrieWithPrefix

func NewTrieWithPrefix(root common.Hash, prefix []byte, db *Database) (*Trie, error)

NewTrieWithPrefix creates a trie with an existing root node that has the specified prefix

func (*Trie) Commit

func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error)

Commit writes all nodes to the trie's memory database, tracking the internal and external (for account tries) references.

Example

This ExampleTrie_Commit function covers some underlying logic of the Commit operation.

// Create a trie1
trie1 := newTrieWithData(testData)

// Commit trie1. The root node after commit is a copied cached node of the original root node.
// But the root's hash is exactly the hash of committed node.
hash, err := trie1.Commit(nil)
if err != nil {
	fmt.Println(err.Error())
	return
}
// Create a new trie with committed data. Note here the root node in trie2 is not the root from trie1.
// The root of trie2 is a new node with hash.
trie2, err := New(hash, trie1.db)
if err != nil {
	fmt.Println("New returns an error:,", err.Error())
	return
}
for _, entry := range testData {
	val := trie2.Get([]byte(entry.k))
	fmt.Printf("The new trie got data: %s -> %s\n", entry.k, string(val))
}
fmt.Println()

// Change an entry in the new trie should not affect the original trie1.
// After node updated, the updated node will have a new flag with a nil hash.
trie2.Update([]byte("doom"), []byte("catastrophe"))

// Commit the trie2. After commit, the changed node in the last update which has nil hash will be
// flushed to disk with a new hash.
newHash, _ := trie2.Commit(nil)
if newHash != hash {
	fmt.Println("The new trie have a different hash from the original.")
}

val := trie1.Get([]byte("doom"))
fmt.Printf("After change trie2, trie1 have key value: %s -> [%s].\n", "doom", val)
Output:

The new trie got data: do -> verb
The new trie got data: ether -> wookiedoo
The new trie got data: horse -> stallion
The new trie got data: shaman -> horse
The new trie got data: doge -> coin
The new trie got data: dog -> puppy
The new trie got data: somethingveryoddindeedthis is -> myothernodedata

The new trie have a different hash from the original.
After change trie2, trie1 have key value: doom -> [].

func (*Trie) Delete

func (t *Trie) Delete(key []byte)

Delete removes any existing value for key from the trie

Example
trie := newTrieWithData(testData)

// Delete an existing entry
trie.Delete([]byte("dog"))

// Try to find the deleted entry, must return an error
val, err := trie.TryGet([]byte("dog"))
if err != nil {
	fmt.Println("TryGet returns an error:", err.Error())
	return
}
fmt.Printf("After deletion, have key value pair: %s -> [%s].\n", "dog", val)
Output:

After deletion, have key value pair: dog -> [].

func (*Trie) Get

func (t *Trie) Get(key []byte) []byte

Get returns the value for key stored in the trie The value bytes must not be modified by the caller

func (*Trie) Hash

func (t *Trie) Hash() common.Hash

Hash returns the root hash of the trie. It does not write to the database and can be used even if the trie does not have one.

func (*Trie) NodeIterator

func (t *Trie) NodeIterator(start []byte) NodeIterator

NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at the key after the given start key

func (*Trie) PrefixIterator

func (t *Trie) PrefixIterator(prefix []byte) NodeIterator

PrefixIterator returns an iterator that returns nodes of the trie with the specified prefix path, it will start iteration at the key after the given prefix path.

func (*Trie) Prove

func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error

Prove constructs a merkle proof for key. The result contains all encoded nodes on the path to the value at key. The value itself is also included in the last node and can be retrieved by verifying the proof.

If the trie does not contain a value for key, the returned proof contains all nodes of the longest existing prefix of the key (at least the root node), ending with the node that proves the absence of the key

func (*Trie) Root

func (t *Trie) Root() []byte

Root returns the root hash of the trie Deprecated: use Hash instead

func (*Trie) SetCacheLimit

func (t *Trie) SetCacheLimit(l uint16)

SetCacheLimit sets the number of 'cache generations' to keep. A cache generation is created by a call to Commit

func (*Trie) TryDelete

func (t *Trie) TryDelete(key []byte) error

TryDelete removes any existing value for key from the trie If a node was not found in the database, a MissingNodeError is returned.

func (*Trie) TryGet

func (t *Trie) TryGet(key []byte) ([]byte, error)

TryGet returns the value for key stored in the trie. The value bytes must not be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*Trie) TryUpdate

func (t *Trie) TryUpdate(key, value []byte) error

TryUpdate associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

If a node was not found in the database, a MissingNodeError is returned.

func (*Trie) Update

func (t *Trie) Update(key, value []byte)

Update associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil

The value bytes must not be modified by the caller while they are stored in the trie.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL