sync_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 th 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 := NewNodeIterator(trie)
  74. for it.Next() {
  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, dstDb); err != nil {
  110. t.Fatalf("failed to process result #%d: %v", index, err)
  111. }
  112. queue = append(queue[:0], sched.Missing(batch)...)
  113. }
  114. // Cross check that the two tries are in sync
  115. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  116. }
  117. // Tests that the trie scheduler can correctly reconstruct the state even if only
  118. // partial results are returned, and the others sent only later.
  119. func TestIterativeDelayedTrieSync(t *testing.T) {
  120. // Create a random trie to copy
  121. srcDb, srcTrie, srcData := makeTestTrie()
  122. // Create a destination trie and sync with the scheduler
  123. dstDb, _ := ethdb.NewMemDatabase()
  124. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  125. queue := append([]common.Hash{}, sched.Missing(10000)...)
  126. for len(queue) > 0 {
  127. // Sync only half of the scheduled nodes
  128. results := make([]SyncResult, len(queue)/2+1)
  129. for i, hash := range queue[:len(results)] {
  130. data, err := srcDb.Get(hash.Bytes())
  131. if err != nil {
  132. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  133. }
  134. results[i] = SyncResult{hash, data}
  135. }
  136. if _, index, err := sched.Process(results, dstDb); err != nil {
  137. t.Fatalf("failed to process result #%d: %v", index, err)
  138. }
  139. queue = append(queue[len(results):], sched.Missing(10000)...)
  140. }
  141. // Cross check that the two tries are in sync
  142. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  143. }
  144. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  145. // requesting retrieval tasks and returning all of them in one go, however in a
  146. // random order.
  147. func TestIterativeRandomTrieSyncIndividual(t *testing.T) { testIterativeRandomTrieSync(t, 1) }
  148. func TestIterativeRandomTrieSyncBatched(t *testing.T) { testIterativeRandomTrieSync(t, 100) }
  149. func testIterativeRandomTrieSync(t *testing.T, batch int) {
  150. // Create a random trie to copy
  151. srcDb, srcTrie, srcData := makeTestTrie()
  152. // Create a destination trie and sync with the scheduler
  153. dstDb, _ := ethdb.NewMemDatabase()
  154. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  155. queue := make(map[common.Hash]struct{})
  156. for _, hash := range sched.Missing(batch) {
  157. queue[hash] = struct{}{}
  158. }
  159. for len(queue) > 0 {
  160. // Fetch all the queued nodes in a random order
  161. results := make([]SyncResult, 0, len(queue))
  162. for hash := range queue {
  163. data, err := srcDb.Get(hash.Bytes())
  164. if err != nil {
  165. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  166. }
  167. results = append(results, SyncResult{hash, data})
  168. }
  169. // Feed the retrieved results back and queue new tasks
  170. if _, index, err := sched.Process(results, dstDb); err != nil {
  171. t.Fatalf("failed to process result #%d: %v", index, err)
  172. }
  173. queue = make(map[common.Hash]struct{})
  174. for _, hash := range sched.Missing(batch) {
  175. queue[hash] = struct{}{}
  176. }
  177. }
  178. // Cross check that the two tries are in sync
  179. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  180. }
  181. // Tests that the trie scheduler can correctly reconstruct the state even if only
  182. // partial results are returned (Even those randomly), others sent only later.
  183. func TestIterativeRandomDelayedTrieSync(t *testing.T) {
  184. // Create a random trie to copy
  185. srcDb, srcTrie, srcData := makeTestTrie()
  186. // Create a destination trie and sync with the scheduler
  187. dstDb, _ := ethdb.NewMemDatabase()
  188. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  189. queue := make(map[common.Hash]struct{})
  190. for _, hash := range sched.Missing(10000) {
  191. queue[hash] = struct{}{}
  192. }
  193. for len(queue) > 0 {
  194. // Sync only half of the scheduled nodes, even those in random order
  195. results := make([]SyncResult, 0, len(queue)/2+1)
  196. for hash := range queue {
  197. data, err := srcDb.Get(hash.Bytes())
  198. if err != nil {
  199. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  200. }
  201. results = append(results, SyncResult{hash, data})
  202. if len(results) >= cap(results) {
  203. break
  204. }
  205. }
  206. // Feed the retrieved results back and queue new tasks
  207. if _, index, err := sched.Process(results, dstDb); err != nil {
  208. t.Fatalf("failed to process result #%d: %v", index, err)
  209. }
  210. for _, result := range results {
  211. delete(queue, result.Hash)
  212. }
  213. for _, hash := range sched.Missing(10000) {
  214. queue[hash] = struct{}{}
  215. }
  216. }
  217. // Cross check that the two tries are in sync
  218. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  219. }
  220. // Tests that a trie sync will not request nodes multiple times, even if they
  221. // have such references.
  222. func TestDuplicateAvoidanceTrieSync(t *testing.T) {
  223. // Create a random trie to copy
  224. srcDb, srcTrie, srcData := makeTestTrie()
  225. // Create a destination trie and sync with the scheduler
  226. dstDb, _ := ethdb.NewMemDatabase()
  227. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  228. queue := append([]common.Hash{}, sched.Missing(0)...)
  229. requested := make(map[common.Hash]struct{})
  230. for len(queue) > 0 {
  231. results := make([]SyncResult, len(queue))
  232. for i, hash := range queue {
  233. data, err := srcDb.Get(hash.Bytes())
  234. if err != nil {
  235. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  236. }
  237. if _, ok := requested[hash]; ok {
  238. t.Errorf("hash %x already requested once", hash)
  239. }
  240. requested[hash] = struct{}{}
  241. results[i] = SyncResult{hash, data}
  242. }
  243. if _, index, err := sched.Process(results, dstDb); err != nil {
  244. t.Fatalf("failed to process result #%d: %v", index, err)
  245. }
  246. queue = append(queue[:0], sched.Missing(0)...)
  247. }
  248. // Cross check that the two tries are in sync
  249. checkTrieContents(t, dstDb, srcTrie.Root(), srcData)
  250. }
  251. // Tests that at any point in time during a sync, only complete sub-tries are in
  252. // the database.
  253. func TestIncompleteTrieSync(t *testing.T) {
  254. // Create a random trie to copy
  255. srcDb, srcTrie, _ := makeTestTrie()
  256. // Create a destination trie and sync with the scheduler
  257. dstDb, _ := ethdb.NewMemDatabase()
  258. sched := NewTrieSync(common.BytesToHash(srcTrie.Root()), dstDb, nil)
  259. added := []common.Hash{}
  260. queue := append([]common.Hash{}, sched.Missing(1)...)
  261. for len(queue) > 0 {
  262. // Fetch a batch of trie nodes
  263. results := make([]SyncResult, len(queue))
  264. for i, hash := range queue {
  265. data, err := srcDb.Get(hash.Bytes())
  266. if err != nil {
  267. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  268. }
  269. results[i] = SyncResult{hash, data}
  270. }
  271. // Process each of the trie nodes
  272. if _, index, err := sched.Process(results, dstDb); err != nil {
  273. t.Fatalf("failed to process result #%d: %v", index, err)
  274. }
  275. for _, result := range results {
  276. added = append(added, result.Hash)
  277. }
  278. // Check that all known sub-tries in the synced trie is complete
  279. for _, root := range added {
  280. if err := checkTrieConsistency(dstDb, root); err != nil {
  281. t.Fatalf("trie inconsistent: %v", err)
  282. }
  283. }
  284. // Fetch the next batch to retrieve
  285. queue = append(queue[:0], sched.Missing(1)...)
  286. }
  287. // Sanity check that removing any node from the database is detected
  288. for _, node := range added[1:] {
  289. key := node.Bytes()
  290. value, _ := dstDb.Get(key)
  291. dstDb.Delete(key)
  292. if err := checkTrieConsistency(dstDb, added[0]); err == nil {
  293. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  294. }
  295. dstDb.Put(key, value)
  296. }
  297. }