trie_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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/big"
  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/crypto"
  31. "github.com/ethereum/go-ethereum/ethdb/leveldb"
  32. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  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(memorydb.New()))
  42. return trie
  43. }
  44. func TestEmptyTrie(t *testing.T) {
  45. var trie Trie
  46. res := trie.Hash()
  47. exp := emptyRoot
  48. if res != 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(memorydb.New()))
  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 := memorydb.New()
  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.dirties, 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. // randTest performs random trie operations.
  287. // Instances of this test are created by Generate.
  288. type randTest []randTestStep
  289. type randTestStep struct {
  290. op int
  291. key []byte // for opUpdate, opDelete, opGet
  292. value []byte // for opUpdate
  293. err error // for debugging
  294. }
  295. const (
  296. opUpdate = iota
  297. opDelete
  298. opGet
  299. opCommit
  300. opHash
  301. opReset
  302. opItercheckhash
  303. opMax // boundary value, not an actual op
  304. )
  305. func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
  306. var allKeys [][]byte
  307. genKey := func() []byte {
  308. if len(allKeys) < 2 || r.Intn(100) < 10 {
  309. // new key
  310. key := make([]byte, r.Intn(50))
  311. r.Read(key)
  312. allKeys = append(allKeys, key)
  313. return key
  314. }
  315. // use existing key
  316. return allKeys[r.Intn(len(allKeys))]
  317. }
  318. var steps randTest
  319. for i := 0; i < size; i++ {
  320. step := randTestStep{op: r.Intn(opMax)}
  321. switch step.op {
  322. case opUpdate:
  323. step.key = genKey()
  324. step.value = make([]byte, 8)
  325. binary.BigEndian.PutUint64(step.value, uint64(i))
  326. case opGet, opDelete:
  327. step.key = genKey()
  328. }
  329. steps = append(steps, step)
  330. }
  331. return reflect.ValueOf(steps)
  332. }
  333. func runRandTest(rt randTest) bool {
  334. triedb := NewDatabase(memorydb.New())
  335. tr, _ := New(common.Hash{}, triedb)
  336. values := make(map[string]string) // tracks content of the trie
  337. for i, step := range rt {
  338. switch step.op {
  339. case opUpdate:
  340. tr.Update(step.key, step.value)
  341. values[string(step.key)] = string(step.value)
  342. case opDelete:
  343. tr.Delete(step.key)
  344. delete(values, string(step.key))
  345. case opGet:
  346. v := tr.Get(step.key)
  347. want := values[string(step.key)]
  348. if string(v) != want {
  349. rt[i].err = fmt.Errorf("mismatch for key 0x%x, got 0x%x want 0x%x", step.key, v, want)
  350. }
  351. case opCommit:
  352. _, rt[i].err = tr.Commit(nil)
  353. case opHash:
  354. tr.Hash()
  355. case opReset:
  356. hash, err := tr.Commit(nil)
  357. if err != nil {
  358. rt[i].err = err
  359. return false
  360. }
  361. newtr, err := New(hash, triedb)
  362. if err != nil {
  363. rt[i].err = err
  364. return false
  365. }
  366. tr = newtr
  367. case opItercheckhash:
  368. checktr, _ := New(common.Hash{}, triedb)
  369. it := NewIterator(tr.NodeIterator(nil))
  370. for it.Next() {
  371. checktr.Update(it.Key, it.Value)
  372. }
  373. if tr.Hash() != checktr.Hash() {
  374. rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
  375. }
  376. }
  377. // Abort the test on error.
  378. if rt[i].err != nil {
  379. return false
  380. }
  381. }
  382. return true
  383. }
  384. func TestRandom(t *testing.T) {
  385. if err := quick.Check(runRandTest, nil); err != nil {
  386. if cerr, ok := err.(*quick.CheckError); ok {
  387. t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
  388. }
  389. t.Fatal(err)
  390. }
  391. }
  392. func BenchmarkGet(b *testing.B) { benchGet(b, false) }
  393. func BenchmarkGetDB(b *testing.B) { benchGet(b, true) }
  394. func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
  395. func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
  396. const benchElemCount = 20000
  397. func benchGet(b *testing.B, commit bool) {
  398. trie := new(Trie)
  399. if commit {
  400. _, tmpdb := tempDB()
  401. trie, _ = New(common.Hash{}, tmpdb)
  402. }
  403. k := make([]byte, 32)
  404. for i := 0; i < benchElemCount; i++ {
  405. binary.LittleEndian.PutUint64(k, uint64(i))
  406. trie.Update(k, k)
  407. }
  408. binary.LittleEndian.PutUint64(k, benchElemCount/2)
  409. if commit {
  410. trie.Commit(nil)
  411. }
  412. b.ResetTimer()
  413. for i := 0; i < b.N; i++ {
  414. trie.Get(k)
  415. }
  416. b.StopTimer()
  417. if commit {
  418. ldb := trie.db.diskdb.(*leveldb.Database)
  419. ldb.Close()
  420. os.RemoveAll(ldb.Path())
  421. }
  422. }
  423. func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
  424. trie := newEmpty()
  425. k := make([]byte, 32)
  426. for i := 0; i < b.N; i++ {
  427. e.PutUint64(k, uint64(i))
  428. trie.Update(k, k)
  429. }
  430. return trie
  431. }
  432. // Benchmarks the trie hashing. Since the trie caches the result of any operation,
  433. // we cannot use b.N as the number of hashing rouns, since all rounds apart from
  434. // the first one will be NOOP. As such, we'll use b.N as the number of account to
  435. // insert into the trie before measuring the hashing.
  436. func BenchmarkHash(b *testing.B) {
  437. // Make the random benchmark deterministic
  438. random := rand.New(rand.NewSource(0))
  439. // Create a realistic account trie to hash
  440. addresses := make([][20]byte, b.N)
  441. for i := 0; i < len(addresses); i++ {
  442. for j := 0; j < len(addresses[i]); j++ {
  443. addresses[i][j] = byte(random.Intn(256))
  444. }
  445. }
  446. accounts := make([][]byte, len(addresses))
  447. for i := 0; i < len(accounts); i++ {
  448. var (
  449. nonce = uint64(random.Int63())
  450. balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
  451. root = emptyRoot
  452. code = crypto.Keccak256(nil)
  453. )
  454. accounts[i], _ = rlp.EncodeToBytes([]interface{}{nonce, balance, root, code})
  455. }
  456. // Insert the accounts into the trie and hash it
  457. trie := newEmpty()
  458. for i := 0; i < len(addresses); i++ {
  459. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  460. }
  461. b.ResetTimer()
  462. b.ReportAllocs()
  463. trie.Hash()
  464. }
  465. func tempDB() (string, *Database) {
  466. dir, err := ioutil.TempDir("", "trie-bench")
  467. if err != nil {
  468. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  469. }
  470. diskdb, err := leveldb.New(dir, 256, 0, "")
  471. if err != nil {
  472. panic(fmt.Sprintf("can't create temporary database: %v", err))
  473. }
  474. return dir, NewDatabase(diskdb)
  475. }
  476. func getString(trie *Trie, k string) []byte {
  477. return trie.Get([]byte(k))
  478. }
  479. func updateString(trie *Trie, k, v string) {
  480. trie.Update([]byte(k), []byte(v))
  481. }
  482. func deleteString(trie *Trie, k string) {
  483. trie.Delete([]byte(k))
  484. }
  485. func TestDecodeNode(t *testing.T) {
  486. t.Parallel()
  487. var (
  488. hash = make([]byte, 20)
  489. elems = make([]byte, 20)
  490. )
  491. for i := 0; i < 5000000; i++ {
  492. rand.Read(hash)
  493. rand.Read(elems)
  494. decodeNode(hash, elems)
  495. }
  496. }