github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/core/state/sync_test.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 state
    18  
    19  import (
    20  	"bytes"
    21  	"math/big"
    22  	"testing"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core/rawdb"
    26  	"github.com/ethereum/go-ethereum/core/types"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/ethdb"
    29  	"github.com/ethereum/go-ethereum/rlp"
    30  	"github.com/ethereum/go-ethereum/trie"
    31  )
    32  
    33  // testAccount is the data associated with an account used by the state tests.
    34  type testAccount struct {
    35  	address common.Address
    36  	balance *big.Int
    37  	nonce   uint64
    38  	code    []byte
    39  }
    40  
    41  // makeTestState create a sample test state to test node-wise reconstruction.
    42  func makeTestState() (Database, common.Hash, []*testAccount) {
    43  	// Create an empty state
    44  	db := NewDatabase(rawdb.NewMemoryDatabase())
    45  	state, _ := New(common.Hash{}, db, nil)
    46  
    47  	// Fill it with some arbitrary data
    48  	var accounts []*testAccount
    49  	for i := byte(0); i < 96; i++ {
    50  		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
    51  		acc := &testAccount{address: common.BytesToAddress([]byte{i})}
    52  
    53  		obj.AddBalance(big.NewInt(int64(11 * i)))
    54  		acc.balance = big.NewInt(int64(11 * i))
    55  
    56  		obj.SetNonce(uint64(42 * i))
    57  		acc.nonce = uint64(42 * i)
    58  
    59  		if i%3 == 0 {
    60  			obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
    61  			acc.code = []byte{i, i, i, i, i}
    62  		}
    63  		if i%5 == 0 {
    64  			for j := byte(0); j < 5; j++ {
    65  				hash := crypto.Keccak256Hash([]byte{i, i, i, i, i, j, j})
    66  				obj.SetState(db, hash, hash)
    67  			}
    68  		}
    69  		state.updateStateObject(obj)
    70  		accounts = append(accounts, acc)
    71  	}
    72  	root, _ := state.Commit(false)
    73  
    74  	// Return the generated state
    75  	return db, root, accounts
    76  }
    77  
    78  // checkStateAccounts cross references a reconstructed state with an expected
    79  // account array.
    80  func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
    81  	// Check root availability and state contents
    82  	state, err := New(root, NewDatabase(db), nil)
    83  	if err != nil {
    84  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    85  	}
    86  	if err := checkStateConsistency(db, root); err != nil {
    87  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    88  	}
    89  	for i, acc := range accounts {
    90  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    91  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    92  		}
    93  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    94  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    95  		}
    96  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    97  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
    98  		}
    99  	}
   100  }
   101  
   102  // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
   103  func checkTrieConsistency(db ethdb.KeyValueStore, root common.Hash) error {
   104  	if v, _ := db.Get(root[:]); v == nil {
   105  		return nil // Consider a non existent state consistent.
   106  	}
   107  	trie, err := trie.New(trie.StateTrieID(root), trie.NewDatabase(db))
   108  	if err != nil {
   109  		return err
   110  	}
   111  	it := trie.NodeIterator(nil)
   112  	for it.Next(true) {
   113  	}
   114  	return it.Error()
   115  }
   116  
   117  // checkStateConsistency checks that all data of a state root is present.
   118  func checkStateConsistency(db ethdb.Database, root common.Hash) error {
   119  	// Create and iterate a state trie rooted in a sub-node
   120  	if _, err := db.Get(root.Bytes()); err != nil {
   121  		return nil // Consider a non existent state consistent.
   122  	}
   123  	state, err := New(root, NewDatabase(db), nil)
   124  	if err != nil {
   125  		return err
   126  	}
   127  	it := NewNodeIterator(state)
   128  	for it.Next() {
   129  	}
   130  	return it.Error
   131  }
   132  
   133  // Tests that an empty state is not scheduled for syncing.
   134  func TestEmptyStateSync(t *testing.T) {
   135  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   136  	sync := NewStateSync(empty, rawdb.NewMemoryDatabase(), nil)
   137  	if paths, nodes, codes := sync.Missing(1); len(paths) != 0 || len(nodes) != 0 || len(codes) != 0 {
   138  		t.Errorf("content requested for empty state: %v, %v, %v", nodes, paths, codes)
   139  	}
   140  }
   141  
   142  // Tests that given a root hash, a state can sync iteratively on a single thread,
   143  // requesting retrieval tasks and returning all of them in one go.
   144  func TestIterativeStateSyncIndividual(t *testing.T) {
   145  	testIterativeStateSync(t, 1, false, false)
   146  }
   147  func TestIterativeStateSyncBatched(t *testing.T) {
   148  	testIterativeStateSync(t, 100, false, false)
   149  }
   150  func TestIterativeStateSyncIndividualFromDisk(t *testing.T) {
   151  	testIterativeStateSync(t, 1, true, false)
   152  }
   153  func TestIterativeStateSyncBatchedFromDisk(t *testing.T) {
   154  	testIterativeStateSync(t, 100, true, false)
   155  }
   156  func TestIterativeStateSyncIndividualByPath(t *testing.T) {
   157  	testIterativeStateSync(t, 1, false, true)
   158  }
   159  func TestIterativeStateSyncBatchedByPath(t *testing.T) {
   160  	testIterativeStateSync(t, 100, false, true)
   161  }
   162  
   163  // stateElement represents the element in the state trie(bytecode or trie node).
   164  type stateElement struct {
   165  	path     string
   166  	hash     common.Hash
   167  	code     common.Hash
   168  	syncPath trie.SyncPath
   169  }
   170  
   171  func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
   172  	// Create a random state to copy
   173  	srcDb, srcRoot, srcAccounts := makeTestState()
   174  	if commit {
   175  		srcDb.TrieDB().Commit(srcRoot, false, nil)
   176  	}
   177  	srcTrie, _ := trie.New(trie.StateTrieID(srcRoot), srcDb.TrieDB())
   178  
   179  	// Create a destination state and sync with the scheduler
   180  	dstDb := rawdb.NewMemoryDatabase()
   181  	sched := NewStateSync(srcRoot, dstDb, nil)
   182  
   183  	var (
   184  		nodeElements []stateElement
   185  		codeElements []stateElement
   186  	)
   187  	paths, nodes, codes := sched.Missing(count)
   188  	for i := 0; i < len(paths); i++ {
   189  		nodeElements = append(nodeElements, stateElement{
   190  			path:     paths[i],
   191  			hash:     nodes[i],
   192  			syncPath: trie.NewSyncPath([]byte(paths[i])),
   193  		})
   194  	}
   195  	for i := 0; i < len(codes); i++ {
   196  		codeElements = append(codeElements, stateElement{
   197  			code: codes[i],
   198  		})
   199  	}
   200  	for len(nodeElements)+len(codeElements) > 0 {
   201  		var (
   202  			nodeResults = make([]trie.NodeSyncResult, len(nodeElements))
   203  			codeResults = make([]trie.CodeSyncResult, len(codeElements))
   204  		)
   205  		for i, element := range codeElements {
   206  			data, err := srcDb.ContractCode(common.Hash{}, element.code)
   207  			if err != nil {
   208  				t.Fatalf("failed to retrieve contract bytecode for hash %x", element.code)
   209  			}
   210  			codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
   211  		}
   212  		for i, node := range nodeElements {
   213  			if bypath {
   214  				if len(node.syncPath) == 1 {
   215  					data, _, err := srcTrie.TryGetNode(node.syncPath[0])
   216  					if err != nil {
   217  						t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[0], err)
   218  					}
   219  					nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
   220  				} else {
   221  					var acc types.StateAccount
   222  					if err := rlp.DecodeBytes(srcTrie.Get(node.syncPath[0]), &acc); err != nil {
   223  						t.Fatalf("failed to decode account on path %x: %v", node.syncPath[0], err)
   224  					}
   225  					id := trie.StorageTrieID(srcRoot, common.BytesToHash(node.syncPath[0]), acc.Root)
   226  					stTrie, err := trie.New(id, srcDb.TrieDB())
   227  					if err != nil {
   228  						t.Fatalf("failed to retriev storage trie for path %x: %v", node.syncPath[1], err)
   229  					}
   230  					data, _, err := stTrie.TryGetNode(node.syncPath[1])
   231  					if err != nil {
   232  						t.Fatalf("failed to retrieve node data for path %x: %v", node.syncPath[1], err)
   233  					}
   234  					nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
   235  				}
   236  			} else {
   237  				data, err := srcDb.TrieDB().Node(node.hash)
   238  				if err != nil {
   239  					t.Fatalf("failed to retrieve node data for key %v", []byte(node.path))
   240  				}
   241  				nodeResults[i] = trie.NodeSyncResult{Path: node.path, Data: data}
   242  			}
   243  		}
   244  		for _, result := range codeResults {
   245  			if err := sched.ProcessCode(result); err != nil {
   246  				t.Errorf("failed to process result %v", err)
   247  			}
   248  		}
   249  		for _, result := range nodeResults {
   250  			if err := sched.ProcessNode(result); err != nil {
   251  				t.Errorf("failed to process result %v", err)
   252  			}
   253  		}
   254  		batch := dstDb.NewBatch()
   255  		if err := sched.Commit(batch); err != nil {
   256  			t.Fatalf("failed to commit data: %v", err)
   257  		}
   258  		batch.Write()
   259  
   260  		paths, nodes, codes = sched.Missing(count)
   261  		nodeElements = nodeElements[:0]
   262  		for i := 0; i < len(paths); i++ {
   263  			nodeElements = append(nodeElements, stateElement{
   264  				path:     paths[i],
   265  				hash:     nodes[i],
   266  				syncPath: trie.NewSyncPath([]byte(paths[i])),
   267  			})
   268  		}
   269  		codeElements = codeElements[:0]
   270  		for i := 0; i < len(codes); i++ {
   271  			codeElements = append(codeElements, stateElement{
   272  				code: codes[i],
   273  			})
   274  		}
   275  	}
   276  	// Cross check that the two states are in sync
   277  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   278  }
   279  
   280  // Tests that the trie scheduler can correctly reconstruct the state even if only
   281  // partial results are returned, and the others sent only later.
   282  func TestIterativeDelayedStateSync(t *testing.T) {
   283  	// Create a random state to copy
   284  	srcDb, srcRoot, srcAccounts := makeTestState()
   285  
   286  	// Create a destination state and sync with the scheduler
   287  	dstDb := rawdb.NewMemoryDatabase()
   288  	sched := NewStateSync(srcRoot, dstDb, nil)
   289  
   290  	var (
   291  		nodeElements []stateElement
   292  		codeElements []stateElement
   293  	)
   294  	paths, nodes, codes := sched.Missing(0)
   295  	for i := 0; i < len(paths); i++ {
   296  		nodeElements = append(nodeElements, stateElement{
   297  			path:     paths[i],
   298  			hash:     nodes[i],
   299  			syncPath: trie.NewSyncPath([]byte(paths[i])),
   300  		})
   301  	}
   302  	for i := 0; i < len(codes); i++ {
   303  		codeElements = append(codeElements, stateElement{
   304  			code: codes[i],
   305  		})
   306  	}
   307  	for len(nodeElements)+len(codeElements) > 0 {
   308  		// Sync only half of the scheduled nodes
   309  		var nodeProcessed int
   310  		var codeProcessed int
   311  		if len(codeElements) > 0 {
   312  			codeResults := make([]trie.CodeSyncResult, len(codeElements)/2+1)
   313  			for i, element := range codeElements[:len(codeResults)] {
   314  				data, err := srcDb.ContractCode(common.Hash{}, element.code)
   315  				if err != nil {
   316  					t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
   317  				}
   318  				codeResults[i] = trie.CodeSyncResult{Hash: element.code, Data: data}
   319  			}
   320  			for _, result := range codeResults {
   321  				if err := sched.ProcessCode(result); err != nil {
   322  					t.Fatalf("failed to process result %v", err)
   323  				}
   324  			}
   325  			codeProcessed = len(codeResults)
   326  		}
   327  		if len(nodeElements) > 0 {
   328  			nodeResults := make([]trie.NodeSyncResult, len(nodeElements)/2+1)
   329  			for i, element := range nodeElements[:len(nodeResults)] {
   330  				data, err := srcDb.TrieDB().Node(element.hash)
   331  				if err != nil {
   332  					t.Fatalf("failed to retrieve contract bytecode for %x", element.code)
   333  				}
   334  				nodeResults[i] = trie.NodeSyncResult{Path: element.path, Data: data}
   335  			}
   336  			for _, result := range nodeResults {
   337  				if err := sched.ProcessNode(result); err != nil {
   338  					t.Fatalf("failed to process result %v", err)
   339  				}
   340  			}
   341  			nodeProcessed = len(nodeResults)
   342  		}
   343  		batch := dstDb.NewBatch()
   344  		if err := sched.Commit(batch); err != nil {
   345  			t.Fatalf("failed to commit data: %v", err)
   346  		}
   347  		batch.Write()
   348  
   349  		paths, nodes, codes = sched.Missing(0)
   350  		nodeElements = nodeElements[nodeProcessed:]
   351  		for i := 0; i < len(paths); i++ {
   352  			nodeElements = append(nodeElements, stateElement{
   353  				path:     paths[i],
   354  				hash:     nodes[i],
   355  				syncPath: trie.NewSyncPath([]byte(paths[i])),
   356  			})
   357  		}
   358  		codeElements = codeElements[codeProcessed:]
   359  		for i := 0; i < len(codes); i++ {
   360  			codeElements = append(codeElements, stateElement{
   361  				code: codes[i],
   362  			})
   363  		}
   364  	}
   365  	// Cross check that the two states are in sync
   366  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   367  }
   368  
   369  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   370  // requesting retrieval tasks and returning all of them in one go, however in a
   371  // random order.
   372  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   373  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   374  
   375  func testIterativeRandomStateSync(t *testing.T, count int) {
   376  	// Create a random state to copy
   377  	srcDb, srcRoot, srcAccounts := makeTestState()
   378  
   379  	// Create a destination state and sync with the scheduler
   380  	dstDb := rawdb.NewMemoryDatabase()
   381  	sched := NewStateSync(srcRoot, dstDb, nil)
   382  
   383  	nodeQueue := make(map[string]stateElement)
   384  	codeQueue := make(map[common.Hash]struct{})
   385  	paths, nodes, codes := sched.Missing(count)
   386  	for i, path := range paths {
   387  		nodeQueue[path] = stateElement{
   388  			path:     path,
   389  			hash:     nodes[i],
   390  			syncPath: trie.NewSyncPath([]byte(path)),
   391  		}
   392  	}
   393  	for _, hash := range codes {
   394  		codeQueue[hash] = struct{}{}
   395  	}
   396  	for len(nodeQueue)+len(codeQueue) > 0 {
   397  		// Fetch all the queued nodes in a random order
   398  		if len(codeQueue) > 0 {
   399  			results := make([]trie.CodeSyncResult, 0, len(codeQueue))
   400  			for hash := range codeQueue {
   401  				data, err := srcDb.ContractCode(common.Hash{}, hash)
   402  				if err != nil {
   403  					t.Fatalf("failed to retrieve node data for %x", hash)
   404  				}
   405  				results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
   406  			}
   407  			for _, result := range results {
   408  				if err := sched.ProcessCode(result); err != nil {
   409  					t.Fatalf("failed to process result %v", err)
   410  				}
   411  			}
   412  		}
   413  		if len(nodeQueue) > 0 {
   414  			results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
   415  			for path, element := range nodeQueue {
   416  				data, err := srcDb.TrieDB().Node(element.hash)
   417  				if err != nil {
   418  					t.Fatalf("failed to retrieve node data for %x %v %v", element.hash, []byte(element.path), element.path)
   419  				}
   420  				results = append(results, trie.NodeSyncResult{Path: path, Data: data})
   421  			}
   422  			for _, result := range results {
   423  				if err := sched.ProcessNode(result); err != nil {
   424  					t.Fatalf("failed to process result %v", err)
   425  				}
   426  			}
   427  		}
   428  		// Feed the retrieved results back and queue new tasks
   429  		batch := dstDb.NewBatch()
   430  		if err := sched.Commit(batch); err != nil {
   431  			t.Fatalf("failed to commit data: %v", err)
   432  		}
   433  		batch.Write()
   434  
   435  		nodeQueue = make(map[string]stateElement)
   436  		codeQueue = make(map[common.Hash]struct{})
   437  		paths, nodes, codes := sched.Missing(count)
   438  		for i, path := range paths {
   439  			nodeQueue[path] = stateElement{
   440  				path:     path,
   441  				hash:     nodes[i],
   442  				syncPath: trie.NewSyncPath([]byte(path)),
   443  			}
   444  		}
   445  		for _, hash := range codes {
   446  			codeQueue[hash] = struct{}{}
   447  		}
   448  	}
   449  	// Cross check that the two states are in sync
   450  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   451  }
   452  
   453  // Tests that the trie scheduler can correctly reconstruct the state even if only
   454  // partial results are returned (Even those randomly), others sent only later.
   455  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   456  	// Create a random state to copy
   457  	srcDb, srcRoot, srcAccounts := makeTestState()
   458  
   459  	// Create a destination state and sync with the scheduler
   460  	dstDb := rawdb.NewMemoryDatabase()
   461  	sched := NewStateSync(srcRoot, dstDb, nil)
   462  
   463  	nodeQueue := make(map[string]stateElement)
   464  	codeQueue := make(map[common.Hash]struct{})
   465  	paths, nodes, codes := sched.Missing(0)
   466  	for i, path := range paths {
   467  		nodeQueue[path] = stateElement{
   468  			path:     path,
   469  			hash:     nodes[i],
   470  			syncPath: trie.NewSyncPath([]byte(path)),
   471  		}
   472  	}
   473  	for _, hash := range codes {
   474  		codeQueue[hash] = struct{}{}
   475  	}
   476  	for len(nodeQueue)+len(codeQueue) > 0 {
   477  		// Sync only half of the scheduled nodes, even those in random order
   478  		if len(codeQueue) > 0 {
   479  			results := make([]trie.CodeSyncResult, 0, len(codeQueue)/2+1)
   480  			for hash := range codeQueue {
   481  				delete(codeQueue, hash)
   482  
   483  				data, err := srcDb.ContractCode(common.Hash{}, hash)
   484  				if err != nil {
   485  					t.Fatalf("failed to retrieve node data for %x", hash)
   486  				}
   487  				results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
   488  
   489  				if len(results) >= cap(results) {
   490  					break
   491  				}
   492  			}
   493  			for _, result := range results {
   494  				if err := sched.ProcessCode(result); err != nil {
   495  					t.Fatalf("failed to process result %v", err)
   496  				}
   497  			}
   498  		}
   499  		if len(nodeQueue) > 0 {
   500  			results := make([]trie.NodeSyncResult, 0, len(nodeQueue)/2+1)
   501  			for path, element := range nodeQueue {
   502  				delete(nodeQueue, path)
   503  
   504  				data, err := srcDb.TrieDB().Node(element.hash)
   505  				if err != nil {
   506  					t.Fatalf("failed to retrieve node data for %x", element.hash)
   507  				}
   508  				results = append(results, trie.NodeSyncResult{Path: path, Data: data})
   509  
   510  				if len(results) >= cap(results) {
   511  					break
   512  				}
   513  			}
   514  			// Feed the retrieved results back and queue new tasks
   515  			for _, result := range results {
   516  				if err := sched.ProcessNode(result); err != nil {
   517  					t.Fatalf("failed to process result %v", err)
   518  				}
   519  			}
   520  		}
   521  		batch := dstDb.NewBatch()
   522  		if err := sched.Commit(batch); err != nil {
   523  			t.Fatalf("failed to commit data: %v", err)
   524  		}
   525  		batch.Write()
   526  
   527  		paths, nodes, codes := sched.Missing(0)
   528  		for i, path := range paths {
   529  			nodeQueue[path] = stateElement{
   530  				path:     path,
   531  				hash:     nodes[i],
   532  				syncPath: trie.NewSyncPath([]byte(path)),
   533  			}
   534  		}
   535  		for _, hash := range codes {
   536  			codeQueue[hash] = struct{}{}
   537  		}
   538  	}
   539  	// Cross check that the two states are in sync
   540  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   541  }
   542  
   543  // Tests that at any point in time during a sync, only complete sub-tries are in
   544  // the database.
   545  func TestIncompleteStateSync(t *testing.T) {
   546  	// Create a random state to copy
   547  	srcDb, srcRoot, srcAccounts := makeTestState()
   548  
   549  	// isCodeLookup to save some hashing
   550  	var isCode = make(map[common.Hash]struct{})
   551  	for _, acc := range srcAccounts {
   552  		if len(acc.code) > 0 {
   553  			isCode[crypto.Keccak256Hash(acc.code)] = struct{}{}
   554  		}
   555  	}
   556  	isCode[common.BytesToHash(emptyCodeHash)] = struct{}{}
   557  	checkTrieConsistency(srcDb.DiskDB(), srcRoot)
   558  
   559  	// Create a destination state and sync with the scheduler
   560  	dstDb := rawdb.NewMemoryDatabase()
   561  	sched := NewStateSync(srcRoot, dstDb, nil)
   562  
   563  	var (
   564  		addedCodes []common.Hash
   565  		addedNodes []common.Hash
   566  	)
   567  	nodeQueue := make(map[string]stateElement)
   568  	codeQueue := make(map[common.Hash]struct{})
   569  	paths, nodes, codes := sched.Missing(1)
   570  	for i, path := range paths {
   571  		nodeQueue[path] = stateElement{
   572  			path:     path,
   573  			hash:     nodes[i],
   574  			syncPath: trie.NewSyncPath([]byte(path)),
   575  		}
   576  	}
   577  	for _, hash := range codes {
   578  		codeQueue[hash] = struct{}{}
   579  	}
   580  	for len(nodeQueue)+len(codeQueue) > 0 {
   581  		// Fetch a batch of state nodes
   582  		if len(codeQueue) > 0 {
   583  			results := make([]trie.CodeSyncResult, 0, len(codeQueue))
   584  			for hash := range codeQueue {
   585  				data, err := srcDb.ContractCode(common.Hash{}, hash)
   586  				if err != nil {
   587  					t.Fatalf("failed to retrieve node data for %x", hash)
   588  				}
   589  				results = append(results, trie.CodeSyncResult{Hash: hash, Data: data})
   590  				addedCodes = append(addedCodes, hash)
   591  			}
   592  			// Process each of the state nodes
   593  			for _, result := range results {
   594  				if err := sched.ProcessCode(result); err != nil {
   595  					t.Fatalf("failed to process result %v", err)
   596  				}
   597  			}
   598  		}
   599  		var nodehashes []common.Hash
   600  		if len(nodeQueue) > 0 {
   601  			results := make([]trie.NodeSyncResult, 0, len(nodeQueue))
   602  			for key, element := range nodeQueue {
   603  				data, err := srcDb.TrieDB().Node(element.hash)
   604  				if err != nil {
   605  					t.Fatalf("failed to retrieve node data for %x", element.hash)
   606  				}
   607  				results = append(results, trie.NodeSyncResult{Path: key, Data: data})
   608  
   609  				if element.hash != srcRoot {
   610  					addedNodes = append(addedNodes, element.hash)
   611  				}
   612  				nodehashes = append(nodehashes, element.hash)
   613  			}
   614  			// Process each of the state nodes
   615  			for _, result := range results {
   616  				if err := sched.ProcessNode(result); err != nil {
   617  					t.Fatalf("failed to process result %v", err)
   618  				}
   619  			}
   620  		}
   621  		batch := dstDb.NewBatch()
   622  		if err := sched.Commit(batch); err != nil {
   623  			t.Fatalf("failed to commit data: %v", err)
   624  		}
   625  		batch.Write()
   626  
   627  		for _, root := range nodehashes {
   628  			// Can't use checkStateConsistency here because subtrie keys may have odd
   629  			// length and crash in LeafKey.
   630  			if err := checkTrieConsistency(dstDb, root); err != nil {
   631  				t.Fatalf("state inconsistent: %v", err)
   632  			}
   633  		}
   634  		// Fetch the next batch to retrieve
   635  		nodeQueue = make(map[string]stateElement)
   636  		codeQueue = make(map[common.Hash]struct{})
   637  		paths, nodes, codes := sched.Missing(1)
   638  		for i, path := range paths {
   639  			nodeQueue[path] = stateElement{
   640  				path:     path,
   641  				hash:     nodes[i],
   642  				syncPath: trie.NewSyncPath([]byte(path)),
   643  			}
   644  		}
   645  		for _, hash := range codes {
   646  			codeQueue[hash] = struct{}{}
   647  		}
   648  	}
   649  	// Sanity check that removing any node from the database is detected
   650  	for _, node := range addedCodes {
   651  		val := rawdb.ReadCode(dstDb, node)
   652  		rawdb.DeleteCode(dstDb, node)
   653  		if err := checkStateConsistency(dstDb, srcRoot); err == nil {
   654  			t.Errorf("trie inconsistency not caught, missing: %x", node)
   655  		}
   656  		rawdb.WriteCode(dstDb, node, val)
   657  	}
   658  	for _, node := range addedNodes {
   659  		val := rawdb.ReadTrieNode(dstDb, node)
   660  		rawdb.DeleteTrieNode(dstDb, node)
   661  		if err := checkStateConsistency(dstDb, srcRoot); err == nil {
   662  			t.Errorf("trie inconsistency not caught, missing: %v", node.Hex())
   663  		}
   664  		rawdb.WriteTrieNode(dstDb, node, val)
   665  	}
   666  }