sync_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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()
  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.Compare(code, acc.code) != 0 {
  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. queue = append(queue[:0], sched.Missing(batch)...)
  128. }
  129. // Cross check that the two states are in sync
  130. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  131. }
  132. // Tests that the trie scheduler can correctly reconstruct the state even if only
  133. // partial results are returned, and the others sent only later.
  134. func TestIterativeDelayedStateSync(t *testing.T) {
  135. // Create a random state to copy
  136. srcDb, srcRoot, srcAccounts := makeTestState()
  137. // Create a destination state and sync with the scheduler
  138. dstDb, _ := ethdb.NewMemDatabase()
  139. sched := NewStateSync(srcRoot, dstDb)
  140. queue := append([]common.Hash{}, sched.Missing(0)...)
  141. for len(queue) > 0 {
  142. // Sync only half of the scheduled nodes
  143. results := make([]trie.SyncResult, len(queue)/2+1)
  144. for i, hash := range queue[:len(results)] {
  145. data, err := srcDb.Get(hash.Bytes())
  146. if err != nil {
  147. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  148. }
  149. results[i] = trie.SyncResult{Hash: hash, Data: data}
  150. }
  151. if index, err := sched.Process(results); err != nil {
  152. t.Fatalf("failed to process result #%d: %v", index, err)
  153. }
  154. queue = append(queue[len(results):], sched.Missing(0)...)
  155. }
  156. // Cross check that the two states are in sync
  157. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  158. }
  159. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  160. // requesting retrieval tasks and returning all of them in one go, however in a
  161. // random order.
  162. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  163. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  164. func testIterativeRandomStateSync(t *testing.T, batch int) {
  165. // Create a random state to copy
  166. srcDb, srcRoot, srcAccounts := makeTestState()
  167. // Create a destination state and sync with the scheduler
  168. dstDb, _ := ethdb.NewMemDatabase()
  169. sched := NewStateSync(srcRoot, dstDb)
  170. queue := make(map[common.Hash]struct{})
  171. for _, hash := range sched.Missing(batch) {
  172. queue[hash] = struct{}{}
  173. }
  174. for len(queue) > 0 {
  175. // Fetch all the queued nodes in a random order
  176. results := make([]trie.SyncResult, 0, len(queue))
  177. for hash, _ := range queue {
  178. data, err := srcDb.Get(hash.Bytes())
  179. if err != nil {
  180. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  181. }
  182. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  183. }
  184. // Feed the retrieved results back and queue new tasks
  185. if index, err := sched.Process(results); err != nil {
  186. t.Fatalf("failed to process result #%d: %v", index, err)
  187. }
  188. queue = make(map[common.Hash]struct{})
  189. for _, hash := range sched.Missing(batch) {
  190. queue[hash] = struct{}{}
  191. }
  192. }
  193. // Cross check that the two states are in sync
  194. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  195. }
  196. // Tests that the trie scheduler can correctly reconstruct the state even if only
  197. // partial results are returned (Even those randomly), others sent only later.
  198. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  199. // Create a random state to copy
  200. srcDb, srcRoot, srcAccounts := makeTestState()
  201. // Create a destination state and sync with the scheduler
  202. dstDb, _ := ethdb.NewMemDatabase()
  203. sched := NewStateSync(srcRoot, dstDb)
  204. queue := make(map[common.Hash]struct{})
  205. for _, hash := range sched.Missing(0) {
  206. queue[hash] = struct{}{}
  207. }
  208. for len(queue) > 0 {
  209. // Sync only half of the scheduled nodes, even those in random order
  210. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  211. for hash, _ := range queue {
  212. delete(queue, hash)
  213. data, err := srcDb.Get(hash.Bytes())
  214. if err != nil {
  215. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  216. }
  217. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  218. if len(results) >= cap(results) {
  219. break
  220. }
  221. }
  222. // Feed the retrieved results back and queue new tasks
  223. if index, err := sched.Process(results); err != nil {
  224. t.Fatalf("failed to process result #%d: %v", index, err)
  225. }
  226. for _, hash := range sched.Missing(0) {
  227. queue[hash] = struct{}{}
  228. }
  229. }
  230. // Cross check that the two states are in sync
  231. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  232. }
  233. // Tests that at any point in time during a sync, only complete sub-tries are in
  234. // the database.
  235. func TestIncompleteStateSync(t *testing.T) {
  236. // Create a random state to copy
  237. srcDb, srcRoot, srcAccounts := makeTestState()
  238. // Create a destination state and sync with the scheduler
  239. dstDb, _ := ethdb.NewMemDatabase()
  240. sched := NewStateSync(srcRoot, dstDb)
  241. added := []common.Hash{}
  242. queue := append([]common.Hash{}, sched.Missing(1)...)
  243. for len(queue) > 0 {
  244. // Fetch a batch of state nodes
  245. results := make([]trie.SyncResult, len(queue))
  246. for i, hash := range queue {
  247. data, err := srcDb.Get(hash.Bytes())
  248. if err != nil {
  249. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  250. }
  251. results[i] = trie.SyncResult{Hash: hash, Data: data}
  252. }
  253. // Process each of the state nodes
  254. if index, err := sched.Process(results); err != nil {
  255. t.Fatalf("failed to process result #%d: %v", index, err)
  256. }
  257. for _, result := range results {
  258. added = append(added, result.Hash)
  259. }
  260. // Check that all known sub-tries in the synced state is complete
  261. for _, root := range added {
  262. // Skim through the accounts and make sure the root hash is not a code node
  263. codeHash := false
  264. for _, acc := range srcAccounts {
  265. if bytes.Compare(root.Bytes(), crypto.Sha3(acc.code)) == 0 {
  266. codeHash = true
  267. break
  268. }
  269. }
  270. // If the root is a real trie node, check consistency
  271. if !codeHash {
  272. if err := checkStateConsistency(dstDb, root); err != nil {
  273. t.Fatalf("state inconsistent: %v", err)
  274. }
  275. }
  276. }
  277. // Fetch the next batch to retrieve
  278. queue = append(queue[:0], sched.Missing(1)...)
  279. }
  280. // Sanity check that removing any node from the database is detected
  281. for _, node := range added[1:] {
  282. key := node.Bytes()
  283. value, _ := dstDb.Get(key)
  284. dstDb.Delete(key)
  285. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  286. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  287. }
  288. dstDb.Put(key, value)
  289. }
  290. }