sync_test.go 12 KB

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