trie_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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) KeyCount() int { return 100 }
  650. func (b *spongeBatch) ValueSize() int { return 100 }
  651. func (b *spongeBatch) Write() error { return nil }
  652. func (b *spongeBatch) Reset() {}
  653. func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
  654. // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
  655. // in the expected order, and calls the callbacks in the expected order.
  656. // The test data was based on the 'master' code, and is basically random. It can be used
  657. // to check whether changes to the trie modifies the write order or data in any way.
  658. func TestCommitSequence(t *testing.T) {
  659. for i, tc := range []struct {
  660. count int
  661. expWriteSeqHash []byte
  662. expCallbackSeqHash []byte
  663. }{
  664. {20, common.FromHex("873c78df73d60e59d4a2bcf3716e8bfe14554549fea2fc147cb54129382a8066"),
  665. common.FromHex("ff00f91ac05df53b82d7f178d77ada54fd0dca64526f537034a5dbe41b17df2a")},
  666. {200, common.FromHex("ba03d891bb15408c940eea5ee3d54d419595102648d02774a0268d892add9c8e"),
  667. common.FromHex("f3cd509064c8d319bbdd1c68f511850a902ad275e6ed5bea11547e23d492a926")},
  668. {2000, common.FromHex("f7a184f20df01c94f09537401d11e68d97ad0c00115233107f51b9c287ce60c7"),
  669. common.FromHex("ff795ea898ba1e4cfed4a33b4cf5535a347a02cf931f88d88719faf810f9a1c9")},
  670. } {
  671. addresses, accounts := makeAccounts(tc.count)
  672. // This spongeDb is used to check the sequence of disk-db-writes
  673. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  674. db := NewDatabase(s)
  675. trie, _ := New(common.Hash{}, db)
  676. // Another sponge is used to check the callback-sequence
  677. callbackSponge := sha3.NewLegacyKeccak256()
  678. // Fill the trie with elements
  679. for i := 0; i < tc.count; i++ {
  680. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  681. }
  682. // Flush trie -> database
  683. root, _ := trie.Commit(nil)
  684. // Flush memdb -> disk (sponge)
  685. db.Commit(root, false, func(c common.Hash) {
  686. // And spongify the callback-order
  687. callbackSponge.Write(c[:])
  688. })
  689. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  690. t.Errorf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  691. }
  692. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  693. t.Errorf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  694. }
  695. }
  696. }
  697. // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
  698. // but uses random blobs instead of 'accounts'
  699. func TestCommitSequenceRandomBlobs(t *testing.T) {
  700. for i, tc := range []struct {
  701. count int
  702. expWriteSeqHash []byte
  703. expCallbackSeqHash []byte
  704. }{
  705. {20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"),
  706. common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")},
  707. {200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"),
  708. common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")},
  709. {2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"),
  710. common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")},
  711. } {
  712. prng := rand.New(rand.NewSource(int64(i)))
  713. // This spongeDb is used to check the sequence of disk-db-writes
  714. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  715. db := NewDatabase(s)
  716. trie, _ := New(common.Hash{}, db)
  717. // Another sponge is used to check the callback-sequence
  718. callbackSponge := sha3.NewLegacyKeccak256()
  719. // Fill the trie with elements
  720. for i := 0; i < tc.count; i++ {
  721. key := make([]byte, 32)
  722. var val []byte
  723. // 50% short elements, 50% large elements
  724. if prng.Intn(2) == 0 {
  725. val = make([]byte, 1+prng.Intn(32))
  726. } else {
  727. val = make([]byte, 1+prng.Intn(4096))
  728. }
  729. prng.Read(key)
  730. prng.Read(val)
  731. trie.Update(key, val)
  732. }
  733. // Flush trie -> database
  734. root, _ := trie.Commit(nil)
  735. // Flush memdb -> disk (sponge)
  736. db.Commit(root, false, func(c common.Hash) {
  737. // And spongify the callback-order
  738. callbackSponge.Write(c[:])
  739. })
  740. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  741. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  742. }
  743. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  744. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  745. }
  746. }
  747. }
  748. func TestCommitSequenceStackTrie(t *testing.T) {
  749. for count := 1; count < 200; count++ {
  750. prng := rand.New(rand.NewSource(int64(count)))
  751. // This spongeDb is used to check the sequence of disk-db-writes
  752. s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
  753. db := NewDatabase(s)
  754. trie, _ := New(common.Hash{}, db)
  755. // Another sponge is used for the stacktrie commits
  756. stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
  757. stTrie := NewStackTrie(stackTrieSponge)
  758. // Fill the trie with elements
  759. for i := 1; i < count; i++ {
  760. // For the stack trie, we need to do inserts in proper order
  761. key := make([]byte, 32)
  762. binary.BigEndian.PutUint64(key, uint64(i))
  763. var val []byte
  764. // 50% short elements, 50% large elements
  765. if prng.Intn(2) == 0 {
  766. val = make([]byte, 1+prng.Intn(32))
  767. } else {
  768. val = make([]byte, 1+prng.Intn(1024))
  769. }
  770. prng.Read(val)
  771. trie.TryUpdate(key, val)
  772. stTrie.TryUpdate(key, val)
  773. }
  774. // Flush trie -> database
  775. root, _ := trie.Commit(nil)
  776. // Flush memdb -> disk (sponge)
  777. db.Commit(root, false, nil)
  778. // And flush stacktrie -> disk
  779. stRoot, err := stTrie.Commit()
  780. if err != nil {
  781. t.Fatalf("Failed to commit stack trie %v", err)
  782. }
  783. if stRoot != root {
  784. t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  785. }
  786. if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  787. // Show the journal
  788. t.Logf("Expected:")
  789. for i, v := range s.journal {
  790. t.Logf("op %d: %v", i, v)
  791. }
  792. t.Logf("Stacktrie:")
  793. for i, v := range stackTrieSponge.journal {
  794. t.Logf("op %d: %v", i, v)
  795. }
  796. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp)
  797. }
  798. }
  799. }
  800. // TestCommitSequenceSmallRoot tests that a trie which is essentially only a
  801. // small (<32 byte) shortnode with an included value is properly committed to a
  802. // database.
  803. // This case might not matter, since in practice, all keys are 32 bytes, which means
  804. // that even a small trie which contains a leaf will have an extension making it
  805. // not fit into 32 bytes, rlp-encoded. However, it's still the correct thing to do.
  806. func TestCommitSequenceSmallRoot(t *testing.T) {
  807. s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
  808. db := NewDatabase(s)
  809. trie, _ := New(common.Hash{}, db)
  810. // Another sponge is used for the stacktrie commits
  811. stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
  812. stTrie := NewStackTrie(stackTrieSponge)
  813. // Add a single small-element to the trie(s)
  814. key := make([]byte, 5)
  815. key[0] = 1
  816. trie.TryUpdate(key, []byte{0x1})
  817. stTrie.TryUpdate(key, []byte{0x1})
  818. // Flush trie -> database
  819. root, _ := trie.Commit(nil)
  820. // Flush memdb -> disk (sponge)
  821. db.Commit(root, false, nil)
  822. // And flush stacktrie -> disk
  823. stRoot, err := stTrie.Commit()
  824. if err != nil {
  825. t.Fatalf("Failed to commit stack trie %v", err)
  826. }
  827. if stRoot != root {
  828. t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  829. }
  830. fmt.Printf("root: %x\n", stRoot)
  831. if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  832. t.Fatalf("test, disk write sequence wrong:\ngot %x exp %x\n", got, exp)
  833. }
  834. }
  835. // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
  836. // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  837. // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  838. // of thousand entries)
  839. func BenchmarkHashFixedSize(b *testing.B) {
  840. b.Run("10", func(b *testing.B) {
  841. b.StopTimer()
  842. acc, add := makeAccounts(20)
  843. for i := 0; i < b.N; i++ {
  844. benchmarkHashFixedSize(b, acc, add)
  845. }
  846. })
  847. b.Run("100", func(b *testing.B) {
  848. b.StopTimer()
  849. acc, add := makeAccounts(100)
  850. for i := 0; i < b.N; i++ {
  851. benchmarkHashFixedSize(b, acc, add)
  852. }
  853. })
  854. b.Run("1K", func(b *testing.B) {
  855. b.StopTimer()
  856. acc, add := makeAccounts(1000)
  857. for i := 0; i < b.N; i++ {
  858. benchmarkHashFixedSize(b, acc, add)
  859. }
  860. })
  861. b.Run("10K", func(b *testing.B) {
  862. b.StopTimer()
  863. acc, add := makeAccounts(10000)
  864. for i := 0; i < b.N; i++ {
  865. benchmarkHashFixedSize(b, acc, add)
  866. }
  867. })
  868. b.Run("100K", func(b *testing.B) {
  869. b.StopTimer()
  870. acc, add := makeAccounts(100000)
  871. for i := 0; i < b.N; i++ {
  872. benchmarkHashFixedSize(b, acc, add)
  873. }
  874. })
  875. }
  876. func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  877. b.ReportAllocs()
  878. trie := newEmpty()
  879. for i := 0; i < len(addresses); i++ {
  880. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  881. }
  882. // Insert the accounts into the trie and hash it
  883. b.StartTimer()
  884. trie.Hash()
  885. b.StopTimer()
  886. }
  887. func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  888. b.Run("10", func(b *testing.B) {
  889. b.StopTimer()
  890. acc, add := makeAccounts(20)
  891. for i := 0; i < b.N; i++ {
  892. benchmarkCommitAfterHashFixedSize(b, acc, add)
  893. }
  894. })
  895. b.Run("100", func(b *testing.B) {
  896. b.StopTimer()
  897. acc, add := makeAccounts(100)
  898. for i := 0; i < b.N; i++ {
  899. benchmarkCommitAfterHashFixedSize(b, acc, add)
  900. }
  901. })
  902. b.Run("1K", func(b *testing.B) {
  903. b.StopTimer()
  904. acc, add := makeAccounts(1000)
  905. for i := 0; i < b.N; i++ {
  906. benchmarkCommitAfterHashFixedSize(b, acc, add)
  907. }
  908. })
  909. b.Run("10K", func(b *testing.B) {
  910. b.StopTimer()
  911. acc, add := makeAccounts(10000)
  912. for i := 0; i < b.N; i++ {
  913. benchmarkCommitAfterHashFixedSize(b, acc, add)
  914. }
  915. })
  916. b.Run("100K", func(b *testing.B) {
  917. b.StopTimer()
  918. acc, add := makeAccounts(100000)
  919. for i := 0; i < b.N; i++ {
  920. benchmarkCommitAfterHashFixedSize(b, acc, add)
  921. }
  922. })
  923. }
  924. func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  925. b.ReportAllocs()
  926. trie := newEmpty()
  927. for i := 0; i < len(addresses); i++ {
  928. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  929. }
  930. // Insert the accounts into the trie and hash it
  931. trie.Hash()
  932. b.StartTimer()
  933. trie.Commit(nil)
  934. b.StopTimer()
  935. }
  936. func BenchmarkDerefRootFixedSize(b *testing.B) {
  937. b.Run("10", func(b *testing.B) {
  938. b.StopTimer()
  939. acc, add := makeAccounts(20)
  940. for i := 0; i < b.N; i++ {
  941. benchmarkDerefRootFixedSize(b, acc, add)
  942. }
  943. })
  944. b.Run("100", func(b *testing.B) {
  945. b.StopTimer()
  946. acc, add := makeAccounts(100)
  947. for i := 0; i < b.N; i++ {
  948. benchmarkDerefRootFixedSize(b, acc, add)
  949. }
  950. })
  951. b.Run("1K", func(b *testing.B) {
  952. b.StopTimer()
  953. acc, add := makeAccounts(1000)
  954. for i := 0; i < b.N; i++ {
  955. benchmarkDerefRootFixedSize(b, acc, add)
  956. }
  957. })
  958. b.Run("10K", func(b *testing.B) {
  959. b.StopTimer()
  960. acc, add := makeAccounts(10000)
  961. for i := 0; i < b.N; i++ {
  962. benchmarkDerefRootFixedSize(b, acc, add)
  963. }
  964. })
  965. b.Run("100K", func(b *testing.B) {
  966. b.StopTimer()
  967. acc, add := makeAccounts(100000)
  968. for i := 0; i < b.N; i++ {
  969. benchmarkDerefRootFixedSize(b, acc, add)
  970. }
  971. })
  972. }
  973. func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  974. b.ReportAllocs()
  975. trie := newEmpty()
  976. for i := 0; i < len(addresses); i++ {
  977. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  978. }
  979. h := trie.Hash()
  980. trie.Commit(nil)
  981. b.StartTimer()
  982. trie.db.Dereference(h)
  983. b.StopTimer()
  984. }
  985. func tempDB() (string, *Database) {
  986. dir, err := ioutil.TempDir("", "trie-bench")
  987. if err != nil {
  988. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  989. }
  990. diskdb, err := leveldb.New(dir, 256, 0, "", false)
  991. if err != nil {
  992. panic(fmt.Sprintf("can't create temporary database: %v", err))
  993. }
  994. return dir, NewDatabase(diskdb)
  995. }
  996. func getString(trie *Trie, k string) []byte {
  997. return trie.Get([]byte(k))
  998. }
  999. func updateString(trie *Trie, k, v string) {
  1000. trie.Update([]byte(k), []byte(v))
  1001. }
  1002. func deleteString(trie *Trie, k string) {
  1003. trie.Delete([]byte(k))
  1004. }
  1005. func TestDecodeNode(t *testing.T) {
  1006. t.Parallel()
  1007. var (
  1008. hash = make([]byte, 20)
  1009. elems = make([]byte, 20)
  1010. )
  1011. for i := 0; i < 5000000; i++ {
  1012. rand.Read(hash)
  1013. rand.Read(elems)
  1014. decodeNode(hash, elems)
  1015. }
  1016. }