sync_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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/core/rawdb"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  26. "github.com/ethereum/go-ethereum/trie"
  27. )
  28. // testAccount is the data associated with an account used by the state tests.
  29. type testAccount struct {
  30. address common.Address
  31. balance *big.Int
  32. nonce uint64
  33. code []byte
  34. }
  35. // makeTestState create a sample test state to test node-wise reconstruction.
  36. func makeTestState() (Database, common.Hash, []*testAccount) {
  37. // Create an empty state
  38. db := NewDatabase(rawdb.NewMemoryDatabase())
  39. state, _ := New(common.Hash{}, db, nil)
  40. // Fill it with some arbitrary data
  41. accounts := []*testAccount{}
  42. for i := byte(0); i < 96; i++ {
  43. obj := state.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  44. acc := &testAccount{address: common.BytesToAddress([]byte{i})}
  45. obj.AddBalance(big.NewInt(int64(11 * i)))
  46. acc.balance = big.NewInt(int64(11 * i))
  47. obj.SetNonce(uint64(42 * i))
  48. acc.nonce = uint64(42 * i)
  49. if i%3 == 0 {
  50. obj.SetCode(crypto.Keccak256Hash([]byte{i, i, i, i, i}), []byte{i, i, i, i, i})
  51. acc.code = []byte{i, i, i, i, i}
  52. }
  53. state.updateStateObject(obj)
  54. accounts = append(accounts, acc)
  55. }
  56. root, _ := state.Commit(false)
  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. // Check root availability and state contents
  64. state, err := New(root, NewDatabase(db), nil)
  65. if err != nil {
  66. t.Fatalf("failed to create state trie at %x: %v", root, err)
  67. }
  68. if err := checkStateConsistency(db, root); err != nil {
  69. t.Fatalf("inconsistent state trie at %x: %v", root, err)
  70. }
  71. for i, acc := range accounts {
  72. if balance := state.GetBalance(acc.address); balance.Cmp(acc.balance) != 0 {
  73. t.Errorf("account %d: balance mismatch: have %v, want %v", i, balance, acc.balance)
  74. }
  75. if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
  76. t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
  77. }
  78. if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
  79. t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
  80. }
  81. }
  82. }
  83. // checkTrieConsistency checks that all nodes in a (sub-)trie are indeed present.
  84. func checkTrieConsistency(db ethdb.Database, root common.Hash) error {
  85. if v, _ := db.Get(root[:]); v == nil {
  86. return nil // Consider a non existent state consistent.
  87. }
  88. trie, err := trie.New(root, trie.NewDatabase(db))
  89. if err != nil {
  90. return err
  91. }
  92. it := trie.NodeIterator(nil)
  93. for it.Next(true) {
  94. }
  95. return it.Error()
  96. }
  97. // checkStateConsistency checks that all data of a state root is present.
  98. func checkStateConsistency(db ethdb.Database, root common.Hash) error {
  99. // Create and iterate a state trie rooted in a sub-node
  100. if _, err := db.Get(root.Bytes()); err != nil {
  101. return nil // Consider a non existent state consistent.
  102. }
  103. state, err := New(root, NewDatabase(db), nil)
  104. if err != nil {
  105. return err
  106. }
  107. it := NewNodeIterator(state)
  108. for it.Next() {
  109. }
  110. return it.Error
  111. }
  112. // Tests that an empty state is not scheduled for syncing.
  113. func TestEmptyStateSync(t *testing.T) {
  114. empty := common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  115. if req := NewStateSync(empty, rawdb.NewMemoryDatabase(), trie.NewSyncBloom(1, memorydb.New())).Missing(1); len(req) != 0 {
  116. t.Errorf("content requested for empty state: %v", req)
  117. }
  118. }
  119. // Tests that given a root hash, a state can sync iteratively on a single thread,
  120. // requesting retrieval tasks and returning all of them in one go.
  121. func TestIterativeStateSyncIndividual(t *testing.T) { testIterativeStateSync(t, 1, false) }
  122. func TestIterativeStateSyncBatched(t *testing.T) { testIterativeStateSync(t, 100, false) }
  123. func TestIterativeStateSyncIndividualFromDisk(t *testing.T) { testIterativeStateSync(t, 1, true) }
  124. func TestIterativeStateSyncBatchedFromDisk(t *testing.T) { testIterativeStateSync(t, 100, true) }
  125. func testIterativeStateSync(t *testing.T, count int, commit bool) {
  126. // Create a random state to copy
  127. srcDb, srcRoot, srcAccounts := makeTestState()
  128. if commit {
  129. srcDb.TrieDB().Commit(srcRoot, false, nil)
  130. }
  131. // Create a destination state and sync with the scheduler
  132. dstDb := rawdb.NewMemoryDatabase()
  133. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  134. queue := append([]common.Hash{}, sched.Missing(count)...)
  135. for len(queue) > 0 {
  136. results := make([]trie.SyncResult, len(queue))
  137. for i, hash := range queue {
  138. data, err := srcDb.TrieDB().Node(hash)
  139. if err != nil {
  140. data, err = srcDb.ContractCode(common.Hash{}, hash)
  141. }
  142. if err != nil {
  143. t.Fatalf("failed to retrieve node data for %x", hash)
  144. }
  145. results[i] = trie.SyncResult{Hash: hash, Data: data}
  146. }
  147. for _, result := range results {
  148. if err := sched.Process(result); err != nil {
  149. t.Fatalf("failed to process result %v", err)
  150. }
  151. }
  152. batch := dstDb.NewBatch()
  153. if err := sched.Commit(batch); err != nil {
  154. t.Fatalf("failed to commit data: %v", err)
  155. }
  156. batch.Write()
  157. queue = append(queue[:0], sched.Missing(count)...)
  158. }
  159. // Cross check that the two states are in sync
  160. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  161. }
  162. // Tests that the trie scheduler can correctly reconstruct the state even if only
  163. // partial results are returned, and the others sent only later.
  164. func TestIterativeDelayedStateSync(t *testing.T) {
  165. // Create a random state to copy
  166. srcDb, srcRoot, srcAccounts := makeTestState()
  167. // Create a destination state and sync with the scheduler
  168. dstDb := rawdb.NewMemoryDatabase()
  169. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  170. queue := append([]common.Hash{}, sched.Missing(0)...)
  171. for len(queue) > 0 {
  172. // Sync only half of the scheduled nodes
  173. results := make([]trie.SyncResult, len(queue)/2+1)
  174. for i, hash := range queue[:len(results)] {
  175. data, err := srcDb.TrieDB().Node(hash)
  176. if err != nil {
  177. data, err = srcDb.ContractCode(common.Hash{}, hash)
  178. }
  179. if err != nil {
  180. t.Fatalf("failed to retrieve node data for %x", hash)
  181. }
  182. results[i] = trie.SyncResult{Hash: hash, Data: data}
  183. }
  184. for _, result := range results {
  185. if err := sched.Process(result); err != nil {
  186. t.Fatalf("failed to process result %v", err)
  187. }
  188. }
  189. batch := dstDb.NewBatch()
  190. if err := sched.Commit(batch); err != nil {
  191. t.Fatalf("failed to commit data: %v", err)
  192. }
  193. batch.Write()
  194. queue = append(queue[len(results):], sched.Missing(0)...)
  195. }
  196. // Cross check that the two states are in sync
  197. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  198. }
  199. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  200. // requesting retrieval tasks and returning all of them in one go, however in a
  201. // random order.
  202. func TestIterativeRandomStateSyncIndividual(t *testing.T) { testIterativeRandomStateSync(t, 1) }
  203. func TestIterativeRandomStateSyncBatched(t *testing.T) { testIterativeRandomStateSync(t, 100) }
  204. func testIterativeRandomStateSync(t *testing.T, count int) {
  205. // Create a random state to copy
  206. srcDb, srcRoot, srcAccounts := makeTestState()
  207. // Create a destination state and sync with the scheduler
  208. dstDb := rawdb.NewMemoryDatabase()
  209. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  210. queue := make(map[common.Hash]struct{})
  211. for _, hash := range sched.Missing(count) {
  212. queue[hash] = struct{}{}
  213. }
  214. for len(queue) > 0 {
  215. // Fetch all the queued nodes in a random order
  216. results := make([]trie.SyncResult, 0, len(queue))
  217. for hash := range queue {
  218. data, err := srcDb.TrieDB().Node(hash)
  219. if err != nil {
  220. data, err = srcDb.ContractCode(common.Hash{}, hash)
  221. }
  222. if err != nil {
  223. t.Fatalf("failed to retrieve node data for %x", hash)
  224. }
  225. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  226. }
  227. // Feed the retrieved results back and queue new tasks
  228. for _, result := range results {
  229. if err := sched.Process(result); err != nil {
  230. t.Fatalf("failed to process result %v", err)
  231. }
  232. }
  233. batch := dstDb.NewBatch()
  234. if err := sched.Commit(batch); err != nil {
  235. t.Fatalf("failed to commit data: %v", err)
  236. }
  237. batch.Write()
  238. queue = make(map[common.Hash]struct{})
  239. for _, hash := range sched.Missing(count) {
  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 the trie scheduler can correctly reconstruct the state even if only
  247. // partial results are returned (Even those randomly), others sent only later.
  248. func TestIterativeRandomDelayedStateSync(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 := rawdb.NewMemoryDatabase()
  253. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  254. queue := make(map[common.Hash]struct{})
  255. for _, hash := range sched.Missing(0) {
  256. queue[hash] = struct{}{}
  257. }
  258. for len(queue) > 0 {
  259. // Sync only half of the scheduled nodes, even those in random order
  260. results := make([]trie.SyncResult, 0, len(queue)/2+1)
  261. for hash := range queue {
  262. delete(queue, hash)
  263. data, err := srcDb.TrieDB().Node(hash)
  264. if err != nil {
  265. data, err = srcDb.ContractCode(common.Hash{}, hash)
  266. }
  267. if err != nil {
  268. t.Fatalf("failed to retrieve node data for %x", hash)
  269. }
  270. results = append(results, trie.SyncResult{Hash: hash, Data: data})
  271. if len(results) >= cap(results) {
  272. break
  273. }
  274. }
  275. // Feed the retrieved results back and queue new tasks
  276. for _, result := range results {
  277. if err := sched.Process(result); err != nil {
  278. t.Fatalf("failed to process result %v", err)
  279. }
  280. }
  281. batch := dstDb.NewBatch()
  282. if err := sched.Commit(batch); err != nil {
  283. t.Fatalf("failed to commit data: %v", err)
  284. }
  285. batch.Write()
  286. for _, hash := range sched.Missing(0) {
  287. queue[hash] = struct{}{}
  288. }
  289. }
  290. // Cross check that the two states are in sync
  291. checkStateAccounts(t, dstDb, srcRoot, srcAccounts)
  292. }
  293. // Tests that at any point in time during a sync, only complete sub-tries are in
  294. // the database.
  295. func TestIncompleteStateSync(t *testing.T) {
  296. // Create a random state to copy
  297. srcDb, srcRoot, srcAccounts := makeTestState()
  298. // isCode reports whether the hash is contract code hash.
  299. isCode := func(hash common.Hash) bool {
  300. for _, acc := range srcAccounts {
  301. if hash == crypto.Keccak256Hash(acc.code) {
  302. return true
  303. }
  304. }
  305. return false
  306. }
  307. checkTrieConsistency(srcDb.TrieDB().DiskDB().(ethdb.Database), srcRoot)
  308. // Create a destination state and sync with the scheduler
  309. dstDb := rawdb.NewMemoryDatabase()
  310. sched := NewStateSync(srcRoot, dstDb, trie.NewSyncBloom(1, dstDb))
  311. added := []common.Hash{}
  312. queue := append([]common.Hash{}, sched.Missing(1)...)
  313. for len(queue) > 0 {
  314. // Fetch a batch of state nodes
  315. results := make([]trie.SyncResult, len(queue))
  316. for i, hash := range queue {
  317. data, err := srcDb.TrieDB().Node(hash)
  318. if err != nil {
  319. data, err = srcDb.ContractCode(common.Hash{}, hash)
  320. }
  321. if err != nil {
  322. t.Fatalf("failed to retrieve node data for %x", hash)
  323. }
  324. results[i] = trie.SyncResult{Hash: hash, Data: data}
  325. }
  326. // Process each of the state nodes
  327. for _, result := range results {
  328. if err := sched.Process(result); err != nil {
  329. t.Fatalf("failed to process result %v", err)
  330. }
  331. }
  332. batch := dstDb.NewBatch()
  333. if err := sched.Commit(batch); err != nil {
  334. t.Fatalf("failed to commit data: %v", err)
  335. }
  336. batch.Write()
  337. for _, result := range results {
  338. added = append(added, result.Hash)
  339. }
  340. // Check that all known sub-tries added so far are complete or missing entirely.
  341. for _, hash := range added {
  342. if isCode(hash) {
  343. continue
  344. }
  345. // Can't use checkStateConsistency here because subtrie keys may have odd
  346. // length and crash in LeafKey.
  347. if err := checkTrieConsistency(dstDb, hash); err != nil {
  348. t.Fatalf("state inconsistent: %v", err)
  349. }
  350. }
  351. // Fetch the next batch to retrieve
  352. queue = append(queue[:0], sched.Missing(1)...)
  353. }
  354. // Sanity check that removing any node from the database is detected
  355. for _, node := range added[1:] {
  356. var (
  357. key = node.Bytes()
  358. code = isCode(node)
  359. val []byte
  360. )
  361. if code {
  362. val = rawdb.ReadCode(dstDb, node)
  363. rawdb.DeleteCode(dstDb, node)
  364. } else {
  365. val = rawdb.ReadTrieNode(dstDb, node)
  366. rawdb.DeleteTrieNode(dstDb, node)
  367. }
  368. if err := checkStateConsistency(dstDb, added[0]); err == nil {
  369. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  370. }
  371. if code {
  372. rawdb.WriteCode(dstDb, node, val)
  373. } else {
  374. rawdb.WriteTrieNode(dstDb, node, val)
  375. }
  376. }
  377. }