sync_test.go 12 KB

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