github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/trie/sync.go (about)

     1  // Copyright 2015 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
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/common/prque"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/ethdb"
    27  )
    28  
    29  // ErrNotRequested is returned by the trie sync when it's requested to process a
    30  // node it did not request.
    31  var ErrNotRequested = errors.New("not requested")
    32  
    33  // ErrAlreadyProcessed is returned by the trie sync when it's requested to process a
    34  // node it already processed previously.
    35  var ErrAlreadyProcessed = errors.New("already processed")
    36  
    37  // maxFetchesPerDepth is the maximum number of pending trie nodes per depth. The
    38  // role of this value is to limit the number of trie nodes that get expanded in
    39  // memory if the node was configured with a significant number of peers.
    40  const maxFetchesPerDepth = 16384
    41  
    42  // request represents a scheduled or already in-flight state retrieval request.
    43  type request struct {
    44  	path []byte      // Merkle path leading to this node for prioritization
    45  	hash common.Hash // Hash of the node data content to retrieve
    46  	data []byte      // Data content of the node, cached until all subtrees complete
    47  	code bool        // Whether this is a code entry
    48  
    49  	parents []*request // Parent state nodes referencing this entry (notify all upon completion)
    50  	deps    int        // Number of dependencies before allowed to commit this node
    51  
    52  	callback LeafCallback // Callback to invoke if a leaf node it reached on this branch
    53  }
    54  
    55  // SyncPath is a path tuple identifying a particular trie node either in a single
    56  // trie (account) or a layered trie (account -> storage).
    57  //
    58  // Content wise the tuple either has 1 element if it addresses a node in a single
    59  // trie or 2 elements if it addresses a node in a stacked trie.
    60  //
    61  // To support aiming arbitrary trie nodes, the path needs to support odd nibble
    62  // lengths. To avoid transferring expanded hex form over the network, the last
    63  // part of the tuple (which needs to index into the middle of a trie) is compact
    64  // encoded. In case of a 2-tuple, the first item is always 32 bytes so that is
    65  // simple binary encoded.
    66  //
    67  // Examples:
    68  //   - Path 0x9  -> {0x19}
    69  //   - Path 0x99 -> {0x0099}
    70  //   - Path 0x01234567890123456789012345678901012345678901234567890123456789019  -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x19}
    71  //   - Path 0x012345678901234567890123456789010123456789012345678901234567890199 -> {0x0123456789012345678901234567890101234567890123456789012345678901, 0x0099}
    72  type SyncPath [][]byte
    73  
    74  // newSyncPath converts an expanded trie path from nibble form into a compact
    75  // version that can be sent over the network.
    76  func newSyncPath(path []byte) SyncPath {
    77  	// If the hash is from the account trie, append a single item, if it
    78  	// is from the a storage trie, append a tuple. Note, the length 64 is
    79  	// clashing between account leaf and storage root. It's fine though
    80  	// because having a trie node at 64 depth means a hash collision was
    81  	// found and we're long dead.
    82  	if len(path) < 64 {
    83  		return SyncPath{hexToCompact(path)}
    84  	}
    85  	return SyncPath{hexToKeybytes(path[:64]), hexToCompact(path[64:])}
    86  }
    87  
    88  // SyncResult is a response with requested data along with it's hash.
    89  type SyncResult struct {
    90  	Hash common.Hash // Hash of the originally unknown trie node
    91  	Data []byte      // Data content of the retrieved node
    92  }
    93  
    94  // syncMemBatch is an in-memory buffer of successfully downloaded but not yet
    95  // persisted data items.
    96  type syncMemBatch struct {
    97  	nodes map[common.Hash][]byte // In-memory membatch of recently completed nodes
    98  	codes map[common.Hash][]byte // In-memory membatch of recently completed codes
    99  }
   100  
   101  // newSyncMemBatch allocates a new memory-buffer for not-yet persisted trie nodes.
   102  func newSyncMemBatch() *syncMemBatch {
   103  	return &syncMemBatch{
   104  		nodes: make(map[common.Hash][]byte),
   105  		codes: make(map[common.Hash][]byte),
   106  	}
   107  }
   108  
   109  // hasNode reports the trie node with specific hash is already cached.
   110  func (batch *syncMemBatch) hasNode(hash common.Hash) bool {
   111  	_, ok := batch.nodes[hash]
   112  	return ok
   113  }
   114  
   115  // hasCode reports the contract code with specific hash is already cached.
   116  func (batch *syncMemBatch) hasCode(hash common.Hash) bool {
   117  	_, ok := batch.codes[hash]
   118  	return ok
   119  }
   120  
   121  // Sync is the main state trie synchronisation scheduler, which provides yet
   122  // unknown trie hashes to retrieve, accepts node data associated with said hashes
   123  // and reconstructs the trie step by step until all is done.
   124  type Sync struct {
   125  	database ethdb.KeyValueReader     // Persistent database to check for existing entries
   126  	membatch *syncMemBatch            // Memory buffer to avoid frequent database writes
   127  	nodeReqs map[common.Hash]*request // Pending requests pertaining to a trie node hash
   128  	codeReqs map[common.Hash]*request // Pending requests pertaining to a code hash
   129  	queue    *prque.Prque             // Priority queue with the pending requests
   130  	fetches  map[int]int              // Number of active fetches per trie node depth
   131  }
   132  
   133  // NewSync creates a new trie data download scheduler.
   134  func NewSync(root common.Hash, database ethdb.KeyValueReader, callback LeafCallback) *Sync {
   135  	ts := &Sync{
   136  		database: database,
   137  		membatch: newSyncMemBatch(),
   138  		nodeReqs: make(map[common.Hash]*request),
   139  		codeReqs: make(map[common.Hash]*request),
   140  		queue:    prque.New(nil),
   141  		fetches:  make(map[int]int),
   142  	}
   143  	ts.AddSubTrie(root, nil, common.Hash{}, callback)
   144  	return ts
   145  }
   146  
   147  // AddSubTrie registers a new trie to the sync code, rooted at the designated parent.
   148  func (s *Sync) AddSubTrie(root common.Hash, path []byte, parent common.Hash, callback LeafCallback) {
   149  	// Short circuit if the trie is empty or already known
   150  	if root == emptyRoot {
   151  		return
   152  	}
   153  	if s.membatch.hasNode(root) {
   154  		return
   155  	}
   156  	// If database says this is a duplicate, then at least the trie node is
   157  	// present, and we hold the assumption that it's NOT legacy contract code.
   158  	if rawdb.HasTrieNode(s.database, root) {
   159  		return
   160  	}
   161  	// Assemble the new sub-trie sync request
   162  	req := &request{
   163  		path:     path,
   164  		hash:     root,
   165  		callback: callback,
   166  	}
   167  	// If this sub-trie has a designated parent, link them together
   168  	if parent != (common.Hash{}) {
   169  		ancestor := s.nodeReqs[parent]
   170  		if ancestor == nil {
   171  			panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
   172  		}
   173  		ancestor.deps++
   174  		req.parents = append(req.parents, ancestor)
   175  	}
   176  	s.schedule(req)
   177  }
   178  
   179  // AddCodeEntry schedules the direct retrieval of a contract code that should not
   180  // be interpreted as a trie node, but rather accepted and stored into the database
   181  // as is.
   182  func (s *Sync) AddCodeEntry(hash common.Hash, path []byte, parent common.Hash) {
   183  	// Short circuit if the entry is empty or already known
   184  	if hash == emptyState {
   185  		return
   186  	}
   187  	if s.membatch.hasCode(hash) {
   188  		return
   189  	}
   190  	// If database says duplicate, the blob is present for sure.
   191  	// Note we only check the existence with new code scheme, fast
   192  	// sync is expected to run with a fresh new node. Even there
   193  	// exists the code with legacy format, fetch and store with
   194  	// new scheme anyway.
   195  	if rawdb.HasCodeWithPrefix(s.database, hash) {
   196  		return
   197  	}
   198  	// Assemble the new sub-trie sync request
   199  	req := &request{
   200  		path: path,
   201  		hash: hash,
   202  		code: true,
   203  	}
   204  	// If this sub-trie has a designated parent, link them together
   205  	if parent != (common.Hash{}) {
   206  		ancestor := s.nodeReqs[parent] // the parent of codereq can ONLY be nodereq
   207  		if ancestor == nil {
   208  			panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
   209  		}
   210  		ancestor.deps++
   211  		req.parents = append(req.parents, ancestor)
   212  	}
   213  	s.schedule(req)
   214  }
   215  
   216  // Missing retrieves the known missing nodes from the trie for retrieval. To aid
   217  // both eth/6x style fast sync and snap/1x style state sync, the paths of trie
   218  // nodes are returned too, as well as separate hash list for codes.
   219  func (s *Sync) Missing(max int) (nodes []common.Hash, paths []SyncPath, codes []common.Hash) {
   220  	var (
   221  		nodeHashes []common.Hash
   222  		nodePaths  []SyncPath
   223  		codeHashes []common.Hash
   224  	)
   225  	for !s.queue.Empty() && (max == 0 || len(nodeHashes)+len(codeHashes) < max) {
   226  		// Retrieve the next item in line
   227  		item, prio := s.queue.Peek()
   228  
   229  		// If we have too many already-pending tasks for this depth, throttle
   230  		depth := int(prio >> 56)
   231  		if s.fetches[depth] > maxFetchesPerDepth {
   232  			break
   233  		}
   234  		// Item is allowed to be scheduled, add it to the task list
   235  		s.queue.Pop()
   236  		s.fetches[depth]++
   237  
   238  		hash := item.(common.Hash)
   239  		if req, ok := s.nodeReqs[hash]; ok {
   240  			nodeHashes = append(nodeHashes, hash)
   241  			nodePaths = append(nodePaths, newSyncPath(req.path))
   242  		} else {
   243  			codeHashes = append(codeHashes, hash)
   244  		}
   245  	}
   246  	return nodeHashes, nodePaths, codeHashes
   247  }
   248  
   249  // Process injects the received data for requested item. Note it can
   250  // happpen that the single response commits two pending requests(e.g.
   251  // there are two requests one for code and one for node but the hash
   252  // is same). In this case the second response for the same hash will
   253  // be treated as "non-requested" item or "already-processed" item but
   254  // there is no downside.
   255  func (s *Sync) Process(result SyncResult) error {
   256  	// If the item was not requested either for code or node, bail out
   257  	if s.nodeReqs[result.Hash] == nil && s.codeReqs[result.Hash] == nil {
   258  		return ErrNotRequested
   259  	}
   260  	// There is an pending code request for this data, commit directly
   261  	var filled bool
   262  	if req := s.codeReqs[result.Hash]; req != nil && req.data == nil {
   263  		filled = true
   264  		req.data = result.Data
   265  		s.commit(req)
   266  	}
   267  	// There is an pending node request for this data, fill it.
   268  	if req := s.nodeReqs[result.Hash]; req != nil && req.data == nil {
   269  		filled = true
   270  		// Decode the node data content and update the request
   271  		node, err := decodeNode(result.Hash[:], result.Data)
   272  		if err != nil {
   273  			return err
   274  		}
   275  		req.data = result.Data
   276  
   277  		// Create and schedule a request for all the children nodes
   278  		requests, err := s.children(req, node)
   279  		if err != nil {
   280  			return err
   281  		}
   282  		if len(requests) == 0 && req.deps == 0 {
   283  			s.commit(req)
   284  		} else {
   285  			req.deps += len(requests)
   286  			for _, child := range requests {
   287  				s.schedule(child)
   288  			}
   289  		}
   290  	}
   291  	if !filled {
   292  		return ErrAlreadyProcessed
   293  	}
   294  	return nil
   295  }
   296  
   297  // Commit flushes the data stored in the internal membatch out to persistent
   298  // storage, returning any occurred error.
   299  func (s *Sync) Commit(dbw ethdb.Batch) error {
   300  	// Dump the membatch into a database dbw
   301  	for key, value := range s.membatch.nodes {
   302  		rawdb.WriteTrieNode(dbw, key, value)
   303  	}
   304  	for key, value := range s.membatch.codes {
   305  		rawdb.WriteCode(dbw, key, value)
   306  	}
   307  	// Drop the membatch data and return
   308  	s.membatch = newSyncMemBatch()
   309  	return nil
   310  }
   311  
   312  // Pending returns the number of state entries currently pending for download.
   313  func (s *Sync) Pending() int {
   314  	return len(s.nodeReqs) + len(s.codeReqs)
   315  }
   316  
   317  // schedule inserts a new state retrieval request into the fetch queue. If there
   318  // is already a pending request for this node, the new request will be discarded
   319  // and only a parent reference added to the old one.
   320  func (s *Sync) schedule(req *request) {
   321  	var reqset = s.nodeReqs
   322  	if req.code {
   323  		reqset = s.codeReqs
   324  	}
   325  	// If we're already requesting this node, add a new reference and stop
   326  	if old, ok := reqset[req.hash]; ok {
   327  		old.parents = append(old.parents, req.parents...)
   328  		return
   329  	}
   330  	reqset[req.hash] = req
   331  
   332  	// Schedule the request for future retrieval. This queue is shared
   333  	// by both node requests and code requests. It can happen that there
   334  	// is a trie node and code has same hash. In this case two elements
   335  	// with same hash and same or different depth will be pushed. But it's
   336  	// ok the worst case is the second response will be treated as duplicated.
   337  	prio := int64(len(req.path)) << 56 // depth >= 128 will never happen, storage leaves will be included in their parents
   338  	for i := 0; i < 14 && i < len(req.path); i++ {
   339  		prio |= int64(15-req.path[i]) << (52 - i*4) // 15-nibble => lexicographic order
   340  	}
   341  	s.queue.Push(req.hash, prio)
   342  }
   343  
   344  // children retrieves all the missing children of a state trie entry for future
   345  // retrieval scheduling.
   346  func (s *Sync) children(req *request, object node) ([]*request, error) {
   347  	// Gather all the children of the node, irrelevant whether known or not
   348  	type child struct {
   349  		path []byte
   350  		node node
   351  	}
   352  	var children []child
   353  
   354  	switch node := (object).(type) {
   355  	case *shortNode:
   356  		key := node.Key
   357  		if hasTerm(key) {
   358  			key = key[:len(key)-1]
   359  		}
   360  		children = []child{{
   361  			node: node.Val,
   362  			path: append(append([]byte(nil), req.path...), key...),
   363  		}}
   364  	case *fullNode:
   365  		for i := 0; i < 17; i++ {
   366  			if node.Children[i] != nil {
   367  				children = append(children, child{
   368  					node: node.Children[i],
   369  					path: append(append([]byte(nil), req.path...), byte(i)),
   370  				})
   371  			}
   372  		}
   373  	default:
   374  		panic(fmt.Sprintf("unknown node: %+v", node))
   375  	}
   376  	// Iterate over the children, and request all unknown ones
   377  	requests := make([]*request, 0, len(children))
   378  	for _, child := range children {
   379  		// Notify any external watcher of a new key/value node
   380  		if req.callback != nil {
   381  			if node, ok := (child.node).(valueNode); ok {
   382  				var paths [][]byte
   383  				if len(child.path) == 2*common.HashLength {
   384  					paths = append(paths, hexToKeybytes(child.path))
   385  				} else if len(child.path) == 4*common.HashLength {
   386  					paths = append(paths, hexToKeybytes(child.path[:2*common.HashLength]))
   387  					paths = append(paths, hexToKeybytes(child.path[2*common.HashLength:]))
   388  				}
   389  				if err := req.callback(paths, child.path, node, req.hash); err != nil {
   390  					return nil, err
   391  				}
   392  			}
   393  		}
   394  		// If the child references another node, resolve or schedule
   395  		if node, ok := (child.node).(hashNode); ok {
   396  			// Try to resolve the node from the local database
   397  			hash := common.BytesToHash(node)
   398  			if s.membatch.hasNode(hash) {
   399  				continue
   400  			}
   401  			// If database says duplicate, then at least the trie node is present
   402  			// and we hold the assumption that it's NOT legacy contract code.
   403  			if rawdb.HasTrieNode(s.database, hash) {
   404  				continue
   405  			}
   406  			// Locally unknown node, schedule for retrieval
   407  			requests = append(requests, &request{
   408  				path:     child.path,
   409  				hash:     hash,
   410  				parents:  []*request{req},
   411  				callback: req.callback,
   412  			})
   413  		}
   414  	}
   415  	return requests, nil
   416  }
   417  
   418  // commit finalizes a retrieval request and stores it into the membatch. If any
   419  // of the referencing parent requests complete due to this commit, they are also
   420  // committed themselves.
   421  func (s *Sync) commit(req *request) (err error) {
   422  	// Write the node content to the membatch
   423  	if req.code {
   424  		s.membatch.codes[req.hash] = req.data
   425  		delete(s.codeReqs, req.hash)
   426  		s.fetches[len(req.path)]--
   427  	} else {
   428  		s.membatch.nodes[req.hash] = req.data
   429  		delete(s.nodeReqs, req.hash)
   430  		s.fetches[len(req.path)]--
   431  	}
   432  	// Check all parents for completion
   433  	for _, parent := range req.parents {
   434  		parent.deps--
   435  		if parent.deps == 0 {
   436  			if err := s.commit(parent); err != nil {
   437  				return err
   438  			}
   439  		}
   440  	}
   441  	return nil
   442  }