github.com/phillinzzz/newBsc@v1.1.6/trie/trie.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package trie implements Merkle Patricia Tries.
    18  package trie
    19  
    20  import (
    21  	"bytes"
    22  	"errors"
    23  	"fmt"
    24  	"sync"
    25  
    26  	"github.com/phillinzzz/newBsc/common"
    27  	"github.com/phillinzzz/newBsc/crypto"
    28  	"github.com/phillinzzz/newBsc/log"
    29  )
    30  
    31  var (
    32  	// emptyRoot is the known root hash of an empty trie.
    33  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    34  
    35  	// emptyState is the known hash of an empty state trie entry.
    36  	emptyState = crypto.Keccak256Hash(nil)
    37  )
    38  
    39  // LeafCallback is a callback type invoked when a trie operation reaches a leaf
    40  // node.
    41  //
    42  // The paths is a path tuple identifying a particular trie node either in a single
    43  // trie (account) or a layered trie (account -> storage). Each path in the tuple
    44  // is in the raw format(32 bytes).
    45  //
    46  // The hexpath is a composite hexary path identifying the trie node. All the key
    47  // bytes are converted to the hexary nibbles and composited with the parent path
    48  // if the trie node is in a layered trie.
    49  //
    50  // It's used by state sync and commit to allow handling external references
    51  // between account and storage tries. And also it's used in the state healing
    52  // for extracting the raw states(leaf nodes) with corresponding paths.
    53  type LeafCallback func(paths [][]byte, hexpath []byte, leaf []byte, parent common.Hash) error
    54  
    55  // Trie is a Merkle Patricia Trie.
    56  // The zero value is an empty trie with no database.
    57  // Use New to create a trie that sits on top of a database.
    58  //
    59  // Trie is not safe for concurrent use.
    60  type Trie struct {
    61  	db   *Database
    62  	root node
    63  	// Keep track of the number leafs which have been inserted since the last
    64  	// hashing operation. This number will not directly map to the number of
    65  	// actually unhashed nodes
    66  	unhashed int
    67  }
    68  
    69  // newFlag returns the cache flag value for a newly created node.
    70  func (t *Trie) newFlag() nodeFlag {
    71  	return nodeFlag{dirty: true}
    72  }
    73  
    74  // New creates a trie with an existing root node from db.
    75  //
    76  // If root is the zero hash or the sha3 hash of an empty string, the
    77  // trie is initially empty and does not require a database. Otherwise,
    78  // New will panic if db is nil and returns a MissingNodeError if root does
    79  // not exist in the database. Accessing the trie loads nodes from db on demand.
    80  func New(root common.Hash, db *Database) (*Trie, error) {
    81  	if db == nil {
    82  		panic("trie.New called without a database")
    83  	}
    84  	trie := &Trie{
    85  		db: db,
    86  	}
    87  	if root != (common.Hash{}) && root != emptyRoot {
    88  		rootnode, err := trie.resolveHash(root[:], nil)
    89  		if err != nil {
    90  			return nil, err
    91  		}
    92  		trie.root = rootnode
    93  	}
    94  	return trie, nil
    95  }
    96  
    97  // NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at
    98  // the key after the given start key.
    99  func (t *Trie) NodeIterator(start []byte) NodeIterator {
   100  	return newNodeIterator(t, start)
   101  }
   102  
   103  // Get returns the value for key stored in the trie.
   104  // The value bytes must not be modified by the caller.
   105  func (t *Trie) Get(key []byte) []byte {
   106  	res, err := t.TryGet(key)
   107  	if err != nil {
   108  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   109  	}
   110  	return res
   111  }
   112  
   113  // TryGet returns the value for key stored in the trie.
   114  // The value bytes must not be modified by the caller.
   115  // If a node was not found in the database, a MissingNodeError is returned.
   116  func (t *Trie) TryGet(key []byte) ([]byte, error) {
   117  	value, newroot, didResolve, err := t.tryGet(t.root, keybytesToHex(key), 0)
   118  	if err == nil && didResolve {
   119  		t.root = newroot
   120  	}
   121  	return value, err
   122  }
   123  
   124  func (t *Trie) tryGet(origNode node, key []byte, pos int) (value []byte, newnode node, didResolve bool, err error) {
   125  	switch n := (origNode).(type) {
   126  	case nil:
   127  		return nil, nil, false, nil
   128  	case valueNode:
   129  		return n, n, false, nil
   130  	case *shortNode:
   131  		if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
   132  			// key not found in trie
   133  			return nil, n, false, nil
   134  		}
   135  		value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key))
   136  		if err == nil && didResolve {
   137  			n = n.copy()
   138  			n.Val = newnode
   139  		}
   140  		return value, n, didResolve, err
   141  	case *fullNode:
   142  		value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1)
   143  		if err == nil && didResolve {
   144  			n = n.copy()
   145  			n.Children[key[pos]] = newnode
   146  		}
   147  		return value, n, didResolve, err
   148  	case hashNode:
   149  		child, err := t.resolveHash(n, key[:pos])
   150  		if err != nil {
   151  			return nil, n, true, err
   152  		}
   153  		value, newnode, _, err := t.tryGet(child, key, pos)
   154  		return value, newnode, true, err
   155  	default:
   156  		panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
   157  	}
   158  }
   159  
   160  // TryGetNode attempts to retrieve a trie node by compact-encoded path. It is not
   161  // possible to use keybyte-encoding as the path might contain odd nibbles.
   162  func (t *Trie) TryGetNode(path []byte) ([]byte, int, error) {
   163  	item, newroot, resolved, err := t.tryGetNode(t.root, compactToHex(path), 0)
   164  	if err != nil {
   165  		return nil, resolved, err
   166  	}
   167  	if resolved > 0 {
   168  		t.root = newroot
   169  	}
   170  	if item == nil {
   171  		return nil, resolved, nil
   172  	}
   173  	return item, resolved, err
   174  }
   175  
   176  func (t *Trie) tryGetNode(origNode node, path []byte, pos int) (item []byte, newnode node, resolved int, err error) {
   177  	// If we reached the requested path, return the current node
   178  	if pos >= len(path) {
   179  		// Although we most probably have the original node expanded, encoding
   180  		// that into consensus form can be nasty (needs to cascade down) and
   181  		// time consuming. Instead, just pull the hash up from disk directly.
   182  		var hash hashNode
   183  		if node, ok := origNode.(hashNode); ok {
   184  			hash = node
   185  		} else {
   186  			hash, _ = origNode.cache()
   187  		}
   188  		if hash == nil {
   189  			return nil, origNode, 0, errors.New("non-consensus node")
   190  		}
   191  		blob, err := t.db.Node(common.BytesToHash(hash))
   192  		return blob, origNode, 1, err
   193  	}
   194  	// Path still needs to be traversed, descend into children
   195  	switch n := (origNode).(type) {
   196  	case nil:
   197  		// Non-existent path requested, abort
   198  		return nil, nil, 0, nil
   199  
   200  	case valueNode:
   201  		// Path prematurely ended, abort
   202  		return nil, nil, 0, nil
   203  
   204  	case *shortNode:
   205  		if len(path)-pos < len(n.Key) || !bytes.Equal(n.Key, path[pos:pos+len(n.Key)]) {
   206  			// Path branches off from short node
   207  			return nil, n, 0, nil
   208  		}
   209  		item, newnode, resolved, err = t.tryGetNode(n.Val, path, pos+len(n.Key))
   210  		if err == nil && resolved > 0 {
   211  			n = n.copy()
   212  			n.Val = newnode
   213  		}
   214  		return item, n, resolved, err
   215  
   216  	case *fullNode:
   217  		item, newnode, resolved, err = t.tryGetNode(n.Children[path[pos]], path, pos+1)
   218  		if err == nil && resolved > 0 {
   219  			n = n.copy()
   220  			n.Children[path[pos]] = newnode
   221  		}
   222  		return item, n, resolved, err
   223  
   224  	case hashNode:
   225  		child, err := t.resolveHash(n, path[:pos])
   226  		if err != nil {
   227  			return nil, n, 1, err
   228  		}
   229  		item, newnode, resolved, err := t.tryGetNode(child, path, pos)
   230  		return item, newnode, resolved + 1, err
   231  
   232  	default:
   233  		panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
   234  	}
   235  }
   236  
   237  // Update associates key with value in the trie. Subsequent calls to
   238  // Get will return value. If value has length zero, any existing value
   239  // is deleted from the trie and calls to Get will return nil.
   240  //
   241  // The value bytes must not be modified by the caller while they are
   242  // stored in the trie.
   243  func (t *Trie) Update(key, value []byte) {
   244  	if err := t.TryUpdate(key, value); err != nil {
   245  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   246  	}
   247  }
   248  
   249  // TryUpdate associates key with value in the trie. Subsequent calls to
   250  // Get will return value. If value has length zero, any existing value
   251  // is deleted from the trie and calls to Get will return nil.
   252  //
   253  // The value bytes must not be modified by the caller while they are
   254  // stored in the trie.
   255  //
   256  // If a node was not found in the database, a MissingNodeError is returned.
   257  func (t *Trie) TryUpdate(key, value []byte) error {
   258  	t.unhashed++
   259  	k := keybytesToHex(key)
   260  	if len(value) != 0 {
   261  		_, n, err := t.insert(t.root, nil, k, valueNode(value))
   262  		if err != nil {
   263  			return err
   264  		}
   265  		t.root = n
   266  	} else {
   267  		_, n, err := t.delete(t.root, nil, k)
   268  		if err != nil {
   269  			return err
   270  		}
   271  		t.root = n
   272  	}
   273  	return nil
   274  }
   275  
   276  func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
   277  	if len(key) == 0 {
   278  		if v, ok := n.(valueNode); ok {
   279  			return !bytes.Equal(v, value.(valueNode)), value, nil
   280  		}
   281  		return true, value, nil
   282  	}
   283  	switch n := n.(type) {
   284  	case *shortNode:
   285  		matchlen := prefixLen(key, n.Key)
   286  		// If the whole key matches, keep this short node as is
   287  		// and only update the value.
   288  		if matchlen == len(n.Key) {
   289  			dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
   290  			if !dirty || err != nil {
   291  				return false, n, err
   292  			}
   293  			return true, &shortNode{n.Key, nn, t.newFlag()}, nil
   294  		}
   295  		// Otherwise branch out at the index where they differ.
   296  		branch := &fullNode{flags: t.newFlag()}
   297  		var err error
   298  		_, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
   299  		if err != nil {
   300  			return false, nil, err
   301  		}
   302  		_, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
   303  		if err != nil {
   304  			return false, nil, err
   305  		}
   306  		// Replace this shortNode with the branch if it occurs at index 0.
   307  		if matchlen == 0 {
   308  			return true, branch, nil
   309  		}
   310  		// Otherwise, replace it with a short node leading up to the branch.
   311  		return true, &shortNode{key[:matchlen], branch, t.newFlag()}, nil
   312  
   313  	case *fullNode:
   314  		dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
   315  		if !dirty || err != nil {
   316  			return false, n, err
   317  		}
   318  		n = n.copy()
   319  		n.flags = t.newFlag()
   320  		n.Children[key[0]] = nn
   321  		return true, n, nil
   322  
   323  	case nil:
   324  		return true, &shortNode{key, value, t.newFlag()}, nil
   325  
   326  	case hashNode:
   327  		// We've hit a part of the trie that isn't loaded yet. Load
   328  		// the node and insert into it. This leaves all child nodes on
   329  		// the path to the value in the trie.
   330  		rn, err := t.resolveHash(n, prefix)
   331  		if err != nil {
   332  			return false, nil, err
   333  		}
   334  		dirty, nn, err := t.insert(rn, prefix, key, value)
   335  		if !dirty || err != nil {
   336  			return false, rn, err
   337  		}
   338  		return true, nn, nil
   339  
   340  	default:
   341  		panic(fmt.Sprintf("%T: invalid node: %v", n, n))
   342  	}
   343  }
   344  
   345  // Delete removes any existing value for key from the trie.
   346  func (t *Trie) Delete(key []byte) {
   347  	if err := t.TryDelete(key); err != nil {
   348  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   349  	}
   350  }
   351  
   352  // TryDelete removes any existing value for key from the trie.
   353  // If a node was not found in the database, a MissingNodeError is returned.
   354  func (t *Trie) TryDelete(key []byte) error {
   355  	t.unhashed++
   356  	k := keybytesToHex(key)
   357  	_, n, err := t.delete(t.root, nil, k)
   358  	if err != nil {
   359  		return err
   360  	}
   361  	t.root = n
   362  	return nil
   363  }
   364  
   365  // delete returns the new root of the trie with key deleted.
   366  // It reduces the trie to minimal form by simplifying
   367  // nodes on the way up after deleting recursively.
   368  func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
   369  	switch n := n.(type) {
   370  	case *shortNode:
   371  		matchlen := prefixLen(key, n.Key)
   372  		if matchlen < len(n.Key) {
   373  			return false, n, nil // don't replace n on mismatch
   374  		}
   375  		if matchlen == len(key) {
   376  			return true, nil, nil // remove n entirely for whole matches
   377  		}
   378  		// The key is longer than n.Key. Remove the remaining suffix
   379  		// from the subtrie. Child can never be nil here since the
   380  		// subtrie must contain at least two other values with keys
   381  		// longer than n.Key.
   382  		dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
   383  		if !dirty || err != nil {
   384  			return false, n, err
   385  		}
   386  		switch child := child.(type) {
   387  		case *shortNode:
   388  			// Deleting from the subtrie reduced it to another
   389  			// short node. Merge the nodes to avoid creating a
   390  			// shortNode{..., shortNode{...}}. Use concat (which
   391  			// always creates a new slice) instead of append to
   392  			// avoid modifying n.Key since it might be shared with
   393  			// other nodes.
   394  			return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
   395  		default:
   396  			return true, &shortNode{n.Key, child, t.newFlag()}, nil
   397  		}
   398  
   399  	case *fullNode:
   400  		dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
   401  		if !dirty || err != nil {
   402  			return false, n, err
   403  		}
   404  		n = n.copy()
   405  		n.flags = t.newFlag()
   406  		n.Children[key[0]] = nn
   407  
   408  		// Check how many non-nil entries are left after deleting and
   409  		// reduce the full node to a short node if only one entry is
   410  		// left. Since n must've contained at least two children
   411  		// before deletion (otherwise it would not be a full node) n
   412  		// can never be reduced to nil.
   413  		//
   414  		// When the loop is done, pos contains the index of the single
   415  		// value that is left in n or -2 if n contains at least two
   416  		// values.
   417  		pos := -1
   418  		for i, cld := range &n.Children {
   419  			if cld != nil {
   420  				if pos == -1 {
   421  					pos = i
   422  				} else {
   423  					pos = -2
   424  					break
   425  				}
   426  			}
   427  		}
   428  		if pos >= 0 {
   429  			if pos != 16 {
   430  				// If the remaining entry is a short node, it replaces
   431  				// n and its key gets the missing nibble tacked to the
   432  				// front. This avoids creating an invalid
   433  				// shortNode{..., shortNode{...}}.  Since the entry
   434  				// might not be loaded yet, resolve it just for this
   435  				// check.
   436  				cnode, err := t.resolve(n.Children[pos], prefix)
   437  				if err != nil {
   438  					return false, nil, err
   439  				}
   440  				if cnode, ok := cnode.(*shortNode); ok {
   441  					k := append([]byte{byte(pos)}, cnode.Key...)
   442  					return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
   443  				}
   444  			}
   445  			// Otherwise, n is replaced by a one-nibble short node
   446  			// containing the child.
   447  			return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
   448  		}
   449  		// n still contains at least two values and cannot be reduced.
   450  		return true, n, nil
   451  
   452  	case valueNode:
   453  		return true, nil, nil
   454  
   455  	case nil:
   456  		return false, nil, nil
   457  
   458  	case hashNode:
   459  		// We've hit a part of the trie that isn't loaded yet. Load
   460  		// the node and delete from it. This leaves all child nodes on
   461  		// the path to the value in the trie.
   462  		rn, err := t.resolveHash(n, prefix)
   463  		if err != nil {
   464  			return false, nil, err
   465  		}
   466  		dirty, nn, err := t.delete(rn, prefix, key)
   467  		if !dirty || err != nil {
   468  			return false, rn, err
   469  		}
   470  		return true, nn, nil
   471  
   472  	default:
   473  		panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
   474  	}
   475  }
   476  
   477  func concat(s1 []byte, s2 ...byte) []byte {
   478  	r := make([]byte, len(s1)+len(s2))
   479  	copy(r, s1)
   480  	copy(r[len(s1):], s2)
   481  	return r
   482  }
   483  
   484  func (t *Trie) resolve(n node, prefix []byte) (node, error) {
   485  	if n, ok := n.(hashNode); ok {
   486  		return t.resolveHash(n, prefix)
   487  	}
   488  	return n, nil
   489  }
   490  
   491  func (t *Trie) resolveHash(n hashNode, prefix []byte) (node, error) {
   492  	hash := common.BytesToHash(n)
   493  	if node := t.db.node(hash); node != nil {
   494  		return node, nil
   495  	}
   496  	return nil, &MissingNodeError{NodeHash: hash, Path: prefix}
   497  }
   498  
   499  // Hash returns the root hash of the trie. It does not write to the
   500  // database and can be used even if the trie doesn't have one.
   501  func (t *Trie) Hash() common.Hash {
   502  	hash, cached, _ := t.hashRoot()
   503  	t.root = cached
   504  	return common.BytesToHash(hash.(hashNode))
   505  }
   506  
   507  // Commit writes all nodes to the trie's memory database, tracking the internal
   508  // and external (for account tries) references.
   509  func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   510  	if t.db == nil {
   511  		panic("commit called on trie with nil database")
   512  	}
   513  	if t.root == nil {
   514  		return emptyRoot, nil
   515  	}
   516  	// Derive the hash for all dirty nodes first. We hold the assumption
   517  	// in the following procedure that all nodes are hashed.
   518  	rootHash := t.Hash()
   519  	h := newCommitter()
   520  	defer returnCommitterToPool(h)
   521  
   522  	// Do a quick check if we really need to commit, before we spin
   523  	// up goroutines. This can happen e.g. if we load a trie for reading storage
   524  	// values, but don't write to it.
   525  	if _, dirty := t.root.cache(); !dirty {
   526  		return rootHash, nil
   527  	}
   528  	var wg sync.WaitGroup
   529  	if onleaf != nil {
   530  		h.onleaf = onleaf
   531  		h.leafCh = make(chan *leaf, leafChanSize)
   532  		wg.Add(1)
   533  		go func() {
   534  			defer wg.Done()
   535  			h.commitLoop(t.db)
   536  		}()
   537  	}
   538  	var newRoot hashNode
   539  	newRoot, err = h.Commit(t.root, t.db)
   540  	if onleaf != nil {
   541  		// The leafch is created in newCommitter if there was an onleaf callback
   542  		// provided. The commitLoop only _reads_ from it, and the commit
   543  		// operation was the sole writer. Therefore, it's safe to close this
   544  		// channel here.
   545  		close(h.leafCh)
   546  		wg.Wait()
   547  	}
   548  	if err != nil {
   549  		return common.Hash{}, err
   550  	}
   551  	t.root = newRoot
   552  	return rootHash, nil
   553  }
   554  
   555  // hashRoot calculates the root hash of the given trie
   556  func (t *Trie) hashRoot() (node, node, error) {
   557  	if t.root == nil {
   558  		return hashNode(emptyRoot.Bytes()), nil, nil
   559  	}
   560  	// If the number of changes is below 100, we let one thread handle it
   561  	h := newHasher(t.unhashed >= 100)
   562  	defer returnHasherToPool(h)
   563  	hashed, cached := h.hash(t.root, true)
   564  	t.unhashed = 0
   565  	return hashed, cached, nil
   566  }
   567  
   568  // Reset drops the referenced root node and cleans all internal state.
   569  func (t *Trie) Reset() {
   570  	t.root = nil
   571  	t.unhashed = 0
   572  }
   573  
   574  func (t *Trie) Size() int {
   575  	return estimateSize(t.root)
   576  }