iterator_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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"
  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.nodes {
  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. for _, key := range db.diskdb.(*ethdb.MemDatabase).Keys() {
  110. if _, ok := hashes[common.BytesToHash(key)]; !ok {
  111. t.Errorf("state entry not reported %x", key)
  112. }
  113. }
  114. }
  115. type kvs struct{ k, v string }
  116. var testdata1 = []kvs{
  117. {"barb", "ba"},
  118. {"bard", "bc"},
  119. {"bars", "bb"},
  120. {"bar", "b"},
  121. {"fab", "z"},
  122. {"food", "ab"},
  123. {"foos", "aa"},
  124. {"foo", "a"},
  125. }
  126. var testdata2 = []kvs{
  127. {"aardvark", "c"},
  128. {"bar", "b"},
  129. {"barb", "bd"},
  130. {"bars", "be"},
  131. {"fab", "z"},
  132. {"foo", "a"},
  133. {"foos", "aa"},
  134. {"food", "ab"},
  135. {"jars", "d"},
  136. }
  137. func TestIteratorSeek(t *testing.T) {
  138. trie := newEmpty()
  139. for _, val := range testdata1 {
  140. trie.Update([]byte(val.k), []byte(val.v))
  141. }
  142. // Seek to the middle.
  143. it := NewIterator(trie.NodeIterator([]byte("fab")))
  144. if err := checkIteratorOrder(testdata1[4:], it); err != nil {
  145. t.Fatal(err)
  146. }
  147. // Seek to a non-existent key.
  148. it = NewIterator(trie.NodeIterator([]byte("barc")))
  149. if err := checkIteratorOrder(testdata1[1:], it); err != nil {
  150. t.Fatal(err)
  151. }
  152. // Seek beyond the end.
  153. it = NewIterator(trie.NodeIterator([]byte("z")))
  154. if err := checkIteratorOrder(nil, it); err != nil {
  155. t.Fatal(err)
  156. }
  157. }
  158. func checkIteratorOrder(want []kvs, it *Iterator) error {
  159. for it.Next() {
  160. if len(want) == 0 {
  161. return fmt.Errorf("didn't expect any more values, got key %q", it.Key)
  162. }
  163. if !bytes.Equal(it.Key, []byte(want[0].k)) {
  164. return fmt.Errorf("wrong key: got %q, want %q", it.Key, want[0].k)
  165. }
  166. want = want[1:]
  167. }
  168. if len(want) > 0 {
  169. return fmt.Errorf("iterator ended early, want key %q", want[0])
  170. }
  171. return nil
  172. }
  173. func TestDifferenceIterator(t *testing.T) {
  174. triea := newEmpty()
  175. for _, val := range testdata1 {
  176. triea.Update([]byte(val.k), []byte(val.v))
  177. }
  178. triea.Commit(nil)
  179. trieb := newEmpty()
  180. for _, val := range testdata2 {
  181. trieb.Update([]byte(val.k), []byte(val.v))
  182. }
  183. trieb.Commit(nil)
  184. found := make(map[string]string)
  185. di, _ := NewDifferenceIterator(triea.NodeIterator(nil), trieb.NodeIterator(nil))
  186. it := NewIterator(di)
  187. for it.Next() {
  188. found[string(it.Key)] = string(it.Value)
  189. }
  190. all := []struct{ k, v string }{
  191. {"aardvark", "c"},
  192. {"barb", "bd"},
  193. {"bars", "be"},
  194. {"jars", "d"},
  195. }
  196. for _, item := range all {
  197. if found[item.k] != item.v {
  198. t.Errorf("iterator value mismatch for %s: got %v want %v", item.k, found[item.k], item.v)
  199. }
  200. }
  201. if len(found) != len(all) {
  202. t.Errorf("iterator count mismatch: got %d values, want %d", len(found), len(all))
  203. }
  204. }
  205. func TestUnionIterator(t *testing.T) {
  206. triea := newEmpty()
  207. for _, val := range testdata1 {
  208. triea.Update([]byte(val.k), []byte(val.v))
  209. }
  210. triea.Commit(nil)
  211. trieb := newEmpty()
  212. for _, val := range testdata2 {
  213. trieb.Update([]byte(val.k), []byte(val.v))
  214. }
  215. trieb.Commit(nil)
  216. di, _ := NewUnionIterator([]NodeIterator{triea.NodeIterator(nil), trieb.NodeIterator(nil)})
  217. it := NewIterator(di)
  218. all := []struct{ k, v string }{
  219. {"aardvark", "c"},
  220. {"barb", "ba"},
  221. {"barb", "bd"},
  222. {"bard", "bc"},
  223. {"bars", "bb"},
  224. {"bars", "be"},
  225. {"bar", "b"},
  226. {"fab", "z"},
  227. {"food", "ab"},
  228. {"foos", "aa"},
  229. {"foo", "a"},
  230. {"jars", "d"},
  231. }
  232. for i, kv := range all {
  233. if !it.Next() {
  234. t.Errorf("Iterator ends prematurely at element %d", i)
  235. }
  236. if kv.k != string(it.Key) {
  237. t.Errorf("iterator value mismatch for element %d: got key %s want %s", i, it.Key, kv.k)
  238. }
  239. if kv.v != string(it.Value) {
  240. t.Errorf("iterator value mismatch for element %d: got value %s want %s", i, it.Value, kv.v)
  241. }
  242. }
  243. if it.Next() {
  244. t.Errorf("Iterator returned extra values.")
  245. }
  246. }
  247. func TestIteratorNoDups(t *testing.T) {
  248. var tr Trie
  249. for _, val := range testdata1 {
  250. tr.Update([]byte(val.k), []byte(val.v))
  251. }
  252. checkIteratorNoDups(t, tr.NodeIterator(nil), nil)
  253. }
  254. // This test checks that nodeIterator.Next can be retried after inserting missing trie nodes.
  255. func TestIteratorContinueAfterErrorDisk(t *testing.T) { testIteratorContinueAfterError(t, false) }
  256. func TestIteratorContinueAfterErrorMemonly(t *testing.T) { testIteratorContinueAfterError(t, true) }
  257. func testIteratorContinueAfterError(t *testing.T, memonly bool) {
  258. diskdb := ethdb.NewMemDatabase()
  259. triedb := NewDatabase(diskdb)
  260. tr, _ := New(common.Hash{}, triedb)
  261. for _, val := range testdata1 {
  262. tr.Update([]byte(val.k), []byte(val.v))
  263. }
  264. tr.Commit(nil)
  265. if !memonly {
  266. triedb.Commit(tr.Hash(), true)
  267. }
  268. wantNodeCount := checkIteratorNoDups(t, tr.NodeIterator(nil), nil)
  269. var (
  270. diskKeys [][]byte
  271. memKeys []common.Hash
  272. )
  273. if memonly {
  274. memKeys = triedb.Nodes()
  275. } else {
  276. diskKeys = diskdb.Keys()
  277. }
  278. for i := 0; i < 20; i++ {
  279. // Create trie that will load all nodes from DB.
  280. tr, _ := New(tr.Hash(), triedb)
  281. // Remove a random node from the database. It can't be the root node
  282. // because that one is already loaded.
  283. var (
  284. rkey common.Hash
  285. rval []byte
  286. robj *cachedNode
  287. )
  288. for {
  289. if memonly {
  290. rkey = memKeys[rand.Intn(len(memKeys))]
  291. } else {
  292. copy(rkey[:], diskKeys[rand.Intn(len(diskKeys))])
  293. }
  294. if rkey != tr.Hash() {
  295. break
  296. }
  297. }
  298. if memonly {
  299. robj = triedb.nodes[rkey]
  300. delete(triedb.nodes, rkey)
  301. } else {
  302. rval, _ = diskdb.Get(rkey[:])
  303. diskdb.Delete(rkey[:])
  304. }
  305. // Iterate until the error is hit.
  306. seen := make(map[string]bool)
  307. it := tr.NodeIterator(nil)
  308. checkIteratorNoDups(t, it, seen)
  309. missing, ok := it.Error().(*MissingNodeError)
  310. if !ok || missing.NodeHash != rkey {
  311. t.Fatal("didn't hit missing node, got", it.Error())
  312. }
  313. // Add the node back and continue iteration.
  314. if memonly {
  315. triedb.nodes[rkey] = robj
  316. } else {
  317. diskdb.Put(rkey[:], rval)
  318. }
  319. checkIteratorNoDups(t, it, seen)
  320. if it.Error() != nil {
  321. t.Fatal("unexpected error", it.Error())
  322. }
  323. if len(seen) != wantNodeCount {
  324. t.Fatal("wrong node iteration count, got", len(seen), "want", wantNodeCount)
  325. }
  326. }
  327. }
  328. // Similar to the test above, this one checks that failure to create nodeIterator at a
  329. // certain key prefix behaves correctly when Next is called. The expectation is that Next
  330. // should retry seeking before returning true for the first time.
  331. func TestIteratorContinueAfterSeekErrorDisk(t *testing.T) {
  332. testIteratorContinueAfterSeekError(t, false)
  333. }
  334. func TestIteratorContinueAfterSeekErrorMemonly(t *testing.T) {
  335. testIteratorContinueAfterSeekError(t, true)
  336. }
  337. func testIteratorContinueAfterSeekError(t *testing.T, memonly bool) {
  338. // Commit test trie to db, then remove the node containing "bars".
  339. diskdb := ethdb.NewMemDatabase()
  340. triedb := NewDatabase(diskdb)
  341. ctr, _ := New(common.Hash{}, triedb)
  342. for _, val := range testdata1 {
  343. ctr.Update([]byte(val.k), []byte(val.v))
  344. }
  345. root, _ := ctr.Commit(nil)
  346. if !memonly {
  347. triedb.Commit(root, true)
  348. }
  349. barNodeHash := common.HexToHash("05041990364eb72fcb1127652ce40d8bab765f2bfe53225b1170d276cc101c2e")
  350. var (
  351. barNodeBlob []byte
  352. barNodeObj *cachedNode
  353. )
  354. if memonly {
  355. barNodeObj = triedb.nodes[barNodeHash]
  356. delete(triedb.nodes, barNodeHash)
  357. } else {
  358. barNodeBlob, _ = diskdb.Get(barNodeHash[:])
  359. diskdb.Delete(barNodeHash[:])
  360. }
  361. // Create a new iterator that seeks to "bars". Seeking can't proceed because
  362. // the node is missing.
  363. tr, _ := New(root, triedb)
  364. it := tr.NodeIterator([]byte("bars"))
  365. missing, ok := it.Error().(*MissingNodeError)
  366. if !ok {
  367. t.Fatal("want MissingNodeError, got", it.Error())
  368. } else if missing.NodeHash != barNodeHash {
  369. t.Fatal("wrong node missing")
  370. }
  371. // Reinsert the missing node.
  372. if memonly {
  373. triedb.nodes[barNodeHash] = barNodeObj
  374. } else {
  375. diskdb.Put(barNodeHash[:], barNodeBlob)
  376. }
  377. // Check that iteration produces the right set of values.
  378. if err := checkIteratorOrder(testdata1[2:], NewIterator(it)); err != nil {
  379. t.Fatal(err)
  380. }
  381. }
  382. func checkIteratorNoDups(t *testing.T, it NodeIterator, seen map[string]bool) int {
  383. if seen == nil {
  384. seen = make(map[string]bool)
  385. }
  386. for it.Next(true) {
  387. if seen[string(it.Path())] {
  388. t.Fatalf("iterator visited node path %x twice", it.Path())
  389. }
  390. seen[string(it.Path())] = true
  391. }
  392. return len(seen)
  393. }