github.com/core-coin/go-core/v2@v2.1.9/core/state/sync_test.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 state
    18  
    19  import (
    20  	"bytes"
    21  	"math/big"
    22  	"testing"
    23  
    24  	"github.com/core-coin/go-core/v2/xcbdb"
    25  	"github.com/core-coin/go-core/v2/xcbdb/memorydb"
    26  
    27  	"github.com/core-coin/go-core/v2/common"
    28  	"github.com/core-coin/go-core/v2/core/rawdb"
    29  	"github.com/core-coin/go-core/v2/crypto"
    30  	"github.com/core-coin/go-core/v2/rlp"
    31  	"github.com/core-coin/go-core/v2/trie"
    32  )
    33  
    34  // testAccount is the data associated with an account used by the state tests.
    35  type testAccount struct {
    36  	address common.Address
    37  	balance *big.Int
    38  	nonce   uint64
    39  	code    []byte
    40  }
    41  
    42  // makeTestState create a sample test state to test node-wise reconstruction.
    43  func makeTestState() (Database, common.Hash, []*testAccount) {
    44  	// Create an empty state
    45  	db := NewDatabase(rawdb.NewMemoryDatabase())
    46  	state, _ := New(common.Hash{}, db, nil)
    47  
    48  	// Fill it with some arbitrary data
    49  	var accounts []*testAccount
    50  	for i := byte(0); i < 96; i++ {
    51  		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
    52  		acc := &testAccount{address: common.BytesToAddress([]byte{i})}
    53  
    54  		obj.AddBalance(big.NewInt(int64(11 * i)))
    55  		acc.balance = big.NewInt(int64(11 * i))
    56  
    57  		obj.SetNonce(uint64(42 * i))
    58  		acc.nonce = uint64(42 * i)
    59  
    60  		if i%3 == 0 {
    61  			obj.SetCode(crypto.SHA3Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
    62  			acc.code = []byte{i, i, i, i, i}
    63  		}
    64  		if i%5 == 0 {
    65  			for j := byte(0); j < 5; j++ {
    66  				hash := crypto.SHA3Hash([]byte{i, i, i, i, i, j, j})
    67  				obj.SetState(db, hash, hash)
    68  			}
    69  		}
    70  		state.updateStateObject(obj)
    71  		accounts = append(accounts, acc)
    72  	}
    73  	root, _ := state.Commit(false)
    74  
    75  	// Return the generated state
    76  	return db, root, accounts
    77  }
    78  
    79  // checkStateAccounts cross references a reconstructed state with an expected
    80  // account array.
    81  func checkStateAccounts(t *testing.T, db xcbdb.Database, root common.Hash, accounts []*testAccount) {
    82  	// Check root availability and state contents
    83  	state, err := New(root, NewDatabase(db), nil)
    84  	if err != nil {
    85  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    86  	}
    87  	if err := checkStateConsistency(db, root); err != nil {
    88  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    89  	}
    90  	for i, acc := range accounts {
    91  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    92  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    93  		}
    94  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    95  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    96  		}
    97  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    98  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
    99  		}
   100  	}
   101  }
   102  
   103  // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
   104  func checkTrieConsistency(db xcbdb.Database, root common.Hash) error {
   105  	if v, _ := db.Get(root[:]); v == nil {
   106  		return nil // Consider a non existent state consistent.
   107  	}
   108  	trie, err := trie.New(root, trie.NewDatabase(db))
   109  	if err != nil {
   110  		return err
   111  	}
   112  	it := trie.NodeIterator(nil)
   113  	for it.Next(true) {
   114  	}
   115  	return it.Error()
   116  }
   117  
   118  // checkStateConsistency checks that all data of a state root is present.
   119  func checkStateConsistency(db xcbdb.Database, root common.Hash) error {
   120  	// Create and iterate a state trie rooted in a sub-node
   121  	if _, err := db.Get(root.Bytes()); err != nil {
   122  		return nil // Consider a non existent state consistent.
   123  	}
   124  	state, err := New(root, NewDatabase(db), nil)
   125  	if err != nil {
   126  		return err
   127  	}
   128  	it := NewNodeIterator(state)
   129  	for it.Next() {
   130  	}
   131  	return it.Error
   132  }
   133  
   134  // Tests that an empty state is not scheduled for syncing.
   135  func TestEmptyStateSync(t *testing.T) {
   136  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   137  	sync := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New()))
   138  	if nodes, paths, codes := sync.Missing(1); len(nodes) != 0 || len(paths) != 0 || len(codes) != 0 {
   139  		t.Errorf(" content requested for empty state: %v, %v, %v", nodes, paths, codes)
   140  	}
   141  }
   142  
   143  // Tests that given a root hash, a state can sync iteratively on a single thread,
   144  // requesting retrieval tasks and returning all of them in one go.
   145  func TestIterativeStateSyncIndividual(t *testing.T) {
   146  	testIterativeStateSync(t, 1, false, false)
   147  }
   148  func TestIterativeStateSyncBatched(t *testing.T) {
   149  	testIterativeStateSync(t, 100, false, false)
   150  }
   151  func TestIterativeStateSyncIndividualFromDisk(t *testing.T) {
   152  	testIterativeStateSync(t, 1, true, false)
   153  }
   154  func TestIterativeStateSyncBatchedFromDisk(t *testing.T) {
   155  	testIterativeStateSync(t, 100, true, false)
   156  }
   157  func TestIterativeStateSyncIndividualByPath(t *testing.T) {
   158  	testIterativeStateSync(t, 1, false, true)
   159  }
   160  func TestIterativeStateSyncBatchedByPath(t *testing.T) {
   161  	testIterativeStateSync(t, 100, false, true)
   162  }
   163  
   164  func testIterativeStateSync(t *testing.T, count int, commit bool, bypath bool) {
   165  	// Create a random state to copy
   166  	srcDb, srcRoot, srcAccounts := makeTestState()
   167  	if commit {
   168  		srcDb.TrieDB().Commit(srcRoot, false, nil)
   169  	}
   170  	srcTrie, _ := trie.New(srcRoot, srcDb.TrieDB())
   171  
   172  	// Create a destination state and sync with the scheduler
   173  	dstDb := rawdb.NewMemoryDatabase()
   174  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   175  
   176  	nodes, paths, codes := sched.Missing(count)
   177  	var (
   178  		hashQueue []common.Hash
   179  		pathQueue []trie.SyncPath
   180  	)
   181  	if !bypath {
   182  		hashQueue = append(append(hashQueue[:0], nodes...), codes...)
   183  	} else {
   184  		hashQueue = append(hashQueue[:0], codes...)
   185  		pathQueue = append(pathQueue[:0], paths...)
   186  	}
   187  	for len(hashQueue)+len(pathQueue) > 0 {
   188  		results := make([]trie.SyncResult, len(hashQueue)+len(pathQueue))
   189  		for i, hash := range hashQueue {
   190  			data, err := srcDb.TrieDB().Node(hash)
   191  			if err != nil {
   192  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   193  			}
   194  			if err != nil {
   195  				t.Fatalf("failed to retrieve node data for hash %x", hash)
   196  			}
   197  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   198  		}
   199  		for i, path := range pathQueue {
   200  			if len(path) == 1 {
   201  				data, _, err := srcTrie.TryGetNode(path[0])
   202  				if err != nil {
   203  					t.Fatalf("failed to retrieve node data for path %x: %v", path, err)
   204  				}
   205  				results[len(hashQueue)+i] = trie.SyncResult{Hash: crypto.SHA3Hash(data), Data: data}
   206  			} else {
   207  				var acc Account
   208  				if err := rlp.DecodeBytes(srcTrie.Get(path[0]), &acc); err != nil {
   209  					t.Fatalf("failed to decode account on path %x: %v", path, err)
   210  				}
   211  				stTrie, err := trie.New(acc.Root, srcDb.TrieDB())
   212  				if err != nil {
   213  					t.Fatalf("failed to retriev storage trie for path %x: %v", path, err)
   214  				}
   215  				data, _, err := stTrie.TryGetNode(path[1])
   216  				if err != nil {
   217  					t.Fatalf("failed to retrieve node data for path %x: %v", path, err)
   218  				}
   219  				results[len(hashQueue)+i] = trie.SyncResult{Hash: crypto.SHA3Hash(data), Data: data}
   220  			}
   221  		}
   222  		for _, result := range results {
   223  			if err := sched.Process(result); err != nil {
   224  				t.Errorf("failed to process result %v", err)
   225  			}
   226  		}
   227  		batch := dstDb.NewBatch()
   228  		if err := sched.Commit(batch); err != nil {
   229  			t.Fatalf("failed to commit data: %v", err)
   230  		}
   231  		batch.Write()
   232  
   233  		nodes, paths, codes = sched.Missing(count)
   234  		if !bypath {
   235  			hashQueue = append(append(hashQueue[:0], nodes...), codes...)
   236  		} else {
   237  			hashQueue = append(hashQueue[:0], codes...)
   238  			pathQueue = append(pathQueue[:0], paths...)
   239  		}
   240  	}
   241  	// Cross check that the two states are in sync
   242  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   243  }
   244  
   245  // Tests that the trie scheduler can correctly reconstruct the state even if only
   246  // partial results are returned, and the others sent only later.
   247  func TestIterativeDelayedStateSync(t *testing.T) {
   248  	// Create a random state to copy
   249  	srcDb, srcRoot, srcAccounts := makeTestState()
   250  
   251  	// Create a destination state and sync with the scheduler
   252  	dstDb := rawdb.NewMemoryDatabase()
   253  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   254  
   255  	nodes, _, codes := sched.Missing(0)
   256  	queue := append(append([]common.Hash{}, nodes...), codes...)
   257  
   258  	for len(queue) > 0 {
   259  		// Sync only half of the scheduled nodes
   260  		results := make([]trie.SyncResult, len(queue)/2+1)
   261  		for i, hash := range queue[:len(results)] {
   262  			data, err := srcDb.TrieDB().Node(hash)
   263  			if err != nil {
   264  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   265  			}
   266  			if err != nil {
   267  				t.Fatalf("failed to retrieve node data for %x", hash)
   268  			}
   269  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   270  		}
   271  		for _, result := range results {
   272  			if err := sched.Process(result); err != nil {
   273  				t.Fatalf("failed to process result %v", err)
   274  			}
   275  		}
   276  		batch := dstDb.NewBatch()
   277  		if err := sched.Commit(batch); err != nil {
   278  			t.Fatalf("failed to commit data: %v", err)
   279  		}
   280  		batch.Write()
   281  
   282  		nodes, _, codes = sched.Missing(0)
   283  		queue = append(append(queue[len(results):], nodes...), codes...)
   284  	}
   285  	// Cross check that the two states are in sync
   286  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   287  }
   288  
   289  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   290  // requesting retrieval tasks and returning all of them in one go, however in a
   291  // random order.
   292  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   293  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   294  
   295  func testIterativeRandomStateSync(t *testing.T, count int) {
   296  	// Create a random state to copy
   297  	srcDb, srcRoot, srcAccounts := makeTestState()
   298  
   299  	// Create a destination state and sync with the scheduler
   300  	dstDb := rawdb.NewMemoryDatabase()
   301  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   302  
   303  	queue := make(map[common.Hash]struct{})
   304  	nodes, _, codes := sched.Missing(count)
   305  	for _, hash := range append(nodes, codes...) {
   306  		queue[hash] = struct{}{}
   307  	}
   308  	for len(queue) > 0 {
   309  		// Fetch all the queued nodes in a random order
   310  		results := make([]trie.SyncResult, 0, len(queue))
   311  		for hash := range queue {
   312  			data, err := srcDb.TrieDB().Node(hash)
   313  			if err != nil {
   314  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   315  			}
   316  			if err != nil {
   317  				t.Fatalf("failed to retrieve node data for %x", hash)
   318  			}
   319  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   320  		}
   321  		// Feed the retrieved results back and queue new tasks
   322  		for _, result := range results {
   323  			if err := sched.Process(result); err != nil {
   324  				t.Fatalf("failed to process result %v", err)
   325  			}
   326  		}
   327  		batch := dstDb.NewBatch()
   328  		if err := sched.Commit(batch); err != nil {
   329  			t.Fatalf("failed to commit data: %v", err)
   330  		}
   331  		batch.Write()
   332  
   333  		queue = make(map[common.Hash]struct{})
   334  		nodes, _, codes = sched.Missing(count)
   335  		for _, hash := range append(nodes, codes...) {
   336  			queue[hash] = struct{}{}
   337  		}
   338  	}
   339  	// Cross check that the two states are in sync
   340  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   341  }
   342  
   343  // Tests that the trie scheduler can correctly reconstruct the state even if only
   344  // partial results are returned (Even those randomly), others sent only later.
   345  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   346  	// Create a random state to copy
   347  	srcDb, srcRoot, srcAccounts := makeTestState()
   348  
   349  	// Create a destination state and sync with the scheduler
   350  	dstDb := rawdb.NewMemoryDatabase()
   351  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   352  
   353  	queue := make(map[common.Hash]struct{})
   354  	nodes, _, codes := sched.Missing(0)
   355  	for _, hash := range append(nodes, codes...) {
   356  		queue[hash] = struct{}{}
   357  	}
   358  	for len(queue) > 0 {
   359  		// Sync only half of the scheduled nodes, even those in random order
   360  		results := make([]trie.SyncResult, 0, len(queue)/2+1)
   361  		for hash := range queue {
   362  			delete(queue, hash)
   363  
   364  			data, err := srcDb.TrieDB().Node(hash)
   365  			if err != nil {
   366  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   367  			}
   368  			if err != nil {
   369  				t.Fatalf("failed to retrieve node data for %x", hash)
   370  			}
   371  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   372  
   373  			if len(results) >= cap(results) {
   374  				break
   375  			}
   376  		}
   377  		// Feed the retrieved results back and queue new tasks
   378  		for _, result := range results {
   379  			if err := sched.Process(result); err != nil {
   380  				t.Fatalf("failed to process result %v", err)
   381  			}
   382  		}
   383  		batch := dstDb.NewBatch()
   384  		if err := sched.Commit(batch); err != nil {
   385  			t.Fatalf("failed to commit data: %v", err)
   386  		}
   387  		batch.Write()
   388  		for _, result := range results {
   389  			delete(queue, result.Hash)
   390  		}
   391  		nodes, _, codes = sched.Missing(0)
   392  		for _, hash := range append(nodes, codes...) {
   393  			queue[hash] = struct{}{}
   394  		}
   395  	}
   396  	// Cross check that the two states are in sync
   397  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   398  }
   399  
   400  // Tests that at any point in time during a sync, only complete sub-tries are in
   401  // the database.
   402  func TestIncompleteStateSync(t *testing.T) {
   403  	// Create a random state to copy
   404  	srcDb, srcRoot, srcAccounts := makeTestState()
   405  
   406  	// isCodeLookup to save some hashing
   407  	var isCode = make(map[common.Hash]struct{})
   408  	for _, acc := range srcAccounts {
   409  		if len(acc.code) > 0 {
   410  			isCode[crypto.SHA3Hash(acc.code)] = struct{}{}
   411  		}
   412  	}
   413  	isCode[common.BytesToHash(emptyCodeHash)] = struct{}{}
   414  	checkTrieConsistency(srcDb.TrieDB().DiskDB().(xcbdb.Database), srcRoot)
   415  
   416  	// Create a destination state and sync with the scheduler
   417  	dstDb := rawdb.NewMemoryDatabase()
   418  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   419  
   420  	var added []common.Hash
   421  
   422  	nodes, _, codes := sched.Missing(1)
   423  	queue := append(append([]common.Hash{}, nodes...), codes...)
   424  
   425  	for len(queue) > 0 {
   426  		// Fetch a batch of state nodes
   427  		results := make([]trie.SyncResult, len(queue))
   428  		for i, hash := range queue {
   429  			data, err := srcDb.TrieDB().Node(hash)
   430  			if err != nil {
   431  				data, err = srcDb.ContractCode(common.Hash{}, hash)
   432  			}
   433  			if err != nil {
   434  				t.Fatalf("failed to retrieve node data for %x", hash)
   435  			}
   436  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   437  		}
   438  		// Process each of the state nodes
   439  		for _, result := range results {
   440  			if err := sched.Process(result); err != nil {
   441  				t.Fatalf("failed to process result %v", err)
   442  			}
   443  		}
   444  		batch := dstDb.NewBatch()
   445  		if err := sched.Commit(batch); err != nil {
   446  			t.Fatalf("failed to commit data: %v", err)
   447  		}
   448  		batch.Write()
   449  		for _, result := range results {
   450  			added = append(added, result.Hash)
   451  			// Check that all known sub-tries added so far are complete or missing entirely.
   452  			if _, ok := isCode[result.Hash]; ok {
   453  				continue
   454  			}
   455  			// Can't use checkStateConsistency here because subtrie keys may have odd
   456  			// length and crash in LeafKey.
   457  			if err := checkTrieConsistency(dstDb, result.Hash); err != nil {
   458  				t.Fatalf("state inconsistent: %v", err)
   459  			}
   460  		}
   461  		// Fetch the next batch to retrieve
   462  		nodes, _, codes = sched.Missing(1)
   463  		queue = append(append(queue[:0], nodes...), codes...)
   464  	}
   465  	// Sanity check that removing any node from the database is detected
   466  	for _, node := range added[1:] {
   467  		var (
   468  			key     = node.Bytes()
   469  			_, code = isCode[node]
   470  			val     []byte
   471  		)
   472  		if code {
   473  			val = rawdb.ReadCode(dstDb, node)
   474  			rawdb.DeleteCode(dstDb, node)
   475  		} else {
   476  			val = rawdb.ReadTrieNode(dstDb, node)
   477  			rawdb.DeleteTrieNode(dstDb, node)
   478  		}
   479  		if err := checkStateConsistency(dstDb, added[0]); err == nil {
   480  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   481  		}
   482  		if code {
   483  			rawdb.WriteCode(dstDb, node, val)
   484  		} else {
   485  			rawdb.WriteTrieNode(dstDb, node, val)
   486  		}
   487  	}
   488  }