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