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