trie_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 = []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(path []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(10000)
  544. trie := newEmpty()
  545. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001337"), accounts[3])
  546. if exp, root := common.HexToHash("4fa6efd292cffa2db0083b8bedd23add2798ae73802442f52486e95c3df7111c"), trie.Hash(); exp != root {
  547. t.Fatalf("1: got %x, exp %x", root, exp)
  548. }
  549. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001338"), accounts[4])
  550. if exp, root := common.HexToHash("cb5fb1213826dad9e604f095f8ceb5258fe6b5c01805ce6ef019a50699d2d479"), trie.Hash(); exp != root {
  551. t.Fatalf("2: got %x, exp %x", root, exp)
  552. }
  553. trie.Update(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000001339"), accounts[4])
  554. if exp, root := common.HexToHash("ed7e06b4010057d8703e7b9a160a6d42cf4021f9020da3c8891030349a646987"), trie.Hash(); exp != root {
  555. t.Fatalf("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("e5e9c29bb50446a4081e6d1d748d2892c6101c1e883a1f77cf21d4094b697822")
  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. for j := 0; j < len(addresses[i]); j++ {
  593. addresses[i][j] = byte(random.Intn(256))
  594. }
  595. }
  596. accounts = make([][]byte, len(addresses))
  597. for i := 0; i < len(accounts); i++ {
  598. var (
  599. nonce = uint64(random.Int63())
  600. balance = new(big.Int).Rand(random, new(big.Int).Exp(common.Big2, common.Big256, nil))
  601. root = emptyRoot
  602. code = crypto.Keccak256(nil)
  603. )
  604. accounts[i], _ = rlp.EncodeToBytes(&account{nonce, balance, root, code})
  605. }
  606. return addresses, accounts
  607. }
  608. // spongeDb is a dummy db backend which accumulates writes in a sponge
  609. type spongeDb struct {
  610. sponge hash.Hash
  611. id string
  612. journal []string
  613. }
  614. func (s *spongeDb) Has(key []byte) (bool, error) { panic("implement me") }
  615. func (s *spongeDb) Get(key []byte) ([]byte, error) { return nil, errors.New("no such elem") }
  616. func (s *spongeDb) Delete(key []byte) error { panic("implement me") }
  617. func (s *spongeDb) NewBatch() ethdb.Batch { return &spongeBatch{s} }
  618. func (s *spongeDb) Stat(property string) (string, error) { panic("implement me") }
  619. func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
  620. func (s *spongeDb) Close() error { return nil }
  621. func (s *spongeDb) Put(key []byte, value []byte) error {
  622. valbrief := value
  623. if len(valbrief) > 8 {
  624. valbrief = valbrief[:8]
  625. }
  626. s.journal = append(s.journal, fmt.Sprintf("%v: PUT([%x...], [%d bytes] %x...)\n", s.id, key[:8], len(value), valbrief))
  627. s.sponge.Write(key)
  628. s.sponge.Write(value)
  629. return nil
  630. }
  631. func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
  632. // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
  633. type spongeBatch struct {
  634. db *spongeDb
  635. }
  636. func (b *spongeBatch) Put(key, value []byte) error {
  637. b.db.Put(key, value)
  638. return nil
  639. }
  640. func (b *spongeBatch) Delete(key []byte) error { panic("implement me") }
  641. func (b *spongeBatch) ValueSize() int { return 100 }
  642. func (b *spongeBatch) Write() error { return nil }
  643. func (b *spongeBatch) Reset() {}
  644. func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
  645. // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
  646. // in the expected order, and calls the callbacks in the expected order.
  647. // The test data was based on the 'master' code, and is basically random. It can be used
  648. // to check whether changes to the trie modifies the write order or data in any way.
  649. func TestCommitSequence(t *testing.T) {
  650. for i, tc := range []struct {
  651. count int
  652. expWriteSeqHash []byte
  653. expCallbackSeqHash []byte
  654. }{
  655. {20, common.FromHex("68c495e45209e243eb7e4f4e8ca8f9f7be71003bd9cafb8061b4534373740193"),
  656. common.FromHex("01783213033d6b7781a641ab499e680d959336d025ac16f44d02f4f0c021bbf5")},
  657. {200, common.FromHex("3b20d16c13c4bc3eb3b8d0ad7a169fef3b1600e056c0665895d03d3d2b2ff236"),
  658. common.FromHex("fb8db0ec82e8f02729f11228940885b181c3047ab0d654ed0110291ca57111a8")},
  659. {2000, common.FromHex("34eff3d1048bebdf77e9ae8bd939f2e7c742edc3dcd1173cff1aad9dbd20451a"),
  660. common.FromHex("1c981604b1a9f8ffa40e0ae66b14830a87f5a4ed8345146a3912e6b2dcb05e63")},
  661. } {
  662. addresses, accounts := makeAccounts(tc.count)
  663. // This spongeDb is used to check the sequence of disk-db-writes
  664. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  665. db := NewDatabase(s)
  666. trie, _ := New(common.Hash{}, db)
  667. // Another sponge is used to check the callback-sequence
  668. callbackSponge := sha3.NewLegacyKeccak256()
  669. // Fill the trie with elements
  670. for i := 0; i < tc.count; i++ {
  671. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  672. }
  673. // Flush trie -> database
  674. root, _ := trie.Commit(nil)
  675. // Flush memdb -> disk (sponge)
  676. db.Commit(root, false, func(c common.Hash) {
  677. // And spongify the callback-order
  678. callbackSponge.Write(c[:])
  679. })
  680. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  681. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  682. }
  683. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  684. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  685. }
  686. }
  687. }
  688. // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
  689. // but uses random blobs instead of 'accounts'
  690. func TestCommitSequenceRandomBlobs(t *testing.T) {
  691. for i, tc := range []struct {
  692. count int
  693. expWriteSeqHash []byte
  694. expCallbackSeqHash []byte
  695. }{
  696. {20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"),
  697. common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")},
  698. {200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"),
  699. common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")},
  700. {2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"),
  701. common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")},
  702. } {
  703. prng := rand.New(rand.NewSource(int64(i)))
  704. // This spongeDb is used to check the sequence of disk-db-writes
  705. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  706. db := NewDatabase(s)
  707. trie, _ := New(common.Hash{}, db)
  708. // Another sponge is used to check the callback-sequence
  709. callbackSponge := sha3.NewLegacyKeccak256()
  710. // Fill the trie with elements
  711. for i := 0; i < tc.count; i++ {
  712. key := make([]byte, 32)
  713. var val []byte
  714. // 50% short elements, 50% large elements
  715. if prng.Intn(2) == 0 {
  716. val = make([]byte, 1+prng.Intn(32))
  717. } else {
  718. val = make([]byte, 1+prng.Intn(4096))
  719. }
  720. prng.Read(key)
  721. prng.Read(val)
  722. trie.Update(key, val)
  723. }
  724. // Flush trie -> database
  725. root, _ := trie.Commit(nil)
  726. // Flush memdb -> disk (sponge)
  727. db.Commit(root, false, func(c common.Hash) {
  728. // And spongify the callback-order
  729. callbackSponge.Write(c[:])
  730. })
  731. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  732. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  733. }
  734. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  735. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  736. }
  737. }
  738. }
  739. func TestCommitSequenceStackTrie(t *testing.T) {
  740. for count := 1; count < 200; count++ {
  741. prng := rand.New(rand.NewSource(int64(count)))
  742. // This spongeDb is used to check the sequence of disk-db-writes
  743. s := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "a"}
  744. db := NewDatabase(s)
  745. trie, _ := New(common.Hash{}, db)
  746. // Another sponge is used for the stacktrie commits
  747. stackTrieSponge := &spongeDb{sponge: sha3.NewLegacyKeccak256(), id: "b"}
  748. stTrie := NewStackTrie(stackTrieSponge)
  749. // Fill the trie with elements
  750. for i := 1; i < count; i++ {
  751. // For the stack trie, we need to do inserts in proper order
  752. key := make([]byte, 32)
  753. binary.BigEndian.PutUint64(key, uint64(i))
  754. var val []byte
  755. // 50% short elements, 50% large elements
  756. if prng.Intn(2) == 0 {
  757. val = make([]byte, 1+prng.Intn(32))
  758. } else {
  759. val = make([]byte, 1+prng.Intn(1024))
  760. }
  761. prng.Read(val)
  762. trie.TryUpdate(key, common.CopyBytes(val))
  763. stTrie.TryUpdate(key, common.CopyBytes(val))
  764. }
  765. // Flush trie -> database
  766. root, _ := trie.Commit(nil)
  767. // Flush memdb -> disk (sponge)
  768. db.Commit(root, false, nil)
  769. // And flush stacktrie -> disk
  770. stRoot, err := stTrie.Commit()
  771. if err != nil {
  772. t.Fatalf("Failed to commit stack trie %v", err)
  773. }
  774. if stRoot != root {
  775. t.Fatalf("root wrong, got %x exp %x", stRoot, root)
  776. }
  777. if got, exp := stackTrieSponge.sponge.Sum(nil), s.sponge.Sum(nil); !bytes.Equal(got, exp) {
  778. // Show the journal
  779. t.Logf("Expected:")
  780. for i, v := range s.journal {
  781. t.Logf("op %d: %v", i, v)
  782. }
  783. t.Logf("Stacktrie:")
  784. for i, v := range stackTrieSponge.journal {
  785. t.Logf("op %d: %v", i, v)
  786. }
  787. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", count, got, exp)
  788. }
  789. }
  790. }
  791. // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
  792. // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  793. // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  794. // of thousand entries)
  795. func BenchmarkHashFixedSize(b *testing.B) {
  796. b.Run("10", func(b *testing.B) {
  797. b.StopTimer()
  798. acc, add := makeAccounts(20)
  799. for i := 0; i < b.N; i++ {
  800. benchmarkHashFixedSize(b, acc, add)
  801. }
  802. })
  803. b.Run("100", func(b *testing.B) {
  804. b.StopTimer()
  805. acc, add := makeAccounts(100)
  806. for i := 0; i < b.N; i++ {
  807. benchmarkHashFixedSize(b, acc, add)
  808. }
  809. })
  810. b.Run("1K", func(b *testing.B) {
  811. b.StopTimer()
  812. acc, add := makeAccounts(1000)
  813. for i := 0; i < b.N; i++ {
  814. benchmarkHashFixedSize(b, acc, add)
  815. }
  816. })
  817. b.Run("10K", func(b *testing.B) {
  818. b.StopTimer()
  819. acc, add := makeAccounts(10000)
  820. for i := 0; i < b.N; i++ {
  821. benchmarkHashFixedSize(b, acc, add)
  822. }
  823. })
  824. b.Run("100K", func(b *testing.B) {
  825. b.StopTimer()
  826. acc, add := makeAccounts(100000)
  827. for i := 0; i < b.N; i++ {
  828. benchmarkHashFixedSize(b, acc, add)
  829. }
  830. })
  831. }
  832. func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  833. b.ReportAllocs()
  834. trie := newEmpty()
  835. for i := 0; i < len(addresses); i++ {
  836. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  837. }
  838. // Insert the accounts into the trie and hash it
  839. b.StartTimer()
  840. trie.Hash()
  841. b.StopTimer()
  842. }
  843. func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  844. b.Run("10", func(b *testing.B) {
  845. b.StopTimer()
  846. acc, add := makeAccounts(20)
  847. for i := 0; i < b.N; i++ {
  848. benchmarkCommitAfterHashFixedSize(b, acc, add)
  849. }
  850. })
  851. b.Run("100", func(b *testing.B) {
  852. b.StopTimer()
  853. acc, add := makeAccounts(100)
  854. for i := 0; i < b.N; i++ {
  855. benchmarkCommitAfterHashFixedSize(b, acc, add)
  856. }
  857. })
  858. b.Run("1K", func(b *testing.B) {
  859. b.StopTimer()
  860. acc, add := makeAccounts(1000)
  861. for i := 0; i < b.N; i++ {
  862. benchmarkCommitAfterHashFixedSize(b, acc, add)
  863. }
  864. })
  865. b.Run("10K", func(b *testing.B) {
  866. b.StopTimer()
  867. acc, add := makeAccounts(10000)
  868. for i := 0; i < b.N; i++ {
  869. benchmarkCommitAfterHashFixedSize(b, acc, add)
  870. }
  871. })
  872. b.Run("100K", func(b *testing.B) {
  873. b.StopTimer()
  874. acc, add := makeAccounts(100000)
  875. for i := 0; i < b.N; i++ {
  876. benchmarkCommitAfterHashFixedSize(b, acc, add)
  877. }
  878. })
  879. }
  880. func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  881. b.ReportAllocs()
  882. trie := newEmpty()
  883. for i := 0; i < len(addresses); i++ {
  884. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  885. }
  886. // Insert the accounts into the trie and hash it
  887. trie.Hash()
  888. b.StartTimer()
  889. trie.Commit(nil)
  890. b.StopTimer()
  891. }
  892. func BenchmarkDerefRootFixedSize(b *testing.B) {
  893. b.Run("10", func(b *testing.B) {
  894. b.StopTimer()
  895. acc, add := makeAccounts(20)
  896. for i := 0; i < b.N; i++ {
  897. benchmarkDerefRootFixedSize(b, acc, add)
  898. }
  899. })
  900. b.Run("100", func(b *testing.B) {
  901. b.StopTimer()
  902. acc, add := makeAccounts(100)
  903. for i := 0; i < b.N; i++ {
  904. benchmarkDerefRootFixedSize(b, acc, add)
  905. }
  906. })
  907. b.Run("1K", func(b *testing.B) {
  908. b.StopTimer()
  909. acc, add := makeAccounts(1000)
  910. for i := 0; i < b.N; i++ {
  911. benchmarkDerefRootFixedSize(b, acc, add)
  912. }
  913. })
  914. b.Run("10K", func(b *testing.B) {
  915. b.StopTimer()
  916. acc, add := makeAccounts(10000)
  917. for i := 0; i < b.N; i++ {
  918. benchmarkDerefRootFixedSize(b, acc, add)
  919. }
  920. })
  921. b.Run("100K", func(b *testing.B) {
  922. b.StopTimer()
  923. acc, add := makeAccounts(100000)
  924. for i := 0; i < b.N; i++ {
  925. benchmarkDerefRootFixedSize(b, acc, add)
  926. }
  927. })
  928. }
  929. func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  930. b.ReportAllocs()
  931. trie := newEmpty()
  932. for i := 0; i < len(addresses); i++ {
  933. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  934. }
  935. h := trie.Hash()
  936. trie.Commit(nil)
  937. b.StartTimer()
  938. trie.db.Dereference(h)
  939. b.StopTimer()
  940. }
  941. func tempDB() (string, *Database) {
  942. dir, err := ioutil.TempDir("", "trie-bench")
  943. if err != nil {
  944. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  945. }
  946. diskdb, err := leveldb.New(dir, 256, 0, "")
  947. if err != nil {
  948. panic(fmt.Sprintf("can't create temporary database: %v", err))
  949. }
  950. return dir, NewDatabase(diskdb)
  951. }
  952. func getString(trie *Trie, k string) []byte {
  953. return trie.Get([]byte(k))
  954. }
  955. func updateString(trie *Trie, k, v string) {
  956. trie.Update([]byte(k), []byte(v))
  957. }
  958. func deleteString(trie *Trie, k string) {
  959. trie.Delete([]byte(k))
  960. }
  961. func TestDecodeNode(t *testing.T) {
  962. t.Parallel()
  963. var (
  964. hash = make([]byte, 20)
  965. elems = make([]byte, 20)
  966. )
  967. for i := 0; i < 5000000; i++ {
  968. rand.Read(hash)
  969. rand.Read(elems)
  970. decodeNode(hash, elems)
  971. }
  972. }