sync_test.go 12 KB

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