sync_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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([]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()
  55. // Remove any potentially cached data from the test state creation
  56. trie.ClearGlobalCache()
  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. // Remove any potentially cached data from the state synchronisation
  64. trie.ClearGlobalCache()
  65. // Check root availability and state contents
  66. state, err := New(root, db)
  67. if err != nil {
  68. t.Fatalf("failed to create state trie at %x: %v", root, err)
  69. }
  70. if err := checkStateConsistency(db, root); err != nil {
  71. t.Fatalf("inconsistent state trie at %x: %v", root, err)
  72. }
  73. for i, acc := range accounts {
  74. if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
  75. t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
  76. }
  77. if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
  78. t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
  79. }
  80. if code := state.GetCode(acc.address); bytes.Compare(code, acc.code) != 0 {
  81. t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
  82. }
  83. }
  84. }
  85. // checkStateConsistency checks that all nodes in a state trie are indeed present.
  86. func checkStateConsistency(db ethdb.Database, root common.Hash) error {
  87. // Remove any potentially cached data from the test state creation or previous checks
  88. trie.ClearGlobalCache()
  89. // Create and iterate a state trie rooted in a sub-node
  90. if _, err := db.Get(root.Bytes()); err != nil {
  91. return nil // Consider a non existent state consistent
  92. }
  93. state, err := New(root, db)
  94. if err != nil {
  95. return err
  96. }
  97. it := NewNodeIterator(state)
  98. for it.Next() {
  99. }
  100. return it.Error
  101. }
  102. // Tests that an empty state is not scheduled for syncing.
  103. func TestEmptyStateSync(t *testing.T) {
  104. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  105. db, _ := ethdb.NewMemDatabase()
  106. if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
  107. t.Errorf("content requested for empty state: %v", req)
  108. }
  109. }
  110. // Tests that given a root hash, a state can sync iteratively on a single thread,
  111. // requesting retrieval tasks and returning all of them in one go.
  112. func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
  113. func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }
  114. func testIterativeStateSync(t *testing.T, batch int) {
  115. // Create a random state to copy
  116. srcDb, srcRoot, srcAccounts := makeTestState()
  117. // Create a destination state and sync with the scheduler
  118. dstDb, _ := ethdb.NewMemDatabase()
  119. sched := NewStateSync(srcRoot, dstDb)
  120. queue := append([]common.Hash{}, sched.Missing(batch)...)
  121. for len(queue) > 0 {
  122. results := make([]trie.SyncResult, len(queue))
  123. for i, hash := range queue {
  124. data, err := srcDb.Get(hash.Bytes())
  125. if err != nil {
  126. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  127. }
  128. results[i] = trie.SyncResult{Hash: hash, Data: data}
  129. }
  130. if index, err := sched.Process(results); err != nil {
  131. t.Fatalf("failed to process result #%d: %v", index, err)
  132. }
  133. queue = append(queue[:0], sched.Missing(batch)...)
  134. }
  135. // Cross check that the two states are in sync
  136. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  137. }
  138. // Tests that the trie scheduler can correctly reconstruct the state even if only
  139. // partial results are returned, and the others sent only later.
  140. func TestIterativeDelayedStateSync(t *testing.T) {
  141. // Create a random state to copy
  142. srcDb, srcRoot, srcAccounts := makeTestState()
  143. // Create a destination state and sync with the scheduler
  144. dstDb, _ := ethdb.NewMemDatabase()
  145. sched := NewStateSync(srcRoot, dstDb)
  146. queue := append([]common.Hash{}, sched.Missing(0)...)
  147. for len(queue) > 0 {
  148. // Sync only half of the scheduled nodes
  149. results := make([]trie.SyncResult, len(queue)/2+1)
  150. for i, hash := range queue[:len(results)] {
  151. data, err := srcDb.Get(hash.Bytes())
  152. if err != nil {
  153. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  154. }
  155. results[i] = trie.SyncResult{Hash: hash, Data: data}
  156. }
  157. if index, err := sched.Process(results); err != nil {
  158. t.Fatalf("failed to process result #%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. queue = make(map[common.Hash]struct{})
  195. for _, hash := range sched.Missing(batch) {
  196. queue[hash] = struct{}{}
  197. }
  198. }
  199. // Cross check that the two states are in sync
  200. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  201. }
  202. // Tests that the trie scheduler can correctly reconstruct the state even if only
  203. // partial results are returned (Even those randomly), others sent only later.
  204. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  205. // Create a random state to copy
  206. srcDb, srcRoot, srcAccounts := makeTestState()
  207. // Create a destination state and sync with the scheduler
  208. dstDb, _ := ethdb.NewMemDatabase()
  209. sched := NewStateSync(srcRoot, dstDb)
  210. queue := make(map[common.Hash]struct{})
  211. for _, hash := range sched.Missing(0) {
  212. queue[hash] = struct{}{}
  213. }
  214. for len(queue) > 0 {
  215. // Sync only half of the scheduled nodes, even those in random order
  216. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  217. for hash, _ := range queue {
  218. delete(queue, hash)
  219. data, err := srcDb.Get(hash.Bytes())
  220. if err != nil {
  221. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  222. }
  223. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  224. if len(results) >= cap(results) {
  225. break
  226. }
  227. }
  228. // Feed the retrieved results back and queue new tasks
  229. if index, err := sched.Process(results); err != nil {
  230. t.Fatalf("failed to process result #%d: %v", index, err)
  231. }
  232. for _, hash := range sched.Missing(0) {
  233. queue[hash] = struct{}{}
  234. }
  235. }
  236. // Cross check that the two states are in sync
  237. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  238. }
  239. // Tests that at any point in time during a sync, only complete sub-tries are in
  240. // the database.
  241. func TestIncompleteStateSync(t *testing.T) {
  242. // Create a random state to copy
  243. srcDb, srcRoot, srcAccounts := makeTestState()
  244. // Create a destination state and sync with the scheduler
  245. dstDb, _ := ethdb.NewMemDatabase()
  246. sched := NewStateSync(srcRoot, dstDb)
  247. added := []common.Hash{}
  248. queue := append([]common.Hash{}, sched.Missing(1)...)
  249. for len(queue) > 0 {
  250. // Fetch a batch of state nodes
  251. results := make([]trie.SyncResult, len(queue))
  252. for i, hash := range queue {
  253. data, err := srcDb.Get(hash.Bytes())
  254. if err != nil {
  255. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  256. }
  257. results[i] = trie.SyncResult{Hash: hash, Data: data}
  258. }
  259. // Process each of the state nodes
  260. if index, err := sched.Process(results); err != nil {
  261. t.Fatalf("failed to process result #%d: %v", index, err)
  262. }
  263. for _, result := range results {
  264. added = append(added, result.Hash)
  265. }
  266. // Check that all known sub-tries in the synced state is complete
  267. for _, root := range added {
  268. // Skim through the accounts and make sure the root hash is not a code node
  269. codeHash := false
  270. for _, acc := range srcAccounts {
  271. if bytes.Compare(root.Bytes(), crypto.Sha3(acc.code)) == 0 {
  272. codeHash = true
  273. break
  274. }
  275. }
  276. // If the root is a real trie node, check consistency
  277. if !codeHash {
  278. if err := checkStateConsistency(dstDb, root); err != nil {
  279. t.Fatalf("state inconsistent: %v", err)
  280. }
  281. }
  282. }
  283. // Fetch the next batch to retrieve
  284. queue = append(queue[:0], sched.Missing(1)...)
  285. }
  286. // Sanity check that removing any node from the database is detected
  287. for _, node := range added[1:] {
  288. key := node.Bytes()
  289. value, _ := dstDb.Get(key)
  290. dstDb.Delete(key)
  291. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  292. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  293. }
  294. dstDb.Put(key, value)
  295. }
  296. }