trie_test.go 14 KB

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