github.com/sonm-io/go-ethereum@v1.8.18/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  	"fmt"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/crypto"
    26  	"github.com/ethereum/go-ethereum/log"
    27  	"github.com/ethereum/go-ethereum/metrics"
    28  )
    29  
    30  var (
    31  	// emptyRoot is the known root hash of an empty trie.
    32  	emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
    33  
    34  	// emptyState is the known hash of an empty state trie entry.
    35  	emptyState = crypto.Keccak256Hash(nil)
    36  )
    37  
    38  var (
    39  	cacheMissCounter   = metrics.NewRegisteredCounter("trie/cachemiss", nil)
    40  	cacheUnloadCounter = metrics.NewRegisteredCounter("trie/cacheunload", nil)
    41  )
    42  
    43  // CacheMisses retrieves a global counter measuring the number of cache misses
    44  // the trie had since process startup. This isn't useful for anything apart from
    45  // trie debugging purposes.
    46  func CacheMisses() int64 {
    47  	return cacheMissCounter.Count()
    48  }
    49  
    50  // CacheUnloads retrieves a global counter measuring the number of cache unloads
    51  // the trie did since process startup. This isn't useful for anything apart from
    52  // trie debugging purposes.
    53  func CacheUnloads() int64 {
    54  	return cacheUnloadCounter.Count()
    55  }
    56  
    57  // LeafCallback is a callback type invoked when a trie operation reaches a leaf
    58  // node. It's used by state sync and commit to allow handling external references
    59  // between account and storage tries.
    60  type LeafCallback func(leaf []byte, parent common.Hash) error
    61  
    62  // Trie is a Merkle Patricia Trie.
    63  // The zero value is an empty trie with no database.
    64  // Use New to create a trie that sits on top of a database.
    65  //
    66  // Trie is not safe for concurrent use.
    67  type Trie struct {
    68  	db   *Database
    69  	root node
    70  
    71  	// Cache generation values.
    72  	// cachegen increases by one with each commit operation.
    73  	// new nodes are tagged with the current generation and unloaded
    74  	// when their generation is older than than cachegen-cachelimit.
    75  	cachegen, cachelimit uint16
    76  }
    77  
    78  // SetCacheLimit sets the number of 'cache generations' to keep.
    79  // A cache generation is created by a call to Commit.
    80  func (t *Trie) SetCacheLimit(l uint16) {
    81  	t.cachelimit = l
    82  }
    83  
    84  // newFlag returns the cache flag value for a newly created node.
    85  func (t *Trie) newFlag() nodeFlag {
    86  	return nodeFlag{dirty: true, gen: t.cachegen}
    87  }
    88  
    89  // New creates a trie with an existing root node from db.
    90  //
    91  // If root is the zero hash or the sha3 hash of an empty string, the
    92  // trie is initially empty and does not require a database. Otherwise,
    93  // New will panic if db is nil and returns a MissingNodeError if root does
    94  // not exist in the database. Accessing the trie loads nodes from db on demand.
    95  func New(root common.Hash, db *Database) (*Trie, error) {
    96  	if db == nil {
    97  		panic("trie.New called without a database")
    98  	}
    99  	trie := &Trie{
   100  		db: db,
   101  	}
   102  	if root != (common.Hash{}) && root != emptyRoot {
   103  		rootnode, err := trie.resolveHash(root[:], nil)
   104  		if err != nil {
   105  			return nil, err
   106  		}
   107  		trie.root = rootnode
   108  	}
   109  	return trie, nil
   110  }
   111  
   112  // NodeIterator returns an iterator that returns nodes of the trie. Iteration starts at
   113  // the key after the given start key.
   114  func (t *Trie) NodeIterator(start []byte) NodeIterator {
   115  	return newNodeIterator(t, start)
   116  }
   117  
   118  // Get returns the value for key stored in the trie.
   119  // The value bytes must not be modified by the caller.
   120  func (t *Trie) Get(key []byte) []byte {
   121  	res, err := t.TryGet(key)
   122  	if err != nil {
   123  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   124  	}
   125  	return res
   126  }
   127  
   128  // TryGet returns the value for key stored in the trie.
   129  // The value bytes must not be modified by the caller.
   130  // If a node was not found in the database, a MissingNodeError is returned.
   131  func (t *Trie) TryGet(key []byte) ([]byte, error) {
   132  	key = keybytesToHex(key)
   133  	value, newroot, didResolve, err := t.tryGet(t.root, key, 0)
   134  	if err == nil && didResolve {
   135  		t.root = newroot
   136  	}
   137  	return value, err
   138  }
   139  
   140  func (t *Trie) tryGet(origNode node, key []byte, pos int) (value []byte, newnode node, didResolve bool, err error) {
   141  	switch n := (origNode).(type) {
   142  	case nil:
   143  		return nil, nil, false, nil
   144  	case valueNode:
   145  		return n, n, false, nil
   146  	case *shortNode:
   147  		if len(key)-pos < len(n.Key) || !bytes.Equal(n.Key, key[pos:pos+len(n.Key)]) {
   148  			// key not found in trie
   149  			return nil, n, false, nil
   150  		}
   151  		value, newnode, didResolve, err = t.tryGet(n.Val, key, pos+len(n.Key))
   152  		if err == nil && didResolve {
   153  			n = n.copy()
   154  			n.Val = newnode
   155  			n.flags.gen = t.cachegen
   156  		}
   157  		return value, n, didResolve, err
   158  	case *fullNode:
   159  		value, newnode, didResolve, err = t.tryGet(n.Children[key[pos]], key, pos+1)
   160  		if err == nil && didResolve {
   161  			n = n.copy()
   162  			n.flags.gen = t.cachegen
   163  			n.Children[key[pos]] = newnode
   164  		}
   165  		return value, n, didResolve, err
   166  	case hashNode:
   167  		child, err := t.resolveHash(n, key[:pos])
   168  		if err != nil {
   169  			return nil, n, true, err
   170  		}
   171  		value, newnode, _, err := t.tryGet(child, key, pos)
   172  		return value, newnode, true, err
   173  	default:
   174  		panic(fmt.Sprintf("%T: invalid node: %v", origNode, origNode))
   175  	}
   176  }
   177  
   178  // Update associates key with value in the trie. Subsequent calls to
   179  // Get will return value. If value has length zero, any existing value
   180  // is deleted from the trie and calls to Get will return nil.
   181  //
   182  // The value bytes must not be modified by the caller while they are
   183  // stored in the trie.
   184  func (t *Trie) Update(key, value []byte) {
   185  	if err := t.TryUpdate(key, value); err != nil {
   186  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   187  	}
   188  }
   189  
   190  // TryUpdate associates key with value in the trie. Subsequent calls to
   191  // Get will return value. If value has length zero, any existing value
   192  // is deleted from the trie and calls to Get will return nil.
   193  //
   194  // The value bytes must not be modified by the caller while they are
   195  // stored in the trie.
   196  //
   197  // If a node was not found in the database, a MissingNodeError is returned.
   198  func (t *Trie) TryUpdate(key, value []byte) error {
   199  	k := keybytesToHex(key)
   200  	if len(value) != 0 {
   201  		_, n, err := t.insert(t.root, nil, k, valueNode(value))
   202  		if err != nil {
   203  			return err
   204  		}
   205  		t.root = n
   206  	} else {
   207  		_, n, err := t.delete(t.root, nil, k)
   208  		if err != nil {
   209  			return err
   210  		}
   211  		t.root = n
   212  	}
   213  	return nil
   214  }
   215  
   216  func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
   217  	if len(key) == 0 {
   218  		if v, ok := n.(valueNode); ok {
   219  			return !bytes.Equal(v, value.(valueNode)), value, nil
   220  		}
   221  		return true, value, nil
   222  	}
   223  	switch n := n.(type) {
   224  	case *shortNode:
   225  		matchlen := prefixLen(key, n.Key)
   226  		// If the whole key matches, keep this short node as is
   227  		// and only update the value.
   228  		if matchlen == len(n.Key) {
   229  			dirty, nn, err := t.insert(n.Val, append(prefix, key[:matchlen]...), key[matchlen:], value)
   230  			if !dirty || err != nil {
   231  				return false, n, err
   232  			}
   233  			return true, &shortNode{n.Key, nn, t.newFlag()}, nil
   234  		}
   235  		// Otherwise branch out at the index where they differ.
   236  		branch := &fullNode{flags: t.newFlag()}
   237  		var err error
   238  		_, branch.Children[n.Key[matchlen]], err = t.insert(nil, append(prefix, n.Key[:matchlen+1]...), n.Key[matchlen+1:], n.Val)
   239  		if err != nil {
   240  			return false, nil, err
   241  		}
   242  		_, branch.Children[key[matchlen]], err = t.insert(nil, append(prefix, key[:matchlen+1]...), key[matchlen+1:], value)
   243  		if err != nil {
   244  			return false, nil, err
   245  		}
   246  		// Replace this shortNode with the branch if it occurs at index 0.
   247  		if matchlen == 0 {
   248  			return true, branch, nil
   249  		}
   250  		// Otherwise, replace it with a short node leading up to the branch.
   251  		return true, &shortNode{key[:matchlen], branch, t.newFlag()}, nil
   252  
   253  	case *fullNode:
   254  		dirty, nn, err := t.insert(n.Children[key[0]], append(prefix, key[0]), key[1:], value)
   255  		if !dirty || err != nil {
   256  			return false, n, err
   257  		}
   258  		n = n.copy()
   259  		n.flags = t.newFlag()
   260  		n.Children[key[0]] = nn
   261  		return true, n, nil
   262  
   263  	case nil:
   264  		return true, &shortNode{key, value, t.newFlag()}, nil
   265  
   266  	case hashNode:
   267  		// We've hit a part of the trie that isn't loaded yet. Load
   268  		// the node and insert into it. This leaves all child nodes on
   269  		// the path to the value in the trie.
   270  		rn, err := t.resolveHash(n, prefix)
   271  		if err != nil {
   272  			return false, nil, err
   273  		}
   274  		dirty, nn, err := t.insert(rn, prefix, key, value)
   275  		if !dirty || err != nil {
   276  			return false, rn, err
   277  		}
   278  		return true, nn, nil
   279  
   280  	default:
   281  		panic(fmt.Sprintf("%T: invalid node: %v", n, n))
   282  	}
   283  }
   284  
   285  // Delete removes any existing value for key from the trie.
   286  func (t *Trie) Delete(key []byte) {
   287  	if err := t.TryDelete(key); err != nil {
   288  		log.Error(fmt.Sprintf("Unhandled trie error: %v", err))
   289  	}
   290  }
   291  
   292  // TryDelete removes any existing value for key from the trie.
   293  // If a node was not found in the database, a MissingNodeError is returned.
   294  func (t *Trie) TryDelete(key []byte) error {
   295  	k := keybytesToHex(key)
   296  	_, n, err := t.delete(t.root, nil, k)
   297  	if err != nil {
   298  		return err
   299  	}
   300  	t.root = n
   301  	return nil
   302  }
   303  
   304  // delete returns the new root of the trie with key deleted.
   305  // It reduces the trie to minimal form by simplifying
   306  // nodes on the way up after deleting recursively.
   307  func (t *Trie) delete(n node, prefix, key []byte) (bool, node, error) {
   308  	switch n := n.(type) {
   309  	case *shortNode:
   310  		matchlen := prefixLen(key, n.Key)
   311  		if matchlen < len(n.Key) {
   312  			return false, n, nil // don't replace n on mismatch
   313  		}
   314  		if matchlen == len(key) {
   315  			return true, nil, nil // remove n entirely for whole matches
   316  		}
   317  		// The key is longer than n.Key. Remove the remaining suffix
   318  		// from the subtrie. Child can never be nil here since the
   319  		// subtrie must contain at least two other values with keys
   320  		// longer than n.Key.
   321  		dirty, child, err := t.delete(n.Val, append(prefix, key[:len(n.Key)]...), key[len(n.Key):])
   322  		if !dirty || err != nil {
   323  			return false, n, err
   324  		}
   325  		switch child := child.(type) {
   326  		case *shortNode:
   327  			// Deleting from the subtrie reduced it to another
   328  			// short node. Merge the nodes to avoid creating a
   329  			// shortNode{..., shortNode{...}}. Use concat (which
   330  			// always creates a new slice) instead of append to
   331  			// avoid modifying n.Key since it might be shared with
   332  			// other nodes.
   333  			return true, &shortNode{concat(n.Key, child.Key...), child.Val, t.newFlag()}, nil
   334  		default:
   335  			return true, &shortNode{n.Key, child, t.newFlag()}, nil
   336  		}
   337  
   338  	case *fullNode:
   339  		dirty, nn, err := t.delete(n.Children[key[0]], append(prefix, key[0]), key[1:])
   340  		if !dirty || err != nil {
   341  			return false, n, err
   342  		}
   343  		n = n.copy()
   344  		n.flags = t.newFlag()
   345  		n.Children[key[0]] = nn
   346  
   347  		// Check how many non-nil entries are left after deleting and
   348  		// reduce the full node to a short node if only one entry is
   349  		// left. Since n must've contained at least two children
   350  		// before deletion (otherwise it would not be a full node) n
   351  		// can never be reduced to nil.
   352  		//
   353  		// When the loop is done, pos contains the index of the single
   354  		// value that is left in n or -2 if n contains at least two
   355  		// values.
   356  		pos := -1
   357  		for i, cld := range &n.Children {
   358  			if cld != nil {
   359  				if pos == -1 {
   360  					pos = i
   361  				} else {
   362  					pos = -2
   363  					break
   364  				}
   365  			}
   366  		}
   367  		if pos >= 0 {
   368  			if pos != 16 {
   369  				// If the remaining entry is a short node, it replaces
   370  				// n and its key gets the missing nibble tacked to the
   371  				// front. This avoids creating an invalid
   372  				// shortNode{..., shortNode{...}}.  Since the entry
   373  				// might not be loaded yet, resolve it just for this
   374  				// check.
   375  				cnode, err := t.resolve(n.Children[pos], prefix)
   376  				if err != nil {
   377  					return false, nil, err
   378  				}
   379  				if cnode, ok := cnode.(*shortNode); ok {
   380  					k := append([]byte{byte(pos)}, cnode.Key...)
   381  					return true, &shortNode{k, cnode.Val, t.newFlag()}, nil
   382  				}
   383  			}
   384  			// Otherwise, n is replaced by a one-nibble short node
   385  			// containing the child.
   386  			return true, &shortNode{[]byte{byte(pos)}, n.Children[pos], t.newFlag()}, nil
   387  		}
   388  		// n still contains at least two values and cannot be reduced.
   389  		return true, n, nil
   390  
   391  	case valueNode:
   392  		return true, nil, nil
   393  
   394  	case nil:
   395  		return false, nil, nil
   396  
   397  	case hashNode:
   398  		// We've hit a part of the trie that isn't loaded yet. Load
   399  		// the node and delete from it. This leaves all child nodes on
   400  		// the path to the value in the trie.
   401  		rn, err := t.resolveHash(n, prefix)
   402  		if err != nil {
   403  			return false, nil, err
   404  		}
   405  		dirty, nn, err := t.delete(rn, prefix, key)
   406  		if !dirty || err != nil {
   407  			return false, rn, err
   408  		}
   409  		return true, nn, nil
   410  
   411  	default:
   412  		panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
   413  	}
   414  }
   415  
   416  func concat(s1 []byte, s2 ...byte) []byte {
   417  	r := make([]byte, len(s1)+len(s2))
   418  	copy(r, s1)
   419  	copy(r[len(s1):], s2)
   420  	return r
   421  }
   422  
   423  func (t *Trie) resolve(n node, prefix []byte) (node, error) {
   424  	if n, ok := n.(hashNode); ok {
   425  		return t.resolveHash(n, prefix)
   426  	}
   427  	return n, nil
   428  }
   429  
   430  func (t *Trie) resolveHash(n hashNode, prefix []byte) (node, error) {
   431  	cacheMissCounter.Inc(1)
   432  
   433  	hash := common.BytesToHash(n)
   434  	if node := t.db.node(hash, t.cachegen); node != nil {
   435  		return node, nil
   436  	}
   437  	return nil, &MissingNodeError{NodeHash: hash, Path: prefix}
   438  }
   439  
   440  // Root returns the root hash of the trie.
   441  // Deprecated: use Hash instead.
   442  func (t *Trie) Root() []byte { return t.Hash().Bytes() }
   443  
   444  // Hash returns the root hash of the trie. It does not write to the
   445  // database and can be used even if the trie doesn't have one.
   446  func (t *Trie) Hash() common.Hash {
   447  	hash, cached, _ := t.hashRoot(nil, nil)
   448  	t.root = cached
   449  	return common.BytesToHash(hash.(hashNode))
   450  }
   451  
   452  // Commit writes all nodes to the trie's memory database, tracking the internal
   453  // and external (for account tries) references.
   454  func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   455  	if t.db == nil {
   456  		panic("commit called on trie with nil database")
   457  	}
   458  	hash, cached, err := t.hashRoot(t.db, onleaf)
   459  	if err != nil {
   460  		return common.Hash{}, err
   461  	}
   462  	t.root = cached
   463  	t.cachegen++
   464  	return common.BytesToHash(hash.(hashNode)), nil
   465  }
   466  
   467  func (t *Trie) hashRoot(db *Database, onleaf LeafCallback) (node, node, error) {
   468  	if t.root == nil {
   469  		return hashNode(emptyRoot.Bytes()), nil, nil
   470  	}
   471  	h := newHasher(t.cachegen, t.cachelimit, onleaf)
   472  	defer returnHasherToPool(h)
   473  	return h.hash(t.root, db, true)
   474  }