sync_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. "fmt"
  20. "math/big"
  21. "testing"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/trie"
  26. )
  27. // testAccount is the data associated with an account used by the state tests.
  28. type testAccount struct {
  29. address common.Address
  30. balance *big.Int
  31. nonce uint64
  32. code []byte
  33. }
  34. // makeTestState create a sample test state to test node-wise reconstruction.
  35. func makeTestState() (ethdb.Database, common.Hash, []*testAccount) {
  36. // Create an empty state
  37. db, _ := ethdb.NewMemDatabase()
  38. state, _ := New(common.Hash{}, db)
  39. // Fill it with some arbitrary data
  40. accounts := []*testAccount{}
  41. for i := byte(0); i < 96; i++ {
  42. obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  43. acc := &testAccount{address: common.BytesToAddress([]byte{i})}
  44. obj.AddBalance(big.NewInt(int64(11 * i)))
  45. acc.balance = big.NewInt(int64(11 * i))
  46. obj.SetNonce(uint64(42 * i))
  47. acc.nonce = uint64(42 * i)
  48. if i%3 == 0 {
  49. obj.SetCode([]byte{i, i, i, i, i})
  50. acc.code = []byte{i, i, i, i, i}
  51. }
  52. state.UpdateStateObject(obj)
  53. accounts = append(accounts, acc)
  54. }
  55. root, _ := state.Commit()
  56. // Remove any potentially cached data from the test state creation
  57. trie.ClearGlobalCache()
  58. // Return the generated state
  59. return db, root, accounts
  60. }
  61. // checkStateAccounts cross references a reconstructed state with an expected
  62. // account array.
  63. func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accounts []*testAccount) {
  64. // Remove any potentially cached data from the state synchronisation
  65. trie.ClearGlobalCache()
  66. // Check root availability and state contents
  67. state, err := New(root, db)
  68. if err != nil {
  69. t.Fatalf("failed to create state trie at %x: %v", root, err)
  70. }
  71. if err := checkStateConsistency(db, root); err != nil {
  72. t.Fatalf("inconsistent state trie at %x: %v", root, err)
  73. }
  74. for i, acc := range accounts {
  75. if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
  76. t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
  77. }
  78. if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
  79. t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
  80. }
  81. if code := state.GetCode(acc.address); bytes.Compare(code, acc.code) != 0 {
  82. t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
  83. }
  84. }
  85. }
  86. // checkStateConsistency checks that all nodes in a state trie and indeed present.
  87. func checkStateConsistency(db ethdb.Database, root common.Hash) (failure error) {
  88. // Capture any panics by the iterator
  89. defer func() {
  90. if r := recover(); r != nil {
  91. failure = fmt.Errorf("%v", r)
  92. }
  93. }()
  94. // Remove any potentially cached data from the test state creation or previous checks
  95. trie.ClearGlobalCache()
  96. // Create and iterate a state trie rooted in a sub-node
  97. if _, err := db.Get(root.Bytes()); err != nil {
  98. return
  99. }
  100. state, err := New(root, db)
  101. if err != nil {
  102. return
  103. }
  104. it := NewNodeIterator(state)
  105. for it.Next() {
  106. }
  107. return nil
  108. }
  109. // Tests that an empty state is not scheduled for syncing.
  110. func TestEmptyStateSync(t *testing.T) {
  111. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  112. db, _ := ethdb.NewMemDatabase()
  113. if req := NewStateSync(empty, db).Missing(1); len(req) != 0 {
  114. t.Errorf("content requested for empty state: %v", req)
  115. }
  116. }
  117. // Tests that given a root hash, a state can sync iteratively on a single thread,
  118. // requesting retrieval tasks and returning all of them in one go.
  119. func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1) }
  120. func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100) }
  121. func testIterativeStateSync(t *testing.T, batch int) {
  122. // Create a random state to copy
  123. srcDb, srcRoot, srcAccounts := makeTestState()
  124. // Create a destination state and sync with the scheduler
  125. dstDb, _ := ethdb.NewMemDatabase()
  126. sched := NewStateSync(srcRoot, dstDb)
  127. queue := append([]common.Hash{}, sched.Missing(batch)...)
  128. for len(queue) > 0 {
  129. results := make([]trie.SyncResult, len(queue))
  130. for i, hash := range queue {
  131. data, err := srcDb.Get(hash.Bytes())
  132. if err != nil {
  133. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  134. }
  135. results[i] = trie.SyncResult{hash, data}
  136. }
  137. if index, err := sched.Process(results); err != nil {
  138. t.Fatalf("failed to process result #%d: %v", index, err)
  139. }
  140. queue = append(queue[:0], sched.Missing(batch)...)
  141. }
  142. // Cross check that the two states are in sync
  143. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  144. }
  145. // Tests that the trie scheduler can correctly reconstruct the state even if only
  146. // partial results are returned, and the others sent only later.
  147. func TestIterativeDelayedStateSync(t *testing.T) {
  148. // Create a random state to copy
  149. srcDb, srcRoot, srcAccounts := makeTestState()
  150. // Create a destination state and sync with the scheduler
  151. dstDb, _ := ethdb.NewMemDatabase()
  152. sched := NewStateSync(srcRoot, dstDb)
  153. queue := append([]common.Hash{}, sched.Missing(0)...)
  154. for len(queue) > 0 {
  155. // Sync only half of the scheduled nodes
  156. results := make([]trie.SyncResult, len(queue)/2+1)
  157. for i, hash := range queue[:len(results)] {
  158. data, err := srcDb.Get(hash.Bytes())
  159. if err != nil {
  160. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  161. }
  162. results[i] = trie.SyncResult{hash, data}
  163. }
  164. if index, err := sched.Process(results); err != nil {
  165. t.Fatalf("failed to process result #%d: %v", index, err)
  166. }
  167. queue = append(queue[len(results):], sched.Missing(0)...)
  168. }
  169. // Cross check that the two states are in sync
  170. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  171. }
  172. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  173. // requesting retrieval tasks and returning all of them in one go, however in a
  174. // random order.
  175. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  176. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  177. func testIterativeRandomStateSync(t *testing.T, batch int) {
  178. // Create a random state to copy
  179. srcDb, srcRoot, srcAccounts := makeTestState()
  180. // Create a destination state and sync with the scheduler
  181. dstDb, _ := ethdb.NewMemDatabase()
  182. sched := NewStateSync(srcRoot, dstDb)
  183. queue := make(map[common.Hash]struct{})
  184. for _, hash := range sched.Missing(batch) {
  185. queue[hash] = struct{}{}
  186. }
  187. for len(queue) > 0 {
  188. // Fetch all the queued nodes in a random order
  189. results := make([]trie.SyncResult, 0, len(queue))
  190. for hash, _ := range queue {
  191. data, err := srcDb.Get(hash.Bytes())
  192. if err != nil {
  193. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  194. }
  195. results = append(results, trie.SyncResult{hash, data})
  196. }
  197. // Feed the retrieved results back and queue new tasks
  198. if index, err := sched.Process(results); err != nil {
  199. t.Fatalf("failed to process result #%d: %v", index, err)
  200. }
  201. queue = make(map[common.Hash]struct{})
  202. for _, hash := range sched.Missing(batch) {
  203. queue[hash] = struct{}{}
  204. }
  205. }
  206. // Cross check that the two states are in sync
  207. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  208. }
  209. // Tests that the trie scheduler can correctly reconstruct the state even if only
  210. // partial results are returned (Even those randomly), others sent only later.
  211. func TestIterativeRandomDelayedStateSync(t *testing.T) {
  212. // Create a random state to copy
  213. srcDb, srcRoot, srcAccounts := makeTestState()
  214. // Create a destination state and sync with the scheduler
  215. dstDb, _ := ethdb.NewMemDatabase()
  216. sched := NewStateSync(srcRoot, dstDb)
  217. queue := make(map[common.Hash]struct{})
  218. for _, hash := range sched.Missing(0) {
  219. queue[hash] = struct{}{}
  220. }
  221. for len(queue) > 0 {
  222. // Sync only half of the scheduled nodes, even those in random order
  223. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  224. for hash, _ := range queue {
  225. delete(queue, hash)
  226. data, err := srcDb.Get(hash.Bytes())
  227. if err != nil {
  228. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  229. }
  230. results = append(results, trie.SyncResult{hash, data})
  231. if len(results) >= cap(results) {
  232. break
  233. }
  234. }
  235. // Feed the retrieved results back and queue new tasks
  236. if index, err := sched.Process(results); err != nil {
  237. t.Fatalf("failed to process result #%d: %v", index, err)
  238. }
  239. for _, hash := range sched.Missing(0) {
  240. queue[hash] = struct{}{}
  241. }
  242. }
  243. // Cross check that the two states are in sync
  244. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  245. }
  246. // Tests that at any point in time during a sync, only complete sub-tries are in
  247. // the database.
  248. func TestIncompleteStateSync(t *testing.T) {
  249. // Create a random state to copy
  250. srcDb, srcRoot, srcAccounts := makeTestState()
  251. // Create a destination state and sync with the scheduler
  252. dstDb, _ := ethdb.NewMemDatabase()
  253. sched := NewStateSync(srcRoot, dstDb)
  254. added := []common.Hash{}
  255. queue := append([]common.Hash{}, sched.Missing(1)...)
  256. for len(queue) > 0 {
  257. // Fetch a batch of state nodes
  258. results := make([]trie.SyncResult, len(queue))
  259. for i, hash := range queue {
  260. data, err := srcDb.Get(hash.Bytes())
  261. if err != nil {
  262. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  263. }
  264. results[i] = trie.SyncResult{hash, data}
  265. }
  266. // Process each of the state nodes
  267. if index, err := sched.Process(results); err != nil {
  268. t.Fatalf("failed to process result #%d: %v", index, err)
  269. }
  270. for _, result := range results {
  271. added = append(added, result.Hash)
  272. }
  273. // Check that all known sub-tries in the synced state is complete
  274. for _, root := range added {
  275. // Skim through the accounts and make sure the root hash is not a code node
  276. codeHash := false
  277. for _, acc := range srcAccounts {
  278. if bytes.Compare(root.Bytes(), crypto.Sha3(acc.code)) == 0 {
  279. codeHash = true
  280. break
  281. }
  282. }
  283. // If the root is a real trie node, check consistency
  284. if !codeHash {
  285. if err := checkStateConsistency(dstDb, root); err != nil {
  286. t.Fatalf("state inconsistent: %v", err)
  287. }
  288. }
  289. }
  290. // Fetch the next batch to retrieve
  291. queue = append(queue[:0], sched.Missing(1)...)
  292. }
  293. // Sanity check that removing any node from the database is detected
  294. for _, node := range added[1:] {
  295. key := node.Bytes()
  296. value, _ := dstDb.Get(key)
  297. dstDb.Delete(key)
  298. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  299. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  300. }
  301. dstDb.Put(key, value)
  302. }
  303. }