github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/cmd/evm/internal/t8ntool/execution.go (about)

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