github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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  	"fmt"
    23  	"math/big"
    24  	"strconv"
    25  	"strings"
    26  
    27  	"golang.org/x/crypto/sha3"
    28  
    29  	"github.com/scroll-tech/go-ethereum/common"
    30  	"github.com/scroll-tech/go-ethereum/common/hexutil"
    31  	"github.com/scroll-tech/go-ethereum/common/math"
    32  	"github.com/scroll-tech/go-ethereum/core"
    33  	"github.com/scroll-tech/go-ethereum/core/rawdb"
    34  	"github.com/scroll-tech/go-ethereum/core/state"
    35  	"github.com/scroll-tech/go-ethereum/core/state/snapshot"
    36  	"github.com/scroll-tech/go-ethereum/core/types"
    37  	"github.com/scroll-tech/go-ethereum/core/vm"
    38  	"github.com/scroll-tech/go-ethereum/crypto"
    39  	"github.com/scroll-tech/go-ethereum/ethdb"
    40  	"github.com/scroll-tech/go-ethereum/params"
    41  	"github.com/scroll-tech/go-ethereum/rlp"
    42  	"github.com/scroll-tech/go-ethereum/rollup/fees"
    43  )
    44  
    45  // StateTest checks transaction processing without block context.
    46  // See https://github.com/ethereum/EIPs/issues/176 for the test format specification.
    47  type StateTest struct {
    48  	json stJSON
    49  }
    50  
    51  // StateSubtest selects a specific configuration of a General State Test.
    52  type StateSubtest struct {
    53  	Fork  string
    54  	Index int
    55  }
    56  
    57  func (t *StateTest) UnmarshalJSON(in []byte) error {
    58  	return json.Unmarshal(in, &t.json)
    59  }
    60  
    61  type stJSON struct {
    62  	Env  stEnv                    `json:"env"`
    63  	Pre  core.GenesisAlloc        `json:"pre"`
    64  	Tx   stTransaction            `json:"transaction"`
    65  	Out  hexutil.Bytes            `json:"out"`
    66  	Post map[string][]stPostState `json:"post"`
    67  }
    68  
    69  type stPostState struct {
    70  	Root            common.UnprefixedHash `json:"hash"`
    71  	Logs            common.UnprefixedHash `json:"logs"`
    72  	TxBytes         hexutil.Bytes         `json:"txbytes"`
    73  	ExpectException string                `json:"expectException"`
    74  	Indexes         struct {
    75  		Data  int `json:"data"`
    76  		Gas   int `json:"gas"`
    77  		Value int `json:"value"`
    78  	}
    79  }
    80  
    81  //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    82  
    83  type stEnv struct {
    84  	Coinbase   common.Address `json:"currentCoinbase"   gencodec:"required"`
    85  	Difficulty *big.Int       `json:"currentDifficulty" gencodec:"required"`
    86  	GasLimit   uint64         `json:"currentGasLimit"   gencodec:"required"`
    87  	Number     uint64         `json:"currentNumber"     gencodec:"required"`
    88  	Timestamp  uint64         `json:"currentTimestamp"  gencodec:"required"`
    89  	BaseFee    *big.Int       `json:"currentBaseFee"  gencodec:"optional"`
    90  }
    91  
    92  type stEnvMarshaling struct {
    93  	Coinbase   common.UnprefixedAddress
    94  	Difficulty *math.HexOrDecimal256
    95  	GasLimit   math.HexOrDecimal64
    96  	Number     math.HexOrDecimal64
    97  	Timestamp  math.HexOrDecimal64
    98  	BaseFee    *math.HexOrDecimal256
    99  }
   100  
   101  //go:generate gencodec -type stTransaction -field-override stTransactionMarshaling -out gen_sttransaction.go
   102  
   103  type stTransaction struct {
   104  	GasPrice             *big.Int            `json:"gasPrice"`
   105  	MaxFeePerGas         *big.Int            `json:"maxFeePerGas"`
   106  	MaxPriorityFeePerGas *big.Int            `json:"maxPriorityFeePerGas"`
   107  	Nonce                uint64              `json:"nonce"`
   108  	To                   string              `json:"to"`
   109  	Data                 []string            `json:"data"`
   110  	AccessLists          []*types.AccessList `json:"accessLists,omitempty"`
   111  	GasLimit             []uint64            `json:"gasLimit"`
   112  	Value                []string            `json:"value"`
   113  	PrivateKey           []byte              `json:"secretKey"`
   114  }
   115  
   116  type stTransactionMarshaling struct {
   117  	GasPrice             *math.HexOrDecimal256
   118  	MaxFeePerGas         *math.HexOrDecimal256
   119  	MaxPriorityFeePerGas *math.HexOrDecimal256
   120  	Nonce                math.HexOrDecimal64
   121  	GasLimit             []math.HexOrDecimal64
   122  	PrivateKey           hexutil.Bytes
   123  }
   124  
   125  // GetChainConfig takes a fork definition and returns a chain config.
   126  // The fork definition can be
   127  // - a plain forkname, e.g. `Byzantium`,
   128  // - a fork basename, and a list of EIPs to enable; e.g. `Byzantium+1884+1283`.
   129  func GetChainConfig(forkString string) (baseConfig *params.ChainConfig, eips []int, err error) {
   130  	var (
   131  		splitForks            = strings.Split(forkString, "+")
   132  		ok                    bool
   133  		baseName, eipsStrings = splitForks[0], splitForks[1:]
   134  	)
   135  	if baseConfig, ok = Forks[baseName]; !ok {
   136  		return nil, nil, UnsupportedForkError{baseName}
   137  	}
   138  	for _, eip := range eipsStrings {
   139  		if eipNum, err := strconv.Atoi(eip); err != nil {
   140  			return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
   141  		} else {
   142  			if !vm.ValidEip(eipNum) {
   143  				return nil, nil, fmt.Errorf("syntax error, invalid eip number %v", eipNum)
   144  			}
   145  			eips = append(eips, eipNum)
   146  		}
   147  	}
   148  	return baseConfig, eips, nil
   149  }
   150  
   151  // Subtests returns all valid subtests of the test.
   152  func (t *StateTest) Subtests() []StateSubtest {
   153  	var sub []StateSubtest
   154  	for fork, pss := range t.json.Post {
   155  		for i := range pss {
   156  			sub = append(sub, StateSubtest{fork, i})
   157  		}
   158  	}
   159  	return sub
   160  }
   161  
   162  // Run executes a specific subtest and verifies the post-state and logs
   163  func (t *StateTest) Run(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, error) {
   164  	snaps, statedb, root, err := t.RunNoVerify(subtest, vmconfig, snapshotter)
   165  	if err != nil {
   166  		return snaps, statedb, err
   167  	}
   168  	post := t.json.Post[subtest.Fork][subtest.Index]
   169  	// N.B: We need to do this in a two-step process, because the first Commit takes care
   170  	// of suicides, and we need to touch the coinbase _after_ it has potentially suicided.
   171  	if root != common.Hash(post.Root) {
   172  		return snaps, statedb, fmt.Errorf("post state root mismatch: got %x, want %x", root, post.Root)
   173  	}
   174  	if logs := rlpHash(statedb.Logs()); logs != common.Hash(post.Logs) {
   175  		return snaps, statedb, fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, post.Logs)
   176  	}
   177  	return snaps, statedb, nil
   178  }
   179  
   180  // RunNoVerify runs a specific subtest and returns the statedb and post-state root
   181  func (t *StateTest) RunNoVerify(subtest StateSubtest, vmconfig vm.Config, snapshotter bool) (*snapshot.Tree, *state.StateDB, common.Hash, error) {
   182  	config, eips, err := GetChainConfig(subtest.Fork)
   183  	if err != nil {
   184  		return nil, nil, common.Hash{}, UnsupportedForkError{subtest.Fork}
   185  	}
   186  	vmconfig.ExtraEips = eips
   187  	block := t.genesis(config).ToBlock(nil)
   188  	snaps, statedb := MakePreState(rawdb.NewMemoryDatabase(), t.json.Pre, snapshotter)
   189  
   190  	var baseFee *big.Int
   191  	if config.IsLondon(new(big.Int)) {
   192  		baseFee = t.json.Env.BaseFee
   193  		if baseFee == nil {
   194  			// Retesteth uses `0x10` for genesis baseFee. Therefore, it defaults to
   195  			// parent - 2 : 0xa as the basefee for 'this' context.
   196  			baseFee = big.NewInt(0x0a)
   197  		}
   198  	}
   199  	post := t.json.Post[subtest.Fork][subtest.Index]
   200  	msg, err := t.json.Tx.toMessage(post, baseFee)
   201  	if err != nil {
   202  		return nil, nil, common.Hash{}, err
   203  	}
   204  
   205  	var ttx types.Transaction
   206  	// Try to recover tx with current signer
   207  	if len(post.TxBytes) != 0 {
   208  		err := ttx.UnmarshalBinary(post.TxBytes)
   209  		if err != nil {
   210  			return nil, nil, common.Hash{}, err
   211  		}
   212  
   213  		if _, err := types.Sender(types.LatestSigner(config), &ttx); err != nil {
   214  			return nil, nil, common.Hash{}, err
   215  		}
   216  	}
   217  
   218  	// Prepare the EVM.
   219  	txContext := core.NewEVMTxContext(msg)
   220  	context := core.NewEVMBlockContext(block.Header(), nil, config, &t.json.Env.Coinbase)
   221  	context.GetHash = vmTestBlockHash
   222  	context.BaseFee = baseFee
   223  	evm := vm.NewEVM(context, txContext, statedb, config, vmconfig)
   224  
   225  	// Execute the message.
   226  	snapshot := statedb.Snapshot()
   227  	gaspool := new(core.GasPool)
   228  	gaspool.AddGas(block.GasLimit())
   229  
   230  	l1DataFee, err := fees.CalculateL1DataFee(&ttx, statedb)
   231  	if err != nil {
   232  		return nil, nil, common.Hash{}, err
   233  	}
   234  
   235  	if _, err = core.ApplyMessage(evm, msg, gaspool, l1DataFee); err != nil {
   236  		statedb.RevertToSnapshot(snapshot)
   237  	}
   238  
   239  	// Commit block
   240  	statedb.Commit(config.IsEIP158(block.Number()))
   241  	// Add 0-value mining reward. This only makes a difference in the cases
   242  	// where
   243  	// - the coinbase suicided, or
   244  	// - there are only 'bad' transactions, which aren't executed. In those cases,
   245  	//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   246  	statedb.AddBalance(block.Coinbase(), new(big.Int))
   247  	// And _now_ get the state root
   248  	root := statedb.IntermediateRoot(config.IsEIP158(block.Number()))
   249  	return snaps, statedb, root, nil
   250  }
   251  
   252  func (t *StateTest) gasLimit(subtest StateSubtest) uint64 {
   253  	return t.json.Tx.GasLimit[t.json.Post[subtest.Fork][subtest.Index].Indexes.Gas]
   254  }
   255  
   256  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc, snapshotter bool) (*snapshot.Tree, *state.StateDB) {
   257  	sdb := state.NewDatabase(db)
   258  	statedb, _ := state.New(common.Hash{}, sdb, nil)
   259  	for addr, a := range accounts {
   260  		statedb.SetCode(addr, a.Code)
   261  		statedb.SetNonce(addr, a.Nonce)
   262  		statedb.SetBalance(addr, a.Balance)
   263  		for k, v := range a.Storage {
   264  			statedb.SetState(addr, k, v)
   265  		}
   266  	}
   267  	// Commit and re-open to start with a clean state.
   268  	root, _ := statedb.Commit(false)
   269  
   270  	var snaps *snapshot.Tree
   271  	if snapshotter {
   272  		snaps, _ = snapshot.New(db, sdb.TrieDB(), 1, root, false, true, false)
   273  	}
   274  	statedb, _ = state.New(root, sdb, snaps)
   275  	return snaps, statedb
   276  }
   277  
   278  func (t *StateTest) genesis(config *params.ChainConfig) *core.Genesis {
   279  	return &core.Genesis{
   280  		Config:     config,
   281  		Coinbase:   t.json.Env.Coinbase,
   282  		Difficulty: t.json.Env.Difficulty,
   283  		GasLimit:   t.json.Env.GasLimit,
   284  		Number:     t.json.Env.Number,
   285  		Timestamp:  t.json.Env.Timestamp,
   286  		Alloc:      t.json.Pre,
   287  	}
   288  }
   289  
   290  func (tx *stTransaction) toMessage(ps stPostState, baseFee *big.Int) (core.Message, error) {
   291  	// Derive sender from private key if present.
   292  	var from common.Address
   293  	if len(tx.PrivateKey) > 0 {
   294  		key, err := crypto.ToECDSA(tx.PrivateKey)
   295  		if err != nil {
   296  			return nil, fmt.Errorf("invalid private key: %v", err)
   297  		}
   298  		from = crypto.PubkeyToAddress(key.PublicKey)
   299  	}
   300  	// Parse recipient if present.
   301  	var to *common.Address
   302  	if tx.To != "" {
   303  		to = new(common.Address)
   304  		if err := to.UnmarshalText([]byte(tx.To)); err != nil {
   305  			return nil, fmt.Errorf("invalid to address: %v", err)
   306  		}
   307  	}
   308  
   309  	// Get values specific to this post state.
   310  	if ps.Indexes.Data > len(tx.Data) {
   311  		return nil, fmt.Errorf("tx data index %d out of bounds", ps.Indexes.Data)
   312  	}
   313  	if ps.Indexes.Value > len(tx.Value) {
   314  		return nil, fmt.Errorf("tx value index %d out of bounds", ps.Indexes.Value)
   315  	}
   316  	if ps.Indexes.Gas > len(tx.GasLimit) {
   317  		return nil, fmt.Errorf("tx gas limit index %d out of bounds", ps.Indexes.Gas)
   318  	}
   319  	dataHex := tx.Data[ps.Indexes.Data]
   320  	valueHex := tx.Value[ps.Indexes.Value]
   321  	gasLimit := tx.GasLimit[ps.Indexes.Gas]
   322  	// Value, Data hex encoding is messy: https://github.com/ethereum/tests/issues/203
   323  	value := new(big.Int)
   324  	if valueHex != "0x" {
   325  		v, ok := math.ParseBig256(valueHex)
   326  		if !ok {
   327  			return nil, fmt.Errorf("invalid tx value %q", valueHex)
   328  		}
   329  		value = v
   330  	}
   331  	data, err := hex.DecodeString(strings.TrimPrefix(dataHex, "0x"))
   332  	if err != nil {
   333  		return nil, fmt.Errorf("invalid tx data %q", dataHex)
   334  	}
   335  	var accessList types.AccessList
   336  	if tx.AccessLists != nil && tx.AccessLists[ps.Indexes.Data] != nil {
   337  		accessList = *tx.AccessLists[ps.Indexes.Data]
   338  	}
   339  	// If baseFee provided, set gasPrice to effectiveGasPrice.
   340  	gasPrice := tx.GasPrice
   341  	if baseFee != nil {
   342  		if tx.MaxFeePerGas == nil {
   343  			tx.MaxFeePerGas = gasPrice
   344  		}
   345  		if tx.MaxFeePerGas == nil {
   346  			tx.MaxFeePerGas = new(big.Int)
   347  		}
   348  		if tx.MaxPriorityFeePerGas == nil {
   349  			tx.MaxPriorityFeePerGas = tx.MaxFeePerGas
   350  		}
   351  		gasPrice = math.BigMin(new(big.Int).Add(tx.MaxPriorityFeePerGas, baseFee),
   352  			tx.MaxFeePerGas)
   353  	}
   354  	if gasPrice == nil {
   355  		return nil, fmt.Errorf("no gas price provided")
   356  	}
   357  
   358  	msg := types.NewMessage(from, to, tx.Nonce, value, gasLimit, gasPrice,
   359  		tx.MaxFeePerGas, tx.MaxPriorityFeePerGas, data, accessList, false)
   360  	return msg, nil
   361  }
   362  
   363  func rlpHash(x interface{}) (h common.Hash) {
   364  	hw := sha3.NewLegacyKeccak256()
   365  	rlp.Encode(hw, x)
   366  	hw.Sum(h[:0])
   367  	return h
   368  }
   369  
   370  func vmTestBlockHash(n uint64) common.Hash {
   371  	return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
   372  }