sync_test.go 12 KB

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