trie_fuzzer.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2020 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 stacktrie
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "hash"
  23. "io"
  24. "sort"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/trie"
  28. "golang.org/x/crypto/sha3"
  29. )
  30. type fuzzer struct {
  31. input io.Reader
  32. exhausted bool
  33. debugging bool
  34. }
  35. func (f *fuzzer) read(size int) []byte {
  36. out := make([]byte, size)
  37. if _, err := f.input.Read(out); err != nil {
  38. f.exhausted = true
  39. }
  40. return out
  41. }
  42. func (f *fuzzer) readSlice(min, max int) []byte {
  43. var a uint16
  44. binary.Read(f.input, binary.LittleEndian, &a)
  45. size := min + int(a)%(max-min)
  46. out := make([]byte, size)
  47. if _, err := f.input.Read(out); err != nil {
  48. f.exhausted = true
  49. }
  50. return out
  51. }
  52. // spongeDb is a dummy db backend which accumulates writes in a sponge
  53. type spongeDb struct {
  54. sponge hash.Hash
  55. debug bool
  56. }
  57. func (s *spongeDb) Has(key []byte) (bool, error) { panic("implement me") }
  58. func (s *spongeDb) Get(key []byte) ([]byte, error) { return nil, errors.New("no such elem") }
  59. func (s *spongeDb) Delete(key []byte) error { panic("implement me") }
  60. func (s *spongeDb) NewBatch() ethdb.Batch { return &spongeBatch{s} }
  61. func (s *spongeDb) Stat(property string) (string, error) { panic("implement me") }
  62. func (s *spongeDb) Compact(start []byte, limit []byte) error { panic("implement me") }
  63. func (s *spongeDb) Close() error { return nil }
  64. func (s *spongeDb) Put(key []byte, value []byte) error {
  65. if s.debug {
  66. fmt.Printf("db.Put %x : %x\n", key, value)
  67. }
  68. s.sponge.Write(key)
  69. s.sponge.Write(value)
  70. return nil
  71. }
  72. func (s *spongeDb) NewIterator(prefix []byte, start []byte) ethdb.Iterator { panic("implement me") }
  73. // spongeBatch is a dummy batch which immediately writes to the underlying spongedb
  74. type spongeBatch struct {
  75. db *spongeDb
  76. }
  77. func (b *spongeBatch) Put(key, value []byte) error {
  78. b.db.Put(key, value)
  79. return nil
  80. }
  81. func (b *spongeBatch) Delete(key []byte) error { panic("implement me") }
  82. func (b *spongeBatch) ValueSize() int { return 100 }
  83. func (b *spongeBatch) Write() error { return nil }
  84. func (b *spongeBatch) Reset() {}
  85. func (b *spongeBatch) Replay(w ethdb.KeyValueWriter) error { return nil }
  86. type kv struct {
  87. k, v []byte
  88. }
  89. type kvs []kv
  90. func (k kvs) Len() int {
  91. return len(k)
  92. }
  93. func (k kvs) Less(i, j int) bool {
  94. return bytes.Compare(k[i].k, k[j].k) < 0
  95. }
  96. func (k kvs) Swap(i, j int) {
  97. k[j], k[i] = k[i], k[j]
  98. }
  99. // The function must return
  100. // 1 if the fuzzer should increase priority of the
  101. // given input during subsequent fuzzing (for example, the input is lexically
  102. // correct and was parsed successfully);
  103. // -1 if the input must not be added to corpus even if gives new coverage; and
  104. // 0 otherwise
  105. // other values are reserved for future use.
  106. func Fuzz(data []byte) int {
  107. f := fuzzer{
  108. input: bytes.NewReader(data),
  109. exhausted: false,
  110. }
  111. return f.fuzz()
  112. }
  113. func Debug(data []byte) int {
  114. f := fuzzer{
  115. input: bytes.NewReader(data),
  116. exhausted: false,
  117. debugging: true,
  118. }
  119. return f.fuzz()
  120. }
  121. func (f *fuzzer) fuzz() int {
  122. // This spongeDb is used to check the sequence of disk-db-writes
  123. var (
  124. spongeA = &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  125. dbA = trie.NewDatabase(spongeA)
  126. trieA, _ = trie.New(common.Hash{}, dbA)
  127. spongeB = &spongeDb{sponge: sha3.NewLegacyKeccak256()}
  128. trieB = trie.NewStackTrie(spongeB)
  129. vals kvs
  130. useful bool
  131. maxElements = 10000
  132. // operate on unique keys only
  133. keys = make(map[string]struct{})
  134. )
  135. // Fill the trie with elements
  136. for i := 0; !f.exhausted && i < maxElements; i++ {
  137. k := f.read(32)
  138. v := f.readSlice(1, 500)
  139. if f.exhausted {
  140. // If it was exhausted while reading, the value may be all zeroes,
  141. // thus 'deletion' which is not supported on stacktrie
  142. break
  143. }
  144. if _, present := keys[string(k)]; present {
  145. // This key is a duplicate, ignore it
  146. continue
  147. }
  148. keys[string(k)] = struct{}{}
  149. vals = append(vals, kv{k: k, v: v})
  150. trieA.Update(k, v)
  151. useful = true
  152. }
  153. if !useful {
  154. return 0
  155. }
  156. // Flush trie -> database
  157. rootA, err := trieA.Commit(nil)
  158. if err != nil {
  159. panic(err)
  160. }
  161. // Flush memdb -> disk (sponge)
  162. dbA.Commit(rootA, false, nil)
  163. // Stacktrie requires sorted insertion
  164. sort.Sort(vals)
  165. for _, kv := range vals {
  166. if f.debugging {
  167. fmt.Printf("{\"0x%x\" , \"0x%x\"} // stacktrie.Update\n", kv.k, kv.v)
  168. }
  169. trieB.Update(kv.k, kv.v)
  170. }
  171. rootB := trieB.Hash()
  172. if _, err := trieB.Commit(); err != nil {
  173. panic(err)
  174. }
  175. if rootA != rootB {
  176. panic(fmt.Sprintf("roots differ: (trie) %x != %x (stacktrie)", rootA, rootB))
  177. }
  178. sumA := spongeA.sponge.Sum(nil)
  179. sumB := spongeB.sponge.Sum(nil)
  180. if !bytes.Equal(sumA, sumB) {
  181. panic(fmt.Sprintf("sequence differ: (trie) %x != %x (stacktrie)", sumA, sumB))
  182. }
  183. return 1
  184. }