sync_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/memorydb"
  22. )
  23. // makeTestTrie create a sample test trie to test node-wise reconstruction.
  24. func makeTestTrie() (*Database, *Trie, map[string][]byte) {
  25. // Create an empty trie
  26. triedb := NewDatabase(memorydb.New())
  27. trie, _ := New(common.Hash{}, triedb)
  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(nil)
  46. // Return the generated trie
  47. return triedb, 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 TestEmptySync(t *testing.T) {
  80. dbA := NewDatabase(memorydb.New())
  81. dbB := NewDatabase(memorydb.New())
  82. emptyA, _ := New(common.Hash{}, dbA)
  83. emptyB, _ := New(emptyRoot, dbB)
  84. for i, trie := range []*Trie{emptyA, emptyB} {
  85. if req := NewSync(trie.Hash(), memorydb.New(), nil, NewSyncBloom(1, memorydb.New())).Missing(1); len(req) != 0 {
  86. t.Errorf("test %d: content requested for empty trie: %v", i, req)
  87. }
  88. }
  89. }
  90. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  91. // requesting retrieval tasks and returning all of them in one go.
  92. func TestIterativeSyncIndividual(t *testing.T) { testIterativeSync(t, 1) }
  93. func TestIterativeSyncBatched(t *testing.T) { testIterativeSync(t, 100) }
  94. func testIterativeSync(t *testing.T, count int) {
  95. // Create a random trie to copy
  96. srcDb, srcTrie, srcData := makeTestTrie()
  97. // Create a destination trie and sync with the scheduler
  98. diskdb := memorydb.New()
  99. triedb := NewDatabase(diskdb)
  100. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  101. queue := append([]common.Hash{}, sched.Missing(count)...)
  102. for len(queue) > 0 {
  103. results := make([]SyncResult, len(queue))
  104. for i, hash := range queue {
  105. data, err := srcDb.Node(hash)
  106. if err != nil {
  107. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  108. }
  109. results[i] = SyncResult{hash, data}
  110. }
  111. if _, index, err := sched.Process(results); err != nil {
  112. t.Fatalf("failed to process result #%d: %v", index, err)
  113. }
  114. batch := diskdb.NewBatch()
  115. if err := sched.Commit(batch); err != nil {
  116. t.Fatalf("failed to commit data: %v", err)
  117. }
  118. batch.Write()
  119. queue = append(queue[:0], sched.Missing(count)...)
  120. }
  121. // Cross check that the two tries are in sync
  122. checkTrieContents(t, triedb, srcTrie.Hash().Bytes(), srcData)
  123. }
  124. // Tests that the trie scheduler can correctly reconstruct the state even if only
  125. // partial results are returned, and the others sent only later.
  126. func TestIterativeDelayedSync(t *testing.T) {
  127. // Create a random trie to copy
  128. srcDb, srcTrie, srcData := makeTestTrie()
  129. // Create a destination trie and sync with the scheduler
  130. diskdb := memorydb.New()
  131. triedb := NewDatabase(diskdb)
  132. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  133. queue := append([]common.Hash{}, sched.Missing(10000)...)
  134. for len(queue) > 0 {
  135. // Sync only half of the scheduled nodes
  136. results := make([]SyncResult, len(queue)/2+1)
  137. for i, hash := range queue[:len(results)] {
  138. data, err := srcDb.Node(hash)
  139. if err != nil {
  140. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  141. }
  142. results[i] = SyncResult{hash, data}
  143. }
  144. if _, index, err := sched.Process(results); err != nil {
  145. t.Fatalf("failed to process result #%d: %v", index, err)
  146. }
  147. batch := diskdb.NewBatch()
  148. if err := sched.Commit(batch); err != nil {
  149. t.Fatalf("failed to commit data: %v", err)
  150. }
  151. batch.Write()
  152. queue = append(queue[len(results):], sched.Missing(10000)...)
  153. }
  154. // Cross check that the two tries are in sync
  155. checkTrieContents(t, triedb, srcTrie.Hash().Bytes(), srcData)
  156. }
  157. // Tests that given a root hash, a trie can sync iteratively on a single thread,
  158. // requesting retrieval tasks and returning all of them in one go, however in a
  159. // random order.
  160. func TestIterativeRandomSyncIndividual(t *testing.T) { testIterativeRandomSync(t, 1) }
  161. func TestIterativeRandomSyncBatched(t *testing.T) { testIterativeRandomSync(t, 100) }
  162. func testIterativeRandomSync(t *testing.T, count int) {
  163. // Create a random trie to copy
  164. srcDb, srcTrie, srcData := makeTestTrie()
  165. // Create a destination trie and sync with the scheduler
  166. diskdb := memorydb.New()
  167. triedb := NewDatabase(diskdb)
  168. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  169. queue := make(map[common.Hash]struct{})
  170. for _, hash := range sched.Missing(count) {
  171. queue[hash] = struct{}{}
  172. }
  173. for len(queue) > 0 {
  174. // Fetch all the queued nodes in a random order
  175. results := make([]SyncResult, 0, len(queue))
  176. for hash := range queue {
  177. data, err := srcDb.Node(hash)
  178. if err != nil {
  179. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  180. }
  181. results = append(results, SyncResult{hash, data})
  182. }
  183. // Feed the retrieved results back and queue new tasks
  184. if _, index, err := sched.Process(results); err != nil {
  185. t.Fatalf("failed to process result #%d: %v", index, err)
  186. }
  187. batch := diskdb.NewBatch()
  188. if err := sched.Commit(batch); err != nil {
  189. t.Fatalf("failed to commit data: %v", err)
  190. }
  191. batch.Write()
  192. queue = make(map[common.Hash]struct{})
  193. for _, hash := range sched.Missing(count) {
  194. queue[hash] = struct{}{}
  195. }
  196. }
  197. // Cross check that the two tries are in sync
  198. checkTrieContents(t, triedb, srcTrie.Hash().Bytes(), srcData)
  199. }
  200. // Tests that the trie scheduler can correctly reconstruct the state even if only
  201. // partial results are returned (Even those randomly), others sent only later.
  202. func TestIterativeRandomDelayedSync(t *testing.T) {
  203. // Create a random trie to copy
  204. srcDb, srcTrie, srcData := makeTestTrie()
  205. // Create a destination trie and sync with the scheduler
  206. diskdb := memorydb.New()
  207. triedb := NewDatabase(diskdb)
  208. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  209. queue := make(map[common.Hash]struct{})
  210. for _, hash := range sched.Missing(10000) {
  211. queue[hash] = struct{}{}
  212. }
  213. for len(queue) > 0 {
  214. // Sync only half of the scheduled nodes, even those in random order
  215. results := make([]SyncResult, 0, len(queue)/2+1)
  216. for hash := range queue {
  217. data, err := srcDb.Node(hash)
  218. if err != nil {
  219. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  220. }
  221. results = append(results, SyncResult{hash, data})
  222. if len(results) >= cap(results) {
  223. break
  224. }
  225. }
  226. // Feed the retrieved results back and queue new tasks
  227. if _, index, err := sched.Process(results); err != nil {
  228. t.Fatalf("failed to process result #%d: %v", index, err)
  229. }
  230. batch := diskdb.NewBatch()
  231. if err := sched.Commit(batch); err != nil {
  232. t.Fatalf("failed to commit data: %v", err)
  233. }
  234. batch.Write()
  235. for _, result := range results {
  236. delete(queue, result.Hash)
  237. }
  238. for _, hash := range sched.Missing(10000) {
  239. queue[hash] = struct{}{}
  240. }
  241. }
  242. // Cross check that the two tries are in sync
  243. checkTrieContents(t, triedb, srcTrie.Hash().Bytes(), srcData)
  244. }
  245. // Tests that a trie sync will not request nodes multiple times, even if they
  246. // have such references.
  247. func TestDuplicateAvoidanceSync(t *testing.T) {
  248. // Create a random trie to copy
  249. srcDb, srcTrie, srcData := makeTestTrie()
  250. // Create a destination trie and sync with the scheduler
  251. diskdb := memorydb.New()
  252. triedb := NewDatabase(diskdb)
  253. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  254. queue := append([]common.Hash{}, sched.Missing(0)...)
  255. requested := make(map[common.Hash]struct{})
  256. for len(queue) > 0 {
  257. results := make([]SyncResult, len(queue))
  258. for i, hash := range queue {
  259. data, err := srcDb.Node(hash)
  260. if err != nil {
  261. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  262. }
  263. if _, ok := requested[hash]; ok {
  264. t.Errorf("hash %x already requested once", hash)
  265. }
  266. requested[hash] = struct{}{}
  267. results[i] = SyncResult{hash, data}
  268. }
  269. if _, index, err := sched.Process(results); err != nil {
  270. t.Fatalf("failed to process result #%d: %v", index, err)
  271. }
  272. batch := diskdb.NewBatch()
  273. if err := sched.Commit(batch); err != nil {
  274. t.Fatalf("failed to commit data: %v", err)
  275. }
  276. batch.Write()
  277. queue = append(queue[:0], sched.Missing(0)...)
  278. }
  279. // Cross check that the two tries are in sync
  280. checkTrieContents(t, triedb, srcTrie.Hash().Bytes(), srcData)
  281. }
  282. // Tests that at any point in time during a sync, only complete sub-tries are in
  283. // the database.
  284. func TestIncompleteSync(t *testing.T) {
  285. // Create a random trie to copy
  286. srcDb, srcTrie, _ := makeTestTrie()
  287. // Create a destination trie and sync with the scheduler
  288. diskdb := memorydb.New()
  289. triedb := NewDatabase(diskdb)
  290. sched := NewSync(srcTrie.Hash(), diskdb, nil, NewSyncBloom(1, diskdb))
  291. var added []common.Hash
  292. queue := append([]common.Hash{}, sched.Missing(1)...)
  293. for len(queue) > 0 {
  294. // Fetch a batch of trie nodes
  295. results := make([]SyncResult, len(queue))
  296. for i, hash := range queue {
  297. data, err := srcDb.Node(hash)
  298. if err != nil {
  299. t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
  300. }
  301. results[i] = SyncResult{hash, data}
  302. }
  303. // Process each of the trie nodes
  304. if _, index, err := sched.Process(results); err != nil {
  305. t.Fatalf("failed to process result #%d: %v", index, err)
  306. }
  307. batch := diskdb.NewBatch()
  308. if err := sched.Commit(batch); err != nil {
  309. t.Fatalf("failed to commit data: %v", err)
  310. }
  311. batch.Write()
  312. for _, result := range results {
  313. added = append(added, result.Hash)
  314. }
  315. // Check that all known sub-tries in the synced trie are complete
  316. for _, root := range added {
  317. if err := checkTrieConsistency(triedb, root); err != nil {
  318. t.Fatalf("trie inconsistent: %v", err)
  319. }
  320. }
  321. // Fetch the next batch to retrieve
  322. queue = append(queue[:0], sched.Missing(1)...)
  323. }
  324. // Sanity check that removing any node from the database is detected
  325. for _, node := range added[1:] {
  326. key := node.Bytes()
  327. value, _ := diskdb.Get(key)
  328. diskdb.Delete(key)
  329. if err := checkTrieConsistency(triedb, added[0]); err == nil {
  330. t.Fatalf("trie inconsistency not caught, missing: %x", key)
  331. }
  332. diskdb.Put(key, value)
  333. }
  334. }