iterator_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Copyright 2014 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. "math/rand"
  21. "testing"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  24. )
  25. func TestIterator(t *testing.T) {
  26. trie := newEmpty()
  27. vals := []struct{ k, v string }{
  28. {"do", "verb"},
  29. {"ether", "wookiedoo"},
  30. {"horse", "stallion"},
  31. {"shaman", "horse"},
  32. {"doge", "coin"},
  33. {"dog", "puppy"},
  34. {"somethingveryoddindeedthis is", "myothernodedata"},
  35. }
  36. all := make(map[string]string)
  37. for _, val := range vals {
  38. all[val.k] = val.v
  39. trie.Update([]byte(val.k), []byte(val.v))
  40. }
  41. trie.Commit(nil)
  42. found := make(map[string]string)
  43. it := NewIterator(trie.NodeIterator(nil))
  44. for it.Next() {
  45. found[string(it.Key)] = string(it.Value)
  46. }
  47. for k, v := range all {
  48. if found[k] != v {
  49. t.Errorf("iterator value mismatch for %s: got %q want %q", k, found[k], v)
  50. }
  51. }
  52. }
  53. type kv struct {
  54. k, v []byte
  55. t bool
  56. }
  57. func TestIteratorLargeData(t *testing.T) {
  58. trie := newEmpty()
  59. vals := make(map[string]*kv)
  60. for i := byte(0); i < 255; i++ {
  61. value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
  62. value2 := &kv{common.LeftPadBytes([]byte{10, i}, 32), []byte{i}, false}
  63. trie.Update(value.k, value.v)
  64. trie.Update(value2.k, value2.v)
  65. vals[string(value.k)] = value
  66. vals[string(value2.k)] = value2
  67. }
  68. it := NewIterator(trie.NodeIterator(nil))
  69. for it.Next() {
  70. vals[string(it.Key)].t = true
  71. }
  72. var untouched []*kv
  73. for _, value := range vals {
  74. if !value.t {
  75. untouched = append(untouched, value)
  76. }
  77. }
  78. if len(untouched) > 0 {
  79. t.Errorf("Missed %d nodes", len(untouched))
  80. for _, value := range untouched {
  81. t.Error(value)
  82. }
  83. }
  84. }
  85. // Tests that the node iterator indeed walks over the entire database contents.
  86. func TestNodeIteratorCoverage(t *testing.T) {
  87. // Create some arbitrary test trie to iterate
  88. db, trie, _ := makeTestTrie()
  89. // Gather all the node hashes found by the iterator
  90. hashes := make(map[common.Hash]struct{})
  91. for it := trie.NodeIterator(nil); it.Next(true); {
  92. if it.Hash() != (common.Hash{}) {
  93. hashes[it.Hash()] = struct{}{}
  94. }
  95. }
  96. // Cross check the hashes and the database itself
  97. for hash := range hashes {
  98. if _, err := db.Node(hash); err != nil {
  99. t.Errorf("failed to retrieve reported node %x: %v", hash, err)
  100. }
  101. }
  102. for hash, obj := range db.dirties {
  103. if obj != nil && hash != (common.Hash{}) {
  104. if _, ok := hashes[hash]; !ok {
  105. t.Errorf("state entry not reported %x", hash)
  106. }
  107. }
  108. }
  109. it := db.diskdb.NewIterator(nil, nil)
  110. for it.Next() {
  111. key := it.Key()
  112. if _, ok := hashes[common.BytesToHash(key)]; !ok {
  113. t.Errorf("state entry not reported %x", key)
  114. }
  115. }
  116. it.Release()
  117. }
  118. type kvs struct{ k, v string }
  119. var testdata1 = []kvs{
  120. {"barb", "ba"},
  121. {"bard", "bc"},
  122. {"bars", "bb"},
  123. {"bar", "b"},
  124. {"fab", "z"},
  125. {"food", "ab"},
  126. {"foos", "aa"},
  127. {"foo", "a"},
  128. }
  129. var testdata2 = []kvs{
  130. {"aardvark", "c"},
  131. {"bar", "b"},
  132. {"barb", "bd"},
  133. {"bars", "be"},
  134. {"fab", "z"},
  135. {"foo", "a"},
  136. {"foos", "aa"},
  137. {"food", "ab"},
  138. {"jars", "d"},
  139. }
  140. func TestIteratorSeek(t *testing.T) {
  141. trie := newEmpty()
  142. for _, val := range testdata1 {
  143. trie.Update([]byte(val.k), []byte(val.v))
  144. }
  145. // Seek to the middle.
  146. it := NewIterator(trie.NodeIterator([]byte("fab")))
  147. if err := checkIteratorOrder(testdata1[4:], it); err != nil {
  148. t.Fatal(err)
  149. }
  150. // Seek to a non-existent key.
  151. it = NewIterator(trie.NodeIterator([]byte("barc")))
  152. if err := checkIteratorOrder(testdata1[1:], it); err != nil {
  153. t.Fatal(err)
  154. }
  155. // Seek beyond the end.
  156. it = NewIterator(trie.NodeIterator([]byte("z")))
  157. if err := checkIteratorOrder(nil, it); err != nil {
  158. t.Fatal(err)
  159. }
  160. }
  161. func checkIteratorOrder(want []kvs, it *Iterator) error {
  162. for it.Next() {
  163. if len(want) == 0 {
  164. return fmt.Errorf("didn't expect any more values, got key %q", it.Key)
  165. }
  166. if !bytes.Equal(it.Key, []byte(want[0].k)) {
  167. return fmt.Errorf("wrong key: got %q, want %q", it.Key, want[0].k)
  168. }
  169. want = want[1:]
  170. }
  171. if len(want) > 0 {
  172. return fmt.Errorf("iterator ended early, want key %q", want[0])
  173. }
  174. return nil
  175. }
  176. func TestDifferenceIterator(t *testing.T) {
  177. triea := newEmpty()
  178. for _, val := range testdata1 {
  179. triea.Update([]byte(val.k), []byte(val.v))
  180. }
  181. triea.Commit(nil)
  182. trieb := newEmpty()
  183. for _, val := range testdata2 {
  184. trieb.Update([]byte(val.k), []byte(val.v))
  185. }
  186. trieb.Commit(nil)
  187. found := make(map[string]string)
  188. di, _ := NewDifferenceIterator(triea.NodeIterator(nil), trieb.NodeIterator(nil))
  189. it := NewIterator(di)
  190. for it.Next() {
  191. found[string(it.Key)] = string(it.Value)
  192. }
  193. all := []struct{ k, v string }{
  194. {"aardvark", "c"},
  195. {"barb", "bd"},
  196. {"bars", "be"},
  197. {"jars", "d"},
  198. }
  199. for _, item := range all {
  200. if found[item.k] != item.v {
  201. t.Errorf("iterator value mismatch for %s: got %v want %v", item.k, found[item.k], item.v)
  202. }
  203. }
  204. if len(found) != len(all) {
  205. t.Errorf("iterator count mismatch: got %d values, want %d", len(found), len(all))
  206. }
  207. }
  208. func TestUnionIterator(t *testing.T) {
  209. triea := newEmpty()
  210. for _, val := range testdata1 {
  211. triea.Update([]byte(val.k), []byte(val.v))
  212. }
  213. triea.Commit(nil)
  214. trieb := newEmpty()
  215. for _, val := range testdata2 {
  216. trieb.Update([]byte(val.k), []byte(val.v))
  217. }
  218. trieb.Commit(nil)
  219. di, _ := NewUnionIterator([]NodeIterator{triea.NodeIterator(nil), trieb.NodeIterator(nil)})
  220. it := NewIterator(di)
  221. all := []struct{ k, v string }{
  222. {"aardvark", "c"},
  223. {"barb", "ba"},
  224. {"barb", "bd"},
  225. {"bard", "bc"},
  226. {"bars", "bb"},
  227. {"bars", "be"},
  228. {"bar", "b"},
  229. {"fab", "z"},
  230. {"food", "ab"},
  231. {"foos", "aa"},
  232. {"foo", "a"},
  233. {"jars", "d"},
  234. }
  235. for i, kv := range all {
  236. if !it.Next() {
  237. t.Errorf("Iterator ends prematurely at element %d", i)
  238. }
  239. if kv.k != string(it.Key) {
  240. t.Errorf("iterator value mismatch for element %d: got key %s want %s", i, it.Key, kv.k)
  241. }
  242. if kv.v != string(it.Value) {
  243. t.Errorf("iterator value mismatch for element %d: got value %s want %s", i, it.Value, kv.v)
  244. }
  245. }
  246. if it.Next() {
  247. t.Errorf("Iterator returned extra values.")
  248. }
  249. }
  250. func TestIteratorNoDups(t *testing.T) {
  251. var tr Trie
  252. for _, val := range testdata1 {
  253. tr.Update([]byte(val.k), []byte(val.v))
  254. }
  255. checkIteratorNoDups(t, tr.NodeIterator(nil), nil)
  256. }
  257. // This test checks that nodeIterator.Next can be retried after inserting missing trie nodes.
  258. func TestIteratorContinueAfterErrorDisk(t *testing.T) { testIteratorContinueAfterError(t, false) }
  259. func TestIteratorContinueAfterErrorMemonly(t *testing.T) { testIteratorContinueAfterError(t, true) }
  260. func testIteratorContinueAfterError(t *testing.T, memonly bool) {
  261. diskdb := memorydb.New()
  262. triedb := NewDatabase(diskdb)
  263. tr, _ := New(common.Hash{}, triedb)
  264. for _, val := range testdata1 {
  265. tr.Update([]byte(val.k), []byte(val.v))
  266. }
  267. tr.Commit(nil)
  268. if !memonly {
  269. triedb.Commit(tr.Hash(), true, nil)
  270. }
  271. wantNodeCount := checkIteratorNoDups(t, tr.NodeIterator(nil), nil)
  272. var (
  273. diskKeys [][]byte
  274. memKeys []common.Hash
  275. )
  276. if memonly {
  277. memKeys = triedb.Nodes()
  278. } else {
  279. it := diskdb.NewIterator(nil, nil)
  280. for it.Next() {
  281. diskKeys = append(diskKeys, it.Key())
  282. }
  283. it.Release()
  284. }
  285. for i := 0; i < 20; i++ {
  286. // Create trie that will load all nodes from DB.
  287. tr, _ := New(tr.Hash(), triedb)
  288. // Remove a random node from the database. It can't be the root node
  289. // because that one is already loaded.
  290. var (
  291. rkey common.Hash
  292. rval []byte
  293. robj *cachedNode
  294. )
  295. for {
  296. if memonly {
  297. rkey = memKeys[rand.Intn(len(memKeys))]
  298. } else {
  299. copy(rkey[:], diskKeys[rand.Intn(len(diskKeys))])
  300. }
  301. if rkey != tr.Hash() {
  302. break
  303. }
  304. }
  305. if memonly {
  306. robj = triedb.dirties[rkey]
  307. delete(triedb.dirties, rkey)
  308. } else {
  309. rval, _ = diskdb.Get(rkey[:])
  310. diskdb.Delete(rkey[:])
  311. }
  312. // Iterate until the error is hit.
  313. seen := make(map[string]bool)
  314. it := tr.NodeIterator(nil)
  315. checkIteratorNoDups(t, it, seen)
  316. missing, ok := it.Error().(*MissingNodeError)
  317. if !ok || missing.NodeHash != rkey {
  318. t.Fatal("didn't hit missing node, got", it.Error())
  319. }
  320. // Add the node back and continue iteration.
  321. if memonly {
  322. triedb.dirties[rkey] = robj
  323. } else {
  324. diskdb.Put(rkey[:], rval)
  325. }
  326. checkIteratorNoDups(t, it, seen)
  327. if it.Error() != nil {
  328. t.Fatal("unexpected error", it.Error())
  329. }
  330. if len(seen) != wantNodeCount {
  331. t.Fatal("wrong node iteration count, got", len(seen), "want", wantNodeCount)
  332. }
  333. }
  334. }
  335. // Similar to the test above, this one checks that failure to create nodeIterator at a
  336. // certain key prefix behaves correctly when Next is called. The expectation is that Next
  337. // should retry seeking before returning true for the first time.
  338. func TestIteratorContinueAfterSeekErrorDisk(t *testing.T) {
  339. testIteratorContinueAfterSeekError(t, false)
  340. }
  341. func TestIteratorContinueAfterSeekErrorMemonly(t *testing.T) {
  342. testIteratorContinueAfterSeekError(t, true)
  343. }
  344. func testIteratorContinueAfterSeekError(t *testing.T, memonly bool) {
  345. // Commit test trie to db, then remove the node containing "bars".
  346. diskdb := memorydb.New()
  347. triedb := NewDatabase(diskdb)
  348. ctr, _ := New(common.Hash{}, triedb)
  349. for _, val := range testdata1 {
  350. ctr.Update([]byte(val.k), []byte(val.v))
  351. }
  352. root, _ := ctr.Commit(nil)
  353. if !memonly {
  354. triedb.Commit(root, true, nil)
  355. }
  356. barNodeHash := common.HexToHash("05041990364eb72fcb1127652ce40d8bab765f2bfe53225b1170d276cc101c2e")
  357. var (
  358. barNodeBlob []byte
  359. barNodeObj *cachedNode
  360. )
  361. if memonly {
  362. barNodeObj = triedb.dirties[barNodeHash]
  363. delete(triedb.dirties, barNodeHash)
  364. } else {
  365. barNodeBlob, _ = diskdb.Get(barNodeHash[:])
  366. diskdb.Delete(barNodeHash[:])
  367. }
  368. // Create a new iterator that seeks to "bars". Seeking can't proceed because
  369. // the node is missing.
  370. tr, _ := New(root, triedb)
  371. it := tr.NodeIterator([]byte("bars"))
  372. missing, ok := it.Error().(*MissingNodeError)
  373. if !ok {
  374. t.Fatal("want MissingNodeError, got", it.Error())
  375. } else if missing.NodeHash != barNodeHash {
  376. t.Fatal("wrong node missing")
  377. }
  378. // Reinsert the missing node.
  379. if memonly {
  380. triedb.dirties[barNodeHash] = barNodeObj
  381. } else {
  382. diskdb.Put(barNodeHash[:], barNodeBlob)
  383. }
  384. // Check that iteration produces the right set of values.
  385. if err := checkIteratorOrder(testdata1[2:], NewIterator(it)); err != nil {
  386. t.Fatal(err)
  387. }
  388. }
  389. func checkIteratorNoDups(t *testing.T, it NodeIterator, seen map[string]bool) int {
  390. if seen == nil {
  391. seen = make(map[string]bool)
  392. }
  393. for it.Next(true) {
  394. if seen[string(it.Path())] {
  395. t.Fatalf("iterator visited node path %x twice", it.Path())
  396. }
  397. seen[string(it.Path())] = true
  398. }
  399. return len(seen)
  400. }