github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/cmd/evm/internal/t8ntool/execution.go (about)

     1  // Copyright 2020 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package t8ntool
    18  
    19  import (
    20  	"fmt"
    21  	"math/big"
    22  	"os"
    23  
    24  	"github.com/tacshi/go-ethereum/common"
    25  	"github.com/tacshi/go-ethereum/common/math"
    26  	"github.com/tacshi/go-ethereum/consensus/ethash"
    27  	"github.com/tacshi/go-ethereum/consensus/misc"
    28  	"github.com/tacshi/go-ethereum/core"
    29  	"github.com/tacshi/go-ethereum/core/rawdb"
    30  	"github.com/tacshi/go-ethereum/core/state"
    31  	"github.com/tacshi/go-ethereum/core/types"
    32  	"github.com/tacshi/go-ethereum/core/vm"
    33  	"github.com/tacshi/go-ethereum/crypto"
    34  	"github.com/tacshi/go-ethereum/ethdb"
    35  	"github.com/tacshi/go-ethereum/log"
    36  	"github.com/tacshi/go-ethereum/params"
    37  	"github.com/tacshi/go-ethereum/rlp"
    38  	"github.com/tacshi/go-ethereum/trie"
    39  	"golang.org/x/crypto/sha3"
    40  )
    41  
    42  type Prestate struct {
    43  	Env stEnv             `json:"env"`
    44  	Pre core.GenesisAlloc `json:"pre"`
    45  }
    46  
    47  // ExecutionResult contains the execution status after running a state test, any
    48  // error that might have occurred and a dump of the final state if requested.
    49  type ExecutionResult struct {
    50  	StateRoot       common.Hash           `json:"stateRoot"`
    51  	TxRoot          common.Hash           `json:"txRoot"`
    52  	ReceiptRoot     common.Hash           `json:"receiptsRoot"`
    53  	LogsHash        common.Hash           `json:"logsHash"`
    54  	Bloom           types.Bloom           `json:"logsBloom"        gencodec:"required"`
    55  	Receipts        types.Receipts        `json:"receipts"`
    56  	Rejected        []*rejectedTx         `json:"rejected,omitempty"`
    57  	Difficulty      *math.HexOrDecimal256 `json:"currentDifficulty" gencodec:"required"`
    58  	GasUsed         math.HexOrDecimal64   `json:"gasUsed"`
    59  	BaseFee         *math.HexOrDecimal256 `json:"currentBaseFee,omitempty"`
    60  	WithdrawalsRoot *common.Hash          `json:"withdrawalsRoot,omitempty"`
    61  }
    62  
    63  type ommer struct {
    64  	Delta   uint64         `json:"delta"`
    65  	Address common.Address `json:"address"`
    66  }
    67  
    68  //go:generate go run github.com/fjl/gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    69  type stEnv struct {
    70  	Coinbase         common.Address                      `json:"currentCoinbase"   gencodec:"required"`
    71  	Difficulty       *big.Int                            `json:"currentDifficulty"`
    72  	Random           *big.Int                            `json:"currentRandom"`
    73  	ParentDifficulty *big.Int                            `json:"parentDifficulty"`
    74  	ParentBaseFee    *big.Int                            `json:"parentBaseFee,omitempty"`
    75  	ParentGasUsed    uint64                              `json:"parentGasUsed,omitempty"`
    76  	ParentGasLimit   uint64                              `json:"parentGasLimit,omitempty"`
    77  	GasLimit         uint64                              `json:"currentGasLimit"   gencodec:"required"`
    78  	Number           uint64                              `json:"currentNumber"     gencodec:"required"`
    79  	Timestamp        uint64                              `json:"currentTimestamp"  gencodec:"required"`
    80  	ParentTimestamp  uint64                              `json:"parentTimestamp,omitempty"`
    81  	BlockHashes      map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
    82  	Ommers           []ommer                             `json:"ommers,omitempty"`
    83  	Withdrawals      []*types.Withdrawal                 `json:"withdrawals,omitempty"`
    84  	BaseFee          *big.Int                            `json:"currentBaseFee,omitempty"`
    85  	ParentUncleHash  common.Hash                         `json:"parentUncleHash"`
    86  }
    87  
    88  type stEnvMarshaling struct {
    89  	Coinbase         common.UnprefixedAddress
    90  	Difficulty       *math.HexOrDecimal256
    91  	Random           *math.HexOrDecimal256
    92  	ParentDifficulty *math.HexOrDecimal256
    93  	ParentBaseFee    *math.HexOrDecimal256
    94  	ParentGasUsed    math.HexOrDecimal64
    95  	ParentGasLimit   math.HexOrDecimal64
    96  	GasLimit         math.HexOrDecimal64
    97  	Number           math.HexOrDecimal64
    98  	Timestamp        math.HexOrDecimal64
    99  	ParentTimestamp  math.HexOrDecimal64
   100  	BaseFee          *math.HexOrDecimal256
   101  }
   102  
   103  type rejectedTx struct {
   104  	Index int    `json:"index"`
   105  	Err   string `json:"error"`
   106  }
   107  
   108  // Apply applies a set of transactions to a pre-state
   109  func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
   110  	txs types.Transactions, miningReward int64,
   111  	getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error)) (*state.StateDB, *ExecutionResult, error) {
   112  	if chainConfig.IsArbitrum() {
   113  		return nil, nil, NewError(ErrorConfig, fmt.Errorf("chain config has arbitrum enabled"))
   114  	}
   115  	// Capture errors for BLOCKHASH operation, if we haven't been supplied the
   116  	// required blockhashes
   117  	var hashError error
   118  	getHash := func(num uint64) common.Hash {
   119  		if pre.Env.BlockHashes == nil {
   120  			hashError = fmt.Errorf("getHash(%d) invoked, no blockhashes provided", num)
   121  			return common.Hash{}
   122  		}
   123  		h, ok := pre.Env.BlockHashes[math.HexOrDecimal64(num)]
   124  		if !ok {
   125  			hashError = fmt.Errorf("getHash(%d) invoked, blockhash for that block not provided", num)
   126  		}
   127  		return h
   128  	}
   129  	var (
   130  		statedb     = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre)
   131  		signer      = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number))
   132  		gaspool     = new(core.GasPool)
   133  		blockHash   = common.Hash{0x13, 0x37}
   134  		rejectedTxs []*rejectedTx
   135  		includedTxs types.Transactions
   136  		gasUsed     = uint64(0)
   137  		receipts    = make(types.Receipts, 0)
   138  		txIndex     = 0
   139  	)
   140  	gaspool.AddGas(pre.Env.GasLimit)
   141  	vmContext := vm.BlockContext{
   142  		CanTransfer: core.CanTransfer,
   143  		Transfer:    core.Transfer,
   144  		Coinbase:    pre.Env.Coinbase,
   145  		BlockNumber: new(big.Int).SetUint64(pre.Env.Number),
   146  		Time:        pre.Env.Timestamp,
   147  		Difficulty:  pre.Env.Difficulty,
   148  		GasLimit:    pre.Env.GasLimit,
   149  		GetHash:     getHash,
   150  	}
   151  	// If currentBaseFee is defined, add it to the vmContext.
   152  	if pre.Env.BaseFee != nil {
   153  		vmContext.BaseFee = new(big.Int).Set(pre.Env.BaseFee)
   154  	}
   155  	// If random is defined, add it to the vmContext.
   156  	if pre.Env.Random != nil {
   157  		rnd := common.BigToHash(pre.Env.Random)
   158  		vmContext.Random = &rnd
   159  	}
   160  	// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
   161  	// done in StateProcessor.Process(block, ...), right before transactions are applied.
   162  	if chainConfig.DAOForkSupport &&
   163  		chainConfig.DAOForkBlock != nil &&
   164  		chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 {
   165  		misc.ApplyDAOHardFork(statedb)
   166  	}
   167  
   168  	for i, tx := range txs {
   169  		msg, err := core.TransactionToMessage(tx, signer, pre.Env.BaseFee)
   170  		if err != nil {
   171  			log.Warn("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
   172  			rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
   173  			continue
   174  		}
   175  		tracer, err := getTracerFn(txIndex, tx.Hash())
   176  		if err != nil {
   177  			return nil, nil, err
   178  		}
   179  		vmConfig.Tracer = tracer
   180  		vmConfig.Debug = (tracer != nil)
   181  		statedb.SetTxContext(tx.Hash(), txIndex)
   182  
   183  		var (
   184  			txContext = core.NewEVMTxContext(msg)
   185  			snapshot  = statedb.Snapshot()
   186  			prevGas   = gaspool.Gas()
   187  		)
   188  		evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)
   189  
   190  		// (ret []byte, usedGas uint64, failed bool, err error)
   191  		msgResult, err := core.ApplyMessage(evm, msg, gaspool)
   192  		if err != nil {
   193  			statedb.RevertToSnapshot(snapshot)
   194  			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From, "error", err)
   195  			rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
   196  			gaspool.SetGas(prevGas)
   197  			continue
   198  		}
   199  		includedTxs = append(includedTxs, tx)
   200  		if hashError != nil {
   201  			return nil, nil, NewError(ErrorMissingBlockhash, hashError)
   202  		}
   203  		gasUsed += msgResult.UsedGas
   204  
   205  		// Receipt:
   206  		{
   207  			var root []byte
   208  			if chainConfig.IsByzantium(vmContext.BlockNumber) {
   209  				statedb.Finalise(true)
   210  			} else {
   211  				root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes()
   212  			}
   213  
   214  			// Create a new receipt for the transaction, storing the intermediate root and
   215  			// gas used by the tx.
   216  			receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: gasUsed}
   217  			if msgResult.Failed() {
   218  				receipt.Status = types.ReceiptStatusFailed
   219  			} else {
   220  				receipt.Status = types.ReceiptStatusSuccessful
   221  			}
   222  			receipt.TxHash = tx.Hash()
   223  			receipt.GasUsed = msgResult.UsedGas
   224  
   225  			// If the transaction created a contract, store the creation address in the receipt.
   226  			if msg.To == nil {
   227  				receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   228  			}
   229  
   230  			// Set the receipt logs and create the bloom filter.
   231  			receipt.Logs = statedb.GetLogs(tx.Hash(), vmContext.BlockNumber.Uint64(), blockHash)
   232  			receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   233  			// These three are non-consensus fields:
   234  			//receipt.BlockHash
   235  			//receipt.BlockNumber
   236  			receipt.TransactionIndex = uint(txIndex)
   237  			receipts = append(receipts, receipt)
   238  		}
   239  
   240  		txIndex++
   241  	}
   242  	statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber))
   243  	// Add mining reward? (-1 means rewards are disabled)
   244  	if miningReward >= 0 {
   245  		// Add mining reward. The mining reward may be `0`, which only makes a difference in the cases
   246  		// where
   247  		// - the coinbase suicided, or
   248  		// - there are only 'bad' transactions, which aren't executed. In those cases,
   249  		//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   250  		var (
   251  			blockReward = big.NewInt(miningReward)
   252  			minerReward = new(big.Int).Set(blockReward)
   253  			perOmmer    = new(big.Int).Div(blockReward, big.NewInt(32))
   254  		)
   255  		for _, ommer := range pre.Env.Ommers {
   256  			// Add 1/32th for each ommer included
   257  			minerReward.Add(minerReward, perOmmer)
   258  			// Add (8-delta)/8
   259  			reward := big.NewInt(8)
   260  			reward.Sub(reward, new(big.Int).SetUint64(ommer.Delta))
   261  			reward.Mul(reward, blockReward)
   262  			reward.Div(reward, big.NewInt(8))
   263  			statedb.AddBalance(ommer.Address, reward)
   264  		}
   265  		statedb.AddBalance(pre.Env.Coinbase, minerReward)
   266  	}
   267  	// Apply withdrawals
   268  	for _, w := range pre.Env.Withdrawals {
   269  		// Amount is in gwei, turn into wei
   270  		amount := new(big.Int).Mul(new(big.Int).SetUint64(w.Amount), big.NewInt(params.GWei))
   271  		statedb.AddBalance(w.Address, amount)
   272  	}
   273  	// Commit block
   274  	root, err := statedb.Commit(chainConfig.IsEIP158(vmContext.BlockNumber))
   275  	if err != nil {
   276  		fmt.Fprintf(os.Stderr, "Could not commit state: %v", err)
   277  		return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not commit state: %v", err))
   278  	}
   279  	execRs := &ExecutionResult{
   280  		StateRoot:   root,
   281  		TxRoot:      types.DeriveSha(includedTxs, trie.NewStackTrie(nil)),
   282  		ReceiptRoot: types.DeriveSha(receipts, trie.NewStackTrie(nil)),
   283  		Bloom:       types.CreateBloom(receipts),
   284  		LogsHash:    rlpHash(statedb.Logs()),
   285  		Receipts:    receipts,
   286  		Rejected:    rejectedTxs,
   287  		Difficulty:  (*math.HexOrDecimal256)(vmContext.Difficulty),
   288  		GasUsed:     (math.HexOrDecimal64)(gasUsed),
   289  		BaseFee:     (*math.HexOrDecimal256)(vmContext.BaseFee),
   290  	}
   291  	if pre.Env.Withdrawals != nil {
   292  		h := types.DeriveSha(types.Withdrawals(pre.Env.Withdrawals), trie.NewStackTrie(nil))
   293  		execRs.WithdrawalsRoot = &h
   294  	}
   295  	return statedb, execRs, nil
   296  }
   297  
   298  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
   299  	sdb := state.NewDatabaseWithConfig(db, &trie.Config{Preimages: true})
   300  	statedb, _ := state.New(common.Hash{}, sdb, nil)
   301  	for addr, a := range accounts {
   302  		statedb.SetCode(addr, a.Code)
   303  		statedb.SetNonce(addr, a.Nonce)
   304  		statedb.SetBalance(addr, a.Balance)
   305  		for k, v := range a.Storage {
   306  			statedb.SetState(addr, k, v)
   307  		}
   308  	}
   309  	// Commit and re-open to start with a clean state.
   310  	root, _ := statedb.Commit(false)
   311  	statedb, _ = state.New(root, sdb, nil)
   312  	return statedb
   313  }
   314  
   315  func rlpHash(x interface{}) (h common.Hash) {
   316  	hw := sha3.NewLegacyKeccak256()
   317  	rlp.Encode(hw, x)
   318  	hw.Sum(h[:0])
   319  	return h
   320  }
   321  
   322  // calcDifficulty is based on ethash.CalcDifficulty. This method is used in case
   323  // the caller does not provide an explicit difficulty, but instead provides only
   324  // parent timestamp + difficulty.
   325  // Note: this method only works for ethash engine.
   326  func calcDifficulty(config *params.ChainConfig, number, currentTime, parentTime uint64,
   327  	parentDifficulty *big.Int, parentUncleHash common.Hash) *big.Int {
   328  	uncleHash := parentUncleHash
   329  	if uncleHash == (common.Hash{}) {
   330  		uncleHash = types.EmptyUncleHash
   331  	}
   332  	parent := &types.Header{
   333  		ParentHash: common.Hash{},
   334  		UncleHash:  uncleHash,
   335  		Difficulty: parentDifficulty,
   336  		Number:     new(big.Int).SetUint64(number - 1),
   337  		Time:       parentTime,
   338  	}
   339  	return ethash.CalcDifficulty(config, currentTime, parent)
   340  }