sync_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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() (ethdb.Database, common.Hash, []*testAccount) {
  35. // Create an empty state
  36. db, _ := 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, 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. // checkStateConsistency checks that all nodes in a state trie are indeed present.
  82. func checkStateConsistency(db ethdb.Database, root common.Hash) error {
  83. // Create and iterate a state trie rooted in a sub-node
  84. if _, err := db.Get(root.Bytes()); err != nil {
  85. return nil // Consider a non existent state consistent
  86. }
  87. state, err := New(root, db)
  88. if err != nil {
  89. return err
  90. }
  91. it := NewNodeIterator(state)
  92. for it.Next() {
  93. }
  94. return it.Error
  95. }
  96. // Tests that an empty state is not scheduled for syncing.
  97. func TestEmptyStateSync(t *testing.T) {
  98. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  99. db, _ := ethdb.NewMemDatabase()
  100. if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
  101. t.Errorf("content requested for empty state: %v", req)
  102. }
  103. }
  104. // Tests that given a root hash, a state can sync iteratively on a single thread,
  105. // requesting retrieval tasks and returning all of them in one go.
  106. func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
  107. func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }
  108. func testIterativeStateSync(t *testing.T, batch int) {
  109. // Create a random state to copy
  110. srcDb, srcRoot, srcAccounts := makeTestState()
  111. // Create a destination state and sync with the scheduler
  112. dstDb, _ := ethdb.NewMemDatabase()
  113. sched := NewStateSync(srcRoot, dstDb)
  114. queue := append([]common.Hash{}, sched.Missing(batch)...)
  115. for len(queue) > 0 {
  116. results := make([]trie.SyncResult, len(queue))
  117. for i, hash := range queue {
  118. data, err := srcDb.Get(hash.Bytes())
  119. if err != nil {
  120. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  121. }
  122. results[i] = trie.SyncResult{Hash: hash, Data: data}
  123. }
  124. if _, index, err := sched.Process(results); err != nil {
  125. t.Fatalf("failed to process result #%d: %v", index, err)
  126. }
  127. if index, err := sched.Commit(dstDb); err != nil {
  128. t.Fatalf("failed to commit data #%d: %v", index, err)
  129. }
  130. queue = append(queue[:0], sched.Missing(batch)...)
  131. }
  132. // Cross check that the two states are in sync
  133. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  134. }
  135. // Tests that the trie scheduler can correctly reconstruct the state even if only
  136. // partial results are returned, and the others sent only later.
  137. func TestIterativeDelayedStateSync(t *testing.T) {
  138. // Create a random state to copy
  139. srcDb, srcRoot, srcAccounts := makeTestState()
  140. // Create a destination state and sync with the scheduler
  141. dstDb, _ := ethdb.NewMemDatabase()
  142. sched := NewStateSync(srcRoot, dstDb)
  143. queue := append([]common.Hash{}, sched.Missing(0)...)
  144. for len(queue) > 0 {
  145. // Sync only half of the scheduled nodes
  146. results := make([]trie.SyncResult, len(queue)/2+1)
  147. for i, hash := range queue[:len(results)] {
  148. data, err := srcDb.Get(hash.Bytes())
  149. if err != nil {
  150. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  151. }
  152. results[i] = trie.SyncResult{Hash: hash, Data: data}
  153. }
  154. if _, index, err := sched.Process(results); err != nil {
  155. t.Fatalf("failed to process result #%d: %v", index, err)
  156. }
  157. if index, err := sched.Commit(dstDb); err != nil {
  158. t.Fatalf("failed to commit data #%d: %v", index, err)
  159. }
  160. queue = append(queue[len(results):], sched.Missing(0)...)
  161. }
  162. // Cross check that the two states are in sync
  163. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  164. }
  165. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  166. // requesting retrieval tasks and returning all of them in one go, however in a
  167. // random order.
  168. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  169. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  170. func testIterativeRandomStateSync(t *testing.T, batch int) {
  171. // Create a random state to copy
  172. srcDb, srcRoot, srcAccounts := makeTestState()
  173. // Create a destination state and sync with the scheduler
  174. dstDb, _ := ethdb.NewMemDatabase()
  175. sched := NewStateSync(srcRoot, dstDb)
  176. queue := make(map[common.Hash]struct{})
  177. for _, hash := range sched.Missing(batch) {
  178. queue[hash] = struct{}{}
  179. }
  180. for len(queue) > 0 {
  181. // Fetch all the queued nodes in a random order
  182. results := make([]trie.SyncResult, 0, len(queue))
  183. for hash := range queue {
  184. data, err := srcDb.Get(hash.Bytes())
  185. if err != nil {
  186. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  187. }
  188. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  189. }
  190. // Feed the retrieved results back and queue new tasks
  191. if _, index, err := sched.Process(results); err != nil {
  192. t.Fatalf("failed to process result #%d: %v", index, err)
  193. }
  194. if index, err := sched.Commit(dstDb); err != nil {
  195. t.Fatalf("failed to commit data #%d: %v", index, err)
  196. }
  197. queue = make(map[common.Hash]struct{})
  198. for _, hash := range sched.Missing(batch) {
  199. queue[hash] = struct{}{}
  200. }
  201. }
  202. // Cross check that the two states are in sync
  203. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  204. }
  205. // Tests that the trie scheduler can correctly reconstruct the state even if only
  206. // partial results are returned (Even those randomly), others sent only later.
  207. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  208. // Create a random state to copy
  209. srcDb, srcRoot, srcAccounts := makeTestState()
  210. // Create a destination state and sync with the scheduler
  211. dstDb, _ := ethdb.NewMemDatabase()
  212. sched := NewStateSync(srcRoot, dstDb)
  213. queue := make(map[common.Hash]struct{})
  214. for _, hash := range sched.Missing(0) {
  215. queue[hash] = struct{}{}
  216. }
  217. for len(queue) > 0 {
  218. // Sync only half of the scheduled nodes, even those in random order
  219. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  220. for hash := range queue {
  221. delete(queue, hash)
  222. data, err := srcDb.Get(hash.Bytes())
  223. if err != nil {
  224. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  225. }
  226. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  227. if len(results) >= cap(results) {
  228. break
  229. }
  230. }
  231. // Feed the retrieved results back and queue new tasks
  232. if _, index, err := sched.Process(results); err != nil {
  233. t.Fatalf("failed to process result #%d: %v", index, err)
  234. }
  235. if index, err := sched.Commit(dstDb); err != nil {
  236. t.Fatalf("failed to commit data #%d: %v", index, err)
  237. }
  238. for _, hash := range sched.Missing(0) {
  239. queue[hash] = struct{}{}
  240. }
  241. }
  242. // Cross check that the two states are in sync
  243. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  244. }
  245. // Tests that at any point in time during a sync, only complete sub-tries are in
  246. // the database.
  247. func TestIncompleteStateSync(t *testing.T) {
  248. // Create a random state to copy
  249. srcDb, srcRoot, srcAccounts := makeTestState()
  250. // Create a destination state and sync with the scheduler
  251. dstDb, _ := ethdb.NewMemDatabase()
  252. sched := NewStateSync(srcRoot, dstDb)
  253. added := []common.Hash{}
  254. queue := append([]common.Hash{}, sched.Missing(1)...)
  255. for len(queue) > 0 {
  256. // Fetch a batch of state nodes
  257. results := make([]trie.SyncResult, len(queue))
  258. for i, hash := range queue {
  259. data, err := srcDb.Get(hash.Bytes())
  260. if err != nil {
  261. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  262. }
  263. results[i] = trie.SyncResult{Hash: hash, Data: data}
  264. }
  265. // Process each of the state nodes
  266. if _, index, err := sched.Process(results); err != nil {
  267. t.Fatalf("failed to process result #%d: %v", index, err)
  268. }
  269. if index, err := sched.Commit(dstDb); err != nil {
  270. t.Fatalf("failed to commit data #%d: %v", index, err)
  271. }
  272. for _, result := range results {
  273. added = append(added, result.Hash)
  274. }
  275. // Check that all known sub-tries in the synced state is complete
  276. for _, root := range added {
  277. // Skim through the accounts and make sure the root hash is not a code node
  278. codeHash := false
  279. for _, acc := range srcAccounts {
  280. if root == crypto.Keccak256Hash(acc.code) {
  281. codeHash = true
  282. break
  283. }
  284. }
  285. // If the root is a real trie node, check consistency
  286. if !codeHash {
  287. if err := checkStateConsistency(dstDb, root); err != nil {
  288. t.Fatalf("state inconsistent: %v", err)
  289. }
  290. }
  291. }
  292. // Fetch the next batch to retrieve
  293. queue = append(queue[:0], sched.Missing(1)...)
  294. }
  295. // Sanity check that removing any node from the database is detected
  296. for _, node := range added[1:] {
  297. key := node.Bytes()
  298. value, _ := dstDb.Get(key)
  299. dstDb.Delete(key)
  300. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  301. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  302. }
  303. dstDb.Put(key, value)
  304. }
  305. }