github.com/theQRL/go-zond@v0.1.1/tests/state_test_util.go (about)

     1  // Copyright 2015 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 tests
    18  
    19  import (
    20  	"encoding/hex"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"strconv"
    26  	"strings"
    27  
    28  	"github.com/theQRL/go-zond/common"
    29  	"github.com/theQRL/go-zond/common/hexutil"
    30  	"github.com/theQRL/go-zond/common/math"
    31  	"github.com/theQRL/go-zond/core"
    32  	"github.com/theQRL/go-zond/core/rawdb"
    33  	"github.com/theQRL/go-zond/core/state"
    34  	"github.com/theQRL/go-zond/core/state/snapshot"
    35  	"github.com/theQRL/go-zond/core/types"
    36  	"github.com/theQRL/go-zond/core/vm"
    37  	"github.com/theQRL/go-zond/crypto"
    38  	"github.com/theQRL/go-zond/params"
    39  	"github.com/theQRL/go-zond/rlp"
    40  	"github.com/theQRL/go-zond/trie"
    41  	"github.com/theQRL/go-zond/trie/triedb/hashdb"
    42  	"github.com/theQRL/go-zond/trie/triedb/pathdb"
    43  	"github.com/theQRL/go-zond/zonddb"
    44  	"golang.org/x/crypto/sha3"
    45  )
    46  
    47  // StateTest checks transaction processing without block context.
    48  // See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
    49  type StateTest struct {
    50  	json stJSON
    51  }
    52  
    53  // StateSubtest selects a specific configuration of a General State Test.
    54  type StateSubtest struct {
    55  	Fork  string
    56  	Index int
    57  }
    58  
    59  func (t *StateTest) UnmarshalJSON(in []byte) error {
    60  	return json.Unmarshal(in, &t.json)
    61  }
    62  
    63  type stJSON struct {
    64  	Env  stEnv                    `json:"env"`
    65  	Pre  core.GenesisAlloc        `json:"pre"`
    66  	Tx   stTransaction            `json:"transaction"`
    67  	Out  hexutil.Bytes            `json:"out"`
    68  	Post map[string][]stPostState `json:"post"`
    69  }
    70  
    71  type stPostState struct {
    72  	Root            common.UnprefixedHash `json:"hash"`
    73  	Logs            common.UnprefixedHash `json:"logs"`
    74  	TxBytes         hexutil.Bytes         `json:"txbytes"`
    75  	ExpectException string                `json:"expectException"`
    76  	Indexes         struct {
    77  		Data  int `json:"data"`
    78  		Gas   int `json:"gas"`
    79  		Value int `json:"value"`
    80  	}
    81  }
    82  
    83  //go:generate go run github.com/fjl/gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    84  
    85  type stEnv struct {
    86  	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
    87  	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"optional"`
    88  	Random     *big.Int       `json:"currentRandom"     gencodec:"optional"`
    89  	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
    90  	Number     uint64         `json:"currentNumber"     gencodec:"required"`
    91  	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
    92  	BaseFee    *big.Int       `json:"currentBaseFee"    gencodec:"optional"`
    93  }
    94  
    95  type stEnvMarshaling struct {
    96  	Coinbase   common.UnprefixedAddress
    97  	Difficulty *math.HexOrDecimal256
    98  	Random     *math.HexOrDecimal256
    99  	GasLimit   math.HexOrDecimal64
   100  	Number     math.HexOrDecimal64
   101  	Timestamp  math.HexOrDecimal64
   102  	BaseFee    *math.HexOrDecimal256
   103  }
   104  
   105  //go:generate go run github.com/fjl/gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go
   106  
   107  type stTransaction struct {
   108  	GasPrice             *big.Int            `json:"gasPrice"`
   109  	MaxFeePerGas         *big.Int            `json:"maxFeePerGas"`
   110  	MaxPriorityFeePerGas *big.Int            `json:"maxPriorityFeePerGas"`
   111  	Nonce                uint64              `json:"nonce"`
   112  	To                   string              `json:"to"`
   113  	Data                 []string            `json:"data"`
   114  	AccessLists          []*types.AccessList `json:"accessLists,omitempty"`
   115  	GasLimit             []uint64            `json:"gasLimit"`
   116  	Value                []string            `json:"value"`
   117  	PrivateKey           []byte              `json:"secretKey"`
   118  	Sender               *common.Address     `json:"sender"`
   119  	BlobVersionedHashes  []common.Hash       `json:"blobVersionedHashes,omitempty"`
   120  	BlobGasFeeCap        *big.Int            `json:"maxFeePerBlobGas,omitempty"`
   121  }
   122  
   123  type stTransactionMarshaling struct {
   124  	GasPrice             *math.HexOrDecimal256
   125  	MaxFeePerGas         *math.HexOrDecimal256
   126  	MaxPriorityFeePerGas *math.HexOrDecimal256
   127  	Nonce                math.HexOrDecimal64
   128  	GasLimit             []math.HexOrDecimal64
   129  	PrivateKey           hexutil.Bytes
   130  	BlobGasFeeCap        *math.HexOrDecimal256
   131  }
   132  
   133  // GetChainConfig takes a fork definition and returns a chain config.
   134  // The fork definition can be
   135  // - a plain forkname, e.g. `Byzantium`,
   136  // - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`.
   137  func GetChainConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) {
   138  	var (
   139  		splitForks            = strings.Split(forkString, "+")
   140  		ok                    bool
   141  		baseName, eipsStrings = splitForks[0], splitForks[1:]
   142  	)
   143  	if baseConfig, ok = Forks[baseName]; !ok {
   144  		return nil, nil, UnsupportedForkError{baseName}
   145  	}
   146  	for _, eip := range eipsStrings {
   147  		if eipNum, err := strconv.Atoi(eip); err != nil {
   148  			return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
   149  		} else {
   150  			if !vm.ValidEip(eipNum) {
   151  				return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
   152  			}
   153  			eips = append(eips, eipNum)
   154  		}
   155  	}
   156  	return baseConfig, eips, nil
   157  }
   158  
   159  // Subtests returns all valid subtests of the test.
   160  func (t *StateTest) Subtests() []StateSubtest {
   161  	var sub []StateSubtest
   162  	for fork, pss := range t.json.Post {
   163  		for i := range pss {
   164  			sub = append(sub, StateSubtest{fork, i})
   165  		}
   166  	}
   167  	return sub
   168  }
   169  
   170  // checkError checks if the error returned by the state transition matches any expected error.
   171  // A failing expectation returns a wrapped version of the original error, if any,
   172  // or a new error detailing the failing expectation.
   173  // This function does not return or modify the original error, it only evaluates and returns expectations for the error.
   174  func (t *StateTest) checkError(subtest StateSubtest, err error) error {
   175  	expectedError := t.json.Post[subtest.Fork][subtest.Index].ExpectException
   176  	if err == nil && expectedError == "" {
   177  		return nil
   178  	}
   179  	if err == nil && expectedError != "" {
   180  		return fmt.Errorf("expected error %q, got no error", expectedError)
   181  	}
   182  	if err != nil && expectedError == "" {
   183  		return fmt.Errorf("unexpected error: %w", err)
   184  	}
   185  	if err != nil && expectedError != "" {
   186  		// Ignore expected errors (TODO MariusVanDerWijden check error string)
   187  		return nil
   188  	}
   189  	return nil
   190  }
   191  
   192  // Run executes a specific subtest and verifies the post-state and logs
   193  func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config, snapshotter bool, scheme string, postCheck func(err error, snaps *snapshot.Tree, state *state.StateDB)) (result error) {
   194  	triedb, snaps, statedb, root, err := t.RunNoVerify(subtest, vmconfig, snapshotter, scheme)
   195  
   196  	// Invoke the callback at the end of function for further analysis.
   197  	defer func() {
   198  		postCheck(result, snaps, statedb)
   199  
   200  		if triedb != nil {
   201  			triedb.Close()
   202  		}
   203  	}()
   204  	checkedErr := t.checkError(subtest, err)
   205  	if checkedErr != nil {
   206  		return checkedErr
   207  	}
   208  	// The error has been checked; if it was unexpected, it's already returned.
   209  	if err != nil {
   210  		// Here, an error exists but it was expected.
   211  		// We do not check the post state or logs.
   212  		return nil
   213  	}
   214  	post := t.json.Post[subtest.Fork][subtest.Index]
   215  	// N.B: We need to do this in a two-step process, because the first Commit takes care
   216  	// of self-destructs, and we need to touch the coinbase _after_ it has potentially self-destructed.
   217  	if root != common.Hash(post.Root) {
   218  		return fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   219  	}
   220  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   221  		return fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   222  	}
   223  	statedb, _ = state.New(root, statedb.Database(), snaps)
   224  	return nil
   225  }
   226  
   227  // RunNoVerify runs a specific subtest and returns the statedb and post-state root
   228  func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapshotter bool, scheme string) (*trie.Database, *snapshot.Tree, *state.StateDB, common.Hash, error) {
   229  	config, eips, err := GetChainConfig(subtest.Fork)
   230  	if err != nil {
   231  		return nil, nil, nil, common.Hash{}, UnsupportedForkError{subtest.Fork}
   232  	}
   233  	vmconfig.ExtraEips = eips
   234  
   235  	block := t.genesis(config).ToBlock()
   236  	triedb, snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, snapshotter, scheme)
   237  
   238  	var baseFee *big.Int
   239  	if config.IsLondon(new(big.Int)) {
   240  		baseFee = t.json.Env.BaseFee
   241  		if baseFee == nil {
   242  			// Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to
   243  			// parent - 2 : 0xa as the basefee for 'this' context.
   244  			baseFee = big.NewInt(0x0a)
   245  		}
   246  	}
   247  	post := t.json.Post[subtest.Fork][subtest.Index]
   248  	msg, err := t.json.Tx.toMessage(post, baseFee)
   249  	if err != nil {
   250  		triedb.Close()
   251  		return nil, nil, nil, common.Hash{}, err
   252  	}
   253  
   254  	// Try to recover tx with current signer
   255  	if len(post.TxBytes) != 0 {
   256  		var ttx types.Transaction
   257  		err := ttx.UnmarshalBinary(post.TxBytes)
   258  		if err != nil {
   259  			triedb.Close()
   260  			return nil, nil, nil, common.Hash{}, err
   261  		}
   262  
   263  		if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil {
   264  			triedb.Close()
   265  			return nil, nil, nil, common.Hash{}, err
   266  		}
   267  	}
   268  
   269  	// Prepare the EVM.
   270  	txContext := core.NewEVMTxContext(msg)
   271  	context := core.NewEVMBlockContext(block.Header(), nil, &t.json.Env.Coinbase)
   272  	context.GetHash = vmTestBlockHash
   273  	context.BaseFee = baseFee
   274  	context.Random = nil
   275  	if t.json.Env.Difficulty != nil {
   276  		context.Difficulty = new(big.Int).Set(t.json.Env.Difficulty)
   277  	}
   278  	if config.IsLondon(new(big.Int)) && t.json.Env.Random != nil {
   279  		rnd := common.BigToHash(t.json.Env.Random)
   280  		context.Random = &rnd
   281  		context.Difficulty = big.NewInt(0)
   282  	}
   283  	evm := vm.NewEVM(context, txContext, statedb, config, vmconfig)
   284  
   285  	// Execute the message.
   286  	snapshot := statedb.Snapshot()
   287  	gaspool := new(core.GasPool)
   288  	gaspool.AddGas(block.GasLimit())
   289  	_, err = core.ApplyMessage(evm, msg, gaspool)
   290  	if err != nil {
   291  		statedb.RevertToSnapshot(snapshot)
   292  	}
   293  	// Add 0-value mining reward. This only makes a difference in the cases
   294  	// where
   295  	// - the coinbase self-destructed, or
   296  	// - there are only 'bad' transactions, which aren't executed. In those cases,
   297  	//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   298  	statedb.AddBalance(block.Coinbase(), new(big.Int))
   299  
   300  	// Commit state mutations into database.
   301  	root, _ := statedb.Commit(block.NumberU64(), config.IsEIP158(block.Number()))
   302  	return triedb, snaps, statedb, root, err
   303  }
   304  
   305  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   306  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   307  }
   308  
   309  func MakePreState(db zonddb.Database, accounts core.GenesisAlloc, snapshotter bool, scheme string) (*trie.Database, *snapshot.Tree, *state.StateDB) {
   310  	tconf := &trie.Config{Preimages: true}
   311  	if scheme == rawdb.HashScheme {
   312  		tconf.HashDB = hashdb.Defaults
   313  	} else {
   314  		tconf.PathDB = pathdb.Defaults
   315  	}
   316  	triedb := trie.NewDatabase(db, tconf)
   317  	sdb := state.NewDatabaseWithNodeDB(db, triedb)
   318  	statedb, _ := state.New(types.EmptyRootHash, sdb, nil)
   319  	for addr, a := range accounts {
   320  		statedb.SetCode(addr, a.Code)
   321  		statedb.SetNonce(addr, a.Nonce)
   322  		statedb.SetBalance(addr, a.Balance)
   323  		for k, v := range a.Storage {
   324  			statedb.SetState(addr, k, v)
   325  		}
   326  	}
   327  	// Commit and re-open to start with a clean state.
   328  	root, _ := statedb.Commit(0, false)
   329  
   330  	var snaps *snapshot.Tree
   331  	if snapshotter {
   332  		snapconfig := snapshot.Config{
   333  			CacheSize:  1,
   334  			Recovery:   false,
   335  			NoBuild:    false,
   336  			AsyncBuild: false,
   337  		}
   338  		snaps, _ = snapshot.New(snapconfig, db, triedb, root)
   339  	}
   340  	statedb, _ = state.New(root, sdb, snaps)
   341  	return triedb, snaps, statedb
   342  }
   343  
   344  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   345  	genesis := &core.Genesis{
   346  		Config:     config,
   347  		Coinbase:   t.json.Env.Coinbase,
   348  		Difficulty: t.json.Env.Difficulty,
   349  		GasLimit:   t.json.Env.GasLimit,
   350  		Number:     t.json.Env.Number,
   351  		Timestamp:  t.json.Env.Timestamp,
   352  		Alloc:      t.json.Pre,
   353  	}
   354  	if t.json.Env.Random != nil {
   355  		// Post-Merge
   356  		genesis.Mixhash = common.BigToHash(t.json.Env.Random)
   357  		genesis.Difficulty = big.NewInt(0)
   358  	}
   359  	return genesis
   360  }
   361  
   362  func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (*core.Message, error) {
   363  	var from common.Address
   364  	// If 'sender' field is present, use that
   365  	if tx.Sender != nil {
   366  		from = *tx.Sender
   367  	} else if len(tx.PrivateKey) > 0 {
   368  		// Derive sender from private key if needed.
   369  		key, err := crypto.ToECDSA(tx.PrivateKey)
   370  		if err != nil {
   371  			return nil, fmt.Errorf("invalid private key: %v", err)
   372  		}
   373  		from = crypto.PubkeyToAddress(key.PublicKey)
   374  	}
   375  	// Parse recipient if present.
   376  	var to *common.Address
   377  	if tx.To != "" {
   378  		to = new(common.Address)
   379  		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
   380  			return nil, fmt.Errorf("invalid to address: %v", err)
   381  		}
   382  	}
   383  
   384  	// Get values specific to this post state.
   385  	if ps.Indexes.Data > len(tx.Data) {
   386  		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
   387  	}
   388  	if ps.Indexes.Value > len(tx.Value) {
   389  		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
   390  	}
   391  	if ps.Indexes.Gas > len(tx.GasLimit) {
   392  		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
   393  	}
   394  	dataHex := tx.Data[ps.Indexes.Data]
   395  	valueHex := tx.Value[ps.Indexes.Value]
   396  	gasLimit := tx.GasLimit[ps.Indexes.Gas]
   397  	// Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
   398  	value := new(big.Int)
   399  	if valueHex != "0x" {
   400  		v, ok := math.ParseBig256(valueHex)
   401  		if !ok {
   402  			return nil, fmt.Errorf("invalid tx value %q", valueHex)
   403  		}
   404  		value = v
   405  	}
   406  	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
   407  	if err != nil {
   408  		return nil, fmt.Errorf("invalid tx data %q", dataHex)
   409  	}
   410  	var accessList types.AccessList
   411  	if tx.AccessLists != nil && tx.AccessLists[ps.Indexes.Data] != nil {
   412  		accessList = *tx.AccessLists[ps.Indexes.Data]
   413  	}
   414  	// If baseFee provided, set gasPrice to effectiveGasPrice.
   415  	gasPrice := tx.GasPrice
   416  	if baseFee != nil {
   417  		if tx.MaxFeePerGas == nil {
   418  			tx.MaxFeePerGas = gasPrice
   419  		}
   420  		if tx.MaxFeePerGas == nil {
   421  			tx.MaxFeePerGas = new(big.Int)
   422  		}
   423  		if tx.MaxPriorityFeePerGas == nil {
   424  			tx.MaxPriorityFeePerGas = tx.MaxFeePerGas
   425  		}
   426  		gasPrice = math.BigMin(new(big.Int).Add(tx.MaxPriorityFeePerGas, baseFee),
   427  			tx.MaxFeePerGas)
   428  	}
   429  	if gasPrice == nil {
   430  		return nil, errors.New("no gas price provided")
   431  	}
   432  
   433  	msg := &core.Message{
   434  		From:          from,
   435  		To:            to,
   436  		Nonce:         tx.Nonce,
   437  		Value:         value,
   438  		GasLimit:      gasLimit,
   439  		GasPrice:      gasPrice,
   440  		GasFeeCap:     tx.MaxFeePerGas,
   441  		GasTipCap:     tx.MaxPriorityFeePerGas,
   442  		Data:          data,
   443  		AccessList:    accessList,
   444  		BlobHashes:    tx.BlobVersionedHashes,
   445  		BlobGasFeeCap: tx.BlobGasFeeCap,
   446  	}
   447  	return msg, nil
   448  }
   449  
   450  func rlpHash(x interface{}) (h common.Hash) {
   451  	hw := sha3.NewLegacyKeccak256()
   452  	rlp.Encode(hw, x)
   453  	hw.Sum(h[:0])
   454  	return h
   455  }
   456  
   457  func vmTestBlockHash(n uint64) common.Hash {
   458  	return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
   459  }