github.com/chain5j/chain5j-pkg@v1.0.7/collection/trees/tree/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 tree
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	prque "github.com/chain5j/chain5j-pkg/collection/queues/preque"
    24  	"github.com/chain5j/chain5j-pkg/database/kvstore"
    25  	"github.com/chain5j/chain5j-pkg/types"
    26  )
    27  
    28  // ErrNotRequested is returned by the trie sync when it's requested to process a
    29  // node it did not request.
    30  var ErrNotRequested = errors.New("not requested")
    31  
    32  // ErrAlreadyProcessed is returned by the trie sync when it's requested to process a
    33  // node it already processed previously.
    34  var ErrAlreadyProcessed = errors.New("already processed")
    35  
    36  // request represents a scheduled or already in-flight state retrieval request.
    37  type request struct {
    38  	hash types.Hash // Hash of the node data content to retrieve
    39  	data []byte     // Data content of the node, cached until all subtrees complete
    40  	raw  bool       // Whether this is a raw entry (code) or a trie node
    41  
    42  	parents []*request // Parent state nodes referencing this entry (notify all upon completion)
    43  	depth   int        // Depth level within the trie the node is located to prioritise DFS
    44  	deps    int        // Number of dependencies before allowed to commit this node
    45  
    46  	callback LeafCallback // Callback to invoke if a leaf node it reached on this branch
    47  }
    48  
    49  // SyncResult is a simple list to return missing nodes along with their request
    50  // hashes.
    51  type SyncResult struct {
    52  	Hash types.Hash // Hash of the originally unknown trie node
    53  	Data []byte     // Data content of the retrieved node
    54  }
    55  
    56  // syncMemBatch is an in-memory buffer of successfully downloaded but not yet
    57  // persisted data items.
    58  type syncMemBatch struct {
    59  	batch map[types.Hash][]byte // In-memory membatch of recently completed items
    60  }
    61  
    62  // newSyncMemBatch allocates a new memory-buffer for not-yet persisted trie nodes.
    63  func newSyncMemBatch() *syncMemBatch {
    64  	return &syncMemBatch{
    65  		batch: make(map[types.Hash][]byte),
    66  	}
    67  }
    68  
    69  // Sync is the main state trie synchronisation scheduler, which provides yet
    70  // unknown trie hashes to retrieve, accepts node data associated with said hashes
    71  // and reconstructs the trie step by step until all is done.
    72  type Sync struct {
    73  	database kvstore.KeyValueReader  // Persistent database to check for existing entries
    74  	membatch *syncMemBatch           // Memory buffer to avoid frequent database writes
    75  	requests map[types.Hash]*request // Pending requests pertaining to a key hash
    76  	queue    *prque.Prque            // Priority queue with the pending requests
    77  	bloom    *SyncBloom              // Bloom filter for fast node existence checks
    78  }
    79  
    80  // NewSync creates a new trie data download scheduler.
    81  func NewSync(root types.Hash, database kvstore.KeyValueReader, callback LeafCallback, bloom *SyncBloom) *Sync {
    82  	ts := &Sync{
    83  		database: database,
    84  		membatch: newSyncMemBatch(),
    85  		requests: make(map[types.Hash]*request),
    86  		queue:    prque.New(),
    87  		bloom:    bloom,
    88  	}
    89  	ts.AddSubTrie(root, 0, types.Hash{}, callback)
    90  	return ts
    91  }
    92  
    93  // AddSubTrie registers a new trie to the sync code, rooted at the designated parent.
    94  func (s *Sync) AddSubTrie(root types.Hash, depth int, parent types.Hash, callback LeafCallback) {
    95  	// Short circuit if the trie is empty or already known
    96  	if root == emptyRoot {
    97  		return
    98  	}
    99  	if _, ok := s.membatch.batch[root]; ok {
   100  		return
   101  	}
   102  	if s.bloom.Contains(root[:]) {
   103  		// Bloom filter says this might be a duplicate, double check
   104  		blob, _ := s.database.Get(root[:])
   105  		if local, err := decodeNode(root[:], blob); local != nil && err == nil {
   106  			return
   107  		}
   108  	}
   109  	// Assemble the new sub-trie sync request
   110  	req := &request{
   111  		hash:     root,
   112  		depth:    depth,
   113  		callback: callback,
   114  	}
   115  	// If this sub-trie has a designated parent, link them together
   116  	if parent != (types.Hash{}) {
   117  		ancestor := s.requests[parent]
   118  		if ancestor == nil {
   119  			panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
   120  		}
   121  		ancestor.deps++
   122  		req.parents = append(req.parents, ancestor)
   123  	}
   124  	s.schedule(req)
   125  }
   126  
   127  // AddRawEntry schedules the direct retrieval of a state entry that should not be
   128  // interpreted as a trie node, but rather accepted and stored into the database
   129  // as is. This method's goal is to support misc state metadata retrievals (e.g.
   130  // contract code).
   131  func (s *Sync) AddRawEntry(hash types.Hash, depth int, parent types.Hash) {
   132  	// Short circuit if the entry is empty or already known
   133  	if hash == emptyState {
   134  		return
   135  	}
   136  	if _, ok := s.membatch.batch[hash]; ok {
   137  		return
   138  	}
   139  	if s.bloom.Contains(hash[:]) {
   140  		// Bloom filter says this might be a duplicate, double check
   141  		if ok, _ := s.database.Has(hash[:]); ok {
   142  			return
   143  		}
   144  	}
   145  	// Assemble the new sub-trie sync request
   146  	req := &request{
   147  		hash:  hash,
   148  		raw:   true,
   149  		depth: depth,
   150  	}
   151  	// If this sub-trie has a designated parent, link them together
   152  	if parent != (types.Hash{}) {
   153  		ancestor := s.requests[parent]
   154  		if ancestor == nil {
   155  			panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
   156  		}
   157  		ancestor.deps++
   158  		req.parents = append(req.parents, ancestor)
   159  	}
   160  	s.schedule(req)
   161  }
   162  
   163  // Missing retrieves the known missing nodes from the trie for retrieval.
   164  func (s *Sync) Missing(max int) []types.Hash {
   165  	var requests []types.Hash
   166  	for !s.queue.Empty() && (max == 0 || len(requests) < max) {
   167  		requests = append(requests, s.queue.PopItem().(types.Hash))
   168  	}
   169  	return requests
   170  }
   171  
   172  // Process injects a batch of retrieved trie nodes data, returning if something
   173  // was committed to the database and also the index of an entry if processing of
   174  // it failed.
   175  func (s *Sync) Process(results []SyncResult) (bool, int, error) {
   176  	committed := false
   177  
   178  	for i, item := range results {
   179  		// If the item was not requested, bail out
   180  		request := s.requests[item.Hash]
   181  		if request == nil {
   182  			return committed, i, ErrNotRequested
   183  		}
   184  		if request.data != nil {
   185  			return committed, i, ErrAlreadyProcessed
   186  		}
   187  		// If the item is a raw entry request, commit directly
   188  		if request.raw {
   189  			request.data = item.Data
   190  			s.commit(request)
   191  			committed = true
   192  			continue
   193  		}
   194  		// Decode the node data content and update the request
   195  		node, err := decodeNode(item.Hash[:], item.Data)
   196  		if err != nil {
   197  			return committed, i, err
   198  		}
   199  		request.data = item.Data
   200  
   201  		// Create and schedule a request for all the children nodes
   202  		requests, err := s.children(request, node)
   203  		if err != nil {
   204  			return committed, i, err
   205  		}
   206  		if len(requests) == 0 && request.deps == 0 {
   207  			s.commit(request)
   208  			committed = true
   209  			continue
   210  		}
   211  		request.deps += len(requests)
   212  		for _, child := range requests {
   213  			s.schedule(child)
   214  		}
   215  	}
   216  	return committed, 0, nil
   217  }
   218  
   219  // Commit flushes the data stored in the internal membatch out to persistent
   220  // storage, returning any occurred error.
   221  func (s *Sync) Commit(dbw kvstore.Batch) error {
   222  	// Dump the membatch into a database dbw
   223  	for key, value := range s.membatch.batch {
   224  		if err := dbw.Put(key[:], value); err != nil {
   225  			return err
   226  		}
   227  		s.bloom.Add(key[:])
   228  	}
   229  	// Drop the membatch data and return
   230  	s.membatch = newSyncMemBatch()
   231  	return nil
   232  }
   233  
   234  // Pending returns the number of state entries currently pending for download.
   235  func (s *Sync) Pending() int {
   236  	return len(s.requests)
   237  }
   238  
   239  // schedule inserts a new state retrieval request into the fetch queue. If there
   240  // is already a pending request for this node, the new request will be discarded
   241  // and only a parent reference added to the old one.
   242  func (s *Sync) schedule(req *request) {
   243  	// If we're already requesting this node, add a new reference and stop
   244  	if old, ok := s.requests[req.hash]; ok {
   245  		old.parents = append(old.parents, req.parents...)
   246  		return
   247  	}
   248  	// Schedule the request for future retrieval
   249  	s.queue.Push(req.hash, float32(req.depth))
   250  	s.requests[req.hash] = req
   251  }
   252  
   253  // children retrieves all the missing children of a state trie entry for future
   254  // retrieval scheduling.
   255  func (s *Sync) children(req *request, object node) ([]*request, error) {
   256  	// Gather all the children of the node, irrelevant whether known or not
   257  	type child struct {
   258  		node  node
   259  		depth int
   260  	}
   261  	var children []child
   262  
   263  	switch node := (object).(type) {
   264  	case *shortNode:
   265  		children = []child{{
   266  			node:  node.Val,
   267  			depth: req.depth + len(node.Key),
   268  		}}
   269  	case *fullNode:
   270  		for i := 0; i < 17; i++ {
   271  			if node.Children[i] != nil {
   272  				children = append(children, child{
   273  					node:  node.Children[i],
   274  					depth: req.depth + 1,
   275  				})
   276  			}
   277  		}
   278  	default:
   279  		panic(fmt.Sprintf("unknown node: %+v", node))
   280  	}
   281  	// Iterate over the children, and request all unknown ones
   282  	requests := make([]*request, 0, len(children))
   283  	for _, child := range children {
   284  		// Notify any external watcher of a new key/value node
   285  		if req.callback != nil {
   286  			if node, ok := (child.node).(valueNode); ok {
   287  				if err := req.callback(node, req.hash); err != nil {
   288  					return nil, err
   289  				}
   290  			}
   291  		}
   292  		// If the child references another node, resolve or schedule
   293  		if node, ok := (child.node).(hashNode); ok {
   294  			// Try to resolve the node from the local database
   295  			hash := types.BytesToHash(node)
   296  			if _, ok := s.membatch.batch[hash]; ok {
   297  				continue
   298  			}
   299  			if s.bloom.Contains(node) {
   300  				// Bloom filter says this might be a duplicate, double check
   301  				if ok, _ := s.database.Has(node); ok {
   302  					continue
   303  				}
   304  				// False positive, bump fault meter
   305  			}
   306  			// Locally unknown node, schedule for retrieval
   307  			requests = append(requests, &request{
   308  				hash:     hash,
   309  				parents:  []*request{req},
   310  				depth:    child.depth,
   311  				callback: req.callback,
   312  			})
   313  		}
   314  	}
   315  	return requests, nil
   316  }
   317  
   318  // commit finalizes a retrieval request and stores it into the membatch. If any
   319  // of the referencing parent requests complete due to this commit, they are also
   320  // committed themselves.
   321  func (s *Sync) commit(req *request) (err error) {
   322  	// Write the node content to the membatch
   323  	s.membatch.batch[req.hash] = req.data
   324  
   325  	delete(s.requests, req.hash)
   326  
   327  	// Check all parents for completion
   328  	for _, parent := range req.parents {
   329  		parent.deps--
   330  		if parent.deps == 0 {
   331  			if err := s.commit(parent); err != nil {
   332  				return err
   333  			}
   334  		}
   335  	}
   336  	return nil
   337  }