sync_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 trie
  17. import (
  18. "bytes"
  19. "testing"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. )
  23. // makeTestTrie create a sample test trie to test node-wise reconstruction.
  24. func makeTestTrie() (ethdb.Database, *Trie, map[string][]byte) {
  25. // Create an empty trie
  26. db, _ := ethdb.NewMemDatabase()
  27. trie, _ := New(common.Hash{}, db)
  28. // Fill it with some arbitrary data
  29. content := make(map[string][]byte)
  30. for i := byte(0); i < 255; i++ {
  31. // Map the same data under multiple keys
  32. key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
  33. content[string(key)] = val
  34. trie.Update(key, val)
  35. key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
  36. content[string(key)] = val
  37. trie.Update(key, val)
  38. // Add some other data to inflate the trie
  39. for j := byte(3); j < 13; j++ {
  40. key, val = common.LeftPadBytes([]byte{j, i}, 32), []byte{j, i}
  41. content[string(key)] = val
  42. trie.Update(key, val)
  43. }
  44. }
  45. trie.Commit()
  46. // Return the generated trie
  47. return db, trie, content
  48. }
  49. // checkTrieContents cross references a reconstructed trie with an expected data
  50. // content map.
  51. func checkTrieContents(t *testing.T, db Database, root []byte, content map[string][]byte) {
  52. // Check root availability and trie contents
  53. trie, err := New(common.BytesToHash(root), db)
  54. if err != nil {
  55. t.Fatalf("failed to create trie at %x: %v", root, err)
  56. }
  57. if err := checkTrieConsistency(db, common.BytesToHash(root)); err != nil {
  58. t.Fatalf("inconsistent trie at %x: %v", root, err)
  59. }
  60. for key, val := range content {
  61. if have := trie.Get([]byte(key)); !bytes.Equal(have, val) {
  62. t.Errorf("entry %x: content mismatch: have %x, want %x", key, have, val)
  63. }
  64. }
  65. }
  66. // checkTrieConsistency checks that all nodes in a trie are indeed present.
  67. func checkTrieConsistency(db Database, root common.Hash) error {
  68. // Create and iterate a trie rooted in a subnode
  69. trie, err := New(root, db)
  70. if err != nil {
  71. return nil // Consider a non existent state consistent
  72. }
  73. it := trie.NodeIterator(nil)
  74. for it.Next(true) {
  75. }
  76. return it.Error()
  77. }
  78. // Tests that an empty trie is not scheduled for syncing.
  79. func TestEmptyTrieSync(t *testing.T) {
  80. emptyA, _ := New(common.Hash{}, nil)
  81. emptyB, _ := New(emptyRoot, nil)
  82. for i, trie := range []*Trie{emptyA, emptyB} {
  83. db, _ := ethdb.NewMemDatabase()
  84. if req := NewTrieSync(common.BytesToHash(trie.Root()), db, nil).Missing(1); len(req) != 0 {
  85. t.Errorf("test %d: content requested for empty trie: %v", i, req)
  86. }
  87. }
  88. }
  89. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  90. // requesting retrieval tasks and returning all of them in one go.
  91. func TestIterativeTrieSyncIndividual(t *testing.T) { testIterativeTrieSync(t, 1) }
  92. func TestIterativeTrieSyncBatched(t *testing.T) { testIterativeTrieSync(t, 100) }
  93. func testIterativeTrieSync(t *testing.T, batch int) {
  94. // Create a random trie to copy
  95. srcDb, srcTrie, srcData := makeTestTrie()
  96. // Create a destination trie and sync with the scheduler
  97. dstDb, _ := ethdb.NewMemDatabase()
  98. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  99. queue := append([]common.Hash{}, sched.Missing(batch)...)
  100. for len(queue) > 0 {
  101. results := make([]SyncResult, len(queue))
  102. for i, hash := range queue {
  103. data, err := srcDb.Get(hash.Bytes())
  104. if err != nil {
  105. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  106. }
  107. results[i] = SyncResult{hash, data}
  108. }
  109. if _, index, err := sched.Process(results); err != nil {
  110. t.Fatalf("failed to process result #%d: %v", index, err)
  111. }
  112. if index, err := sched.Commit(dstDb); err != nil {
  113. t.Fatalf("failed to commit data #%d: %v", index, err)
  114. }
  115. queue = append(queue[:0], sched.Missing(batch)...)
  116. }
  117. // Cross check that the two tries are in sync
  118. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  119. }
  120. // Tests that the trie scheduler can correctly reconstruct the state even if only
  121. // partial results are returned, and the others sent only later.
  122. func TestIterativeDelayedTrieSync(t *testing.T) {
  123. // Create a random trie to copy
  124. srcDb, srcTrie, srcData := makeTestTrie()
  125. // Create a destination trie and sync with the scheduler
  126. dstDb, _ := ethdb.NewMemDatabase()
  127. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  128. queue := append([]common.Hash{}, sched.Missing(10000)...)
  129. for len(queue) > 0 {
  130. // Sync only half of the scheduled nodes
  131. results := make([]SyncResult, len(queue)/2+1)
  132. for i, hash := range queue[:len(results)] {
  133. data, err := srcDb.Get(hash.Bytes())
  134. if err != nil {
  135. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  136. }
  137. results[i] = SyncResult{hash, data}
  138. }
  139. if _, index, err := sched.Process(results); err != nil {
  140. t.Fatalf("failed to process result #%d: %v", index, err)
  141. }
  142. if index, err := sched.Commit(dstDb); err != nil {
  143. t.Fatalf("failed to commit data #%d: %v", index, err)
  144. }
  145. queue = append(queue[len(results):], sched.Missing(10000)...)
  146. }
  147. // Cross check that the two tries are in sync
  148. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  149. }
  150. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  151. // requesting retrieval tasks and returning all of them in one go, however in a
  152. // random order.
  153. func TestIterativeRandomTrieSyncIndividual(t *testing.T) { testIterativeRandomTrieSync(t, 1) }
  154. func TestIterativeRandomTrieSyncBatched(t *testing.T) { testIterativeRandomTrieSync(t, 100) }
  155. func testIterativeRandomTrieSync(t *testing.T, batch int) {
  156. // Create a random trie to copy
  157. srcDb, srcTrie, srcData := makeTestTrie()
  158. // Create a destination trie and sync with the scheduler
  159. dstDb, _ := ethdb.NewMemDatabase()
  160. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  161. queue := make(map[common.Hash]struct{})
  162. for _, hash := range sched.Missing(batch) {
  163. queue[hash] = struct{}{}
  164. }
  165. for len(queue) > 0 {
  166. // Fetch all the queued nodes in a random order
  167. results := make([]SyncResult, 0, len(queue))
  168. for hash := range queue {
  169. data, err := srcDb.Get(hash.Bytes())
  170. if err != nil {
  171. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  172. }
  173. results = append(results, SyncResult{hash, data})
  174. }
  175. // Feed the retrieved results back and queue new tasks
  176. if _, index, err := sched.Process(results); err != nil {
  177. t.Fatalf("failed to process result #%d: %v", index, err)
  178. }
  179. if index, err := sched.Commit(dstDb); err != nil {
  180. t.Fatalf("failed to commit data #%d: %v", index, err)
  181. }
  182. queue = make(map[common.Hash]struct{})
  183. for _, hash := range sched.Missing(batch) {
  184. queue[hash] = struct{}{}
  185. }
  186. }
  187. // Cross check that the two tries are in sync
  188. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  189. }
  190. // Tests that the trie scheduler can correctly reconstruct the state even if only
  191. // partial results are returned (Even those randomly), others sent only later.
  192. func TestIterativeRandomDelayedTrieSync(t *testing.T) {
  193. // Create a random trie to copy
  194. srcDb, srcTrie, srcData := makeTestTrie()
  195. // Create a destination trie and sync with the scheduler
  196. dstDb, _ := ethdb.NewMemDatabase()
  197. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  198. queue := make(map[common.Hash]struct{})
  199. for _, hash := range sched.Missing(10000) {
  200. queue[hash] = struct{}{}
  201. }
  202. for len(queue) > 0 {
  203. // Sync only half of the scheduled nodes, even those in random order
  204. results := make([]SyncResult, 0, len(queue)/2+1)
  205. for hash := range queue {
  206. data, err := srcDb.Get(hash.Bytes())
  207. if err != nil {
  208. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  209. }
  210. results = append(results, SyncResult{hash, data})
  211. if len(results) >= cap(results) {
  212. break
  213. }
  214. }
  215. // Feed the retrieved results back and queue new tasks
  216. if _, index, err := sched.Process(results); err != nil {
  217. t.Fatalf("failed to process result #%d: %v", index, err)
  218. }
  219. if index, err := sched.Commit(dstDb); err != nil {
  220. t.Fatalf("failed to commit data #%d: %v", index, err)
  221. }
  222. for _, result := range results {
  223. delete(queue, result.Hash)
  224. }
  225. for _, hash := range sched.Missing(10000) {
  226. queue[hash] = struct{}{}
  227. }
  228. }
  229. // Cross check that the two tries are in sync
  230. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  231. }
  232. // Tests that a trie sync will not request nodes multiple times, even if they
  233. // have such references.
  234. func TestDuplicateAvoidanceTrieSync(t *testing.T) {
  235. // Create a random trie to copy
  236. srcDb, srcTrie, srcData := makeTestTrie()
  237. // Create a destination trie and sync with the scheduler
  238. dstDb, _ := ethdb.NewMemDatabase()
  239. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  240. queue := append([]common.Hash{}, sched.Missing(0)...)
  241. requested := make(map[common.Hash]struct{})
  242. for len(queue) > 0 {
  243. results := make([]SyncResult, len(queue))
  244. for i, hash := range queue {
  245. data, err := srcDb.Get(hash.Bytes())
  246. if err != nil {
  247. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  248. }
  249. if _, ok := requested[hash]; ok {
  250. t.Errorf("hash %x already requested once", hash)
  251. }
  252. requested[hash] = struct{}{}
  253. results[i] = SyncResult{hash, data}
  254. }
  255. if _, index, err := sched.Process(results); err != nil {
  256. t.Fatalf("failed to process result #%d: %v", index, err)
  257. }
  258. if index, err := sched.Commit(dstDb); err != nil {
  259. t.Fatalf("failed to commit data #%d: %v", index, err)
  260. }
  261. queue = append(queue[:0], sched.Missing(0)...)
  262. }
  263. // Cross check that the two tries are in sync
  264. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  265. }
  266. // Tests that at any point in time during a sync, only complete sub-tries are in
  267. // the database.
  268. func TestIncompleteTrieSync(t *testing.T) {
  269. // Create a random trie to copy
  270. srcDb, srcTrie, _ := makeTestTrie()
  271. // Create a destination trie and sync with the scheduler
  272. dstDb, _ := ethdb.NewMemDatabase()
  273. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  274. added := []common.Hash{}
  275. queue := append([]common.Hash{}, sched.Missing(1)...)
  276. for len(queue) > 0 {
  277. // Fetch a batch of trie nodes
  278. results := make([]SyncResult, len(queue))
  279. for i, hash := range queue {
  280. data, err := srcDb.Get(hash.Bytes())
  281. if err != nil {
  282. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  283. }
  284. results[i] = SyncResult{hash, data}
  285. }
  286. // Process each of the trie nodes
  287. if _, index, err := sched.Process(results); err != nil {
  288. t.Fatalf("failed to process result #%d: %v", index, err)
  289. }
  290. if index, err := sched.Commit(dstDb); err != nil {
  291. t.Fatalf("failed to commit data #%d: %v", index, err)
  292. }
  293. for _, result := range results {
  294. added = append(added, result.Hash)
  295. }
  296. // Check that all known sub-tries in the synced trie are complete
  297. for _, root := range added {
  298. if err := checkTrieConsistency(dstDb, root); err != nil {
  299. t.Fatalf("trie inconsistent: %v", err)
  300. }
  301. }
  302. // Fetch the next batch to retrieve
  303. queue = append(queue[:0], sched.Missing(1)...)
  304. }
  305. // Sanity check that removing any node from the database is detected
  306. for _, node := range added[1:] {
  307. key := node.Bytes()
  308. value, _ := dstDb.Get(key)
  309. dstDb.Delete(key)
  310. if err := checkTrieConsistency(dstDb, added[0]); err == nil {
  311. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  312. }
  313. dstDb.Put(key, value)
  314. }
  315. }