github.com/core-coin/go-core/v2@v2.1.9/trie/sync.go (about)

     1  // Copyright 2015 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package trie
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/core-coin/go-core/v2/xcbdb"
    24  
    25  	"github.com/core-coin/go-core/v2/common"
    26  	"github.com/core-coin/go-core/v2/common/prque"
    27  	"github.com/core-coin/go-core/v2/core/rawdb"
    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 xcbdb.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 xcbdb.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 == emptyState {
   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 xcb/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 xcbdb.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  		s.bloom.Add(key[:])
   318  	}
   319  	for key, value := range s.membatch.codes {
   320  		rawdb.WriteCode(dbw, key, value)
   321  		s.bloom.Add(key[:])
   322  	}
   323  	// Drop the membatch data and return
   324  	s.membatch = newSyncMemBatch()
   325  	return nil
   326  }
   327  
   328  // Pending returns the number of state entries currently pending for download.
   329  func (s *Sync) Pending() int {
   330  	return len(s.nodeReqs) + len(s.codeReqs)
   331  }
   332  
   333  // schedule inserts a new state retrieval request into the fetch queue. If there
   334  // is already a pending request for this node, the new request will be discarded
   335  // and only a parent reference added to the old one.
   336  func (s *Sync) schedule(req *request) {
   337  	var reqset = s.nodeReqs
   338  	if req.code {
   339  		reqset = s.codeReqs
   340  	}
   341  	// If we're already requesting this node, add a new reference and stop
   342  	if old, ok := reqset[req.hash]; ok {
   343  		old.parents = append(old.parents, req.parents...)
   344  		return
   345  	}
   346  	reqset[req.hash] = req
   347  
   348  	// Schedule the request for future retrieval. This queue is shared
   349  	// by both node requests and code requests. It can happen that there
   350  	// is a trie node and code has same hash. In this case two elements
   351  	// with same hash and same or different depth will be pushed. But it's
   352  	// ok the worst case is the second response will be treated as duplicated.
   353  	prio := int64(len(req.path)) << 56 // depth >= 128 will never happen, storage leaves will be included in their parents
   354  	for i := 0; i < 14 && i < len(req.path); i++ {
   355  		prio |= int64(15-req.path[i]) << (52 - i*4) // 15-nibble => lexicographic order
   356  	}
   357  	s.queue.Push(req.hash, prio)
   358  }
   359  
   360  // children retrieves all the missing children of a state trie entry for future
   361  // retrieval scheduling.
   362  func (s *Sync) children(req *request, object node) ([]*request, error) {
   363  	// Gather all the children of the node, irrelevant whether known or not
   364  	type child struct {
   365  		path []byte
   366  		node node
   367  	}
   368  	var children []child
   369  
   370  	switch node := (object).(type) {
   371  	case *shortNode:
   372  		key := node.Key
   373  		if hasTerm(key) {
   374  			key = key[:len(key)-1]
   375  		}
   376  		children = []child{{
   377  			node: node.Val,
   378  			path: append(append([]byte(nil), req.path...), key...),
   379  		}}
   380  	case *fullNode:
   381  		for i := 0; i < 17; i++ {
   382  			if node.Children[i] != nil {
   383  				children = append(children, child{
   384  					node: node.Children[i],
   385  					path: append(append([]byte(nil), req.path...), byte(i)),
   386  				})
   387  			}
   388  		}
   389  	default:
   390  		panic(fmt.Sprintf("unknown node: %+v", node))
   391  	}
   392  	// Iterate over the children, and request all unknown ones
   393  	requests := make([]*request, 0, len(children))
   394  	for _, child := range children {
   395  		// Notify any external watcher of a new key/value node
   396  		if req.callback != nil {
   397  			if node, ok := (child.node).(valueNode); ok {
   398  				if err := req.callback(child.path, node, req.hash); err != nil {
   399  					return nil, err
   400  				}
   401  			}
   402  		}
   403  		// If the child references another node, resolve or schedule
   404  		if node, ok := (child.node).(hashNode); ok {
   405  			// Try to resolve the node from the local database
   406  			hash := common.BytesToHash(node)
   407  			if s.membatch.hasNode(hash) {
   408  				continue
   409  			}
   410  			if s.bloom == nil || s.bloom.Contains(node) {
   411  				// Bloom filter says this might be a duplicate, double check.
   412  				// If database says yes, then at least the trie node is present
   413  				// and we hold the assumption that it's NOT legacy contract code.
   414  				if blob := rawdb.ReadTrieNode(s.database, common.BytesToHash(node)); len(blob) > 0 {
   415  					continue
   416  				}
   417  				// False positive, bump fault meter
   418  				bloomFaultMeter.Mark(1)
   419  			}
   420  			// Locally unknown node, schedule for retrieval
   421  			requests = append(requests, &request{
   422  				path:     child.path,
   423  				hash:     hash,
   424  				parents:  []*request{req},
   425  				callback: req.callback,
   426  			})
   427  		}
   428  	}
   429  	return requests, nil
   430  }
   431  
   432  // commit finalizes a retrieval request and stores it into the membatch. If any
   433  // of the referencing parent requests complete due to this commit, they are also
   434  // committed themselves.
   435  func (s *Sync) commit(req *request) (err error) {
   436  	// Write the node content to the membatch
   437  	if req.code {
   438  		s.membatch.codes[req.hash] = req.data
   439  		delete(s.codeReqs, req.hash)
   440  		s.fetches[len(req.path)]--
   441  	} else {
   442  		s.membatch.nodes[req.hash] = req.data
   443  		delete(s.nodeReqs, req.hash)
   444  		s.fetches[len(req.path)]--
   445  	}
   446  	// Check all parents for completion
   447  	for _, parent := range req.parents {
   448  		parent.deps--
   449  		if parent.deps == 0 {
   450  			if err := s.commit(parent); err != nil {
   451  				return err
   452  			}
   453  		}
   454  	}
   455  	return nil
   456  }