trie_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. package trie
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "math/rand"
  9. "net/http"
  10. "reflect"
  11. "testing"
  12. "time"
  13. "github.com/ethereum/go-ethereum/ethutil"
  14. )
  15. const LONG_WORD = "1234567890abcdefghijklmnopqrstuvwxxzABCEFGHIJKLMNOPQRSTUVWXYZ"
  16. type MemDatabase struct {
  17. db map[string][]byte
  18. }
  19. func NewMemDatabase() (*MemDatabase, error) {
  20. db := &MemDatabase{db: make(map[string][]byte)}
  21. return db, nil
  22. }
  23. func (db *MemDatabase) Put(key []byte, value []byte) {
  24. db.db[string(key)] = value
  25. }
  26. func (db *MemDatabase) Get(key []byte) ([]byte, error) {
  27. return db.db[string(key)], nil
  28. }
  29. func (db *MemDatabase) Delete(key []byte) error {
  30. delete(db.db, string(key))
  31. return nil
  32. }
  33. func (db *MemDatabase) Print() {}
  34. func (db *MemDatabase) Close() {}
  35. func (db *MemDatabase) LastKnownTD() []byte { return nil }
  36. func NewTrie() (*MemDatabase, *Trie) {
  37. db, _ := NewMemDatabase()
  38. return db, New(db, "")
  39. }
  40. func TestTrieSync(t *testing.T) {
  41. db, trie := NewTrie()
  42. trie.Update("dog", LONG_WORD)
  43. if len(db.db) != 0 {
  44. t.Error("Expected no data in database")
  45. }
  46. trie.Sync()
  47. if len(db.db) == 0 {
  48. t.Error("Expected data to be persisted")
  49. }
  50. }
  51. func TestTrieDirtyTracking(t *testing.T) {
  52. _, trie := NewTrie()
  53. trie.Update("dog", LONG_WORD)
  54. if !trie.cache.IsDirty {
  55. t.Error("Expected trie to be dirty")
  56. }
  57. trie.Sync()
  58. if trie.cache.IsDirty {
  59. t.Error("Expected trie not to be dirty")
  60. }
  61. trie.Update("test", LONG_WORD)
  62. trie.cache.Undo()
  63. if trie.cache.IsDirty {
  64. t.Error("Expected trie not to be dirty")
  65. }
  66. }
  67. func TestTrieReset(t *testing.T) {
  68. _, trie := NewTrie()
  69. trie.Update("cat", LONG_WORD)
  70. if len(trie.cache.nodes) == 0 {
  71. t.Error("Expected cached nodes")
  72. }
  73. trie.cache.Undo()
  74. if len(trie.cache.nodes) != 0 {
  75. t.Error("Expected no nodes after undo")
  76. }
  77. }
  78. func TestTrieGet(t *testing.T) {
  79. _, trie := NewTrie()
  80. trie.Update("cat", LONG_WORD)
  81. x := trie.Get("cat")
  82. if x != LONG_WORD {
  83. t.Error("expected %s, got %s", LONG_WORD, x)
  84. }
  85. }
  86. func TestTrieUpdating(t *testing.T) {
  87. _, trie := NewTrie()
  88. trie.Update("cat", LONG_WORD)
  89. trie.Update("cat", LONG_WORD+"1")
  90. x := trie.Get("cat")
  91. if x != LONG_WORD+"1" {
  92. t.Error("expected %S, got %s", LONG_WORD+"1", x)
  93. }
  94. }
  95. func TestTrieCmp(t *testing.T) {
  96. _, trie1 := NewTrie()
  97. _, trie2 := NewTrie()
  98. trie1.Update("doge", LONG_WORD)
  99. trie2.Update("doge", LONG_WORD)
  100. if !trie1.Cmp(trie2) {
  101. t.Error("Expected tries to be equal")
  102. }
  103. trie1.Update("dog", LONG_WORD)
  104. trie2.Update("cat", LONG_WORD)
  105. if trie1.Cmp(trie2) {
  106. t.Errorf("Expected tries not to be equal %x %x", trie1.Root, trie2.Root)
  107. }
  108. }
  109. func TestTrieDelete(t *testing.T) {
  110. _, trie := NewTrie()
  111. trie.Update("cat", LONG_WORD)
  112. exp := trie.Root
  113. trie.Update("dog", LONG_WORD)
  114. trie.Delete("dog")
  115. if !reflect.DeepEqual(exp, trie.Root) {
  116. t.Errorf("Expected tries to be equal %x : %x", exp, trie.Root)
  117. }
  118. trie.Update("dog", LONG_WORD)
  119. exp = trie.Root
  120. trie.Update("dude", LONG_WORD)
  121. trie.Delete("dude")
  122. if !reflect.DeepEqual(exp, trie.Root) {
  123. t.Errorf("Expected tries to be equal %x : %x", exp, trie.Root)
  124. }
  125. }
  126. func TestTrieDeleteWithValue(t *testing.T) {
  127. _, trie := NewTrie()
  128. trie.Update("c", LONG_WORD)
  129. exp := trie.Root
  130. trie.Update("ca", LONG_WORD)
  131. trie.Update("cat", LONG_WORD)
  132. trie.Delete("ca")
  133. trie.Delete("cat")
  134. if !reflect.DeepEqual(exp, trie.Root) {
  135. t.Errorf("Expected tries to be equal %x : %x", exp, trie.Root)
  136. }
  137. }
  138. func TestTriePurge(t *testing.T) {
  139. _, trie := NewTrie()
  140. trie.Update("c", LONG_WORD)
  141. trie.Update("ca", LONG_WORD)
  142. trie.Update("cat", LONG_WORD)
  143. lenBefore := len(trie.cache.nodes)
  144. it := trie.NewIterator()
  145. if num := it.Purge(); num != 3 {
  146. t.Errorf("Expected purge to return 3, got %d", num)
  147. }
  148. if lenBefore == len(trie.cache.nodes) {
  149. t.Errorf("Expected cached nodes to be deleted")
  150. }
  151. }
  152. func h(str string) string {
  153. d, err := hex.DecodeString(str)
  154. if err != nil {
  155. panic(err)
  156. }
  157. return string(d)
  158. }
  159. func get(in string) (out string) {
  160. if len(in) > 2 && in[:2] == "0x" {
  161. out = h(in[2:])
  162. } else {
  163. out = in
  164. }
  165. return
  166. }
  167. type Test struct {
  168. Name string
  169. In map[string]string
  170. Root string
  171. }
  172. func CreateTest(name string, data []byte) (Test, error) {
  173. t := Test{Name: name}
  174. err := json.Unmarshal(data, &t)
  175. if err != nil {
  176. return Test{}, fmt.Errorf("%v", err)
  177. }
  178. return t, nil
  179. }
  180. func CreateTests(uri string, cb func(Test)) map[string]Test {
  181. resp, err := http.Get(uri)
  182. if err != nil {
  183. panic(err)
  184. }
  185. defer resp.Body.Close()
  186. data, err := ioutil.ReadAll(resp.Body)
  187. var objmap map[string]*json.RawMessage
  188. err = json.Unmarshal(data, &objmap)
  189. if err != nil {
  190. panic(err)
  191. }
  192. tests := make(map[string]Test)
  193. for name, testData := range objmap {
  194. test, err := CreateTest(name, *testData)
  195. if err != nil {
  196. panic(err)
  197. }
  198. if cb != nil {
  199. cb(test)
  200. }
  201. tests[name] = test
  202. }
  203. return tests
  204. }
  205. func RandomData() [][]string {
  206. data := [][]string{
  207. {"0x000000000000000000000000ec4f34c97e43fbb2816cfd95e388353c7181dab1", "0x4e616d6552656700000000000000000000000000000000000000000000000000"},
  208. {"0x0000000000000000000000000000000000000000000000000000000000000045", "0x22b224a1420a802ab51d326e29fa98e34c4f24ea"},
  209. {"0x0000000000000000000000000000000000000000000000000000000000000046", "0x67706c2076330000000000000000000000000000000000000000000000000000"},
  210. {"0x000000000000000000000000697c7b8c961b56f675d570498424ac8de1a918f6", "0x6f6f6f6820736f2067726561742c207265616c6c6c793f000000000000000000"},
  211. {"0x0000000000000000000000007ef9e639e2733cb34e4dfc576d4b23f72db776b2", "0x4655474156000000000000000000000000000000000000000000000000000000"},
  212. {"0x6f6f6f6820736f2067726561742c207265616c6c6c793f000000000000000000", "0x697c7b8c961b56f675d570498424ac8de1a918f6"},
  213. {"0x4655474156000000000000000000000000000000000000000000000000000000", "0x7ef9e639e2733cb34e4dfc576d4b23f72db776b2"},
  214. {"0x4e616d6552656700000000000000000000000000000000000000000000000000", "0xec4f34c97e43fbb2816cfd95e388353c7181dab1"},
  215. }
  216. var c [][]string
  217. for len(data) != 0 {
  218. e := rand.Intn(len(data))
  219. c = append(c, data[e])
  220. copy(data[e:], data[e+1:])
  221. data[len(data)-1] = nil
  222. data = data[:len(data)-1]
  223. }
  224. return c
  225. }
  226. const MaxTest = 1000
  227. // This test insert data in random order and seeks to find indifferences between the different tries
  228. func TestRegression(t *testing.T) {
  229. rand.Seed(time.Now().Unix())
  230. roots := make(map[string]int)
  231. for i := 0; i < MaxTest; i++ {
  232. _, trie := NewTrie()
  233. data := RandomData()
  234. for _, test := range data {
  235. trie.Update(test[0], test[1])
  236. }
  237. trie.Delete("0x4e616d6552656700000000000000000000000000000000000000000000000000")
  238. roots[string(trie.Root.([]byte))] += 1
  239. }
  240. if len(roots) > 1 {
  241. for root, num := range roots {
  242. t.Errorf("%x => %d\n", root, num)
  243. }
  244. }
  245. }
  246. func TestDelete(t *testing.T) {
  247. _, trie := NewTrie()
  248. trie.Update("a", "jeffreytestlongstring")
  249. trie.Update("aa", "otherstring")
  250. trie.Update("aaa", "othermorestring")
  251. trie.Update("aabbbbccc", "hithere")
  252. trie.Update("abbcccdd", "hstanoehutnaheoustnh")
  253. trie.Update("rnthaoeuabbcccdd", "hstanoehutnaheoustnh")
  254. trie.Update("rneuabbcccdd", "hstanoehutnaheoustnh")
  255. trie.Update("rneuabboeusntahoeucccdd", "hstanoehutnaheoustnh")
  256. trie.Update("rnxabboeusntahoeucccdd", "hstanoehutnaheoustnh")
  257. trie.Delete("aaboaestnuhbccc")
  258. trie.Delete("a")
  259. trie.Update("a", "nthaonethaosentuh")
  260. trie.Update("c", "shtaosntehua")
  261. trie.Delete("a")
  262. trie.Update("aaaa", "testmegood")
  263. _, t2 := NewTrie()
  264. trie.NewIterator().Each(func(key string, v *ethutil.Value) {
  265. if key == "aaaa" {
  266. t2.Update(key, v.Str())
  267. } else {
  268. t2.Update(key, v.Str())
  269. }
  270. })
  271. a := ethutil.NewValue(trie.Root).Bytes()
  272. b := ethutil.NewValue(t2.Root).Bytes()
  273. if bytes.Compare(a, b) != 0 {
  274. t.Errorf("Expected %x and %x to be equal", a, b)
  275. }
  276. }
  277. func TestTerminator(t *testing.T) {
  278. key := CompactDecode("hello")
  279. if !HasTerm(key) {
  280. t.Errorf("Expected %v to have a terminator", key)
  281. }
  282. }
  283. func TestIt(t *testing.T) {
  284. _, trie := NewTrie()
  285. trie.Update("cat", "cat")
  286. trie.Update("doge", "doge")
  287. trie.Update("wallace", "wallace")
  288. it := trie.Iterator()
  289. inputs := []struct {
  290. In, Out string
  291. }{
  292. {"", "cat"},
  293. {"bobo", "cat"},
  294. {"c", "cat"},
  295. {"car", "cat"},
  296. {"catering", "doge"},
  297. {"w", "wallace"},
  298. {"wallace123", ""},
  299. }
  300. for _, test := range inputs {
  301. res := string(it.Next(test.In))
  302. if res != test.Out {
  303. t.Errorf(test.In, "failed. Got", res, "Expected", test.Out)
  304. }
  305. }
  306. }
  307. func TestBeginsWith(t *testing.T) {
  308. a := CompactDecode("hello")
  309. b := CompactDecode("hel")
  310. if BeginsWith(a, b) {
  311. t.Errorf("Expected %x to begin with %x", a, b)
  312. }
  313. if BeginsWith(b, a) {
  314. t.Errorf("Expected %x not to begin with %x", b, a)
  315. }
  316. }
  317. /*
  318. func TestRndCase(t *testing.T) {
  319. _, trie := NewTrie()
  320. data := []struct{ k, v string }{
  321. {"0000000000000000000000000000000000000000000000000000000000000001", "a07573657264617461000000000000000000000000000000000000000000000000"},
  322. {"0000000000000000000000000000000000000000000000000000000000000003", "8453bb5b31"},
  323. {"0000000000000000000000000000000000000000000000000000000000000004", "850218711a00"},
  324. {"0000000000000000000000000000000000000000000000000000000000000005", "9462d7705bd0b3ecbc51a8026a25597cb28a650c79"},
  325. {"0000000000000000000000000000000000000000000000000000000000000010", "947e70f9460402290a3e487dae01f610a1a8218fda"},
  326. {"0000000000000000000000000000000000000000000000000000000000000111", "01"},
  327. {"0000000000000000000000000000000000000000000000000000000000000112", "a053656e6174650000000000000000000000000000000000000000000000000000"},
  328. {"0000000000000000000000000000000000000000000000000000000000000113", "a053656e6174650000000000000000000000000000000000000000000000000000"},
  329. {"53656e6174650000000000000000000000000000000000000000000000000000", "94977e3f62f5e1ed7953697430303a3cfa2b5b736e"},
  330. }
  331. for _, e := range data {
  332. trie.Update(string(ethutil.Hex2Bytes(e.k)), string(ethutil.Hex2Bytes(e.v)))
  333. }
  334. fmt.Printf("root after update %x\n", trie.Root)
  335. trie.NewIterator().Each(func(k string, v *ethutil.Value) {
  336. fmt.Printf("%x %x\n", k, v.Bytes())
  337. })
  338. data = []struct{ k, v string }{
  339. {"0000000000000000000000000000000000000000000000000000000000000112", ""},
  340. {"436974697a656e73000000000000000000000000000000000000000000000001", ""},
  341. {"436f757274000000000000000000000000000000000000000000000000000002", ""},
  342. {"53656e6174650000000000000000000000000000000000000000000000000000", ""},
  343. {"436f757274000000000000000000000000000000000000000000000000000000", ""},
  344. {"53656e6174650000000000000000000000000000000000000000000000000001", ""},
  345. {"0000000000000000000000000000000000000000000000000000000000000113", ""},
  346. {"436974697a656e73000000000000000000000000000000000000000000000000", ""},
  347. {"436974697a656e73000000000000000000000000000000000000000000000002", ""},
  348. {"436f757274000000000000000000000000000000000000000000000000000001", ""},
  349. {"0000000000000000000000000000000000000000000000000000000000000111", ""},
  350. {"53656e6174650000000000000000000000000000000000000000000000000002", ""},
  351. }
  352. for _, e := range data {
  353. trie.Delete(string(ethutil.Hex2Bytes(e.k)))
  354. }
  355. fmt.Printf("root after delete %x\n", trie.Root)
  356. trie.NewIterator().Each(func(k string, v *ethutil.Value) {
  357. fmt.Printf("%x %x\n", k, v.Bytes())
  358. })
  359. fmt.Printf("%x\n", trie.Get(string(ethutil.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))))
  360. }
  361. */