github.com/core-coin/go-core/v2@v2.1.9/tests/fuzzers/trie/trie-fuzzer.go (about)

     1  // Copyright 2019 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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/core-coin/go-core/v2/xcbdb/memorydb"
    25  
    26  	"github.com/core-coin/go-core/v2/common"
    27  	"github.com/core-coin/go-core/v2/trie"
    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  	opCommit
    56  	opHash
    57  	opReset
    58  	opItercheckhash
    59  	opProve
    60  	opMax // boundary value, not an actual op
    61  )
    62  
    63  type dataSource struct {
    64  	input  []byte
    65  	reader *bytes.Reader
    66  }
    67  
    68  func newDataSource(input []byte) *dataSource {
    69  	return &dataSource{
    70  		input, bytes.NewReader(input),
    71  	}
    72  }
    73  func (ds *dataSource) ReadByte() byte {
    74  	if b, err := ds.reader.ReadByte(); err != nil {
    75  		return 0
    76  	} else {
    77  		return b
    78  	}
    79  }
    80  func (ds *dataSource) Read(buf []byte) (int, error) {
    81  	return ds.reader.Read(buf)
    82  }
    83  func (ds *dataSource) Ended() bool {
    84  	return ds.reader.Len() == 0
    85  }
    86  
    87  func Generate(input []byte) randTest {
    88  
    89  	var allKeys [][]byte
    90  	r := newDataSource(input)
    91  	genKey := func() []byte {
    92  
    93  		if len(allKeys) < 2 || r.ReadByte() < 0x0f {
    94  			// new key
    95  			key := make([]byte, r.ReadByte()%50)
    96  			r.Read(key)
    97  			allKeys = append(allKeys, key)
    98  			return key
    99  		}
   100  		// use existing key
   101  		return allKeys[int(r.ReadByte())%len(allKeys)]
   102  	}
   103  
   104  	var steps randTest
   105  
   106  	for i := 0; !r.Ended(); i++ {
   107  
   108  		step := randTestStep{op: int(r.ReadByte()) % opMax}
   109  		switch step.op {
   110  		case opUpdate:
   111  			step.key = genKey()
   112  			step.value = make([]byte, 8)
   113  			binary.BigEndian.PutUint64(step.value, uint64(i))
   114  		case opGet, opDelete, opProve:
   115  			step.key = genKey()
   116  		}
   117  		steps = append(steps, step)
   118  		if len(steps) > 500 {
   119  			break
   120  		}
   121  	}
   122  
   123  	return steps
   124  }
   125  
   126  // The function must return
   127  // 1 if the fuzzer should increase priority of the
   128  //
   129  //	given input during subsequent fuzzing (for example, the input is lexically
   130  //	correct and was parsed successfully);
   131  //
   132  // -1 if the input must not be added to corpus even if gives new coverage; and
   133  // 0  otherwise
   134  // other values are reserved for future use.
   135  func Fuzz(input []byte) int {
   136  	program := Generate(input)
   137  	if len(program) == 0 {
   138  		return 0
   139  	}
   140  	if err := runRandTest(program); err != nil {
   141  		panic(err)
   142  	}
   143  	return 1
   144  }
   145  
   146  func runRandTest(rt randTest) error {
   147  
   148  	triedb := trie.NewDatabase(memorydb.New())
   149  
   150  	tr, _ := trie.New(common.Hash{}, triedb)
   151  	values := make(map[string]string) // tracks content of the trie
   152  
   153  	for i, step := range rt {
   154  		switch step.op {
   155  		case opUpdate:
   156  			tr.Update(step.key, step.value)
   157  			values[string(step.key)] = string(step.value)
   158  		case opDelete:
   159  			tr.Delete(step.key)
   160  			delete(values, string(step.key))
   161  		case opGet:
   162  			v := tr.Get(step.key)
   163  			want := values[string(step.key)]
   164  			if string(v) != want {
   165  				rt[i].err = fmt.Errorf("mismatch for key 0x%x, got 0x%x want 0x%x", step.key, v, want)
   166  			}
   167  		case opCommit:
   168  			_, rt[i].err = tr.Commit(nil)
   169  		case opHash:
   170  			tr.Hash()
   171  		case opReset:
   172  			hash, err := tr.Commit(nil)
   173  			if err != nil {
   174  				return err
   175  			}
   176  			newtr, err := trie.New(hash, triedb)
   177  			if err != nil {
   178  				return err
   179  			}
   180  			tr = newtr
   181  		case opItercheckhash:
   182  			checktr, _ := trie.New(common.Hash{}, triedb)
   183  			it := trie.NewIterator(tr.NodeIterator(nil))
   184  			for it.Next() {
   185  				checktr.Update(it.Key, it.Value)
   186  			}
   187  			if tr.Hash() != checktr.Hash() {
   188  				return fmt.Errorf("hash mismatch in opItercheckhash")
   189  			}
   190  		case opProve:
   191  			rt[i].err = tr.Prove(step.key, 0, proofDb{})
   192  		}
   193  		// Abort the test on error.
   194  		if rt[i].err != nil {
   195  			return rt[i].err
   196  		}
   197  	}
   198  	return nil
   199  }