sync_test.go 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package state

import (
	"bytes"
	"math/big"
	"testing"

	"github.com/ethereum/go-ethereum/common"
25
	"github.com/ethereum/go-ethereum/crypto"
26 27 28 29 30 31 32 33 34 35 36 37 38
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/trie"
)

// testAccount is the data associated with an account used by the state tests.
type testAccount struct {
	address common.Address
	balance *big.Int
	nonce   uint64
	code    []byte
}

// makeTestState create a sample test state to test node-wise reconstruction.
39
func makeTestState() (Database, *ethdb.MemDatabase, common.Hash, []*testAccount) {
40
	// Create an empty state
41 42
	mem, _ := ethdb.NewMemDatabase()
	db := NewDatabase(mem)
43
	state, _ := New(common.Hash{}, db)
44 45 46

	// Fill it with some arbitrary data
	accounts := []*testAccount{}
47
	for i := byte(0); i < 96; i++ {
48 49 50 51 52 53 54 55 56 57
		obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
		acc := &testAccount{address: common.BytesToAddress([]byte{i})}

		obj.AddBalance(big.NewInt(int64(11 * i)))
		acc.balance = big.NewInt(int64(11 * i))

		obj.SetNonce(uint64(42 * i))
		acc.nonce = uint64(42 * i)

		if i%3 == 0 {
58
			obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
59 60
			acc.code = []byte{i, i, i, i, i}
		}
61
		state.updateStateObject(obj)
62 63
		accounts = append(accounts, acc)
	}
64
	root, _ := state.CommitTo(mem, false)
65 66

	// Return the generated state
67
	return db, mem, root, accounts
68 69 70 71 72
}

// checkStateAccounts cross references a reconstructed state with an expected
// account array.
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 76 77 78 79 80 81
	if err != nil {
		t.Fatalf("failed to create state trie at %x: %v", root, err)
	}
	if err := checkStateConsistency(db, root); err != nil {
		t.Fatalf("inconsistent state trie at %x: %v", root, err)
	}
	for i, acc := range accounts {
82 83 84 85 86 87
		if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
			t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
		}
		if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
			t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
		}
88
		if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
89 90 91 92 93
			t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
		}
	}
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
// checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
	if v, _ := db.Get(root[:]); v == nil {
		return nil // Consider a non existent state consistent.
	}
	trie, err := trie.New(root, db)
	if err != nil {
		return err
	}
	it := trie.NodeIterator(nil)
	for it.Next(true) {
	}
	return it.Error()
}

// checkStateConsistency checks that all data of a state root is present.
110
func checkStateConsistency(db ethdb.Database, root common.Hash) error {
111 112
	// Create and iterate a state trie rooted in a sub-node
	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 120
	it := NewNodeIterator(state)
	for it.Next() {
121
	}
122
	return it.Error
123 124
}

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
// Tests that an empty state is not scheduled for syncing.
func TestEmptyStateSync(t *testing.T) {
	empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
	db, _ := ethdb.NewMemDatabase()
	if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
		t.Errorf("content requested for empty state: %v", req)
	}
}

// Tests that given a root hash, a state can sync iteratively on a single thread,
// requesting retrieval tasks and returning all of them in one go.
func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
func TestIterativeStateSyncBatched(t *testing.T)    { testIterativeStateSync(t, 100) }

