sync_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/ethdb"
  23. "github.com/ethereum/go-ethereum/trie"
  24. )
  25. // testAccount is the data associated with an account used by the state tests.
  26. type testAccount struct {
  27. address common.Address
  28. balance *big.Int
  29. nonce uint64
  30. code []byte
  31. }
  32. // makeTestState create a sample test state to test node-wise reconstruction.
  33. func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
  34. // Create an empty state
  35. db, _ := ethdb.NewMemDatabase()
  36. state, _ := New(common.Hash{}, db)
  37. // Fill it with some arbitrary data
  38. accounts := []*testAccount{}
  39. for i := byte(0); i < 255; i++ {
  40. obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  41. acc := &testAccount{address: common.BytesToAddress([]byte{i})}
  42. obj.AddBalance(big.NewInt(int64(11 * i)))
  43. acc.balance = big.NewInt(int64(11 * i))
  44. obj.SetNonce(uint64(42 * i))
  45. acc.nonce = uint64(42 * i)
  46. if i%3 == 0 {
  47. obj.SetCode([]byte{i, i, i, i, i})
  48. acc.code = []byte{i, i, i, i, i}
  49. }
  50. state.UpdateStateObject(obj)
  51. accounts = append(accounts, acc)
  52. }
  53. root, _ := state.Commit()
  54. // Return the generated state
  55. return db, root, accounts
  56. }
  57. // checkStateAccounts cross references a reconstructed state with an expected
  58. // account array.
  59. func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
  60. state, _ := New(root, db)
  61. for i, acc := range accounts {
  62. if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
  63. t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
  64. }
  65. if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
  66. t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
  67. }
  68. if code := state.GetCode(acc.address); bytes.Compare(code, acc.code) != 0 {
  69. t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
  70. }
  71. }
  72. }
  73. // Tests that an empty state is not scheduled for syncing.
  74. func TestEmptyStateSync(t *testing.T) {
  75. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  76. db, _ := ethdb.NewMemDatabase()
  77. if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
  78. t.Errorf("content requested for empty state: %v", req)
  79. }
  80. }
  81. // Tests that given a root hash, a state can sync iteratively on a single thread,
  82. // requesting retrieval tasks and returning all of them in one go.
  83. func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
  84. func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }
  85. func testIterativeStateSync(t *testing.T, batch int) {
  86. // Create a random state to copy
  87. srcDb, srcRoot, srcAccounts := makeTestState()
  88. // Create a destination state and sync with the scheduler
  89. dstDb, _ := ethdb.NewMemDatabase()
  90. sched := NewStateSync(srcRoot, dstDb)
  91. queue := append([]common.Hash{}, sched.Missing(batch)...)
  92. for len(queue) > 0 {
  93. results := make([]trie.SyncResult, len(queue))
  94. for i, hash := range queue {
  95. data, err := srcDb.Get(hash.Bytes())
  96. if err != nil {
  97. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  98. }
  99. results[i] = trie.SyncResult{hash, data}
  100. }
  101. if index, err := sched.Process(results); err != nil {
  102. t.Fatalf("failed to process result #%d: %v", index, err)
  103. }
  104. queue = append(queue[:0], sched.Missing(batch)...)
  105. }
  106. // Cross check that the two states are in sync
  107. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  108. }
  109. // Tests that the trie scheduler can correctly reconstruct the state even if only
  110. // partial results are returned, and the others sent only later.
  111. func TestIterativeDelayedStateSync(t *testing.T) {
  112. // Create a random state to copy
  113. srcDb, srcRoot, srcAccounts := makeTestState()
  114. // Create a destination state and sync with the scheduler
  115. dstDb, _ := ethdb.NewMemDatabase()
  116. sched := NewStateSync(srcRoot, dstDb)
  117. queue := append([]common.Hash{}, sched.Missing(0)...)
  118. for len(queue) > 0 {
  119. // Sync only half of the scheduled nodes
  120. results := make([]trie.SyncResult, len(queue)/2+1)
  121. for i, hash := range queue[:len(results)] {
  122. data, err := srcDb.Get(hash.Bytes())
  123. if err != nil {
  124. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  125. }
  126. results[i] = trie.SyncResult{hash, data}
  127. }
  128. if index, err := sched.Process(results); err != nil {
  129. t.Fatalf("failed to process result #%d: %v", index, err)
  130. }
  131. queue = append(queue[len(results):], sched.Missing(0)...)
  132. }
  133. // Cross check that the two states are in sync
  134. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  135. }
  136. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  137. // requesting retrieval tasks and returning all of them in one go, however in a
  138. // random order.
  139. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  140. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  141. func testIterativeRandomStateSync(t *testing.T, batch int) {
  142. // Create a random state to copy
  143. srcDb, srcRoot, srcAccounts := makeTestState()
  144. // Create a destination state and sync with the scheduler
  145. dstDb, _ := ethdb.NewMemDatabase()
  146. sched := NewStateSync(srcRoot, dstDb)
  147. queue := make(map[common.Hash]struct{})
  148. for _, hash := range sched.Missing(batch) {
  149. queue[hash] = struct{}{}
  150. }
  151. for len(queue) > 0 {
  152. // Fetch all the queued nodes in a random order
  153. results := make([]trie.SyncResult, 0, len(queue))
  154. for hash, _ := range queue {
  155. data, err := srcDb.Get(hash.Bytes())
  156. if err != nil {
  157. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  158. }
  159. results = append(results, trie.SyncResult{hash, data})
  160. }
  161. // Feed the retrieved results back and queue new tasks
  162. if index, err := sched.Process(results); err != nil {
  163. t.Fatalf("failed to process result #%d: %v", index, err)
  164. }
  165. queue = make(map[common.Hash]struct{})
  166. for _, hash := range sched.Missing(batch) {
  167. queue[hash] = struct{}{}
  168. }
  169. }
  170. // Cross check that the two states are in sync
  171. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  172. }
  173. // Tests that the trie scheduler can correctly reconstruct the state even if only
  174. // partial results are returned (Even those randomly), others sent only later.
  175. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  176. // Create a random state to copy
  177. srcDb, srcRoot, srcAccounts := makeTestState()
  178. // Create a destination state and sync with the scheduler
  179. dstDb, _ := ethdb.NewMemDatabase()
  180. sched := NewStateSync(srcRoot, dstDb)
  181. queue := make(map[common.Hash]struct{})
  182. for _, hash := range sched.Missing(0) {
  183. queue[hash] = struct{}{}
  184. }
  185. for len(queue) > 0 {
  186. // Sync only half of the scheduled nodes, even those in random order
  187. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  188. for hash, _ := range queue {
  189. delete(queue, hash)
  190. data, err := srcDb.Get(hash.Bytes())
  191. if err != nil {
  192. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  193. }
  194. results = append(results, trie.SyncResult{hash, data})
  195. if len(results) >= cap(results) {
  196. break
  197. }
  198. }
  199. // Feed the retrieved results back and queue new tasks
  200. if index, err := sched.Process(results); err != nil {
  201. t.Fatalf("failed to process result #%d: %v", index, err)
  202. }
  203. for _, hash := range sched.Missing(0) {
  204. queue[hash] = struct{}{}
  205. }
  206. }
  207. // Cross check that the two states are in sync
  208. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  209. }