github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/trie/trie.go (about)

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