func testIterativeStateSync(t *testing.T, batch int) {
	// Create a random state to copy
141
	_, srcMem, srcRoot, srcAccounts := makeTestState()
142 143 144 145 146 147 148 149 150

	// Create a destination state and sync with the scheduler
	dstDb, _ := ethdb.NewMemDatabase()
	sched := NewStateSync(srcRoot, dstDb)

	queue := append([]common.Hash{}, sched.Missing(batch)...)
	for len(queue) > 0 {
		results := make([]trie.SyncResult, len(queue))
		for i, hash := range queue {
151
			data, err := srcMem.Get(hash.Bytes())
152 153 154
			if err != nil {
				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
			}
Felix Lange's avatar
Felix Lange committed
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 161 162
		if index, err := sched.Commit(dstDb); err != nil {
			t.Fatalf("failed to commit data #%d: %v", index, err)
		}
163 164 165 166 167 168 169 170 171 172
		queue = append(queue[:0], sched.Missing(batch)...)
	}
	// Cross check that the two states are in sync
	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
}

// Tests that the trie scheduler can correctly reconstruct the state even if only
// partial results are returned, and the others sent only later.
func TestIterativeDelayedStateSync(t *testing.T) {
	// Create a random state to copy
173
	_, srcMem, srcRoot, srcAccounts := makeTestState()
174 175 176 177 178 179 180 181 182 183

	// Create a destination state and sync with the scheduler
	dstDb, _ := ethdb.NewMemDatabase()
	sched := NewStateSync(srcRoot, dstDb)

	queue := append([]common.Hash{}, sched.Missing(0)...)
	for len(queue) > 0 {
		// Sync only half of the scheduled nodes
		results := make([]trie.SyncResult, len(queue)/2+1)
		for i, hash := range queue[:len(results)] {
184
			data, err := srcMem.Get(hash.Bytes())
185 186 187
			if err != nil {
				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
			}
Felix Lange's avatar
Felix Lange committed
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 194 195
		if index, err := sched.Commit(dstDb); err != nil {
			t.Fatalf("failed to commit data #%d: %v", index, err)
		}
196 197 198 199 200 201 202 203 204 205 206 207 208 209
		queue = append(queue[len(results):], sched.Missing(0)...)
	}
	// Cross check that the two states are in sync
	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
}

// Tests that given a root hash, a trie can sync iteratively on a single thread,
// requesting retrieval tasks and returning all of them in one go, however in a
// random order.
func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
func TestIterativeRandomStateSyncBatched(t *testing.T)    { testIterativeRandomStateSync(t, 100) }

func testIterativeRandomStateSync(t *testing.T, batch int) {
	// Create a random state to copy
210
	_, srcMem, srcRoot, srcAccounts := makeTestState()
211 212 213 214 215 216 217 218 219 220 221 222

	// Create a destination state and sync with the scheduler
	dstDb, _ := ethdb.NewMemDatabase()
	sched := NewStateSync(srcRoot, dstDb)

	queue := make(map[common.Hash]struct{})
	for _, hash := range sched.Missing(batch) {
		queue[hash] = struct{}{}
	}
	for len(queue) > 0 {
		// Fetch all the queued nodes in a random order
		results := make([]trie.SyncResult, 0, len(queue))
Felix Lange's avatar
Felix Lange committed
223
		for hash := range queue {
224
			data, err := srcMem.Get(hash.Bytes())
225 226 227
			if err != nil {
				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
			}
Felix Lange's avatar
Felix Lange committed
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 235 236
		if index, err := sched.Commit(dstDb); err != nil {
			t.Fatalf("failed to commit data #%d: %v", index, err)
		}
237 238 239 240 241 242 243 244 245 246 247 248 249
		queue = make(map[common.Hash]struct{})
		for _, hash := range sched.Missing(batch) {
			queue[hash] = struct{}{}
		}
	}
	// Cross check that the two states are in sync
	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
}

// Tests that the trie scheduler can correctly reconstruct the state even if only
// partial results are returned (Even those randomly), others sent only later.
func TestIterativeRandomDelayedStateSync(t *testing.T) {
	// Create a random state to copy
250
	_, srcMem, srcRoot, srcAccounts := makeTestState()
251 252 253 254 255 256 257 258 259 260 261 262

	// Create a destination state and sync with the scheduler
	dstDb, _ := ethdb.NewMemDatabase()
	sched := NewStateSync(srcRoot, dstDb)

	queue := make(map[common.Hash]struct{})
	for _, hash := range sched.Missing(0) {
		queue[hash] = struct{}{}
	}
	for len(queue) > 0 {
		// Sync only half of the scheduled nodes, even those in random order
		results := make([]trie.SyncResult, 0, len(queue)/2+1)
Felix Lange's avatar
Felix Lange committed
263
		for hash := range queue {
264 265
			delete(queue, hash)

266
			data, err := srcMem.Get(hash.Bytes())
267 268 269
			if err != nil {
				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
			}
Felix Lange's avatar
Felix Lange committed
270
			results = append(results, trie.SyncResult{Hash: hash, Data: data})
271 272 273 274 275 276

			if len(results) >= cap(results) {
				break
			}
		}
		// 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 281 282
		if index, err := sched.Commit(dstDb); err != nil {
			t.Fatalf("failed to commit data #%d: %v", index, err)
		}
283 284 285 286 287 288 289
		for _, hash := range sched.Missing(0) {
			queue[hash] = struct{}{}
		}
	}
	// Cross check that the two states are in sync
	checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
}
290 291 292 293 294

// Tests that at any point in time during a sync, only complete sub-tries are in
// the database.
func TestIncompleteStateSync(t *testing.T) {
	// Create a random state to copy
295 296 297
	_, srcMem, srcRoot, srcAccounts := makeTestState()

	checkTrieConsistency(srcMem, srcRoot)
298 299 300 301 302 303 304 305 306 307 308

	// Create a destination state and sync with the scheduler
	dstDb, _ := ethdb.NewMemDatabase()
	sched := NewStateSync(srcRoot, dstDb)

	added := []common.Hash{}
	queue := append([]common.Hash{}, sched.Missing(1)...)
	for len(queue) > 0 {
		// Fetch a batch of state nodes
		results := make([]trie.SyncResult, len(queue))
		for i, hash := range queue {
309
			data, err := srcMem.Get(hash.Bytes())
310 311 312
			if err != nil {
				t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
			}
Felix Lange's avatar
Felix Lange committed
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 318
			t.Fatalf("failed to process result #%d: %v", index, err)
		}
319 320 321
		if index, err := sched.Commit(dstDb); err != nil {
			t.Fatalf("failed to commit data #%d: %v", index, err)
		}
322 323 324
		for _, result := range results {
			added = append(added, result.Hash)
		}
325 326 327
		// Check that all known sub-tries added so far are complete or missing entirely.
	checkSubtries:
		for _, hash := range added {
328
			for _, acc := range srcAccounts {
329 330
				if hash == crypto.Keccak256Hash(acc.code) {
					continue checkSubtries // skip trie check of code nodes.
331 332
				}
			}
333 334 335 336
			// Can't use checkStateConsistency here because subtrie keys may have odd
			// length and crash in LeafKey.
			if err := checkTrieConsistency(dstDb, hash); err != nil {
				t.Fatalf("state inconsistent: %v", err)
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
			}
		}
		// Fetch the next batch to retrieve
		queue = append(queue[:0], sched.Missing(1)...)
	}
	// Sanity check that removing any node from the database is detected
	for _, node := range added[1:] {
		key := node.Bytes()
		value, _ := dstDb.Get(key)

		dstDb.Delete(key)
		if err := checkStateConsistency(dstDb, added[0]); err == nil {
			t.Fatalf("trie inconsistency not caught, missing: %x", key)
		}
		dstDb.Put(key, value)
	}
}