github.com/calmw/ethereum@v0.1.1/tests/fuzzers/trie/trie-fuzzer.go (about)

     1  // Copyright 2019 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  
    17  package trie
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  	"fmt"
    23  
    24  	"github.com/calmw/ethereum/core/rawdb"
    25  	"github.com/calmw/ethereum/core/types"
    26  	"github.com/calmw/ethereum/trie"
    27  	"github.com/calmw/ethereum/trie/trienode"
    28  )
    29  
    30  // randTest performs random trie operations.
    31  // Instances of this test are created by Generate.
    32  type randTest []randTestStep
    33  
    34  type randTestStep struct {
    35  	op    int
    36  	key   []byte // for opUpdate, opDelete, opGet
    37  	value []byte // for opUpdate
    38  	err   error  // for debugging
    39  }
    40  
    41  type proofDb struct{}
    42  
    43  func (proofDb) Put(key []byte, value []byte) error {
    44  	return nil
    45  }
    46  
    47  func (proofDb) Delete(key []byte) error {
    48  	return nil
    49  }
    50  
    51  const (
    52  	opUpdate = iota
    53  	opDelete
    54  	opGet
    55  	opHash
    56  	opCommit
    57  	opItercheckhash
    58  	opProve
    59  	opMax // boundary value, not an actual op
    60  )
    61  
    62  type dataSource struct {
    63  	input  []byte
    64  	reader *bytes.Reader
    65  }
    66  
    67  func newDataSource(input []byte) *dataSource {
    68  	return &dataSource{
    69  		input, bytes.NewReader(input),
    70  	}
    71  }
    72  func (ds *dataSource) readByte() byte {
    73  	if b, err := ds.reader.ReadByte(); err != nil {
    74  		return 0
    75  	} else {
    76  		return b
    77  	}
    78  }
    79  func (ds *dataSource) Read(buf []byte) (int, error) {
    80  	return ds.reader.Read(buf)
    81  }
    82  func (ds *dataSource) Ended() bool {
    83  	return ds.reader.Len() == 0
    84  }
    85  
    86  func Generate(input []byte) randTest {
    87  	var allKeys [][]byte
    88  	r := newDataSource(input)
    89  	genKey := func() []byte {
    90  		if len(allKeys) < 2 || r.readByte() < 0x0f {
    91  			// new key
    92  			key := make([]byte, r.readByte()%50)
    93  			r.Read(key)
    94  			allKeys = append(allKeys, key)
    95  			return key
    96  		}
    97  		// use existing key
    98  		return allKeys[int(r.readByte())%len(allKeys)]
    99  	}
   100  
   101  	var steps randTest
   102  
   103  	for i := 0; !r.Ended(); i++ {
   104  		step := randTestStep{op: int(r.readByte()) % opMax}
   105  		switch step.op {
   106  		case opUpdate:
   107  			step.key = genKey()
   108  			step.value = make([]byte, 8)
   109  			binary.BigEndian.PutUint64(step.value, uint64(i))
   110  		case opGet, opDelete, opProve:
   111  			step.key = genKey()
   112  		}
   113  		steps = append(steps, step)
   114  		if len(steps) > 500 {
   115  			break
   116  		}
   117  	}
   118  
   119  	return steps
   120  }
   121  
   122  // Fuzz is the fuzzing entry-point.
   123  // The function must return
   124  //
   125  //   - 1 if the fuzzer should increase priority of the
   126  //     given input during subsequent fuzzing (for example, the input is lexically
   127  //     correct and was parsed successfully);
   128  //   - -1 if the input must not be added to corpus even if gives new coverage; and
   129  //   - 0 otherwise
   130  //
   131  // other values are reserved for future use.
   132  func Fuzz(input []byte) int {
   133  	program := Generate(input)
   134  	if len(program) == 0 {
   135  		return 0
   136  	}
   137  	if err := runRandTest(program); err != nil {
   138  		panic(err)
   139  	}
   140  	return 1
   141  }
   142  
   143  func runRandTest(rt randTest) error {
   144  	var (
   145  		triedb = trie.NewDatabase(rawdb.NewMemoryDatabase())
   146  		tr     = trie.NewEmpty(triedb)
   147  		origin = types.EmptyRootHash
   148  		values = make(map[string]string) // tracks content of the trie
   149  	)
   150  	for i, step := range rt {
   151  		switch step.op {
   152  		case opUpdate:
   153  			tr.MustUpdate(step.key, step.value)
   154  			values[string(step.key)] = string(step.value)
   155  		case opDelete:
   156  			tr.MustDelete(step.key)
   157  			delete(values, string(step.key))
   158  		case opGet:
   159  			v := tr.MustGet(step.key)
   160  			want := values[string(step.key)]
   161  			if string(v) != want {
   162  				rt[i].err = fmt.Errorf("mismatch for key %#x, got %#x want %#x", step.key, v, want)
   163  			}
   164  		case opHash:
   165  			tr.Hash()
   166  		case opCommit:
   167  			hash, nodes := tr.Commit(false)
   168  			if nodes != nil {
   169  				if err := triedb.Update(hash, origin, trienode.NewWithNodeSet(nodes)); err != nil {
   170  					return err
   171  				}
   172  			}
   173  			newtr, err := trie.New(trie.TrieID(hash), triedb)
   174  			if err != nil {
   175  				return err
   176  			}
   177  			tr = newtr
   178  			origin = hash
   179  		case opItercheckhash:
   180  			checktr := trie.NewEmpty(triedb)
   181  			it := trie.NewIterator(tr.NodeIterator(nil))
   182  			for it.Next() {
   183  				checktr.MustUpdate(it.Key, it.Value)
   184  			}
   185  			if tr.Hash() != checktr.Hash() {
   186  				return fmt.Errorf("hash mismatch in opItercheckhash")
   187  			}
   188  		case opProve:
   189  			rt[i].err = tr.Prove(step.key, 0, proofDb{})
   190  		}
   191  		// Abort the test on error.
   192  		if rt[i].err != nil {
   193  			return rt[i].err
   194  		}
   195  	}
   196  	return nil
   197  }