iterator_test.go 9.5 KB

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