github.com/kjezek/go-ethereum@v1.9.6/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/crypto"
    27  	"github.com/ethereum/go-ethereum/ethdb"
    28  	"github.com/ethereum/go-ethereum/ethdb/memorydb"
    29  	"github.com/ethereum/go-ethereum/trie"
    30  )
    31  
    32  // testAccount is the data associated with an account used by the state tests.
    33  type testAccount struct {
    34  	address common.Address
    35  	balance *big.Int
    36  	nonce   uint64
    37  	code    []byte
    38  }
    39  
    40  // makeTestState create a sample test state to test node-wise reconstruction.
    41  func makeTestState() (Database, common.Hash, []*testAccount) {
    42  	// Create an empty state
    43  	db := NewDatabase(rawdb.NewMemoryDatabase())
    44  	state, _ := New(common.Hash{}, db)
    45  
    46  	// Fill it with some arbitrary data
    47  	accounts := []*testAccount{}
    48  	for i := byte(0); i < 96; i++ {
    49  		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
    50  		acc := &testAccount{address: common.BytesToAddress([]byte{i})}
    51  
    52  		obj.AddBalance(big.NewInt(int64(11 * i)))
    53  		acc.balance = big.NewInt(int64(11 * i))
    54  
    55  		obj.SetNonce(uint64(42 * i))
    56  		acc.nonce = uint64(42 * i)
    57  
    58  		if i%3 == 0 {
    59  			obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
    60  			acc.code = []byte{i, i, i, i, i}
    61  		}
    62  		state.updateStateObject(obj)
    63  		accounts = append(accounts, acc)
    64  	}
    65  	root, _ := state.Commit(false)
    66  
    67  	// Return the generated state
    68  	return db, root, accounts
    69  }
    70  
    71  // checkStateAccounts cross references a reconstructed state with an expected
    72  // account array.
    73  func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
    74  	// Check root availability and state contents
    75  	state, err := New(root, NewDatabase(db))
    76  	if err != nil {
    77  		t.Fatalf("failed to create state trie at %x: %v", root, err)
    78  	}
    79  	if err := checkStateConsistency(db, root); err != nil {
    80  		t.Fatalf("inconsistent state trie at %x: %v", root, err)
    81  	}
    82  	for i, acc := range accounts {
    83  		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
    84  			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
    85  		}
    86  		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
    87  			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
    88  		}
    89  		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
    90  			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
    91  		}
    92  	}
    93  }
    94  
    95  // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
    96  func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
    97  	if v, _ := db.Get(root[:]); v == nil {
    98  		return nil // Consider a non existent state consistent.
    99  	}
   100  	trie, err := trie.New(root, trie.NewDatabase(db))
   101  	if err != nil {
   102  		return err
   103  	}
   104  	it := trie.NodeIterator(nil)
   105  	for it.Next(true) {
   106  	}
   107  	return it.Error()
   108  }
   109  
   110  // checkStateConsistency checks that all data of a state root is present.
   111  func checkStateConsistency(db ethdb.Database, root common.Hash) error {
   112  	// Create and iterate a state trie rooted in a sub-node
   113  	if _, err := db.Get(root.Bytes()); err != nil {
   114  		return nil // Consider a non existent state consistent.
   115  	}
   116  	state, err := New(root, NewDatabase(db))
   117  	if err != nil {
   118  		return err
   119  	}
   120  	it := NewNodeIterator(state)
   121  	for it.Next() {
   122  	}
   123  	return it.Error
   124  }
   125  
   126  // Tests that an empty state is not scheduled for syncing.
   127  func TestEmptyStateSync(t *testing.T) {
   128  	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
   129  	if req := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New())).Missing(1); len(req) != 0 {
   130  		t.Errorf("content requested for empty state: %v", req)
   131  	}
   132  }
   133  
   134  // Tests that given a root hash, a state can sync iteratively on a single thread,
   135  // requesting retrieval tasks and returning all of them in one go.
   136  func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
   137  func TestIterativeStateSyncBatched(t *testing.T)    { testIterativeStateSync(t, 100) }
   138  
   139  func testIterativeStateSync(t *testing.T, batch int) {
   140  	// Create a random state to copy
   141  	srcDb, srcRoot, srcAccounts := makeTestState()
   142  
   143  	// Create a destination state and sync with the scheduler
   144  	dstDb := rawdb.NewMemoryDatabase()
   145  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   146  
   147  	queue := append([]common.Hash{}, sched.Missing(batch)...)
   148  	for len(queue) > 0 {
   149  		results := make([]trie.SyncResult, len(queue))
   150  		for i, hash := range queue {
   151  			data, err := srcDb.TrieDB().Node(hash)
   152  			if err != nil {
   153  				t.Fatalf("failed to retrieve node data for %x", hash)
   154  			}
   155  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   156  		}
   157  		if _, index, err := sched.Process(results); err != nil {
   158  			t.Fatalf("failed to process result #%d: %v", index, err)
   159  		}
   160  		if index, err := sched.Commit(dstDb); err != nil {
   161  			t.Fatalf("failed to commit data #%d: %v", index, err)
   162  		}
   163  		queue = append(queue[:0], sched.Missing(batch)...)
   164  	}
   165  	// Cross check that the two states are in sync
   166  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   167  }
   168  
   169  // Tests that the trie scheduler can correctly reconstruct the state even if only
   170  // partial results are returned, and the others sent only later.
   171  func TestIterativeDelayedStateSync(t *testing.T) {
   172  	// Create a random state to copy
   173  	srcDb, srcRoot, srcAccounts := makeTestState()
   174  
   175  	// Create a destination state and sync with the scheduler
   176  	dstDb := rawdb.NewMemoryDatabase()
   177  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   178  
   179  	queue := append([]common.Hash{}, sched.Missing(0)...)
   180  	for len(queue) > 0 {
   181  		// Sync only half of the scheduled nodes
   182  		results := make([]trie.SyncResult, len(queue)/2+1)
   183  		for i, hash := range queue[:len(results)] {
   184  			data, err := srcDb.TrieDB().Node(hash)
   185  			if err != nil {
   186  				t.Fatalf("failed to retrieve node data for %x", hash)
   187  			}
   188  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   189  		}
   190  		if _, index, err := sched.Process(results); err != nil {
   191  			t.Fatalf("failed to process result #%d: %v", index, err)
   192  		}
   193  		if index, err := sched.Commit(dstDb); err != nil {
   194  			t.Fatalf("failed to commit data #%d: %v", index, err)
   195  		}
   196  		queue = append(queue[len(results):], sched.Missing(0)...)
   197  	}
   198  	// Cross check that the two states are in sync
   199  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   200  }
   201  
   202  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   203  // requesting retrieval tasks and returning all of them in one go, however in a
   204  // random order.
   205  func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
   206  func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }
   207  
   208  func testIterativeRandomStateSync(t *testing.T, batch int) {
   209  	// Create a random state to copy
   210  	srcDb, srcRoot, srcAccounts := makeTestState()
   211  
   212  	// Create a destination state and sync with the scheduler
   213  	dstDb := rawdb.NewMemoryDatabase()
   214  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   215  
   216  	queue := make(map[common.Hash]struct{})
   217  	for _, hash := range sched.Missing(batch) {
   218  		queue[hash] = struct{}{}
   219  	}
   220  	for len(queue) > 0 {
   221  		// Fetch all the queued nodes in a random order
   222  		results := make([]trie.SyncResult, 0, len(queue))
   223  		for hash := range queue {
   224  			data, err := srcDb.TrieDB().Node(hash)
   225  			if err != nil {
   226  				t.Fatalf("failed to retrieve node data for %x", hash)
   227  			}
   228  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   229  		}
   230  		// Feed the retrieved results back and queue new tasks
   231  		if _, index, err := sched.Process(results); err != nil {
   232  			t.Fatalf("failed to process result #%d: %v", index, err)
   233  		}
   234  		if index, err := sched.Commit(dstDb); err != nil {
   235  			t.Fatalf("failed to commit data #%d: %v", index, err)
   236  		}
   237  		queue = make(map[common.Hash]struct{})
   238  		for _, hash := range sched.Missing(batch) {
   239  			queue[hash] = struct{}{}
   240  		}
   241  	}
   242  	// Cross check that the two states are in sync
   243  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   244  }
   245  
   246  // Tests that the trie scheduler can correctly reconstruct the state even if only
   247  // partial results are returned (Even those randomly), others sent only later.
   248  func TestIterativeRandomDelayedStateSync(t *testing.T) {
   249  	// Create a random state to copy
   250  	srcDb, srcRoot, srcAccounts := makeTestState()
   251  
   252  	// Create a destination state and sync with the scheduler
   253  	dstDb := rawdb.NewMemoryDatabase()
   254  	sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
   255  
   256  	queue := make(map[common.Hash]struct{})
   257  	for _, hash := range sched.Missing(0) {
   258  		queue[hash] = struct{}{}
   259  	}
   260  	for len(queue) > 0 {
   261  		// Sync only half of the scheduled nodes, even those in random order
   262  		results := make([]trie.SyncResult, 0, len(queue)/2+1)
   263  		for hash := range queue {
   264  			delete(queue, hash)
   265  
   266  			data, err := srcDb.TrieDB().Node(hash)
   267  			if err != nil {
   268  				t.Fatalf("failed to retrieve node data for %x", hash)
   269  			}
   270  			results = append(results, trie.SyncResult{Hash: hash, Data: data})
   271  
   272  			if len(results) >= cap(results) {
   273  				break
   274  			}
   275  		}
   276  		// Feed the retrieved results back and queue new tasks
   277  		if _, index, err := sched.Process(results); err != nil {
   278  			t.Fatalf("failed to process result #%d: %v", index, err)
   279  		}
   280  		if index, err := sched.Commit(dstDb); err != nil {
   281  			t.Fatalf("failed to commit data #%d: %v", index, err)
   282  		}
   283  		for _, hash := range sched.Missing(0) {
   284  			queue[hash] = struct{}{}
   285  		}
   286  	}
   287  	// Cross check that the two states are in sync
   288  	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
   289  }
   290  
   291  // Tests that at any point in time during a sync, only complete sub-tries are in
   292  // the database.
   293  func TestIncompleteStateSync(t *testing.T) {
   294  	// Create a random state to copy
   295  	srcDb, srcRoot, srcAccounts := makeTestState()
   296  
   297  	checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)
   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  	added := []common.Hash{}
   304  	queue := append([]common.Hash{}, sched.Missing(1)...)
   305  	for len(queue) > 0 {
   306  		// Fetch a batch of state nodes
   307  		results := make([]trie.SyncResult, len(queue))
   308  		for i, hash := range queue {
   309  			data, err := srcDb.TrieDB().Node(hash)
   310  			if err != nil {
   311  				t.Fatalf("failed to retrieve node data for %x", hash)
   312  			}
   313  			results[i] = trie.SyncResult{Hash: hash, Data: data}
   314  		}
   315  		// Process each of the state nodes
   316  		if _, index, err := sched.Process(results); err != nil {
   317  			t.Fatalf("failed to process result #%d: %v", index, err)
   318  		}
   319  		if index, err := sched.Commit(dstDb); err != nil {
   320  			t.Fatalf("failed to commit data #%d: %v", index, err)
   321  		}
   322  		for _, result := range results {
   323  			added = append(added, result.Hash)
   324  		}
   325  		// Check that all known sub-tries added so far are complete or missing entirely.
   326  	checkSubtries:
   327  		for _, hash := range added {
   328  			for _, acc := range srcAccounts {
   329  				if hash == crypto.Keccak256Hash(acc.code) {
   330  					continue checkSubtries // skip trie check of code nodes.
   331  				}
   332  			}
   333  			// Can't use checkStateConsistency here because subtrie keys may have odd
   334  			// length and crash in LeafKey.
   335  			if err := checkTrieConsistency(dstDb, hash); err != nil {
   336  				t.Fatalf("state inconsistent: %v", err)
   337  			}
   338  		}
   339  		// Fetch the next batch to retrieve
   340  		queue = append(queue[:0], sched.Missing(1)...)
   341  	}
   342  	// Sanity check that removing any node from the database is detected
   343  	for _, node := range added[1:] {
   344  		key := node.Bytes()
   345  		value, _ := dstDb.Get(key)
   346  
   347  		dstDb.Delete(key)
   348  		if err := checkStateConsistency(dstDb, added[0]); err == nil {
   349  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   350  		}
   351  		dstDb.Put(key, value)
   352  	}
   353  }