trie_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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, nil)
  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("case 1: 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("case 2: 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. // TestRandomCases tests som cases that were found via random fuzzing
  287. func TestRandomCases(t *testing.T) {
  288. var rt []randTestStep = []randTestStep{
  289. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 0
  290. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 1
  291. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000002")}, // step 2
  292. {op: 2, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 3
  293. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 4
  294. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 5
  295. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 6
  296. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 7
  297. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000008")}, // step 8
  298. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000009")}, // step 9
  299. {op: 2, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 10
  300. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 11
  301. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 12
  302. {op: 0, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("000000000000000d")}, // step 13
  303. {op: 6, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 14
  304. {op: 1, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("")}, // step 15
  305. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 16
  306. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000011")}, // step 17
  307. {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 18
  308. {op: 3, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 19
  309. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000014")}, // step 20
  310. {op: 0, key: common.Hex2Bytes("d51b182b95d677e5f1c82508c0228de96b73092d78ce78b2230cd948674f66fd1483bd"), value: common.Hex2Bytes("0000000000000015")}, // step 21
  311. {op: 0, key: common.Hex2Bytes("c2a38512b83107d665c65235b0250002882ac2022eb00711552354832c5f1d030d0e408e"), value: common.Hex2Bytes("0000000000000016")}, // step 22
  312. {op: 5, key: common.Hex2Bytes(""), value: common.Hex2Bytes("")}, // step 23
  313. {op: 1, key: common.Hex2Bytes("980c393656413a15c8da01978ed9f89feb80b502f58f2d640e3a2f5f7a99a7018f1b573befd92053ac6f78fca4a87268"), value: common.Hex2Bytes("")}, // step 24
  314. {op: 1, key: common.Hex2Bytes("fd"), value: common.Hex2Bytes("")}, // step 25
  315. }
  316. runRandTest(rt)
  317. }
  318. // randTest performs random trie operations.
  319. // Instances of this test are created by Generate.
  320. type randTest []randTestStep
  321. type randTestStep struct {
  322. op int
  323. key []byte // for opUpdate, opDelete, opGet
  324. value []byte // for opUpdate
  325. err error // for debugging
  326. }
  327. const (
  328. opUpdate = iota
  329. opDelete
  330. opGet
  331. opCommit
  332. opHash
  333. opReset
  334. opItercheckhash
  335. opMax // boundary value, not an actual op
  336. )
  337. func (randTest) Generate(r *rand.Rand, size int) reflect.Value {
  338. var allKeys [][]byte
  339. genKey := func() []byte {
  340. if len(allKeys) < 2 || r.Intn(100) < 10 {
  341. // new key
  342. key := make([]byte, r.Intn(50))
  343. r.Read(key)
  344. allKeys = append(allKeys, key)
  345. return key
  346. }
  347. // use existing key
  348. return allKeys[r.Intn(len(allKeys))]
  349. }
  350. var steps randTest
  351. for i := 0; i < size; i++ {
  352. step := randTestStep{op: r.Intn(opMax)}
  353. switch step.op {
  354. case opUpdate:
  355. step.key = genKey()
  356. step.value = make([]byte, 8)
  357. binary.BigEndian.PutUint64(step.value, uint64(i))
  358. case opGet, opDelete:
  359. step.key = genKey()
  360. }
  361. steps = append(steps, step)
  362. }
  363. return reflect.ValueOf(steps)
  364. }
  365. func runRandTest(rt randTest) bool {
  366. triedb := NewDatabase(memorydb.New())
  367. tr, _ := New(common.Hash{}, triedb)
  368. values := make(map[string]string) // tracks content of the trie
  369. for i, step := range rt {
  370. fmt.Printf("{op: %d, key: common.Hex2Bytes(\"%x\"), value: common.Hex2Bytes(\"%x\")}, // step %d\n",
  371. step.op, step.key, step.value, i)
  372. switch step.op {
  373. case opUpdate:
  374. tr.Update(step.key, step.value)
  375. values[string(step.key)] = string(step.value)
  376. case opDelete:
  377. tr.Delete(step.key)
  378. delete(values, string(step.key))
  379. case opGet:
  380. v := tr.Get(step.key)
  381. want := values[string(step.key)]
  382. if string(v) != want {
  383. rt[i].err = fmt.Errorf("mismatch for key 0x%x, got 0x%x want 0x%x", step.key, v, want)
  384. }
  385. case opCommit:
  386. _, rt[i].err = tr.Commit(nil)
  387. case opHash:
  388. tr.Hash()
  389. case opReset:
  390. hash, err := tr.Commit(nil)
  391. if err != nil {
  392. rt[i].err = err
  393. return false
  394. }
  395. newtr, err := New(hash, triedb)
  396. if err != nil {
  397. rt[i].err = err
  398. return false
  399. }
  400. tr = newtr
  401. case opItercheckhash:
  402. checktr, _ := New(common.Hash{}, triedb)
  403. it := NewIterator(tr.NodeIterator(nil))
  404. for it.Next() {
  405. checktr.Update(it.Key, it.Value)
  406. }
  407. if tr.Hash() != checktr.Hash() {
  408. rt[i].err = fmt.Errorf("hash mismatch in opItercheckhash")
  409. }
  410. }
  411. // Abort the test on error.
  412. if rt[i].err != nil {
  413. return false
  414. }
  415. }
  416. return true
  417. }
  418. func TestRandom(t *testing.T) {
  419. if err := quick.Check(runRandTest, nil); err != nil {
  420. if cerr, ok := err.(*quick.CheckError); ok {
  421. t.Fatalf("random test iteration %d failed: %s", cerr.Count, spew.Sdump(cerr.In))
  422. }
  423. t.Fatal(err)
  424. }
  425. }
  426. func BenchmarkGet(b *testing.B) { benchGet(b, false) }
  427. func BenchmarkGetDB(b *testing.B) { benchGet(b, true) }
  428. func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
  429. func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
  430. const benchElemCount = 20000
  431. func benchGet(b *testing.B, commit bool) {
  432. trie := new(Trie)
  433. if commit {
  434. _, tmpdb := tempDB()
  435. trie, _ = New(common.Hash{}, tmpdb)
  436. }
  437. k := make([]byte, 32)
  438. for i := 0; i < benchElemCount; i++ {
  439. binary.LittleEndian.PutUint64(k, uint64(i))
  440. trie.Update(k, k)
  441. }
  442. binary.LittleEndian.PutUint64(k, benchElemCount/2)
  443. if commit {
  444. trie.Commit(nil)
  445. }
  446. b.ResetTimer()
  447. for i := 0; i < b.N; i++ {
  448. trie.Get(k)
  449. }
  450. b.StopTimer()
  451. if commit {
  452. ldb := trie.db.diskdb.(*leveldb.Database)
  453. ldb.Close()
  454. os.RemoveAll(ldb.Path())
  455. }
  456. }
  457. func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
  458. trie := newEmpty()
  459. k := make([]byte, 32)
  460. b.ReportAllocs()
  461. for i := 0; i < b.N; i++ {
  462. e.PutUint64(k, uint64(i))
  463. trie.Update(k, k)
  464. }
  465. return trie
  466. }
  467. // Benchmarks the trie hashing. Since the trie caches the result of any operation,
  468. // we cannot use b.N as the number of hashing rouns, since all rounds apart from
  469. // the first one will be NOOP. As such, we'll use b.N as the number of account to
  470. // insert into the trie before measuring the hashing.
  471. // BenchmarkHash-6 288680 4561 ns/op 682 B/op 9 allocs/op
  472. // BenchmarkHash-6 275095 4800 ns/op 685 B/op 9 allocs/op
  473. // pure hasher:
  474. // BenchmarkHash-6 319362 4230 ns/op 675 B/op 9 allocs/op
  475. // BenchmarkHash-6 257460 4674 ns/op 689 B/op 9 allocs/op
  476. // With hashing in-between and pure hasher:
  477. // BenchmarkHash-6 225417 7150 ns/op 982 B/op 12 allocs/op
  478. // BenchmarkHash-6 220378 6197 ns/op 983 B/op 12 allocs/op
  479. // same with old hasher
  480. // BenchmarkHash-6 229758 6437 ns/op 981 B/op 12 allocs/op
  481. // BenchmarkHash-6 212610 7137 ns/op 986 B/op 12 allocs/op
  482. func BenchmarkHash(b *testing.B) {
  483. // Create a realistic account trie to hash. We're first adding and hashing N
  484. // entries, then adding N more.
  485. addresses, accounts := makeAccounts(2 * b.N)
  486. // Insert the accounts into the trie and hash it
  487. trie := newEmpty()
  488. i := 0
  489. for ; i < len(addresses)/2; i++ {
  490. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  491. }
  492. trie.Hash()
  493. for ; i < len(addresses); i++ {
  494. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  495. }
  496. b.ResetTimer()
  497. b.ReportAllocs()
  498. //trie.hashRoot(nil, nil)
  499. trie.Hash()
  500. }
  501. type account struct {
  502. Nonce uint64
  503. Balance *big.Int
  504. Root common.Hash
  505. Code []byte
  506. }
  507. // Benchmarks the trie Commit following a Hash. Since the trie caches the result of any operation,
  508. // we cannot use b.N as the number of hashing rouns, since all rounds apart from
  509. // the first one will be NOOP. As such, we'll use b.N as the number of account to
  510. // insert into the trie before measuring the hashing.
  511. func BenchmarkCommitAfterHash(b *testing.B) {
  512. b.Run("no-onleaf", func(b *testing.B) {
  513. benchmarkCommitAfterHash(b, nil)
  514. })
  515. var a account
  516. onleaf := func(leaf []byte, parent common.Hash) error {
  517. rlp.DecodeBytes(leaf, &a)
  518. return nil
  519. }
  520. b.Run("with-onleaf", func(b *testing.B) {
  521. benchmarkCommitAfterHash(b, onleaf)
  522. })
  523. }
  524. func benchmarkCommitAfterHash(b *testing.B, onleaf LeafCallback) {
  525. // Make the random benchmark deterministic
  526. addresses, accounts := makeAccounts(b.N)
  527. trie := newEmpty()
  528. for i := 0; i < len(addresses); i++ {
  529. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  530. }
  531. // Insert the accounts into the trie and hash it
  532. trie.Hash()
  533. b.ResetTimer()
  534. b.ReportAllocs()
  535. trie.Commit(onleaf)
  536. }
  537. func TestTinyTrie(t *testing.T) {
  538. // Create a realistic account trie to hash
  539. _, accounts := makeAccounts(10000)
  540. trie := newEmpty()
  541. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
  542. if exp, root := common.HexToHash("4fa6efd292cffa2db0083b8bedd23add2798ae73802442f52486e95c3df7111c"), trie.Hash(); exp != root {
  543. t.Fatalf("1: got %x, exp %x", root, exp)
  544. }
  545. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
  546. if exp, root := common.HexToHash("cb5fb1213826dad9e604f095f8ceb5258fe6b5c01805ce6ef019a50699d2d479"), trie.Hash(); exp != root {
  547. t.Fatalf("2: got %x, exp %x", root, exp)
  548. }
  549. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
  550. if exp, root := common.HexToHash("ed7e06b4010057d8703e7b9a160a6d42cf4021f9020da3c8891030349a646987"), trie.Hash(); exp != root {
  551. t.Fatalf("3: got %x, exp %x", root, exp)
  552. }
  553. checktr, _ := New(common.Hash{}, trie.db)
  554. it := NewIterator(trie.NodeIterator(nil))
  555. for it.Next() {
  556. checktr.Update(it.Key, it.Value)
  557. }
  558. if troot, itroot := trie.Hash(), checktr.Hash(); troot != itroot {
  559. t.Fatalf("hash mismatch in opItercheckhash, trie: %x, check: %x", troot, itroot)
  560. }
  561. }
  562. func TestCommitAfterHash(t *testing.T) {
  563. // Create a realistic account trie to hash
  564. addresses, accounts := makeAccounts(1000)
  565. trie := newEmpty()
  566. for i := 0; i < len(addresses); i++ {
  567. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  568. }
  569. // Insert the accounts into the trie and hash it
  570. trie.Hash()
  571. trie.Commit(nil)
  572. root := trie.Hash()
  573. exp := common.HexToHash("e5e9c29bb50446a4081e6d1d748d2892c6101c1e883a1f77cf21d4094b697822")
  574. if exp != root {
  575. t.Errorf("got %x, exp %x", root, exp)
  576. }
  577. root, _ = trie.Commit(nil)
  578. if exp != root {
  579. t.Errorf("got %x, exp %x", root, exp)
  580. }
  581. }
  582. func makeAccounts(size int) (addresses [][20]byte, accounts [][]byte) {
  583. // Make the random benchmark deterministic
  584. random := rand.New(rand.NewSource(0))
  585. // Create a realistic account trie to hash
  586. addresses = make([][20]byte, size)
  587. for i := 0; i < len(addresses); i++ {
  588. for j := 0; j < len(addresses[i]); j++ {
  589. addresses[i][j] = byte(random.Intn(256))
  590. }
  591. }
  592. accounts = make([][]byte, len(addresses))
  593. for i := 0; i < len(accounts); i++ {
  594. var (
  595. nonce = uint64(random.Int63())
  596. balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
  597. root = emptyRoot
  598. code = crypto.Keccak256(nil)
  599. )
  600. accounts[i], _ = rlp.EncodeToBytes(&account{nonce, balance, root, code})
  601. }
  602. return addresses, accounts
  603. }
  604. // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
  605. // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  606. // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  607. // of thousand entries)
  608. func BenchmarkHashFixedSize(b *testing.B) {
  609. b.Run("10", func(b *testing.B) {
  610. b.StopTimer()
  611. acc, add := makeAccounts(20)
  612. for i := 0; i < b.N; i++ {
  613. benchmarkHashFixedSize(b, acc, add)
  614. }
  615. })
  616. b.Run("100", func(b *testing.B) {
  617. b.StopTimer()
  618. acc, add := makeAccounts(100)
  619. for i := 0; i < b.N; i++ {
  620. benchmarkHashFixedSize(b, acc, add)
  621. }
  622. })
  623. b.Run("1K", func(b *testing.B) {
  624. b.StopTimer()
  625. acc, add := makeAccounts(1000)
  626. for i := 0; i < b.N; i++ {
  627. benchmarkHashFixedSize(b, acc, add)
  628. }
  629. })
  630. b.Run("10K", func(b *testing.B) {
  631. b.StopTimer()
  632. acc, add := makeAccounts(10000)
  633. for i := 0; i < b.N; i++ {
  634. benchmarkHashFixedSize(b, acc, add)
  635. }
  636. })
  637. b.Run("100K", func(b *testing.B) {
  638. b.StopTimer()
  639. acc, add := makeAccounts(100000)
  640. for i := 0; i < b.N; i++ {
  641. benchmarkHashFixedSize(b, acc, add)
  642. }
  643. })
  644. }
  645. func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  646. b.ReportAllocs()
  647. trie := newEmpty()
  648. for i := 0; i < len(addresses); i++ {
  649. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  650. }
  651. // Insert the accounts into the trie and hash it
  652. b.StartTimer()
  653. trie.Hash()
  654. b.StopTimer()
  655. }
  656. func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  657. b.Run("10", func(b *testing.B) {
  658. b.StopTimer()
  659. acc, add := makeAccounts(20)
  660. for i := 0; i < b.N; i++ {
  661. benchmarkCommitAfterHashFixedSize(b, acc, add)
  662. }
  663. })
  664. b.Run("100", func(b *testing.B) {
  665. b.StopTimer()
  666. acc, add := makeAccounts(100)
  667. for i := 0; i < b.N; i++ {
  668. benchmarkCommitAfterHashFixedSize(b, acc, add)
  669. }
  670. })
  671. b.Run("1K", func(b *testing.B) {
  672. b.StopTimer()
  673. acc, add := makeAccounts(1000)
  674. for i := 0; i < b.N; i++ {
  675. benchmarkCommitAfterHashFixedSize(b, acc, add)
  676. }
  677. })
  678. b.Run("10K", func(b *testing.B) {
  679. b.StopTimer()
  680. acc, add := makeAccounts(10000)
  681. for i := 0; i < b.N; i++ {
  682. benchmarkCommitAfterHashFixedSize(b, acc, add)
  683. }
  684. })
  685. b.Run("100K", func(b *testing.B) {
  686. b.StopTimer()
  687. acc, add := makeAccounts(100000)
  688. for i := 0; i < b.N; i++ {
  689. benchmarkCommitAfterHashFixedSize(b, acc, add)
  690. }
  691. })
  692. }
  693. func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  694. b.ReportAllocs()
  695. trie := newEmpty()
  696. for i := 0; i < len(addresses); i++ {
  697. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  698. }
  699. // Insert the accounts into the trie and hash it
  700. trie.Hash()
  701. b.StartTimer()
  702. trie.Commit(nil)
  703. b.StopTimer()
  704. }
  705. func BenchmarkDerefRootFixedSize(b *testing.B) {
  706. b.Run("10", func(b *testing.B) {
  707. b.StopTimer()
  708. acc, add := makeAccounts(20)
  709. for i := 0; i < b.N; i++ {
  710. benchmarkDerefRootFixedSize(b, acc, add)
  711. }
  712. })
  713. b.Run("100", func(b *testing.B) {
  714. b.StopTimer()
  715. acc, add := makeAccounts(100)
  716. for i := 0; i < b.N; i++ {
  717. benchmarkDerefRootFixedSize(b, acc, add)
  718. }
  719. })
  720. b.Run("1K", func(b *testing.B) {
  721. b.StopTimer()
  722. acc, add := makeAccounts(1000)
  723. for i := 0; i < b.N; i++ {
  724. benchmarkDerefRootFixedSize(b, acc, add)
  725. }
  726. })
  727. b.Run("10K", func(b *testing.B) {
  728. b.StopTimer()
  729. acc, add := makeAccounts(10000)
  730. for i := 0; i < b.N; i++ {
  731. benchmarkDerefRootFixedSize(b, acc, add)
  732. }
  733. })
  734. b.Run("100K", func(b *testing.B) {
  735. b.StopTimer()
  736. acc, add := makeAccounts(100000)
  737. for i := 0; i < b.N; i++ {
  738. benchmarkDerefRootFixedSize(b, acc, add)
  739. }
  740. })
  741. }
  742. func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  743. b.ReportAllocs()
  744. trie := newEmpty()
  745. for i := 0; i < len(addresses); i++ {
  746. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  747. }
  748. h := trie.Hash()
  749. trie.Commit(nil)
  750. b.StartTimer()
  751. trie.db.Dereference(h)
  752. b.StopTimer()
  753. }
  754. func tempDB() (string, *Database) {
  755. dir, err := ioutil.TempDir("", "trie-bench")
  756. if err != nil {
  757. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  758. }
  759. diskdb, err := leveldb.New(dir, 256, 0, "")
  760. if err != nil {
  761. panic(fmt.Sprintf("can't create temporary database: %v", err))
  762. }
  763. return dir, NewDatabase(diskdb)
  764. }
  765. func getString(trie *Trie, k string) []byte {
  766. return trie.Get([]byte(k))
  767. }
  768. func updateString(trie *Trie, k, v string) {
  769. trie.Update([]byte(k), []byte(v))
  770. }
  771. func deleteString(trie *Trie, k string) {
  772. trie.Delete([]byte(k))
  773. }
  774. func TestDecodeNode(t *testing.T) {
  775. t.Parallel()
  776. var (
  777. hash = make([]byte, 20)
  778. elems = make([]byte, 20)
  779. )
  780. for i := 0; i < 5000000; i++ {
  781. rand.Read(hash)
  782. rand.Read(elems)
  783. decodeNode(hash, elems)
  784. }
  785. }