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