trie_test.go 15 KB

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