github.com/ylsGit/go-ethereum@v1.6.5/trie/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 trie
    18  
    19  import (
    20  	"bytes"
    21  	"testing"
    22  
    23  	"github.com/ethereum/go-ethereum/common"
    24  	"github.com/ethereum/go-ethereum/ethdb"
    25  )
    26  
    27  // makeTestTrie create a sample test trie to test node-wise reconstruction.
    28  func makeTestTrie() (ethdb.Database, *Trie, map[string][]byte) {
    29  	// Create an empty trie
    30  	db, _ := ethdb.NewMemDatabase()
    31  	trie, _ := New(common.Hash{}, db)
    32  
    33  	// Fill it with some arbitrary data
    34  	content := make(map[string][]byte)
    35  	for i := byte(0); i < 255; i++ {
    36  		// Map the same data under multiple keys
    37  		key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
    38  		content[string(key)] = val
    39  		trie.Update(key, val)
    40  
    41  		key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
    42  		content[string(key)] = val
    43  		trie.Update(key, val)
    44  
    45  		// Add some other data to inflate th trie
    46  		for j := byte(3); j < 13; j++ {
    47  			key, val = common.LeftPadBytes([]byte{j, i}, 32), []byte{j, i}
    48  			content[string(key)] = val
    49  			trie.Update(key, val)
    50  		}
    51  	}
    52  	trie.Commit()
    53  
    54  	// Return the generated trie
    55  	return db, trie, content
    56  }
    57  
    58  // checkTrieContents cross references a reconstructed trie with an expected data
    59  // content map.
    60  func checkTrieContents(t *testing.T, db Database, root []byte, content map[string][]byte) {
    61  	// Check root availability and trie contents
    62  	trie, err := New(common.BytesToHash(root), db)
    63  	if err != nil {
    64  		t.Fatalf("failed to create trie at %x: %v", root, err)
    65  	}
    66  	if err := checkTrieConsistency(db, common.BytesToHash(root)); err != nil {
    67  		t.Fatalf("inconsistent trie at %x: %v", root, err)
    68  	}
    69  	for key, val := range content {
    70  		if have := trie.Get([]byte(key)); !bytes.Equal(have, val) {
    71  			t.Errorf("entry %x: content mismatch: have %x, want %x", key, have, val)
    72  		}
    73  	}
    74  }
    75  
    76  // checkTrieConsistency checks that all nodes in a trie are indeed present.
    77  func checkTrieConsistency(db Database, root common.Hash) error {
    78  	// Create and iterate a trie rooted in a subnode
    79  	trie, err := New(root, db)
    80  	if err != nil {
    81  		return nil // // Consider a non existent state consistent
    82  	}
    83  	it := trie.NodeIterator(nil)
    84  	for it.Next(true) {
    85  	}
    86  	return it.Error()
    87  }
    88  
    89  // Tests that an empty trie is not scheduled for syncing.
    90  func TestEmptyTrieSync(t *testing.T) {
    91  	emptyA, _ := New(common.Hash{}, nil)
    92  	emptyB, _ := New(emptyRoot, nil)
    93  
    94  	for i, trie := range []*Trie{emptyA, emptyB} {
    95  		db, _ := ethdb.NewMemDatabase()
    96  		if req := NewTrieSync(common.BytesToHash(trie.Root()), db, nil).Missing(1); len(req) != 0 {
    97  			t.Errorf("test %d: content requested for empty trie: %v", i, req)
    98  		}
    99  	}
   100  }
   101  
   102  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   103  // requesting retrieval tasks and returning all of them in one go.
   104  func TestIterativeTrieSyncIndividual(t *testing.T) { testIterativeTrieSync(t, 1) }
   105  func TestIterativeTrieSyncBatched(t *testing.T)    { testIterativeTrieSync(t, 100) }
   106  
   107  func testIterativeTrieSync(t *testing.T, batch int) {
   108  	// Create a random trie to copy
   109  	srcDb, srcTrie, srcData := makeTestTrie()
   110  
   111  	// Create a destination trie and sync with the scheduler
   112  	dstDb, _ := ethdb.NewMemDatabase()
   113  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   114  
   115  	queue := append([]common.Hash{}, sched.Missing(batch)...)
   116  	for len(queue) > 0 {
   117  		results := make([]SyncResult, len(queue))
   118  		for i, hash := range queue {
   119  			data, err := srcDb.Get(hash.Bytes())
   120  			if err != nil {
   121  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   122  			}
   123  			results[i] = SyncResult{hash, data}
   124  		}
   125  		if _, index, err := sched.Process(results, dstDb); err != nil {
   126  			t.Fatalf("failed to process result #%d: %v", index, err)
   127  		}
   128  		queue = append(queue[:0], sched.Missing(batch)...)
   129  	}
   130  	// Cross check that the two tries are in sync
   131  	checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
   132  }
   133  
   134  // Tests that the trie scheduler can correctly reconstruct the state even if only
   135  // partial results are returned, and the others sent only later.
   136  func TestIterativeDelayedTrieSync(t *testing.T) {
   137  	// Create a random trie to copy
   138  	srcDb, srcTrie, srcData := makeTestTrie()
   139  
   140  	// Create a destination trie and sync with the scheduler
   141  	dstDb, _ := ethdb.NewMemDatabase()
   142  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   143  
   144  	queue := append([]common.Hash{}, sched.Missing(10000)...)
   145  	for len(queue) > 0 {
   146  		// Sync only half of the scheduled nodes
   147  		results := make([]SyncResult, len(queue)/2+1)
   148  		for i, hash := range queue[:len(results)] {
   149  			data, err := srcDb.Get(hash.Bytes())
   150  			if err != nil {
   151  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   152  			}
   153  			results[i] = SyncResult{hash, data}
   154  		}
   155  		if _, index, err := sched.Process(results, dstDb); err != nil {
   156  			t.Fatalf("failed to process result #%d: %v", index, err)
   157  		}
   158  		queue = append(queue[len(results):], sched.Missing(10000)...)
   159  	}
   160  	// Cross check that the two tries are in sync
   161  	checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
   162  }
   163  
   164  // Tests that given a root hash, a trie can sync iteratively on a single thread,
   165  // requesting retrieval tasks and returning all of them in one go, however in a
   166  // random order.
   167  func TestIterativeRandomTrieSyncIndividual(t *testing.T) { testIterativeRandomTrieSync(t, 1) }
   168  func TestIterativeRandomTrieSyncBatched(t *testing.T)    { testIterativeRandomTrieSync(t, 100) }
   169  
   170  func testIterativeRandomTrieSync(t *testing.T, batch int) {
   171  	// Create a random trie to copy
   172  	srcDb, srcTrie, srcData := makeTestTrie()
   173  
   174  	// Create a destination trie and sync with the scheduler
   175  	dstDb, _ := ethdb.NewMemDatabase()
   176  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   177  
   178  	queue := make(map[common.Hash]struct{})
   179  	for _, hash := range sched.Missing(batch) {
   180  		queue[hash] = struct{}{}
   181  	}
   182  	for len(queue) > 0 {
   183  		// Fetch all the queued nodes in a random order
   184  		results := make([]SyncResult, 0, len(queue))
   185  		for hash := range queue {
   186  			data, err := srcDb.Get(hash.Bytes())
   187  			if err != nil {
   188  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   189  			}
   190  			results = append(results, SyncResult{hash, data})
   191  		}
   192  		// Feed the retrieved results back and queue new tasks
   193  		if _, index, err := sched.Process(results, dstDb); err != nil {
   194  			t.Fatalf("failed to process result #%d: %v", index, err)
   195  		}
   196  		queue = make(map[common.Hash]struct{})
   197  		for _, hash := range sched.Missing(batch) {
   198  			queue[hash] = struct{}{}
   199  		}
   200  	}
   201  	// Cross check that the two tries are in sync
   202  	checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
   203  }
   204  
   205  // Tests that the trie scheduler can correctly reconstruct the state even if only
   206  // partial results are returned (Even those randomly), others sent only later.
   207  func TestIterativeRandomDelayedTrieSync(t *testing.T) {
   208  	// Create a random trie to copy
   209  	srcDb, srcTrie, srcData := makeTestTrie()
   210  
   211  	// Create a destination trie and sync with the scheduler
   212  	dstDb, _ := ethdb.NewMemDatabase()
   213  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   214  
   215  	queue := make(map[common.Hash]struct{})
   216  	for _, hash := range sched.Missing(10000) {
   217  		queue[hash] = struct{}{}
   218  	}
   219  	for len(queue) > 0 {
   220  		// Sync only half of the scheduled nodes, even those in random order
   221  		results := make([]SyncResult, 0, len(queue)/2+1)
   222  		for hash := range queue {
   223  			data, err := srcDb.Get(hash.Bytes())
   224  			if err != nil {
   225  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   226  			}
   227  			results = append(results, SyncResult{hash, data})
   228  
   229  			if len(results) >= cap(results) {
   230  				break
   231  			}
   232  		}
   233  		// Feed the retrieved results back and queue new tasks
   234  		if _, index, err := sched.Process(results, dstDb); err != nil {
   235  			t.Fatalf("failed to process result #%d: %v", index, err)
   236  		}
   237  		for _, result := range results {
   238  			delete(queue, result.Hash)
   239  		}
   240  		for _, hash := range sched.Missing(10000) {
   241  			queue[hash] = struct{}{}
   242  		}
   243  	}
   244  	// Cross check that the two tries are in sync
   245  	checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
   246  }
   247  
   248  // Tests that a trie sync will not request nodes multiple times, even if they
   249  // have such references.
   250  func TestDuplicateAvoidanceTrieSync(t *testing.T) {
   251  	// Create a random trie to copy
   252  	srcDb, srcTrie, srcData := makeTestTrie()
   253  
   254  	// Create a destination trie and sync with the scheduler
   255  	dstDb, _ := ethdb.NewMemDatabase()
   256  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   257  
   258  	queue := append([]common.Hash{}, sched.Missing(0)...)
   259  	requested := make(map[common.Hash]struct{})
   260  
   261  	for len(queue) > 0 {
   262  		results := make([]SyncResult, len(queue))
   263  		for i, hash := range queue {
   264  			data, err := srcDb.Get(hash.Bytes())
   265  			if err != nil {
   266  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   267  			}
   268  			if _, ok := requested[hash]; ok {
   269  				t.Errorf("hash %x already requested once", hash)
   270  			}
   271  			requested[hash] = struct{}{}
   272  
   273  			results[i] = SyncResult{hash, data}
   274  		}
   275  		if _, index, err := sched.Process(results, dstDb); err != nil {
   276  			t.Fatalf("failed to process result #%d: %v", index, err)
   277  		}
   278  		queue = append(queue[:0], sched.Missing(0)...)
   279  	}
   280  	// Cross check that the two tries are in sync
   281  	checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
   282  }
   283  
   284  // Tests that at any point in time during a sync, only complete sub-tries are in
   285  // the database.
   286  func TestIncompleteTrieSync(t *testing.T) {
   287  	// Create a random trie to copy
   288  	srcDb, srcTrie, _ := makeTestTrie()
   289  
   290  	// Create a destination trie and sync with the scheduler
   291  	dstDb, _ := ethdb.NewMemDatabase()
   292  	sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
   293  
   294  	added := []common.Hash{}
   295  	queue := append([]common.Hash{}, sched.Missing(1)...)
   296  	for len(queue) > 0 {
   297  		// Fetch a batch of trie nodes
   298  		results := make([]SyncResult, len(queue))
   299  		for i, hash := range queue {
   300  			data, err := srcDb.Get(hash.Bytes())
   301  			if err != nil {
   302  				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
   303  			}
   304  			results[i] = SyncResult{hash, data}
   305  		}
   306  		// Process each of the trie nodes
   307  		if _, index, err := sched.Process(results, dstDb); err != nil {
   308  			t.Fatalf("failed to process result #%d: %v", index, err)
   309  		}
   310  		for _, result := range results {
   311  			added = append(added, result.Hash)
   312  		}
   313  		// Check that all known sub-tries in the synced trie is complete
   314  		for _, root := range added {
   315  			if err := checkTrieConsistency(dstDb, root); err != nil {
   316  				t.Fatalf("trie inconsistent: %v", err)
   317  			}
   318  		}
   319  		// Fetch the next batch to retrieve
   320  		queue = append(queue[:0], sched.Missing(1)...)
   321  	}
   322  	// Sanity check that removing any node from the database is detected
   323  	for _, node := range added[1:] {
   324  		key := node.Bytes()
   325  		value, _ := dstDb.Get(key)
   326  
   327  		dstDb.Delete(key)
   328  		if err := checkTrieConsistency(dstDb, added[0]); err == nil {
   329  			t.Fatalf("trie inconsistency not caught, missing: %x", key)
   330  		}
   331  		dstDb.Put(key, value)
   332  	}
   333  }