trie_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  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. }
  612. func (s *spongeDb) Has(key []byte) (bool, error) { panic("implement me") }
  613. func (s *spongeDb) Get(key []byte) ([]byte, error) { return nil, errors.New("no such elem") }
  614. func (s *spongeDb) Delete(key []byte) error { panic("implement me") }
  615. func (s *spongeDb) NewBatch() ethdb.Batch { return &spongeBatch{s} }
  616. func (s *spongeDb) Stat(property string) (string, error) { panic("implement me") }
  617. func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
  618. func (s *spongeDb) Close() error { return nil }
  619. func (s *spongeDb) Put(key []byte, value []byte) error {
  620. s.sponge.Write(key)
  621. s.sponge.Write(value)
  622. return nil
  623. }
  624. func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
  625. // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
  626. type spongeBatch struct {
  627. db *spongeDb
  628. }
  629. func (b *spongeBatch) Put(key, value []byte) error {
  630. b.db.Put(key, value)
  631. return nil
  632. }
  633. func (b *spongeBatch) Delete(key []byte) error { panic("implement me") }
  634. func (b *spongeBatch) ValueSize() int { return 100 }
  635. func (b *spongeBatch) Write() error { return nil }
  636. func (b *spongeBatch) Reset() {}
  637. func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
  638. // TestCommitSequence tests that the trie.Commit operation writes the elements of the trie
  639. // in the expected order, and calls the callbacks in the expected order.
  640. // The test data was based on the 'master' code, and is basically random. It can be used
  641. // to check whether changes to the trie modifies the write order or data in any way.
  642. func TestCommitSequence(t *testing.T) {
  643. for i, tc := range []struct {
  644. count int
  645. expWriteSeqHash []byte
  646. expCallbackSeqHash []byte
  647. }{
  648. {20, common.FromHex("68c495e45209e243eb7e4f4e8ca8f9f7be71003bd9cafb8061b4534373740193"),
  649. common.FromHex("01783213033d6b7781a641ab499e680d959336d025ac16f44d02f4f0c021bbf5")},
  650. {200, common.FromHex("3b20d16c13c4bc3eb3b8d0ad7a169fef3b1600e056c0665895d03d3d2b2ff236"),
  651. common.FromHex("fb8db0ec82e8f02729f11228940885b181c3047ab0d654ed0110291ca57111a8")},
  652. {2000, common.FromHex("34eff3d1048bebdf77e9ae8bd939f2e7c742edc3dcd1173cff1aad9dbd20451a"),
  653. common.FromHex("1c981604b1a9f8ffa40e0ae66b14830a87f5a4ed8345146a3912e6b2dcb05e63")},
  654. } {
  655. addresses, accounts := makeAccounts(tc.count)
  656. // This spongeDb is used to check the sequence of disk-db-writes
  657. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  658. db := NewDatabase(s)
  659. trie, _ := New(common.Hash{}, db)
  660. // Another sponge is used to check the callback-sequence
  661. callbackSponge := sha3.NewLegacyKeccak256()
  662. // Fill the trie with elements
  663. for i := 0; i < tc.count; i++ {
  664. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  665. }
  666. // Flush trie -> database
  667. root, _ := trie.Commit(nil)
  668. // Flush memdb -> disk (sponge)
  669. db.Commit(root, false, func(c common.Hash) {
  670. // And spongify the callback-order
  671. callbackSponge.Write(c[:])
  672. })
  673. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  674. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  675. }
  676. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  677. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  678. }
  679. }
  680. }
  681. // TestCommitSequenceRandomBlobs is identical to TestCommitSequence
  682. // but uses random blobs instead of 'accounts'
  683. func TestCommitSequenceRandomBlobs(t *testing.T) {
  684. for i, tc := range []struct {
  685. count int
  686. expWriteSeqHash []byte
  687. expCallbackSeqHash []byte
  688. }{
  689. {20, common.FromHex("8e4a01548551d139fa9e833ebc4e66fc1ba40a4b9b7259d80db32cff7b64ebbc"),
  690. common.FromHex("450238d73bc36dc6cc6f926987e5428535e64be403877c4560e238a52749ba24")},
  691. {200, common.FromHex("6869b4e7b95f3097a19ddb30ff735f922b915314047e041614df06958fc50554"),
  692. common.FromHex("0ace0b03d6cb8c0b82f6289ef5b1a1838306b455a62dafc63cada8e2924f2550")},
  693. {2000, common.FromHex("444200e6f4e2df49f77752f629a96ccf7445d4698c164f962bbd85a0526ef424"),
  694. common.FromHex("117d30dafaa62a1eed498c3dfd70982b377ba2b46dd3e725ed6120c80829e518")},
  695. } {
  696. prng := rand.New(rand.NewSource(int64(i)))
  697. // This spongeDb is used to check the sequence of disk-db-writes
  698. s := &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  699. db := NewDatabase(s)
  700. trie, _ := New(common.Hash{}, db)
  701. // Another sponge is used to check the callback-sequence
  702. callbackSponge := sha3.NewLegacyKeccak256()
  703. // Fill the trie with elements
  704. for i := 0; i < tc.count; i++ {
  705. key := make([]byte, 32)
  706. var val []byte
  707. // 50% short elements, 50% large elements
  708. if prng.Intn(2) == 0 {
  709. val = make([]byte, 1+prng.Intn(32))
  710. } else {
  711. val = make([]byte, 1+prng.Intn(4096))
  712. }
  713. prng.Read(key)
  714. prng.Read(val)
  715. trie.Update(key, val)
  716. }
  717. // Flush trie -> database
  718. root, _ := trie.Commit(nil)
  719. // Flush memdb -> disk (sponge)
  720. db.Commit(root, false, func(c common.Hash) {
  721. // And spongify the callback-order
  722. callbackSponge.Write(c[:])
  723. })
  724. if got, exp := s.sponge.Sum(nil), tc.expWriteSeqHash; !bytes.Equal(got, exp) {
  725. t.Fatalf("test %d, disk write sequence wrong:\ngot %x exp %x\n", i, got, exp)
  726. }
  727. if got, exp := callbackSponge.Sum(nil), tc.expCallbackSeqHash; !bytes.Equal(got, exp) {
  728. t.Fatalf("test %d, call back sequence wrong:\ngot: %x exp %x\n", i, got, exp)
  729. }
  730. }
  731. }
  732. // BenchmarkCommitAfterHashFixedSize benchmarks the Commit (after Hash) of a fixed number of updates to a trie.
  733. // This benchmark is meant to capture the difference on efficiency of small versus large changes. Typically,
  734. // storage tries are small (a couple of entries), whereas the full post-block account trie update is large (a couple
  735. // of thousand entries)
  736. func BenchmarkHashFixedSize(b *testing.B) {
  737. b.Run("10", func(b *testing.B) {
  738. b.StopTimer()
  739. acc, add := makeAccounts(20)
  740. for i := 0; i < b.N; i++ {
  741. benchmarkHashFixedSize(b, acc, add)
  742. }
  743. })
  744. b.Run("100", func(b *testing.B) {
  745. b.StopTimer()
  746. acc, add := makeAccounts(100)
  747. for i := 0; i < b.N; i++ {
  748. benchmarkHashFixedSize(b, acc, add)
  749. }
  750. })
  751. b.Run("1K", func(b *testing.B) {
  752. b.StopTimer()
  753. acc, add := makeAccounts(1000)
  754. for i := 0; i < b.N; i++ {
  755. benchmarkHashFixedSize(b, acc, add)
  756. }
  757. })
  758. b.Run("10K", func(b *testing.B) {
  759. b.StopTimer()
  760. acc, add := makeAccounts(10000)
  761. for i := 0; i < b.N; i++ {
  762. benchmarkHashFixedSize(b, acc, add)
  763. }
  764. })
  765. b.Run("100K", func(b *testing.B) {
  766. b.StopTimer()
  767. acc, add := makeAccounts(100000)
  768. for i := 0; i < b.N; i++ {
  769. benchmarkHashFixedSize(b, acc, add)
  770. }
  771. })
  772. }
  773. func benchmarkHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  774. b.ReportAllocs()
  775. trie := newEmpty()
  776. for i := 0; i < len(addresses); i++ {
  777. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  778. }
  779. // Insert the accounts into the trie and hash it
  780. b.StartTimer()
  781. trie.Hash()
  782. b.StopTimer()
  783. }
  784. func BenchmarkCommitAfterHashFixedSize(b *testing.B) {
  785. b.Run("10", func(b *testing.B) {
  786. b.StopTimer()
  787. acc, add := makeAccounts(20)
  788. for i := 0; i < b.N; i++ {
  789. benchmarkCommitAfterHashFixedSize(b, acc, add)
  790. }
  791. })
  792. b.Run("100", func(b *testing.B) {
  793. b.StopTimer()
  794. acc, add := makeAccounts(100)
  795. for i := 0; i < b.N; i++ {
  796. benchmarkCommitAfterHashFixedSize(b, acc, add)
  797. }
  798. })
  799. b.Run("1K", func(b *testing.B) {
  800. b.StopTimer()
  801. acc, add := makeAccounts(1000)
  802. for i := 0; i < b.N; i++ {
  803. benchmarkCommitAfterHashFixedSize(b, acc, add)
  804. }
  805. })
  806. b.Run("10K", func(b *testing.B) {
  807. b.StopTimer()
  808. acc, add := makeAccounts(10000)
  809. for i := 0; i < b.N; i++ {
  810. benchmarkCommitAfterHashFixedSize(b, acc, add)
  811. }
  812. })
  813. b.Run("100K", func(b *testing.B) {
  814. b.StopTimer()
  815. acc, add := makeAccounts(100000)
  816. for i := 0; i < b.N; i++ {
  817. benchmarkCommitAfterHashFixedSize(b, acc, add)
  818. }
  819. })
  820. }
  821. func benchmarkCommitAfterHashFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  822. b.ReportAllocs()
  823. trie := newEmpty()
  824. for i := 0; i < len(addresses); i++ {
  825. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  826. }
  827. // Insert the accounts into the trie and hash it
  828. trie.Hash()
  829. b.StartTimer()
  830. trie.Commit(nil)
  831. b.StopTimer()
  832. }
  833. func BenchmarkDerefRootFixedSize(b *testing.B) {
  834. b.Run("10", func(b *testing.B) {
  835. b.StopTimer()
  836. acc, add := makeAccounts(20)
  837. for i := 0; i < b.N; i++ {
  838. benchmarkDerefRootFixedSize(b, acc, add)
  839. }
  840. })
  841. b.Run("100", func(b *testing.B) {
  842. b.StopTimer()
  843. acc, add := makeAccounts(100)
  844. for i := 0; i < b.N; i++ {
  845. benchmarkDerefRootFixedSize(b, acc, add)
  846. }
  847. })
  848. b.Run("1K", func(b *testing.B) {
  849. b.StopTimer()
  850. acc, add := makeAccounts(1000)
  851. for i := 0; i < b.N; i++ {
  852. benchmarkDerefRootFixedSize(b, acc, add)
  853. }
  854. })
  855. b.Run("10K", func(b *testing.B) {
  856. b.StopTimer()
  857. acc, add := makeAccounts(10000)
  858. for i := 0; i < b.N; i++ {
  859. benchmarkDerefRootFixedSize(b, acc, add)
  860. }
  861. })
  862. b.Run("100K", func(b *testing.B) {
  863. b.StopTimer()
  864. acc, add := makeAccounts(100000)
  865. for i := 0; i < b.N; i++ {
  866. benchmarkDerefRootFixedSize(b, acc, add)
  867. }
  868. })
  869. }
  870. func benchmarkDerefRootFixedSize(b *testing.B, addresses [][20]byte, accounts [][]byte) {
  871. b.ReportAllocs()
  872. trie := newEmpty()
  873. for i := 0; i < len(addresses); i++ {
  874. trie.Update(crypto.Keccak256(addresses[i][:]), accounts[i])
  875. }
  876. h := trie.Hash()
  877. trie.Commit(nil)
  878. b.StartTimer()
  879. trie.db.Dereference(h)
  880. b.StopTimer()
  881. }
  882. func tempDB() (string, *Database) {
  883. dir, err := ioutil.TempDir("", "trie-bench")
  884. if err != nil {
  885. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  886. }
  887. diskdb, err := leveldb.New(dir, 256, 0, "")
  888. if err != nil {
  889. panic(fmt.Sprintf("can't create temporary database: %v", err))
  890. }
  891. return dir, NewDatabase(diskdb)
  892. }
  893. func getString(trie *Trie, k string) []byte {
  894. return trie.Get([]byte(k))
  895. }
  896. func updateString(trie *Trie, k, v string) {
  897. trie.Update([]byte(k), []byte(v))
  898. }
  899. func deleteString(trie *Trie, k string) {
  900. trie.Delete([]byte(k))
  901. }
  902. func TestDecodeNode(t *testing.T) {
  903. t.Parallel()
  904. var (
  905. hash = make([]byte, 20)
  906. elems = make([]byte, 20)
  907. )
  908. for i := 0; i < 5000000; i++ {
  909. rand.Read(hash)
  910. rand.Read(elems)
  911. decodeNode(hash, elems)
  912. }
  913. }