trie

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2022 License: GPL-3.0 Imports: 27 Imported by: 0

Documentation

Overview

Package trie implements Merkle Patricia Tries.

Index

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 ErrCommitDisabled = errors.New("no database for committing")
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 VerifyProof

func VerifyProof(rootHash common.Hash, key []byte, proofDb ethdb.KeyValueReader) (value []byte, 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. rootHash表示要验证的树的根,key为要验证的路径 如果返回的err为nil说明验证通过,此时返回的value代表key对应的值

func VerifyRangeProof

func VerifyRangeProof(rootHash common.Hash, firstKey []byte, lastKey []byte, keys [][]byte, values [][]byte, proof ethdb.KeyValueReader) (bool, error)

VerifyRangeProof checks whether the given leaf nodes and edge proof can prove the given trie leaves range is matched with the specific root. Besides, the range should be consecutive (no gap inside) and monotonic increasing.

Note the given proof actually contains two edge proofs. Both of them can be non-existent proofs. For example the first proof is for a non-existent key 0x03, the last proof is for a non-existent key 0x10. The given batch leaves are [0x04, 0x05, .. 0x09]. It's still feasible to prove the given batch is valid.

The firstKey is paired with firstProof, not necessarily the same as keys[0] (unless firstProof is an existent proof). Similarly, lastKey and lastProof are paired.

Expect the normal case, this function can also be used to verify the following range proofs:

  • All elements proof. In this case the proof can be nil, but the range should be all the leaves in the trie.
  • One element proof. In this case no matter the edge proof is a non-existent proof or not, we can always verify the correctness of the proof.
  • Zero element proof. In this case a single non-existent proof is enough to prove. Besides, if there are still some other leaves available on the right side, then an error will be returned.

Except returning the error to indicate the proof is valid or not, the function will also return a flag to indicate whether there exists more accounts/slots in the trie.

Note: This method does not verify that the proof is of minimal form. If the input proofs are 'bloated' with neighbour leaves or random data, aside from the 'useful' data, then the proof will still be accepted. keys和values中的数据一一对应,代表要验证的键值对,而且输入的key必须要单调递增 返回的bool代表树中在最后一个验证的key后面是否还有节点,error代表验证是否通过

Types

type Config

type Config struct {
	Cache int // Memory allowance (MB) to use for caching trie nodes in memory
	// fastcache保存到的文件
	Journal string // Journal of clean cache to survive node restarts
	// 是否记录梅克尔树的key的原像
	Preimages bool // Flag whether the preimage of trie key is recorded
}

Config defines all necessary options for database.

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.

Note, the trie Database is **not** thread safe in its mutations, but it **is** thread safe in providing individual, independent node access. The rationale behind this split design is to provide read access to RPC handlers and sync servers even while the trie is executing expensive garbage collection. Database类型是保存在内存中的梅克尔树与保存在硬盘中的数据库的中间层 数据先写入到内存中,积累到足够数量再写入到硬盘中

func NewDatabase

func NewDatabase(diskdb ethdb.KeyValueStore) *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 NewDatabaseWithConfig

func NewDatabaseWithConfig(diskdb ethdb.KeyValueStore, config *Config) *Database

NewDatabaseWithConfig 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 flushes old but still referenced trie nodes until the total memory usage goes below the given threshold.

Note, this method is a non-synchronized mutator. It is unsafe to call this concurrently with other mutators. 将保存在内存中的数据写入到数据库中,使得内存占用小于输入的大小 根据flush-lits中的顺序来写入数据库,从oldest开始依次写入,newest最后写入

func (*Database) Commit

func (db *Database) Commit(node common.Hash, report bool, callback func(common.Hash)) 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.

Note, this method is a non-synchronized mutator. It is unsafe to call this concurrently with other mutators.

func (*Database) Dereference

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

Dereference removes an existing reference from a root node. 输入树根,对这个树根解引用

func (*Database) DiskDB

func (db *Database) DiskDB() ethdb.KeyValueStore

DiskDB retrieves the persistent storage backing the trie database.

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. 从数据库中查询节点,返回的是rlp编码,字节数组 先从cleans中查询,再从dirties中查询,最后从diskdb中查询 从diskdb中查询成功后会缓存到cleans中

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. 返回dirties中保存的所有节点的哈希

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. This function is used to add reference between internal trie node and external node(e.g. storage trie root), all internal trie nodes are referenced together by database itself. 用来在外部节点和内部节点间增加引用

func (*Database) SaveCache

func (db *Database) SaveCache(dir string) error

SaveCache atomically saves fast cache data to the given dir using all available CPU cores. 保存fastcache到文件中,使用cpu的所有核心

func (*Database) SaveCachePeriodically

func (db *Database) SaveCachePeriodically(dir string, interval time.Duration, stopCh <-chan struct{})

SaveCachePeriodically atomically saves fast cache data to the given dir with the specified interval. All dump operation will only use a single CPU core. 定期将db.clean保存到文件中,使用单线程保存

func (*Database) Size

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

type Iterator

type Iterator struct {

	// 当前所处的key
	Key []byte // Current data key on which the iterator is positioned on
	// 当前所处的value
	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. 梅克尔树的迭代器 Iterator里面可以指定不同的NodeIterator NodeIterator总共有三种 分别是 nodeIterator,differenceIterator,unionIterator Iterator每次调用Next将会迭代到下一个叶子节点,获取该节点保存的键值对

func NewIterator

func NewIterator(it NodeIterator) *Iterator

NewIterator creates a new key-value iterator from a node iterator. Note that the value returned by the iterator is raw. If the content is encoded (e.g. storage value is RLP-encoded), it's caller's duty to decode it. 新建一个Iterator

func (*Iterator) Next

func (it *Iterator) Next() bool

Next moves the iterator forward one key-value entry. 迭代到下一个叶子节点

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(paths [][]byte, hexpath []byte, leaf []byte, parent common.Hash) error

LeafCallback is a callback type invoked when a trie operation reaches a leaf node.

The paths is a path tuple identifying a particular trie node either in a single trie (account) or a layered trie (account -> storage). Each path in the tuple is in the raw format(32 bytes).

The hexpath is a composite hexary path identifying the trie node. All the key bytes are converted to the hexary nibbles and composited with the parent path if the trie node is in a layered trie.

It's used by state sync and commit to allow handling external references between account and storage tries. And also it's used in the state healing for extracting the raw states(leaf nodes) with corresponding paths. 当到达叶子节点的时候调用的函数

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 references 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

	// AddResolver sets an intermediate database to use for looking up trie nodes
	// before reaching into the real persistent layer.
	//
	// This is not required for normal operation, rather is an optimization for
	// cases where trie nodes can be recovered from some external mechanism without
	// reading from disk. In those cases, this resolver allows short circuiting
	// accesses and returning them from memory.
	//
	// Before adding a similar mechanism to any other place in Geth, consider
	// making trie.Database an interface and wrapping at that level. It's a huge
	// refactor, but it could be worth it if another occurrence arises.
	// 只有nodeIterator支持该方法
	// differenceIterator,unionIterator不支持该方法
	AddResolver(ethdb.KeyValueStore)
}

NodeIterator is an iterator to traverse the trie pre-order. NodeIterator对梅克尔树进行先序遍历 nodeIterator,differenceIterator,unionIterator实现了NodeIterator接口 外部可以使用NewDifferenceIterator,NewUnionIterator两种 NodeIterator用来迭代树中的所有节点

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. 遍历在b中而不在a中的节点

func NewUnionIterator

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

NewUnionIterator constructs a NodeIterator that iterates over elements in the union of the provided NodeIterators. Returns the iterator, and a pointer to an integer recording the number of nodes visited. 创建一个unionIterator对象 遍历所有给定的NodeIterator里的节点

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. SecureTrie在内部保存的树是对输入的key进行哈希计算后的key Database中保存了每个key的原像preimage

func NewSecure

func NewSecure(root common.Hash, db *Database) (*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 or 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. 新建一个SecureTrie,必须指定db

func (*SecureTrie) Commit

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

Commit writes all nodes and the secure hash pre-images to the trie's database. Nodes are stored 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. 根据sha3的哈希值获取原来的key

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.KeyValueWriter) 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 not be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*SecureTrie) TryGetNode

