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