trie_test.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. "hash"
  23. "io/ioutil"
  24. "math/big"
  25. "math/rand"
  26. "os"
  27. "reflect"
  28. "testing"
  29. "testing/quick"
  30. "github.com/davecgh/go-spew/spew"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/ethdb/leveldb"
  35. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "golang.org/x/crypto/sha3"
  38. )
  39. func init() {
  40. spew.Config.Indent = " "
  41. spew.Config.DisableMethods = false
  42. }
  43. // Used for testing
  44. func newEmpty() *Trie {
  45. trie, _ := New(common.Hash{}, NewDatabase(memorydb.New()))
  46. return trie
  47. }
  48. func TestEmptyTrie(t *testing.T) {
  49. var trie Trie
  50. res := trie.Hash()
  51. exp := emptyRoot
  52. if res != exp {
  53. t.Errorf("expected %x got %x", exp, res)
  54. }
  55. }
  56. func TestNull(t *testing.T) {
  57. var trie Trie
  58. key := make([]byte, 32)
  59. value := []byte("test")
  60. trie.Update(key, value)
  61. if !bytes.Equal(trie.Get(key), value) {
  62. t.Fatal("wrong value")
  63. }
  64. }
  65. func TestMissingRoot(t *testing.T) {
  66. trie, err := New(common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), NewDatabase(memorydb.New()))
  67. if trie != nil {
  68. t.Error("New returned non-nil trie for invalid root")
  69. }
  70. if _, ok := err.(*MissingNodeError); !ok {
  71. t.Errorf("New returned wrong error: %v", err)
  72. }
  73. }
  74. func TestMissingNodeDisk(t *testing.T) { testMissingNode(t, false) }
  75. func TestMissingNodeMemonly(t *testing.T) { testMissingNode(t, true) }
  76. func testMissingNode(t *testing.T, memonly bool) {
  77. diskdb := memorydb.New()
  78. triedb := NewDatabase(diskdb)
  79. trie, _ := New(common.Hash{}, triedb)
  80. updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
  81. updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
  82. root, _ := trie.Commit(nil)
  83. if !memonly {
  84. triedb.Commit(root, true, nil)
  85. }
  86. trie, _ = New(root, triedb)
  87. _, err := trie.TryGet([]byte("120000"))
  88. if err != nil {
  89. t.Errorf("Unexpected error: %v", err)
  90. }
  91. trie, _ = New(root, triedb)
  92. _, err = trie.TryGet([]byte("120099"))
  93. if err != nil {
  94. t.Errorf("Unexpected error: %v", err)
  95. }
  96. trie, _ = New(root, triedb)
  97. _, err = trie.TryGet([]byte("123456"))
  98. if err != nil {
  99. t.Errorf("Unexpected error: %v", err)
  100. }
  101. trie, _ = New(root, triedb)
  102. err = trie.TryUpdate([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
  103. if err != nil {
  104. t.Errorf("Unexpected error: %v", err)
  105. }
  106. trie, _ = New(root, triedb)
  107. err = trie.TryDelete([]byte("123456"))
  108. if err != nil {
  109. t.Errorf("Unexpected error: %v", err)
  110. }
  111. hash := common.HexToHash("0xe1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9")
  112. if memonly {
  113. delete(triedb.dirties, hash)
  114. } else {
  115. diskdb.Delete(hash[:])
  116. }
  117. trie, _ = New(root, triedb)
  118. _, err = trie.TryGet([]byte("120000"))
  119. if _, ok := err.(*MissingNodeError); !ok {
  120. t.Errorf("Wrong error: %v", err)
  121. }
  122. trie, _ = New(root, triedb)
  123. _, err = trie.TryGet([]byte("120099"))
  124. if _, ok := err.(*MissingNodeError); !ok {
  125. t.Errorf("Wrong error: %v", err)
  126. }
  127. trie, _ = New(root, triedb)
  128. _, err = trie.TryGet([]byte("123456"))
  129. if err != nil {
  130. t.Errorf("Unexpected error: %v", err)
  131. }
  132. trie, _ = New(root, triedb)
  133. err = trie.TryUpdate([]byte("120099"), []byte("zxcv"))
  134. if _, ok := err.(*MissingNodeError); !ok {
  135. t.Errorf("Wrong error: %v", err)
  136. }
  137. trie, _ = New(root, triedb)
  138. err = trie.TryDelete([]byte("123456"))
  139. if _, ok := err.(*MissingNodeError); !ok {
  140. t.Errorf("Wrong error: %v", err)
  141. }
  142. }
  143. func TestInsert(t *testing.T) {
  144. trie := newEmpty()
  145. updateString(trie, "doe", "reindeer")
  146. updateString(trie, "dog", "puppy")
  147. updateString(trie, "dogglesworth", "cat")
  148. exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
  149. root := trie.Hash()
  150. if root != exp {
  151. t.Errorf("case 1: exp %x got %x", exp, root)
  152. }
  153. trie = newEmpty()
  154. updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
  155. exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
  156. root, err := trie.Commit(nil)
  157. if err != nil {
  158. t.Fatalf("commit error: %v", err)
  159. }
  160. if root != exp {
  161. t.Errorf("case 2: exp %x got %x", exp, root)
  162. }
  163. }
  164. func TestGet(t *testing.T) {
  165. trie := newEmpty()
  166. updateString(trie, "doe", "reindeer")
  167. updateString(trie, "dog", "puppy")
  168. updateString(trie, "dogglesworth", "cat")
  169. for i := 0; i < 2; i++ {
  170. res := getString(trie, "dog")
  171. if !bytes.Equal(res, []byte("puppy")) {
  172. t.Errorf("expected puppy got %x", res)
  173. }
  174. unknown := getString(trie, "unknown")
  175. if unknown != nil {
  176. t.Errorf("expected nil got %x", unknown)
  177. }
  178. if i == 1 {
  179. return
  180. }
  181. trie.Commit(nil)
  182. }
  183. }
  184. func TestDelete(t *testing.T) {
  185. trie := newEmpty()
  186. vals := []struct{ k, v string }{
  187. {"do", "verb"},
  188. {"ether", "wookiedoo"},
  189. {"horse", "stallion"},
  190. {"shaman", "horse"},
  191. {"doge", "coin"},
  192. {"ether", ""},
  193. {"dog", "puppy"},
  194. {"shaman", ""},
  195. }
  196. for _, val := range vals {
  197. if val.v != "" {
  198. updateString(trie, val.k, val.v)
  199. } else {
  200. deleteString(trie, val.k)
  201. }
  202. }
  203. hash := trie.Hash()
  204. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  205. if hash != exp {
  206. t.Errorf("expected %x got %x", exp, hash)
  207. }
  208. }
  209. func TestEmptyValues(t *testing.T) {
  210. trie := newEmpty()
  211. vals := []struct{ k, v string }{
  212. {"do", "verb"},
  213. {"ether", "wookiedoo"},
  214. {"horse", "stallion"},
  215. {"shaman", "horse"},
  216. {"doge", "coin"},
  217. {"ether", ""},
  218. {"dog", "puppy"},
  219. {"shaman", ""},
  220. }
  221. for _, val := range vals {
  222. updateString(trie, val.k, val.v)
  223. }
  224. hash := trie.Hash()
  225. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  226. if hash != exp {
  227. t.Errorf("expected %x got %x", exp, hash)
  228. }
  229. }
  230. func TestReplication(t *testing.T) {
  231. trie := newEmpty()
  232. vals := []struct{ k, v string }{
  233. {"do", "verb"},
  234. {"ether", "wookiedoo"},
  235. {"horse", "stallion"},
  236. {"shaman", "horse"},
  237. {"doge", "coin"},
  238. {"dog", "puppy"},
  239. {"somethingveryoddindeedthis is", "myothernodedata"},
  240. }
  241. for _, val := range vals {
  242. updateString(trie, val.k, val.v)
  243. }
  244. exp, err := trie.Commit(nil)
  245. if err != nil {
  246. t.Fatalf("commit error: %v", err)
  247. }
  248. // create a new trie on top of the database and check that lookups work.
  249. trie2, err := New(exp, trie.db)
  250. if err != nil {
  251. t.Fatalf("can't recreate trie at %x: %v", exp, err)
  252. }
  253. for _, kv := range vals {
  254. if string(getString(trie2, kv.k)) != kv.v {
  255. t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
  256. }
  257. }
  258. hash, err := trie2.Commit(nil)
  259. if err != nil {
  260. t.Fatalf("commit error: %v", err)
  261. }
  262. if hash != exp {
  263. t.Errorf("root failure. expected %x got %x", exp, hash)
  264. }
  265. // perform some insertions on the new trie.
  266. vals2 := []struct{ k, v string }{
  267. {"do", "verb"},
  268. {"ether", "wookiedoo"},
  269. {"horse", "stallion"},
  270. // {"shaman", "horse"},
  271. // {"doge", "coin"},
  272. // {"ether", ""},
  273. // {"dog", "puppy"},
  274. // {"somethingveryoddindeedthis is", "myothernodedata"},
  275. // {"shaman", ""},
  276. }
  277. for _, val := range vals2 {
  278. updateString(trie2, val.k, val.v)
  279. }
  280. if hash := trie2.Hash(); hash != exp {
  281. t.Errorf("root failure. expected %x got %x", exp, hash)
  282. }
  283. }
  284. func TestLargeValue(t *testing.T) {
  285. trie := newEmpty()
  286. trie.Update([]byte("key1"), []byte{99, 99, 99, 99})
  287. trie.Update([]byte("key2"), bytes.Repeat([]byte{1}, 32))
  288. trie.Hash()
  289. }
  290. // TestRandomCases tests som cases that were found via random fuzzing
  291. func TestRandomCases(t *testing.T) {
  292. var rt = []randTestStep{
  293. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 0
  294. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 1
  295. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")}, // step 2
  296. {op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 3
  297. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 4
  298. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 5
  299. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 6
  300. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 7
  301. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")}, // step 8
  302. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")}, // step 9
  303. {op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 10
  304. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 11
  305. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 12
  306. {op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")}, // step 13
  307. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 14
  308. {op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 15
  309. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 16
  310. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")}, // step 17
  311. {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 18
  312. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 19
  313. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")}, // step 20
  314. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")}, // step 21
  315. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")}, // step 22
  316. {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 23
  317. {op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24
  318. {op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 25
  319. }
  320. runRandTest(rt)
  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. opMax // boundary value, not an actual op
  340. )
  341. func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
  342. var allKeys [][]byte
  343. genKey := func() []byte {
  344. if len(allKeys) < 2 || r.Intn(100) < 10 {
  345. // new key
  346. key := make([]byte, r.Intn(50))
  347. r.Read(key)
  348. allKeys = append(allKeys, key)
  349. return key
  350. }
  351. // use existing key
  352. return allKeys[r.Intn(len(allKeys))]
  353. }
  354. var steps randTest
  355. for i := 0; i < size; i++ {
  356. step := randTestStep{op: r.Intn(opMax)}
  357. switch step.op {
  358. case opUpdate:
  359. step.key = genKey()
  360. step.value = make([]byte, 8)
  361. binary.BigEndian.PutUint64(step.value, uint64(i))
  362. case opGet, opDelete:
  363. step.key = genKey()
  364. }
  365. steps = append(steps, step)
  366. }
  367. return reflect.ValueOf(steps)
  368. }
  369. func runRandTest(rt randTest) bool {
  370. triedb := NewDatabase(memorydb.New())
  371. tr, _ := New(common.Hash{}, triedb)
  372. values := make(map[string]string) // tracks content of the trie
  373. for i, step := range rt {
  374. fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n",
  375. step.op, step.key, step.value, i)
  376. switch step.op {
  377. case opUpdate:
  378. tr.Update(step.key, step.value)
  379. values[string(step.key)] = string(step.value)
  380. case opDelete:
  381. tr.Delete(step.key)
  382. delete(values, string(step.key))
  383. case opGet:
  384. v := tr.Get(step.key)
  385. want := values[string(step.key)]
  386. if string(v) != want {
  387. rt[i].err = fmt.Errorf("mismatch for key 0x%x, got 0x%x want 0x%x", step.key, v, want)
  388. }
  389. case opCommit:
  390. _, rt[i].err = tr.Commit(nil)
  391. case opHash:
  392. tr.Hash()
  393. case opReset:
  394. hash, err := tr.Commit(nil)
  395. if err != nil {
  396. rt[i].err = err
  397. return false
  398. }
  399. newtr, err := New(hash, triedb)
  400. if err != nil {
  401. rt[i].err = err
  402. return false
  403. }
  404. tr = newtr
  405. case opItercheckhash:
  406. checktr, _ := New(common.Hash{}, triedb)
  407. it := NewIterator(tr.NodeIterator(nil))
  408. for it.Next() {
  409. checktr.Update(it.Key, it.Value)
  410. }
  411. if tr.Hash() != checktr.Hash() {
  412. rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
  413. }
  414. }
  415. // Abort the test on error.
  416. if rt[i].err != nil {
  417. return false
  418. }
  419. }
  420. return true
  421. }
  422. func TestRandom(t *testing.T) {
  423. if err := quick.Check(runRandTest, nil); err != nil {
  424. if cerr, ok := err.(*quick.CheckError); ok {
  425. t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
  426. }
  427. t.Fatal(err)
  428. }
  429. }
  430. func BenchmarkGet(b *testing.B) { benchGet(b, false) }
  431. func BenchmarkGetDB(b *testing.B) { benchGet(b, true) }
  432. func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
  433. func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
  434. const benchElemCount = 20000
  435. func benchGet(b *testing.B, commit bool) {
  436. trie := new(Trie)
  437. if commit {
  438. _, tmpdb := tempDB()
  439. trie, _ = New(common.Hash{}, tmpdb)
  440. }
  441. k := make([]byte, 32)
  442. for i := 0; i < benchElemCount; i++ {
  443. binary.LittleEndian.PutUint64(k, uint64(i))
  444. trie.Update(k, k)
  445. }
  446. binary.LittleEndian.PutUint64(k, benchElemCount/2)
  447. if commit {
  448. trie.Commit(nil)
  449. }
  450. b.ResetTimer()
  451. for i := 0; i < b.N; i++ {
  452. trie.Get(k)
  453. }
  454. b.StopTimer()
  455. if commit {
  456. ldb := trie.db.diskdb.(*leveldb.Database)
  457. ldb.Close()
  458. os.RemoveAll(ldb.Path())
  459. }
  460. }
  461. func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
  462. trie := newEmpty()
  463. k := make([]byte, 32)
  464. b.ReportAllocs()
  465. for i := 0; i < b.N; i++ {
  466. e.PutUint64(k, uint64(i))
  467. trie.Update(k, k)
  468. }
  469. return trie
  470. }
  471. // Benchmarks the trie hashing. Since the trie caches the result of any operation,
  472. // we cannot use b.N as the number of hashing rouns, since all rounds apart from
  473. // the first one will be NOOP. As such, we'll use b.N as the number of account to
  474. // insert into the trie before measuring the hashing.
  475. // BenchmarkHash-6 288680 4561 ns/op 682 B/op 9 allocs/op
  476. // BenchmarkHash-6 275095 4800 ns/op 685 B/op 9 allocs/op
  477. // pure hasher:
  478. // BenchmarkHash-6 319362 4230 ns/op 675 B/op 9 allocs/op
  479. // BenchmarkHash-6 257460 4674 ns/op 689 B/op 9 allocs/op
  480. // With hashing in-between and pure hasher:
  481. // BenchmarkHash-6 225417 7150 ns/op 982 B/op 12 allocs/op
  482. // BenchmarkHash-6 220378 6197 ns/op 983 B/op 12 allocs/op
  483. // same with old hasher
  484. // BenchmarkHash-6 229758 6437 ns/op 981 B/op 12 allocs/op
  485. // BenchmarkHash-6 212610 7137 ns/op 986 B/op 12 allocs/op
  486. func BenchmarkHash(b *testing.B) {
  487. // Create a realistic account trie to hash. We're first adding and hashing N
  488. // entries, then adding N more.
  489. addresses, accounts := makeAccounts(2 * b.N)
  490. // Insert the accounts into the trie and hash it
  491. trie := newEmpty()
  492. i := 0
  493. for ; i < len(addresses)/2; i++ {
  494. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  495. }
  496. trie.Hash()
  497. for ; i < len(addresses); i++ {
  498. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  499. }
  500. b.ResetTimer()
  501. b.ReportAllocs()
  502. //trie.hashRoot(nil, nil)
  503. trie.Hash()
  504. }
  505. type account struct {
  506. Nonce uint64
  507. Balance *big.Int
  508. Root common.Hash
  509. Code []byte
  510. }
  511. // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation,
  512. // we cannot use b.N as the number of hashing rouns, since all rounds apart from
  513. // the first one will be NOOP. As such, we'll use b.N as the number of account to
  514. // insert into the trie before measuring the hashing.
  515. func BenchmarkCommitAfterHash(b *testing.B) {
  516. b.Run("no-onleaf", func(b *testing.B) {
  517. benchmarkCommitAfterHash(b, nil)
  518. })
  519. var a account
  520. onleaf := func(paths [][]byte, hexpath []byte, leaf []byte, parent common.Hash) error {
  521. rlp.DecodeBytes(leaf, &a)
  522. return nil
  523. }
  524. b.Run("with-onleaf", func(b *testing.B) {
  525. benchmarkCommitAfterHash(b, onleaf)
  526. })
  527. }
  528. func benchmarkCommitAfterHash(b *testing.B, onleaf LeafCallback) {
  529. // Make the random benchmark deterministic
  530. addresses, accounts := makeAccounts(b.N)
  531. trie := newEmpty()
  532. for i := 0; i < len(addresses); i++ {
  533. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  534. }
  535. // Insert the accounts into the trie and hash it
  536. trie.Hash()
  537. b.ResetTimer()
  538. b.ReportAllocs()
  539. trie.Commit(onleaf)
  540. }
  541. func TestTinyTrie(t *testing.T) {
  542. // Create a realistic account trie to hash
  543. _, accounts := makeAccounts(5)
  544. trie := newEmpty()
  545. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
  546. if exp, root := common.HexToHash("8c6a85a4d9fda98feff88450299e574e5378e32391f75a055d470ac0653f1005"), trie.Hash(); exp != root {
  547. t.Errorf("1: got %x, exp %x", root, exp)
  548. }
  549. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
  550. if exp, root := common.HexToHash("ec63b967e98a5720e7f720482151963982890d82c9093c0d486b7eb8883a66b1"), trie.Hash(); exp != root {
  551. t.Errorf("2: got %x, exp %x", root, exp)
  552. }
  553. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
  554. if exp, root := common.HexToHash("0608c1d1dc3905fa22204c7a0e43644831c3b6d3def0f274be623a948197e64a"), trie.Hash(); exp != root {
  555. t.Errorf("3: got %x, exp %x", root, exp)
  556. }
  557. checktr, _ := New(common.Hash{}, trie.db)
  558. it := NewIterator(trie.NodeIterator(nil))
  559. for it.Next() {
  560. checktr.Update(it.Key, it.Value)
  561. }
  562. if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot {
  563. t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot)
  564. }
  565. }
  566. func TestCommitAfterHash(t *testing.T) {
  567. // Create a realistic account trie to hash
  568. addresses, accounts := makeAccounts(1000)
  569. trie := newEmpty()
  570. for i := 0; i < len(addresses); i++ {
  571. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  572. }
  573. // Insert the accounts into the trie and hash it
  574. trie.Hash()
  575. trie.Commit(nil)
  576. root := trie.Hash()
  577. exp := common.HexToHash("72f9d3f3fe1e1dd7b8936442e7642aef76371472d94319900790053c493f3fe6")
  578. if exp != root {
  579. t.Errorf("got %x, exp %x", root, exp)
  580. }
  581. root, _ = trie.Commit(nil)
  582. if exp != root {
  583. t.Errorf("got %x, exp %x", root, exp)
  584. }
  585. }
  586. func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
  587. // Make the random benchmark deterministic
  588. random := rand.New(rand.NewSource(0))
  589. // Create a realistic account trie to hash
  590. addresses = make([][20]byte, size)
  591. for i := 0; i < len(addresses); i++ {
  592. data := make([]byte, 20)
  593. random.Read(data)
  594. copy(addresses[i][:], data)
  595. }
  596. accounts = make([][]byte, len(addresses))
  597. for i := 0; i < len(accounts); i++ {
  598. var (
  599. nonce = uint64(random.Int63())
  600. root = emptyRoot
  601. code = crypto.Keccak256(nil)
  602. )
  603. // The big.Rand function is not deterministic with regards to 64 vs 32 bit systems,
  604. // and will consume different amount of data from the rand source.
  605. //balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
  606. // Therefore, we instead just read via byte buffer
  607. numBytes := random.Uint32() % 33 // [0, 32] bytes
  608. balanceBytes := make([]byte, numBytes)
  609. random.Read(balanceBytes)
  610. balance := new(big.Int).SetBytes(balanceBytes)
  611. data, _ := rlp.EncodeToBytes(&account{nonce, balance, root, code})
  612. accounts[i] = data
  613. }
  614. return addresses, accounts
  615. }
  616. // spongeDb is a dummy db backend which accumulates writes in a sponge
  617. type spongeDb struct {
  618. sponge hash.Hash
  619. id string
  620. journal []string
  621. }
  622. func (s *spongeDb) Has(key []byte) (bool, error) { panic("implement me") }
  623. func (s *spongeDb) Get(key []byte) ([]byte, error) { return nil, errors.New("no such elem") }
  624. func (s *spongeDb) Delete(key []byte) error { panic("implement me") }
  625. func (s *spongeDb) NewBatch() ethdb.Batch { return &spongeBatch{s} }
  626. func (s *spongeDb) Stat(property string) (string, error) { panic("implement me") }
  627. func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
  628. func (s *spongeDb) Close() error { return nil }
  629. func (s *spongeDb) Put(key []byte, value []byte) error {
  630. valbrief := value
  631. if len(valbrief) > 8 {
  632. valbrief = valbrief[:8]
  633. }
  634. s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, key[:8], len(value), valbrief))
  635. s.sponge.Write(key)
  636. s.sponge.Write(value)
  637. return nil
  638. }
  639. func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
  640. // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
  641. type spongeBatch struct {
  642. db *spongeDb
  643. }
  644. func (b *spongeBatch) Put(key, value []byte) error {
  645. b.db.Put(key, value)
  646. return nil
  647. }
  648. func (b *spongeBatch) Delete(key []byte) error { panic("implement me") }
  649. func (b *spongeBatch) ValueSize() int { return 100 }
  650. func (b *spongeBatch) Write() error { return nil }
  651. func (b *spongeBatch) Reset() {}
  652. func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
  653. // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
  654. // in the expected order, and calls the callbacks in the expected order.
  655. // The test data was based on the 'master' code, and is basically random. It can be used
  656. // to check whether changes to the trie modifies the write order or data in any way.
  657. func TestCommitSequence(t *testing.T) {
  658. for i, tc := range []struct {
  659. count int
  660. expWriteSeqHash []byte
  661. expCallbackSeqHash []byte
  662. }{
  663. {20, common.FromHex("873c78df73d60e59d4a2bcf3716e8bfe14554549fea2fc147cb54129382a8066"),
  664. common.FromHex("ff00f91ac05df53b82d7f178d77ada54fd0dca64526f537034a5dbe41b17df2a")},
  665. {200, common.FromHex("ba03d891bb15408c940eea5ee3d54d419595102648d02774a0268d892add9c8e"),
  666. common.FromHex("f3cd509064c8d319bbdd1c68f511850a902ad275e6ed5bea11547e23d492a926")},
  667. {2000, common.FromHex("f7a184f20df01c94f09537401d11e68d97ad0c00115233107f51b9c287ce60c7"),
  668. common.FromHex("ff795ea898ba1e4cfed4a33b4cf5535a347a02cf931f88d88719faf810f9a1c9")},
  669. } {
  670. addresses, accounts := makeAccounts(tc.count)
  671. // This spongeDb is used to check the sequence of disk-db-writes
  672. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  673. db := NewDatabase(s)
  674. trie, _ := New(common.Hash{}, db)
  675. // Another sponge is used to check the callback-sequence
  676. callbackSponge := sha3.NewLegacyKeccak256()
  677. // Fill the trie with elements
  678. for i := 0; i < tc.count; i++ {
  679. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  680. }
  681. // Flush trie -> database
  682. root, _ := trie.Commit(nil)
  683. // Flush memdb -> disk (sponge)
  684. db.Commit(root, false, func(c common.Hash) {
  685. // And spongify the callback-order
  686. callbackSponge.Write(c[:])
  687. })
  688. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  689. t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  690. }
  691. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  692. t.Errorf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  693. }
  694. }
  695. }
  696. // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
  697. // but uses random blobs instead of 'accounts'
  698. func TestCommitSequenceRandomBlobs(t *testing.T) {
  699. for i, tc := range []struct {
  700. count int
  701. expWriteSeqHash []byte
  702. expCallbackSeqHash []byte
  703. }{
  704. {20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"),
  705. common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")},
  706. {200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"),
  707. common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")},
  708. {2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"),
  709. common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")},
  710. } {
  711. prng := rand.New(rand.NewSource(int64(i)))
  712. // This spongeDb is used to check the sequence of disk-db-writes
  713. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  714. db := NewDatabase(s)
  715. trie, _ := New(common.Hash{}, db)
  716. // Another sponge is used to check the callback-sequence
  717. callbackSponge := sha3.NewLegacyKeccak256()
  718. // Fill the trie with elements
  719. for i := 0; i < tc.count; i++ {
  720. key := make([]byte, 32)
  721. var val []byte
  722. // 50% short elements, 50% large elements
  723. if prng.Intn(2) == 0 {
  724. val = make([]byte, 1+prng.Intn(32))
  725. } else {
  726. val = make([]byte, 1+prng.Intn(4096))
  727. }
  728. prng.Read(key)
  729. prng.Read(val)
  730. trie.Update(key, val)
  731. }
  732. // Flush trie -> database
  733. root, _ := trie.Commit(nil)
  734. // Flush memdb -> disk (sponge)
  735. db.Commit(root, false, func(c common.Hash) {
  736. // And spongify the callback-order
  737. callbackSponge.Write(c[:])
  738. })
  739. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  740. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  741. }
  742. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  743. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  744. }
  745. }
  746. }
  747. func TestCommitSequenceStackTrie(t *testing.T) {
  748. for count := 1; count < 200; count++ {
  749. prng := rand.New(rand.NewSource(int64(count)))
  750. // This spongeDb is used to check the sequence of disk-db-writes
  751. s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
  752. db := NewDatabase(s)
  753. trie, _ := New(common.Hash{}, db)
  754. // Another sponge is used for the stacktrie commits
  755. stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
  756. stTrie := NewStackTrie(stackTrieSponge)
  757. // Fill the trie with elements
  758. for i := 1; i < count; i++ {
  759. // For the stack trie, we need to do inserts in proper order
  760. key := make([]byte, 32)
  761. binary.BigEndian.PutUint64(key, uint64(i))
  762. var val []byte
  763. // 50% short elements, 50% large elements
  764. if prng.Intn(2) == 0 {
  765. val = make([]byte, 1+prng.Intn(32))
  766. } else {
  767. val = make([]byte, 1+prng.Intn(1024))
  768. }
  769. prng.Read(val)
  770. trie.TryUpdate(key, val)
  771. stTrie.TryUpdate(key, val)
  772. }
  773. // Flush trie -> database
  774. root, _ := trie.Commit(nil)
  775. // Flush memdb -> disk (sponge)
  776. db.Commit(root, false, nil)
  777. // And flush stacktrie -> disk
  778. stRoot, err := stTrie.Commit()
  779. if err != nil {
  780. t.Fatalf("Failed to commit stack trie %v", err)
  781. }
  782. if stRoot != root {
  783. t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  784. }
  785. if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  786. // Show the journal
  787. t.Logf("Expected:")
  788. for i, v := range s.journal {
  789. t.Logf("op %d: %v", i, v)
  790. }
  791. t.Logf("Stacktrie:")
  792. for i, v := range stackTrieSponge.journal {
  793. t.Logf("op %d: %v", i, v)
  794. }
  795. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp)
  796. }
  797. }
  798. }
  799. // TestCommitSequenceSmallRoot tests that a trie which is essentially only a
  800. // small (<32 byte) shortnode with an included value is properly committed to a
  801. // database.
  802. // This case might not matter, since in practice, all keys are 32 bytes, which means
  803. // that even a small trie which contains a leaf will have an extension making it
  804. // not fit into 32 bytes, rlp-encoded. However, it's still the correct thing to do.
  805. func TestCommitSequenceSmallRoot(t *testing.T) {
  806. s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
  807. db := NewDatabase(s)
  808. trie, _ := New(common.Hash{}, db)
  809. // Another sponge is used for the stacktrie commits
  810. stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
  811. stTrie := NewStackTrie(stackTrieSponge)
  812. // Add a single small-element to the trie(s)
  813. key := make([]byte, 5)
  814. key[0] = 1
  815. trie.TryUpdate(key, []byte{0x1})
  816. stTrie.TryUpdate(key, []byte{0x1})
  817. // Flush trie -> database
  818. root, _ := trie.Commit(nil)
  819. // Flush memdb -> disk (sponge)
  820. db.Commit(root, false, nil)
  821. // And flush stacktrie -> disk
  822. stRoot, err := stTrie.Commit()
  823. if err != nil {
  824. t.Fatalf("Failed to commit stack trie %v", err)
  825. }
  826. if stRoot != root {
  827. t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  828. }
  829. fmt.Printf("root: %x\n", stRoot)
  830. if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  831. t.Fatalf("test, disk write sequence wrong:\ngot %x exp %x\n", got, exp)
  832. }
  833. }
  834. // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
  835. // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  836. // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  837. // of thousand entries)
  838. func BenchmarkHashFixedSize(b *testing.B) {
  839. b.Run("10", func(b *testing.B) {
  840. b.StopTimer()
  841. acc, add := makeAccounts(20)
  842. for i := 0; i < b.N; i++ {
  843. benchmarkHashFixedSize(b, acc, add)
  844. }
  845. })
  846. b.Run("100", func(b *testing.B) {
  847. b.StopTimer()
  848. acc, add := makeAccounts(100)
  849. for i := 0; i < b.N; i++ {
  850. benchmarkHashFixedSize(b, acc, add)
  851. }
  852. })
  853. b.Run("1K", func(b *testing.B) {
  854. b.StopTimer()
  855. acc, add := makeAccounts(1000)
  856. for i := 0; i < b.N; i++ {
  857. benchmarkHashFixedSize(b, acc, add)
  858. }
  859. })
  860. b.Run("10K", func(b *testing.B) {
  861. b.StopTimer()
  862. acc, add := makeAccounts(10000)
  863. for i := 0; i < b.N; i++ {
  864. benchmarkHashFixedSize(b, acc, add)
  865. }
  866. })
  867. b.Run("100K", func(b *testing.B) {
  868. b.StopTimer()
  869. acc, add := makeAccounts(100000)
  870. for i := 0; i < b.N; i++ {
  871. benchmarkHashFixedSize(b, acc, add)
  872. }
  873. })
  874. }
  875. func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  876. b.ReportAllocs()
  877. trie := newEmpty()
  878. for i := 0; i < len(addresses); i++ {
  879. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  880. }
  881. // Insert the accounts into the trie and hash it
  882. b.StartTimer()
  883. trie.Hash()
  884. b.StopTimer()
  885. }
  886. func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  887. b.Run("10", func(b *testing.B) {
  888. b.StopTimer()
  889. acc, add := makeAccounts(20)
  890. for i := 0; i < b.N; i++ {
  891. benchmarkCommitAfterHashFixedSize(b, acc, add)
  892. }
  893. })
  894. b.Run("100", func(b *testing.B) {
  895. b.StopTimer()
  896. acc, add := makeAccounts(100)
  897. for i := 0; i < b.N; i++ {
  898. benchmarkCommitAfterHashFixedSize(b, acc, add)
  899. }
  900. })
  901. b.Run("1K", func(b *testing.B) {
  902. b.StopTimer()
  903. acc, add := makeAccounts(1000)
  904. for i := 0; i < b.N; i++ {
  905. benchmarkCommitAfterHashFixedSize(b, acc, add)
  906. }
  907. })
  908. b.Run("10K", func(b *testing.B) {
  909. b.StopTimer()
  910. acc, add := makeAccounts(10000)
  911. for i := 0; i < b.N; i++ {
  912. benchmarkCommitAfterHashFixedSize(b, acc, add)
  913. }
  914. })
  915. b.Run("100K", func(b *testing.B) {
  916. b.StopTimer()
  917. acc, add := makeAccounts(100000)
  918. for i := 0; i < b.N; i++ {
  919. benchmarkCommitAfterHashFixedSize(b, acc, add)
  920. }
  921. })
  922. }
  923. func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  924. b.ReportAllocs()
  925. trie := newEmpty()
  926. for i := 0; i < len(addresses); i++ {
  927. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  928. }
  929. // Insert the accounts into the trie and hash it
  930. trie.Hash()
  931. b.StartTimer()
  932. trie.Commit(nil)
  933. b.StopTimer()
  934. }
  935. func BenchmarkDerefRootFixedSize(b *testing.B) {
  936. b.Run("10", func(b *testing.B) {
  937. b.StopTimer()
  938. acc, add := makeAccounts(20)
  939. for i := 0; i < b.N; i++ {
  940. benchmarkDerefRootFixedSize(b, acc, add)
  941. }
  942. })
  943. b.Run("100", func(b *testing.B) {
  944. b.StopTimer()
  945. acc, add := makeAccounts(100)
  946. for i := 0; i < b.N; i++ {
  947. benchmarkDerefRootFixedSize(b, acc, add)
  948. }
  949. })
  950. b.Run("1K", func(b *testing.B) {
  951. b.StopTimer()
  952. acc, add := makeAccounts(1000)
  953. for i := 0; i < b.N; i++ {
  954. benchmarkDerefRootFixedSize(b, acc, add)
  955. }
  956. })
  957. b.Run("10K", func(b *testing.B) {
  958. b.StopTimer()
  959. acc, add := makeAccounts(10000)
  960. for i := 0; i < b.N; i++ {
  961. benchmarkDerefRootFixedSize(b, acc, add)
  962. }
  963. })
  964. b.Run("100K", func(b *testing.B) {
  965. b.StopTimer()
  966. acc, add := makeAccounts(100000)
  967. for i := 0; i < b.N; i++ {
  968. benchmarkDerefRootFixedSize(b, acc, add)
  969. }
  970. })
  971. }
  972. func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  973. b.ReportAllocs()
  974. trie := newEmpty()
  975. for i := 0; i < len(addresses); i++ {
  976. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  977. }
  978. h := trie.Hash()
  979. trie.Commit(nil)
  980. b.StartTimer()
  981. trie.db.Dereference(h)
  982. b.StopTimer()
  983. }
  984. func tempDB() (string, *Database) {
  985. dir, err := ioutil.TempDir("", "trie-bench")
  986. if err != nil {
  987. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  988. }
  989. diskdb, err := leveldb.New(dir, 256, 0, "", false)
  990. if err != nil {
  991. panic(fmt.Sprintf("can't create temporary database: %v", err))
  992. }
  993. return dir, NewDatabase(diskdb)
  994. }
  995. func getString(trie *Trie, k string) []byte {
  996. return trie.Get([]byte(k))
  997. }
  998. func updateString(trie *Trie, k, v string) {
  999. trie.Update([]byte(k), []byte(v))
  1000. }
  1001. func deleteString(trie *Trie, k string) {
  1002. trie.Delete([]byte(k))
  1003. }
  1004. func TestDecodeNode(t *testing.T) {
  1005. t.Parallel()
  1006. var (
  1007. hash = make([]byte, 20)
  1008. elems = make([]byte, 20)
  1009. )
  1010. for i := 0; i < 5000000; i++ {
  1011. rand.Read(hash)
  1012. rand.Read(elems)
  1013. decodeNode(hash, elems)
  1014. }
  1015. }