func (t *SecureTrie) TryGetNode(path []byte) ([]byte, int, error)

TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not possible to use keybyte-encoding as the path might contain odd nibbles.

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 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) TryUpdateAccount

func (t *SecureTrie) TryUpdateAccount(key []byte, acc *types.StateAccount) error

TryUpdate account will abstract the write of an account to the secure trie.

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 StackTrie

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

StackTrie is a trie implementation that expects keys to be inserted in order. Once it determines that a subtree will no longer be inserted into, it will hash it and free up the memory it uses. key按照顺序插入的类型

func NewFromBinary

func NewFromBinary(data []byte, db ethdb.KeyValueWriter) (*StackTrie, error)

NewFromBinary initialises a serialized stacktrie with the given db. 输入字节数组解码为StackTrie

func NewStackTrie

func NewStackTrie(db ethdb.KeyValueWriter) *StackTrie

NewStackTrie allocates and initializes an empty trie. 新建一个StackTrie对象 设置nodeType为emptyNode 设置db为输入的db

func (*StackTrie) Commit

func (st *StackTrie) Commit() (common.Hash, error)

Commit will firstly hash the entrie trie if it's still not hashed and then commit all nodes to the associated database. Actually most of the trie nodes MAY have been committed already. The main purpose here is to commit the root node.

