trie_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. "os"
  23. "testing"
  24. "github.com/davecgh/go-spew/spew"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. )
  28. func init() {
  29. spew.Config.Indent = " "
  30. spew.Config.DisableMethods = true
  31. }
  32. // Used for testing
  33. func newEmpty() *Trie {
  34. db, _ := ethdb.NewMemDatabase()
  35. trie, _ := New(common.Hash{}, db)
  36. return trie
  37. }
  38. func TestEmptyTrie(t *testing.T) {
  39. var trie Trie
  40. res := trie.Hash()
  41. exp := emptyRoot
  42. if res != common.Hash(exp) {
  43. t.Errorf("expected %x got %x", exp, res)
  44. }
  45. }
  46. func TestNull(t *testing.T) {
  47. var trie Trie
  48. key := make([]byte, 32)
  49. value := common.FromHex("0x823140710bf13990e4500136726d8b55")
  50. trie.Update(key, value)
  51. value = trie.Get(key)
  52. }
  53. func TestMissingRoot(t *testing.T) {
  54. db, _ := ethdb.NewMemDatabase()
  55. trie, err := New(common.HexToHash("0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"), db)
  56. if trie != nil {
  57. t.Error("New returned non-nil trie for invalid root")
  58. }
  59. if _, ok := err.(*MissingNodeError); !ok {
  60. t.Errorf("New returned wrong error: %v", err)
  61. }
  62. }
  63. func TestMissingNode(t *testing.T) {
  64. db, _ := ethdb.NewMemDatabase()
  65. trie, _ := New(common.Hash{}, db)
  66. updateString(trie, "120000", "qwerqwerqwerqwerqwerqwerqwerqwer")
  67. updateString(trie, "123456", "asdfasdfasdfasdfasdfasdfasdfasdf")
  68. root, _ := trie.Commit()
  69. ClearGlobalCache()
  70. trie, _ = New(root, db)
  71. _, err := trie.TryGet([]byte("120000"))
  72. if err != nil {
  73. t.Errorf("Unexpected error: %v", err)
  74. }
  75. trie, _ = New(root, db)
  76. _, err = trie.TryGet([]byte("120099"))
  77. if err != nil {
  78. t.Errorf("Unexpected error: %v", err)
  79. }
  80. trie, _ = New(root, db)
  81. _, err = trie.TryGet([]byte("123456"))
  82. if err != nil {
  83. t.Errorf("Unexpected error: %v", err)
  84. }
  85. trie, _ = New(root, db)
  86. err = trie.TryUpdate([]byte("120099"), []byte("zxcvzxcvzxcvzxcvzxcvzxcvzxcvzxcv"))
  87. if err != nil {
  88. t.Errorf("Unexpected error: %v", err)
  89. }
  90. trie, _ = New(root, db)
  91. err = trie.TryDelete([]byte("123456"))
  92. if err != nil {
  93. t.Errorf("Unexpected error: %v", err)
  94. }
  95. db.Delete(common.FromHex("e1d943cc8f061a0c0b98162830b970395ac9315654824bf21b73b891365262f9"))
  96. ClearGlobalCache()
  97. trie, _ = New(root, db)
  98. _, err = trie.TryGet([]byte("120000"))
  99. if _, ok := err.(*MissingNodeError); !ok {
  100. t.Errorf("Wrong error: %v", err)
  101. }
  102. trie, _ = New(root, db)
  103. _, err = trie.TryGet([]byte("120099"))
  104. if _, ok := err.(*MissingNodeError); !ok {
  105. t.Errorf("Wrong error: %v", err)
  106. }
  107. trie, _ = New(root, db)
  108. _, err = trie.TryGet([]byte("123456"))
  109. if err != nil {
  110. t.Errorf("Unexpected error: %v", err)
  111. }
  112. trie, _ = New(root, db)
  113. err = trie.TryUpdate([]byte("120099"), []byte("zxcv"))
  114. if _, ok := err.(*MissingNodeError); !ok {
  115. t.Errorf("Wrong error: %v", err)
  116. }
  117. trie, _ = New(root, db)
  118. err = trie.TryDelete([]byte("123456"))
  119. if _, ok := err.(*MissingNodeError); !ok {
  120. t.Errorf("Wrong error: %v", err)
  121. }
  122. }
  123. func TestInsert(t *testing.T) {
  124. trie := newEmpty()
  125. updateString(trie, "doe", "reindeer")
  126. updateString(trie, "dog", "puppy")
  127. updateString(trie, "dogglesworth", "cat")
  128. exp := common.HexToHash("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3")
  129. root := trie.Hash()
  130. if root != exp {
  131. t.Errorf("exp %x got %x", exp, root)
  132. }
  133. trie = newEmpty()
  134. updateString(trie, "A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
  135. exp = common.HexToHash("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab")
  136. root, err := trie.Commit()
  137. if err != nil {
  138. t.Fatalf("commit error: %v", err)
  139. }
  140. if root != exp {
  141. t.Errorf("exp %x got %x", exp, root)
  142. }
  143. }
  144. func TestGet(t *testing.T) {
  145. trie := newEmpty()
  146. updateString(trie, "doe", "reindeer")
  147. updateString(trie, "dog", "puppy")
  148. updateString(trie, "dogglesworth", "cat")
  149. for i := 0; i < 2; i++ {
  150. res := getString(trie, "dog")
  151. if !bytes.Equal(res, []byte("puppy")) {
  152. t.Errorf("expected puppy got %x", res)
  153. }
  154. unknown := getString(trie, "unknown")
  155. if unknown != nil {
  156. t.Errorf("expected nil got %x", unknown)
  157. }
  158. if i == 1 {
  159. return
  160. }
  161. trie.Commit()
  162. }
  163. }
  164. func TestDelete(t *testing.T) {
  165. trie := newEmpty()
  166. vals := []struct{ k, v string }{
  167. {"do", "verb"},
  168. {"ether", "wookiedoo"},
  169. {"horse", "stallion"},
  170. {"shaman", "horse"},
  171. {"doge", "coin"},
  172. {"ether", ""},
  173. {"dog", "puppy"},
  174. {"shaman", ""},
  175. }
  176. for _, val := range vals {
  177. if val.v != "" {
  178. updateString(trie, val.k, val.v)
  179. } else {
  180. deleteString(trie, val.k)
  181. }
  182. }
  183. hash := trie.Hash()
  184. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  185. if hash != exp {
  186. t.Errorf("expected %x got %x", exp, hash)
  187. }
  188. }
  189. func TestEmptyValues(t *testing.T) {
  190. trie := newEmpty()
  191. vals := []struct{ k, v string }{
  192. {"do", "verb"},
  193. {"ether", "wookiedoo"},
  194. {"horse", "stallion"},
  195. {"shaman", "horse"},
  196. {"doge", "coin"},
  197. {"ether", ""},
  198. {"dog", "puppy"},
  199. {"shaman", ""},
  200. }
  201. for _, val := range vals {
  202. updateString(trie, val.k, val.v)
  203. }
  204. hash := trie.Hash()
  205. exp := common.HexToHash("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84")
  206. if hash != exp {
  207. t.Errorf("expected %x got %x", exp, hash)
  208. }
  209. }
  210. func TestReplication(t *testing.T) {
  211. trie := newEmpty()
  212. vals := []struct{ k, v string }{
  213. {"do", "verb"},
  214. {"ether", "wookiedoo"},
  215. {"horse", "stallion"},
  216. {"shaman", "horse"},
  217. {"doge", "coin"},
  218. {"dog", "puppy"},
  219. {"somethingveryoddindeedthis is", "myothernodedata"},
  220. }
  221. for _, val := range vals {
  222. updateString(trie, val.k, val.v)
  223. }
  224. exp, err := trie.Commit()
  225. if err != nil {
  226. t.Fatalf("commit error: %v", err)
  227. }
  228. // create a new trie on top of the database and check that lookups work.
  229. trie2, err := New(exp, trie.db)
  230. if err != nil {
  231. t.Fatalf("can't recreate trie at %x: %v", exp, err)
  232. }
  233. for _, kv := range vals {
  234. if string(getString(trie2, kv.k)) != kv.v {
  235. t.Errorf("trie2 doesn't have %q => %q", kv.k, kv.v)
  236. }
  237. }
  238. hash, err := trie2.Commit()
  239. if err != nil {
  240. t.Fatalf("commit error: %v", err)
  241. }
  242. if hash != exp {
  243. t.Errorf("root failure. expected %x got %x", exp, hash)
  244. }
  245. // perform some insertions on the new trie.
  246. vals2 := []struct{ k, v string }{
  247. {"do", "verb"},
  248. {"ether", "wookiedoo"},
  249. {"horse", "stallion"},
  250. // {"shaman", "horse"},
  251. // {"doge", "coin"},
  252. // {"ether", ""},
  253. // {"dog", "puppy"},
  254. // {"somethingveryoddindeedthis is", "myothernodedata"},
  255. // {"shaman", ""},
  256. }
  257. for _, val := range vals2 {
  258. updateString(trie2, val.k, val.v)
  259. }
  260. if trie2.Hash() != exp {
  261. t.Errorf("root failure. expected %x got %x", exp, hash)
  262. }
  263. }
  264. func paranoiaCheck(t1 *Trie) (bool, *Trie) {
  265. t2 := new(Trie)
  266. it := NewIterator(t1)
  267. for it.Next() {
  268. t2.Update(it.Key, it.Value)
  269. }
  270. return t2.Hash() == t1.Hash(), t2
  271. }
  272. func TestParanoia(t *testing.T) {
  273. t.Skip()
  274. trie := newEmpty()
  275. vals := []struct{ k, v string }{
  276. {"do", "verb"},
  277. {"ether", "wookiedoo"},
  278. {"horse", "stallion"},
  279. {"shaman", "horse"},
  280. {"doge", "coin"},
  281. {"ether", ""},
  282. {"dog", "puppy"},
  283. {"shaman", ""},
  284. {"somethingveryoddindeedthis is", "myothernodedata"},
  285. }
  286. for _, val := range vals {
  287. updateString(trie, val.k, val.v)
  288. }
  289. trie.Commit()
  290. ok, t2 := paranoiaCheck(trie)
  291. if !ok {
  292. t.Errorf("trie paranoia check failed %x %x", trie.Hash(), t2.Hash())
  293. }
  294. }
  295. // Not an actual test
  296. func TestOutput(t *testing.T) {
  297. t.Skip()
  298. base := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  299. trie := newEmpty()
  300. for i := 0; i < 50; i++ {
  301. updateString(trie, fmt.Sprintf("%s%d", base, i), "valueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
  302. }
  303. fmt.Println("############################## FULL ################################")
  304. fmt.Println(trie.root)
  305. trie.Commit()
  306. fmt.Println("############################## SMALL ################################")
  307. trie2, _ := New(trie.Hash(), trie.db)
  308. getString(trie2, base+"20")
  309. fmt.Println(trie2.root)
  310. }
  311. func TestLargeValue(t *testing.T) {
  312. trie := newEmpty()
  313. trie.Update([]byte("key1"), []byte{99, 99, 99, 99})
  314. trie.Update([]byte("key2"), bytes.Repeat([]byte{1}, 32))
  315. trie.Hash()
  316. }
  317. type kv struct {
  318. k, v []byte
  319. t bool
  320. }
  321. func TestLargeData(t *testing.T) {
  322. trie := newEmpty()
  323. vals := make(map[string]*kv)
  324. for i := byte(0); i < 255; i++ {
  325. value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
  326. value2 := &kv{common.LeftPadBytes([]byte{10, i}, 32), []byte{i}, false}
  327. trie.Update(value.k, value.v)
  328. trie.Update(value2.k, value2.v)
  329. vals[string(value.k)] = value
  330. vals[string(value2.k)] = value2
  331. }
  332. it := NewIterator(trie)
  333. for it.Next() {
  334. vals[string(it.Key)].t = true
  335. }
  336. var untouched []*kv
  337. for _, value := range vals {
  338. if !value.t {
  339. untouched = append(untouched, value)
  340. }
  341. }
  342. if len(untouched) > 0 {
  343. t.Errorf("Missed %d nodes", len(untouched))
  344. for _, value := range untouched {
  345. t.Error(value)
  346. }
  347. }
  348. }
  349. func BenchmarkGet(b *testing.B) { benchGet(b, false) }
  350. func BenchmarkGetDB(b *testing.B) { benchGet(b, true) }
  351. func BenchmarkUpdateBE(b *testing.B) { benchUpdate(b, binary.BigEndian) }
  352. func BenchmarkUpdateLE(b *testing.B) { benchUpdate(b, binary.LittleEndian) }
  353. func BenchmarkHashBE(b *testing.B) { benchHash(b, binary.BigEndian) }
  354. func BenchmarkHashLE(b *testing.B) { benchHash(b, binary.LittleEndian) }
  355. const benchElemCount = 20000
  356. func benchGet(b *testing.B, commit bool) {
  357. trie := new(Trie)
  358. if commit {
  359. dir, tmpdb := tempDB()
  360. defer os.RemoveAll(dir)
  361. trie, _ = New(common.Hash{}, tmpdb)
  362. }
  363. k := make([]byte, 32)
  364. for i := 0; i < benchElemCount; i++ {
  365. binary.LittleEndian.PutUint64(k, uint64(i))
  366. trie.Update(k, k)
  367. }
  368. binary.LittleEndian.PutUint64(k, benchElemCount/2)
  369. if commit {
  370. trie.Commit()
  371. }
  372. b.ResetTimer()
  373. for i := 0; i < b.N; i++ {
  374. trie.Get(k)
  375. }
  376. }
  377. func benchUpdate(b *testing.B, e binary.ByteOrder) *Trie {
  378. trie := newEmpty()
  379. k := make([]byte, 32)
  380. for i := 0; i < b.N; i++ {
  381. e.PutUint64(k, uint64(i))
  382. trie.Update(k, k)
  383. }
  384. return trie
  385. }
  386. func benchHash(b *testing.B, e binary.ByteOrder) {
  387. trie := newEmpty()
  388. k := make([]byte, 32)
  389. for i := 0; i < benchElemCount; i++ {
  390. e.PutUint64(k, uint64(i))
  391. trie.Update(k, k)
  392. }
  393. b.ResetTimer()
  394. for i := 0; i < b.N; i++ {
  395. trie.Hash()
  396. }
  397. }
  398. func tempDB() (string, Database) {
  399. dir, err := ioutil.TempDir("", "trie-bench")
  400. if err != nil {
  401. panic(fmt.Sprintf("can't create temporary directory: %v", err))
  402. }
  403. db, err := ethdb.NewLDBDatabase(dir, 256, 0)
  404. if err != nil {
  405. panic(fmt.Sprintf("can't create temporary database: %v", err))
  406. }
  407. return dir, db
  408. }
  409. func getString(trie *Trie, k string) []byte {
  410. return trie.Get([]byte(k))
  411. }
  412. func updateString(trie *Trie, k, v string) {
  413. trie.Update([]byte(k), []byte(v))
  414. }
  415. func deleteString(trie *Trie, k string) {
  416. trie.Delete([]byte(k))
  417. }