github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/core/state/sync_test.go (about) 1 // Copyright 2015 The Spectrum Authors 2 // This file is part of the Spectrum library. 3 // 4 // The Spectrum 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 Spectrum 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 Spectrum 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/SmartMeshFoundation/Spectrum/common" 25 "github.com/SmartMeshFoundation/Spectrum/crypto" 26 "github.com/SmartMeshFoundation/Spectrum/ethdb" 27 "github.com/SmartMeshFoundation/Spectrum/trie" 28 ) 29 30 // testAccount is the data associated with an account used by the state tests. 31 type testAccount struct { 32 address common.Address 33 balance *big.Int 34 nonce uint64 35 code []byte 36 } 37 38 // 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 mem, _ := ethdb.NewMemDatabase() 42 db := NewDatabase(mem) 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.CommitTo(mem, false) 65 66 // Return the generated state 67 return db, mem, 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, 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 db, _ := ethdb.NewMemDatabase() 129 if req := NewStateSync(empty, db).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 _, srcMem, srcRoot, srcAccounts := makeTestState() 142 143 // Create a destination state and sync with the scheduler 144 dstDb, _ := ethdb.NewMemDatabase() 145 sched := NewStateSync(srcRoot, 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 := srcMem.Get(hash.Bytes()) 152 if err != nil { 153 t.Fatalf("failed to retrieve node data for %x: %v", hash, err) 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 _, srcMem, srcRoot, srcAccounts := makeTestState() 174 175 // Create a destination state and sync with the scheduler 176 dstDb, _ := ethdb.NewMemDatabase() 177 sched := NewStateSync(srcRoot, 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 := srcMem.Get(hash.Bytes()) 185 if err != nil { 186 t.Fatalf("failed to retrieve node data for %x: %v", hash, err) 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 _, srcMem, srcRoot, srcAccounts := makeTestState() 211 212 // Create a destination state and sync with the scheduler 213 dstDb, _ := ethdb.NewMemDatabase() 214 sched := NewStateSync(srcRoot, 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 := srcMem.Get(hash.Bytes()) 225 if err != nil { 226 t.Fatalf("failed to retrieve node data for %x: %v", hash, err) 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 _, srcMem, srcRoot, srcAccounts := makeTestState() 251 252 // Create a destination state and sync with the scheduler 253 dstDb, _ := ethdb.NewMemDatabase() 254 sched := NewStateSync(srcRoot, 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 := srcMem.Get(hash.Bytes()) 267 if err != nil { 268 t.Fatalf("failed to retrieve node data for %x: %v", hash, err) 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 _, srcMem, srcRoot, srcAccounts := makeTestState() 296 297 checkTrieConsistency(srcMem, srcRoot) 298 299 // Create a destination state and sync with the scheduler 300 dstDb, _ := ethdb.NewMemDatabase() 301 sched := NewStateSync(srcRoot, 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 := srcMem.Get(hash.Bytes()) 310 if err != nil { 311 t.Fatalf("failed to retrieve node data for %x: %v", hash, err) 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 }