The associated database is expected, otherwise the whole commit functionality should be disabled. 把整棵树各个节点 hash->rlp 映射写入数据库 返回树根的哈希

func (*StackTrie) Hash

func (st *StackTrie) Hash() (h common.Hash)

Hash returns the hash of the current node 执行后st.type变为hashedNode,返回树的哈希值 st.val执行后可能是rlp编码也可能是哈希

func (*StackTrie) MarshalBinary

func (st *StackTrie) MarshalBinary() (data []byte, err error)

MarshalBinary implements encoding.BinaryMarshaler 返回StackTrie编码后的字节数组 使用gob包进行编码,递归编码child nil child使用0标记,不为nil的child有前缀1

func (*StackTrie) Reset

func (st *StackTrie) Reset()

让StackTrie的各个字段都清空

func (*StackTrie) TryUpdate

func (st *StackTrie) TryUpdate(key, value []byte) error

TryUpdate inserts a (key, value) pair into the stack trie 设置key对应的值为value value的长度不能为0,因为StackTrie不支持删除操作

func (*StackTrie) UnmarshalBinary

func (st *StackTrie) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler 输入字节数组解码到StackTrie

func (*StackTrie) Update

func (st *StackTrie) Update(key, value []byte)

type Sync

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

Sync is the main state 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.

func NewSync

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

NewSync creates a new trie data download scheduler.

func (*Sync) AddCodeEntry

func (s *Sync) AddCodeEntry(hash common.Hash, path []byte, parent common.Hash)

AddCodeEntry schedules the direct retrieval of a contract code that should not be interpreted as a trie node, but rather accepted and stored into the database as is. 构造一个请求code的request对象

func (*Sync) AddSubTrie

func (s *Sync) AddSubTrie(root common.Hash, path []byte, parent common.Hash, callback LeafCallback)

AddSubTrie registers a new trie to the sync code, rooted at the designated parent. 构造一个请求节点的request对象

func (*Sync) Commit

func (s *Sync) Commit(dbw ethdb.Batch) error

Commit flushes the data stored in the internal membatch out to persistent storage, returning any occurred error. 将membatch中的数据写入到输入的dbw数据库中 然后重置membatch

func (*Sync) Missing

func (s *Sync) Missing(max int) (nodes []common.Hash, paths []SyncPath, codes []common.Hash)

Missing retrieves the known missing nodes from the trie for retrieval. To aid both eth/6x style fast sync and snap/1x style state sync, the paths of trie nodes are returned too, as well as separate hash list for codes. 返回要请求节点和代码的哈希 max用来限制返回的 节点和代码哈希总和的个数,也就是最多请求max个 max为0代表不限制

func (*Sync) Pending

func (s *Sync) Pending() int

Pending returns the number of state entries currently pending for download. 当前还在等待下载的请求就是nodeReqs和codeReqs的和

func (*Sync) Process

func (s *Sync) Process(result SyncResult) error

