sync_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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)
  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))
  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))
  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, batch 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(batch)...)
  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. if index, err := sched.Commit(dstDb); err != nil {
  143. t.Fatalf("failed to commit data #%d: %v", index, err)
  144. }
  145. queue = append(queue[:0], sched.Missing(batch)...)
  146. }
  147. // Cross check that the two states are in sync
  148. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  149. }
  150. // Tests that the trie scheduler can correctly reconstruct the state even if only
  151. // partial results are returned, and the others sent only later.
  152. func TestIterativeDelayedStateSync(t *testing.T) {
  153. // Create a random state to copy
  154. srcDb, srcRoot, srcAccounts := makeTestState()
  155. // Create a destination state and sync with the scheduler
  156. dstDb := rawdb.NewMemoryDatabase()
  157. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  158. queue := append([]common.Hash{}, sched.Missing(0)...)
  159. for len(queue) > 0 {
  160. // Sync only half of the scheduled nodes
  161. results := make([]trie.SyncResult, len(queue)/2+1)
  162. for i, hash := range queue[:len(results)] {
  163. data, err := srcDb.TrieDB().Node(hash)
  164. if err != nil {
  165. t.Fatalf("failed to retrieve node data for %x", hash)
  166. }
  167. results[i] = trie.SyncResult{Hash: hash, Data: data}
  168. }
  169. if _, index, err := sched.Process(results); err != nil {
  170. t.Fatalf("failed to process result #%d: %v", index, err)
  171. }
  172. if index, err := sched.Commit(dstDb); err != nil {
  173. t.Fatalf("failed to commit data #%d: %v", index, err)
  174. }
  175. queue = append(queue[len(results):], sched.Missing(0)...)
  176. }
  177. // Cross check that the two states are in sync
  178. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  179. }
  180. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  181. // requesting retrieval tasks and returning all of them in one go, however in a
  182. // random order.
  183. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  184. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  185. func testIterativeRandomStateSync(t *testing.T, batch int) {
  186. // Create a random state to copy
  187. srcDb, srcRoot, srcAccounts := makeTestState()
  188. // Create a destination state and sync with the scheduler
  189. dstDb := rawdb.NewMemoryDatabase()
  190. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  191. queue := make(map[common.Hash]struct{})
  192. for _, hash := range sched.Missing(batch) {
  193. queue[hash] = struct{}{}
  194. }
  195. for len(queue) > 0 {
  196. // Fetch all the queued nodes in a random order
  197. results := make([]trie.SyncResult, 0, len(queue))
  198. for hash := range queue {
  199. data, err := srcDb.TrieDB().Node(hash)
  200. if err != nil {
  201. t.Fatalf("failed to retrieve node data for %x", hash)
  202. }
  203. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  204. }
  205. // Feed the retrieved results back and queue new tasks
  206. if _, index, err := sched.Process(results); err != nil {
  207. t.Fatalf("failed to process result #%d: %v", index, err)
  208. }
  209. if index, err := sched.Commit(dstDb); err != nil {
  210. t.Fatalf("failed to commit data #%d: %v", index, err)
  211. }
  212. queue = make(map[common.Hash]struct{})
  213. for _, hash := range sched.Missing(batch) {
  214. queue[hash] = struct{}{}
  215. }
  216. }
  217. // Cross check that the two states are in sync
  218. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  219. }
  220. // Tests that the trie scheduler can correctly reconstruct the state even if only
  221. // partial results are returned (Even those randomly), others sent only later.
  222. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  223. // Create a random state to copy
  224. srcDb, srcRoot, srcAccounts := makeTestState()
  225. // Create a destination state and sync with the scheduler
  226. dstDb := rawdb.NewMemoryDatabase()
  227. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  228. queue := make(map[common.Hash]struct{})
  229. for _, hash := range sched.Missing(0) {
  230. queue[hash] = struct{}{}
  231. }
  232. for len(queue) > 0 {
  233. // Sync only half of the scheduled nodes, even those in random order
  234. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  235. for hash := range queue {
  236. delete(queue, hash)
  237. data, err := srcDb.TrieDB().Node(hash)
  238. if err != nil {
  239. t.Fatalf("failed to retrieve node data for %x", hash)
  240. }
  241. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  242. if len(results) >= cap(results) {
  243. break
  244. }
  245. }
  246. // Feed the retrieved results back and queue new tasks
  247. if _, index, err := sched.Process(results); err != nil {
  248. t.Fatalf("failed to process result #%d: %v", index, err)
  249. }
  250. if index, err := sched.Commit(dstDb); err != nil {
  251. t.Fatalf("failed to commit data #%d: %v", index, err)
  252. }
  253. for _, hash := range sched.Missing(0) {
  254. queue[hash] = struct{}{}
  255. }
  256. }
  257. // Cross check that the two states are in sync
  258. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  259. }
  260. // Tests that at any point in time during a sync, only complete sub-tries are in
  261. // the database.
  262. func TestIncompleteStateSync(t *testing.T) {
  263. // Create a random state to copy
  264. srcDb, srcRoot, srcAccounts := makeTestState()
  265. checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)
  266. // Create a destination state and sync with the scheduler
  267. dstDb := rawdb.NewMemoryDatabase()
  268. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  269. added := []common.Hash{}
  270. queue := append([]common.Hash{}, sched.Missing(1)...)
  271. for len(queue) > 0 {
  272. // Fetch a batch of state nodes
  273. results := make([]trie.SyncResult, len(queue))
  274. for i, hash := range queue {
  275. data, err := srcDb.TrieDB().Node(hash)
  276. if err != nil {
  277. t.Fatalf("failed to retrieve node data for %x", hash)
  278. }
  279. results[i] = trie.SyncResult{Hash: hash, Data: data}
  280. }
  281. // Process each of the state nodes
  282. if _, index, err := sched.Process(results); err != nil {
  283. t.Fatalf("failed to process result #%d: %v", index, err)
  284. }
  285. if index, err := sched.Commit(dstDb); err != nil {
  286. t.Fatalf("failed to commit data #%d: %v", index, err)
  287. }
  288. for _, result := range results {
  289. added = append(added, result.Hash)
  290. }
  291. // Check that all known sub-tries added so far are complete or missing entirely.
  292. checkSubtries:
  293. for _, hash := range added {
  294. for _, acc := range srcAccounts {
  295. if hash == crypto.Keccak256Hash(acc.code) {
  296. continue checkSubtries // skip trie check of code nodes.
  297. }
  298. }
  299. // Can't use checkStateConsistency here because subtrie keys may have odd
  300. // length and crash in LeafKey.
  301. if err := checkTrieConsistency(dstDb, hash); err != nil {
  302. t.Fatalf("state inconsistent: %v", err)
  303. }
  304. }
  305. // Fetch the next batch to retrieve
  306. queue = append(queue[:0], sched.Missing(1)...)
  307. }
  308. // Sanity check that removing any node from the database is detected
  309. for _, node := range added[1:] {
  310. key := node.Bytes()
  311. value, _ := dstDb.Get(key)
  312. dstDb.Delete(key)
  313. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  314. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  315. }
  316. dstDb.Put(key, value)
  317. }
  318. }