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