trie_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "math/rand"
  24. "os"
  25. "reflect"
  26. "testing"
  27. "testing/quick"
  28. "github.com/davecgh/go-spew/spew"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. )
  32. func init() {
  33. spew.Config.Indent = " "
  34. spew.Config.DisableMethods = false
  35. }
  36. // Used for testing
  37. func newEmpty() *Trie {
  38. db, _ := ethdb.NewMemDatabase()
  39. trie, _ := New(common.Hash{}, db)
  40. return trie
  41. }
  42. func TestEmptyTrie(t *testing.T) {
  43. var trie Trie
  44. res := trie.Hash()
  45. exp := emptyRoot
  46. if res != common.Hash(exp) {
  47. t.Errorf("expected %x got %x", exp, res)
  48. }
  49. }
  50. func TestNull(t *testing.T) {
  51. var trie Trie
  52. key := make([]byte, 32)
  53. value := []byte("test")
  54. trie.Update(key, value)
  55. if !bytes.Equal(trie.Get(key), value) {
  56. t.Fatal("wrong value")
  57. }
  58. }
  59. func TestMissingRoot(t *testing.T) {
  60. db, _ := ethdb.NewMemDatabase()
  61. trie, err := New(common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), db)
  62. if trie != nil {
  63. t.Error("New returned non-nil trie for invalid root")
  64. }
  65. if _, ok := err.(*MissingNodeError); !ok {
  66. t.Errorf("New returned wrong error: %v", err)
  67. }
  68. }
  69. func TestMissingNode(t *testing.T) {
  70. db, _ := ethdb.NewMemDatabase()
  71. trie, _ := New(common.Hash{}, db)
  72. updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
  73. updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
  74. root, _ := trie.Commit()
  75. trie, _ = New(root, db)
  76. _, err := trie.TryGet([]byte("120000"))
  77. if err != nil {
  78. t.Errorf("Unexpected error: %v", err)
  79. }
  80. trie, _ = New(root, db)
  81. _, err = trie.TryGet([]byte("120099"))
  82. if err != nil {
  83. t.Errorf("Unexpected error: %v", err)
  84. }
  85. trie, _ = New(root, db)
  86. _, err = trie.TryGet([]byte("123456"))
  87. if err != nil {
  88. t.Errorf("Unexpected error: %v", err)
  89. }
  90. trie, _ = New(root, db)
  91. err = trie.TryUpdate([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
  92. if err != nil {
  93. t.Errorf("Unexpected error: %v", err)
  94. }
  95. trie, _ = New(root, db)
  96. err = trie.TryDelete([]byte("123456"))
  97. if err != nil {
  98. t.Errorf("Unexpected error: %v", err)
  99. }
  100. db.Delete(common.FromHex("e1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9"))
  101. trie, _ = New(root, db)
  102. _, err = trie.TryGet([]byte("120000"))
  103. if _, ok := err.(*MissingNodeError); !ok {
  104. t.Errorf("Wrong error: %v", err)
  105. }
  106. trie, _ = New(root, db)
  107. _, err = trie.TryGet([]byte("120099"))
  108. if _, ok := err.(*MissingNodeError); !ok {
  109. t.Errorf("Wrong error: %v", err)
  110. }
  111. trie, _ = New(root, db)
  112. _, err = trie.TryGet([]byte("123456"))
  113. if err != nil {
  114. t.Errorf("Unexpected error: %v", err)
  115. }
  116. trie, _ = New(root, db)
  117. err = trie.TryUpdate([]byte("120099"), []byte("zxcv"))
  118. if _, ok := err.(*MissingNodeError); !ok {
  119. t.Errorf("Wrong error: %v", err)
  120. }
  121. trie, _ = New(root, db)
  122. err = trie.TryDelete([]byte("123456"))
  123. if _, ok := err.(*MissingNodeError); !ok {
  124. t.Errorf("Wrong error: %v", err)
  125. }
  126. }
  127. func TestInsert(t *testing.T) {
  128. trie := newEmpty()
  129. updateString(trie, "doe", "reindeer")
  130. updateString(trie, "dog", "puppy")
  131. updateString(trie, "dogglesworth", "cat")
  132. exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
  133. root := trie.Hash()
  134. if root != exp {
  135. t.Errorf("exp %x got %x", exp, root)
  136. }
  137. trie = newEmpty()
  138. updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
  139. exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
  140. root, err := trie.Commit()
  141. if err != nil {
  142. t.Fatalf("commit error: %v", err)
  143. }
  144. if root != exp {
  145. t.Errorf("exp %x got %x", exp, root)
  146. }
  147. }
  148. func TestGet(t *testing.T) {
  149. trie := newEmpty()
  150. updateString(trie, "doe", "reindeer")
  151. updateString(trie, "dog", "puppy")
  152. updateString(trie, "dogglesworth", "cat")
  153. for i := 0; i < 2; i++ {
  154. res := getString(trie, "dog")
  155. if !bytes.Equal(res, []byte("puppy")) {
  156. t.Errorf("expected puppy got %x", res)
  157. }
  158. unknown := getString(trie, "unknown")
  159. if unknown != nil {
  160. t.Errorf("expected nil got %x", unknown)
  161. }
  162. if i == 1 {
  163. return
  164. }
  165. trie.Commit()
  166. }
  167. }
  168. func TestDelete(t *testing.T) {
  169. trie := newEmpty()
  170. vals := []struct{ k, v string }{
  171. {"do", "verb"},
  172. {"ether", "wookiedoo"},
  173. {"horse", "stallion"},
  174. {"shaman", "horse"},
  175. {"doge", "coin"},
  176. {"ether", ""},
  177. {"dog", "puppy"},
  178. {"shaman", ""},
  179. }
  180. for _, val := range vals {
  181. if val.v != "" {
  182. updateString(trie, val.k, val.v)
  183. } else {
  184. deleteString(trie, val.k)
  185. }
  186. }
  187. hash := trie.Hash()
  188. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  189. if hash != exp {
  190. t.Errorf("expected %x got %x", exp, hash)
  191. }
  192. }
  193. func TestEmptyValues(t *testing.T) {
  194. trie := newEmpty()
  195. vals := []struct{ k, v string }{
  196. {"do", "verb"},
  197. {"ether", "wookiedoo"},
  198. {"horse", "stallion"},
  199. {"shaman", "horse"},
  200. {"doge", "coin"},
  201. {"ether", ""},
  202. {"dog", "puppy"},
  203. {"shaman", ""},
  204. }
  205. for _, val := range vals {
  206. updateString(trie, val.k, val.v)
  207. }
  208. hash := trie.Hash()
  209. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  210. if hash != exp {
  211. t.Errorf("expected %x got %x", exp, hash)
  212. }
  213. }
  214. func TestReplication(t *testing.T) {
  215. trie := newEmpty()
  216. vals := []struct{ k, v string }{
  217. {"do", "verb"},
  218. {"ether", "wookiedoo"},
  219. {"horse", "stallion"},
  220. {"shaman", "horse"},
  221. {"doge", "coin"},
  222. {"dog", "puppy"},
  223. {"somethingveryoddindeedthis is", "myothernodedata"},
  224. }
  225. for _, val := range vals {
  226. updateString(trie, val.k, val.v)
  227. }
  228. exp, err := trie.Commit()
  229. if err != nil {
  230. t.Fatalf("commit error: %v", err)
  231. }
  232. // create a new trie on top of the database and check that lookups work.
  233. trie2, err := New(exp, trie.db)
  234. if err != nil {
  235. t.Fatalf("can't recreate trie at %x: %v", exp, err)
  236. }
  237. for _, kv := range vals {
  238. if string(getString(trie2, kv.k)) != kv.v {
  239. t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
  240. }
  241. }
  242. hash, err := trie2.Commit()
  243. if err != nil {
  244. t.Fatalf("commit error: %v", err)
  245. }
  246. if hash != exp {
  247. t.Errorf("root failure. expected %x got %x", exp, hash)
  248. }
  249. // perform some insertions on the new trie.
  250. vals2 := []struct{ k, v string }{
  251. {"do", "verb"},
  252. {"ether", "wookiedoo"},
  253. {"horse", "stallion"},
  254. // {"shaman", "horse"},
  255. // {"doge", "coin"},
  256. // {"ether", ""},
  257. // {"dog", "puppy"},
  258. // {"somethingveryoddindeedthis is", "myothernodedata"},
  259. // {"shaman", ""},
  260. }
  261. for _, val := range vals2 {
  262. updateString(trie2, val.k, val.v)
  263. }
  264. if hash := trie2.Hash(); hash != exp {
  265. t.Errorf("root failure. expected %x got %x", exp, hash)
  266. }
  267. }
  268. func TestLargeValue(t *testing.T) {
  269. trie := newEmpty()
  270. trie.Update([]byte("key1"), []byte{99, 99, 99, 99})
  271. trie.Update([]byte("key2"), bytes.Repeat([]byte{1}, 32))
  272. trie.Hash()
  273. }
  274. type countingDB struct {
  275. Database
  276. gets map[string]int
  277. }
  278. func (db *countingDB) Get(key []byte) ([]byte, error) {
  279. db.gets[string(key)]++
  280. return db.Database.Get(key)
  281. }
  282. // TestCacheUnload checks that decoded nodes are unloaded after a
  283. // certain number of commit operations.
  284. func TestCacheUnload(t *testing.T) {
  285. // Create test trie with two branches.
  286. trie := newEmpty()
  287. key1 := "---------------------------------"
  288. key2 := "---some other branch"
  289. updateString(trie, key1, "this is the branch of key1.")
  290. updateString(trie, key2, "this is the branch of key2.")
  291. root, _ := trie.Commit()
  292. // Commit the trie repeatedly and access key1.
  293. // The branch containing it is loaded from DB exactly two times:
  294. // in the 0th and 6th iteration.
  295. db := &countingDB{Database: trie.db, gets: make(map[string]int)}
  296. trie, _ = New(root, db)
  297. trie.SetCacheLimit(5)
  298. for i := 0; i < 12; i++ {
  299. getString(trie, key1)
  300. trie.Commit()
  301. }
  302. // Check that it got loaded two times.
  303. for dbkey, count := range db.gets {
  304. if count != 2 {
  305. t.Errorf("db key %x loaded %d times, want %d times", []byte(dbkey), count, 2)
  306. }
  307. }
  308. }
  309. // randTest performs random trie operations.
  310. // Instances of this test are created by Generate.
  311. type randTest []randTestStep
  312. type randTestStep struct {
  313. op int
  314. key []byte // for opUpdate, opDelete, opGet
  315. value []byte // for opUpdate
  316. err error // for debugging
  317. }
  318. const (
  319. opUpdate = iota
  320. opDelete
  321. opGet
  322. opCommit
  323. opHash
  324. opReset
  325. opItercheckhash
  326. opCheckCacheInvariant
  327. opMax // boundary value, not an actual op
  328. )
  329. func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
  330. var allKeys [][]byte
  331. genKey := func() []byte {
  332. if len(allKeys) < 2 || r.Intn(100) < 10 {
  333. // new key
  334. key := make([]byte, r.Intn(50))
  335. r.Read(key)
  336. allKeys = append(allKeys, key)
  337. return key
  338. }
  339. // use existing key
  340. return allKeys[r.Intn(len(allKeys))]
  341. }
  342. var steps randTest
  343. for i := 0; i < size; i++ {
  344. step := randTestStep{op: r.Intn(opMax)}
  345. switch step.op {
  346. case opUpdate:
  347. step.key = genKey()
  348. step.value = make([]byte, 8)
  349. binary.BigEndian.PutUint64(step.value, uint64(i))
  350. case opGet, opDelete:
  351. step.key = genKey()
  352. }
  353. steps = append(steps, step)
  354. }
  355. return reflect.ValueOf(steps)
  356. }
  357. func runRandTest(rt randTest) bool {
  358. db, _ := ethdb.NewMemDatabase()
  359. tr, _ := New(common.Hash{}, db)
  360. values := make(map[string]string) // tracks content of the trie
  361. for i, step := range rt {
  362. switch step.op {
  363. case opUpdate:
  364. tr.Update(step.key, step.value)
  365. values[string(step.key)] = string(step.value)
  366. case opDelete:
  367. tr.Delete(step.key)
  368. delete(values, string(step.key))
  369. case opGet:
  370. v := tr.Get(step.key)
  371. want := values[string(step.key)]
  372. if string(v) != want {
  373. rt[i].err = fmt.Errorf("mismatch for key 0x%x, got 0x%x want 0x%x", step.key, v, want)
  374. }
  375. case opCommit:
  376. _, rt[i].err = tr.Commit()
  377. case opHash:
  378. tr.Hash()
  379. case opReset:
  380. hash, err := tr.Commit()
  381. if err != nil {
  382. rt[i].err = err
  383. return false
  384. }
  385. newtr, err := New(hash, db)
  386. if err != nil {
  387. rt[i].err = err
  388. return false
  389. }
  390. tr = newtr
  391. case opItercheckhash:
  392. checktr, _ := New(common.Hash{}, nil)
  393. it := NewIterator(tr.NodeIterator(nil))
  394. for it.Next() {
  395. checktr.Update(it.Key, it.Value)
  396. }
  397. if tr.Hash() != checktr.Hash() {
  398. rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
  399. }
  400. case opCheckCacheInvariant:
  401. rt[i].err = checkCacheInvariant(tr.root, nil, tr.cachegen, false, 0)
  402. }
  403. // Abort the test on error.
  404. if rt[i].err != nil {
  405. return false
  406. }
  407. }
  408. return true
  409. }
  410. func checkCacheInvariant(n, parent node, parentCachegen uint16, parentDirty bool, depth int) error {
  411. var children []node
  412. var flag nodeFlag
  413. switch n := n.(type) {
  414. case *shortNode:
  415. flag = n.flags
  416. children = []node{n.Val}
  417. case *fullNode:
  418. flag = n.flags
  419. children = n.Children[:]
  420. default:
  421. return nil
  422. }
  423. errorf := func(format string, args ...interface{}) error {
  424. msg := fmt.Sprintf(format, args...)
  425. msg += fmt.Sprintf("\nat depth %d node %s", depth, spew.Sdump(n))
  426. msg += fmt.Sprintf("parent: %s", spew.Sdump(parent))
  427. return errors.New(msg)
  428. }
  429. if flag.gen > parentCachegen {
  430. return errorf("cache invariant violation: %d > %d\n", flag.gen, parentCachegen)
  431. }
  432. if depth > 0 && !parentDirty && flag.dirty {
  433. return errorf("cache invariant violation: %d > %d\n", flag.gen, parentCachegen)
  434. }
  435. for _, child := range children {
  436. if err := checkCacheInvariant(child, n, flag.gen, flag.dirty, depth+1); err != nil {
  437. return err
  438. }
  439. }
  440. return nil
  441. }
  442. func TestRandom(t *testing.T) {
  443. if err := quick.Check(runRandTest, nil); err != nil {
  444. if cerr, ok := err.(*quick.CheckError); ok {
  445. t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
  446. }
  447. t.Fatal(err)
  448. }
  449. }
  450. func BenchmarkGet(b *testing.B) { benchGet(b, false) }
  451. func BenchmarkGetDB(b *testing.B) { benchGet(b, true) }
  452. func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
  453. func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
  454. func BenchmarkHashBE(b *testing.B) { benchHash(b, binary.BigEndian) }
  455. func BenchmarkHashLE(b *testing.B) { benchHash(b, binary.LittleEndian) }
  456. const benchElemCount = 20000
  457. func benchGet(b *testing.B, commit bool) {
  458. trie := new(Trie)
  459. if commit {
  460. _, tmpdb := tempDB()
  461. trie, _ = New(common.Hash{}, tmpdb)
  462. }
  463. k := make([]byte, 32)
  464. for i := 0; i < benchElemCount; i++ {
  465. binary.LittleEndian.PutUint64(k, uint64(i))
  466. trie.Update(k, k)
  467. }
  468. binary.LittleEndian.PutUint64(k, benchElemCount/2)
  469. if commit {
  470. trie.Commit()
  471. }
  472. b.ResetTimer()
  473. for i := 0; i < b.N; i++ {
  474. trie.Get(k)
  475. }
  476. b.StopTimer()
  477. if commit {
  478. ldb := trie.db.(*ethdb.LDBDatabase)
  479. ldb.Close()
  480. os.RemoveAll(ldb.Path())
  481. }
  482. }
  483. func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
  484. trie := newEmpty()
  485. k := make([]byte, 32)
  486. for i := 0; i < b.N; i++ {
  487. e.PutUint64(k, uint64(i))
  488. trie.Update(k, k)
  489. }
  490. return trie
  491. }
  492. func benchHash(b *testing.B, e binary.ByteOrder) {
  493. trie := newEmpty()
  494. k := make([]byte, 32)
  495. for i := 0; i < benchElemCount; i++ {
  496. e.PutUint64(k, uint64(i))
  497. trie.Update(k, k)
  498. }
  499. b.ResetTimer()
  500. for i := 0; i < b.N; i++ {
  501. trie.Hash()
  502. }
  503. }
  504. func tempDB() (string, Database) {
  505. dir, err := ioutil.TempDir("", "trie-bench")
  506. if err != nil {
  507. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  508. }
  509. db, err := ethdb.NewLDBDatabase(dir, 256, 0)
  510. if err != nil {
  511. panic(fmt.Sprintf("can't create temporary database: %v", err))
  512. }
  513. return dir, db
  514. }
  515. func getString(trie *Trie, k string) []byte {
  516. return trie.Get([]byte(k))
  517. }
  518. func updateString(trie *Trie, k, v string) {
  519. trie.Update([]byte(k), []byte(v))
  520. }
  521. func deleteString(trie *Trie, k string) {
  522. trie.Delete([]byte(k))
  523. }