Process injects the received data for requested item. Note it can happpen that the single response commits two pending requests(e.g. there are two requests one for code and one for node but the hash is same). In this case the second response for the same hash will be treated as "non-requested" item or "already-processed" item but there is no downside. 下载好的数据调用Process进行处理 对于code直接保存到membatch中,等待调用Commit写入数据库 对于node继续构造子节点的请求并放入请求队列,如果没有子节点请求那么将这个节点写入membatch等待Commit

type SyncBloom

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

SyncBloom is a bloom filter used during fast sync to quickly decide if a trie node or contract code already exists on disk or not. It self populates from the provided disk database on creation in a background thread and will only start returning live results once that's finished.

func NewSyncBloom

func NewSyncBloom(memory uint64, database ethdb.Iteratee) *SyncBloom

NewSyncBloom creates a new bloom filter of the given size (in megabytes) and initializes it from the database. The bloom is hard coded to use 3 filters. 新建一个SyncBloom对象,memory代表布隆过滤使用的空间大小(单位是M) 首先创建布隆过滤器对象,然后调用该对象的init和meter方法

func (*SyncBloom) Add

func (b *SyncBloom) Add(hash []byte)

Add inserts a new trie node hash into the bloom filter. 向布隆过滤器加入一个哈希

func (*SyncBloom) Close

func (b *SyncBloom) Close() error

Close terminates any background initializer still running and releases all the memory allocated for the bloom.

func (*SyncBloom) Contains

func (b *SyncBloom) Contains(hash []byte) bool

Contains tests if the bloom filter contains the given hash:

  • false: the bloom definitely does not contain hash
  • true: the bloom maybe contains hash

While the bloom is being initialized, any query will return true. 检测一个哈希是否在布隆过滤器内

type SyncPath

type SyncPath [][]byte

SyncPath is a path tuple identifying a particular trie node either in a single trie (account) or a layered trie (account -> storage).

Content wise the tuple either has 1 element if it addresses a node in a single trie or 2 elements if it addresses a node in a stacked trie.

To support aiming arbitrary trie nodes, the path needs to support odd nibble lengths. To avoid transferring expanded hex form over the network, the last part of the tuple (which needs to index into the middle of a trie) is compact encoded. In case of a 2-tuple, the first item is always 32 bytes so that is simple binary encoded.

Examples:

  • Path 0x9 -> {0x19}
  • Path 0x99 -> {0x0099}
  • Path 0x01234567890123456789012345678901012345678901234567890123456789019 -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x19}
  • Path 0x012345678901234567890123456789010123456789012345678901234567890199 -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x0099}

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 response with requested data along with it's hash. 查询的结果 包括节点的哈希以及该节点的内容

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. root为空,新建一个空树 root不为空,根据root从数据库中重新加载整颗树

func (*Trie) Commit

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

Commit writes all nodes to the trie's memory database, tracking the internal and external (for account tries) references. 对树进行过插入删除等操作后调用Commit来提交到内存数据库中,也就是db.dirties中 onleaf不为nil的话,树中的每个叶子节点都会调用一次onleaf t.root被修改为缓存树,返回树根的哈希

func (*Trie) Delete

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

Delete removes any existing value for key from the trie.

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. 输入key是原始的格式 Get函数不返回错误,有错误直接在日志打印

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 doesn't have one. 计算整棵树的哈希,设置root为缓存树的根,并返回树根哈希

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) Prove

func (t *Trie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) 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. 计算给定key的梅克尔证明,将每一层的计算结果写入proofDb 写入的结果就是路径上的每一个节点对应的 hash->rlp 映射 fromLevel代表从树的哪一层开始计算

func (*Trie) Reset

func (t *Trie) Reset()

Reset drops the referenced root node and cleans all internal state.

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. 输入key是原始格式 TyrGet有错误将会返回

func (*Trie) TryGetNode

func (t *Trie) TryGetNode(path []byte) ([]byte, int, error)

TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not possible to use keybyte-encoding as the path might contain odd nibbles. 输入compact格式的path查询树中节点 这个函数用来获取树中的任意节点,得到节点的rlp编码

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) TryUpdateAccount

func (t *Trie) TryUpdateAccount(key []byte, acc *types.StateAccount) error

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