github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/common"
    25  	"github.com/phillinzzz/newBsc/common/math"
    26  	"github.com/phillinzzz/newBsc/consensus/misc"
    27  	"github.com/phillinzzz/newBsc/core"
    28  	"github.com/phillinzzz/newBsc/core/rawdb"
    29  	"github.com/phillinzzz/newBsc/core/state"
    30  	"github.com/phillinzzz/newBsc/core/types"
    31  	"github.com/phillinzzz/newBsc/core/vm"
    32  	"github.com/phillinzzz/newBsc/crypto"
    33  	"github.com/phillinzzz/newBsc/ethdb"
    34  	"github.com/phillinzzz/newBsc/log"
    35  	"github.com/phillinzzz/newBsc/params"
    36  	"github.com/phillinzzz/newBsc/rlp"
    37  	"github.com/phillinzzz/newBsc/trie"
    38  	"golang.org/x/crypto/sha3"
    39  )
    40  
    41  type Prestate struct {
    42  	Env stEnv             `json:"env"`
    43  	Pre core.GenesisAlloc `json:"pre"`
    44  }
    45  
    46  // ExecutionResult contains the execution status after running a state test, any
    47  // error that might have occurred and a dump of the final state if requested.
    48  type ExecutionResult struct {
    49  	StateRoot   common.Hash    `json:"stateRoot"`
    50  	TxRoot      common.Hash    `json:"txRoot"`
    51  	ReceiptRoot common.Hash    `json:"receiptRoot"`
    52  	LogsHash    common.Hash    `json:"logsHash"`
    53  	Bloom       types.Bloom    `json:"logsBloom"        gencodec:"required"`
    54  	Receipts    types.Receipts `json:"receipts"`
    55  	Rejected    []int          `json:"rejected,omitempty"`
    56  }
    57  
    58  type ommer struct {
    59  	Delta   uint64         `json:"delta"`
    60  	Address common.Address `json:"address"`
    61  }
    62  
    63  //go:generate gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
    64  type stEnv struct {
    65  	Coinbase    common.Address                      `json:"currentCoinbase"   gencodec:"required"`
    66  	Difficulty  *big.Int                            `json:"currentDifficulty" gencodec:"required"`
    67  	GasLimit    uint64                              `json:"currentGasLimit"   gencodec:"required"`
    68  	Number      uint64                              `json:"currentNumber"     gencodec:"required"`
    69  	Timestamp   uint64                              `json:"currentTimestamp"  gencodec:"required"`
    70  	BlockHashes map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
    71  	Ommers      []ommer                             `json:"ommers,omitempty"`
    72  }
    73  
    74  type stEnvMarshaling struct {
    75  	Coinbase   common.UnprefixedAddress
    76  	Difficulty *math.HexOrDecimal256
    77  	GasLimit   math.HexOrDecimal64
    78  	Number     math.HexOrDecimal64
    79  	Timestamp  math.HexOrDecimal64
    80  }
    81  
    82  // Apply applies a set of transactions to a pre-state
    83  func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
    84  	txs types.Transactions, miningReward int64,
    85  	getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.Tracer, err error)) (*state.StateDB, *ExecutionResult, error) {
    86  
    87  	// Capture errors for BLOCKHASH operation, if we haven't been supplied the
    88  	// required blockhashes
    89  	var hashError error
    90  	getHash := func(num uint64) common.Hash {
    91  		if pre.Env.BlockHashes == nil {
    92  			hashError = fmt.Errorf("getHash(%d) invoked, no blockhashes provided", num)
    93  			return common.Hash{}
    94  		}
    95  		h, ok := pre.Env.BlockHashes[math.HexOrDecimal64(num)]
    96  		if !ok {
    97  			hashError = fmt.Errorf("getHash(%d) invoked, blockhash for that block not provided", num)
    98  		}
    99  		return h
   100  	}
   101  	var (
   102  		statedb     = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre)
   103  		signer      = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number))
   104  		gaspool     = new(core.GasPool)
   105  		blockHash   = common.Hash{0x13, 0x37}
   106  		rejectedTxs []int
   107  		includedTxs types.Transactions
   108  		gasUsed     = uint64(0)
   109  		receipts    = make(types.Receipts, 0)
   110  		txIndex     = 0
   111  	)
   112  	gaspool.AddGas(pre.Env.GasLimit)
   113  	vmContext := vm.BlockContext{
   114  		CanTransfer: core.CanTransfer,
   115  		Transfer:    core.Transfer,
   116  		Coinbase:    pre.Env.Coinbase,
   117  		BlockNumber: new(big.Int).SetUint64(pre.Env.Number),
   118  		Time:        new(big.Int).SetUint64(pre.Env.Timestamp),
   119  		Difficulty:  pre.Env.Difficulty,
   120  		GasLimit:    pre.Env.GasLimit,
   121  		GetHash:     getHash,
   122  	}
   123  	// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
   124  	// done in StateProcessor.Process(block, ...), right before transactions are applied.
   125  	if chainConfig.DAOForkSupport &&
   126  		chainConfig.DAOForkBlock != nil &&
   127  		chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 {
   128  		misc.ApplyDAOHardFork(statedb)
   129  	}
   130  
   131  	for i, tx := range txs {
   132  		msg, err := tx.AsMessage(signer)
   133  		if err != nil {
   134  			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
   135  			rejectedTxs = append(rejectedTxs, i)
   136  			continue
   137  		}
   138  		tracer, err := getTracerFn(txIndex, tx.Hash())
   139  		if err != nil {
   140  			return nil, nil, err
   141  		}
   142  		vmConfig.Tracer = tracer
   143  		vmConfig.Debug = (tracer != nil)
   144  		statedb.Prepare(tx.Hash(), blockHash, txIndex)
   145  		txContext := core.NewEVMTxContext(msg)
   146  		snapshot := statedb.Snapshot()
   147  		evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)
   148  
   149  		// (ret []byte, usedGas uint64, failed bool, err error)
   150  		msgResult, err := core.ApplyMessage(evm, msg, gaspool)
   151  		if err != nil {
   152  			statedb.RevertToSnapshot(snapshot)
   153  			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From(), "error", err)
   154  			rejectedTxs = append(rejectedTxs, i)
   155  			continue
   156  		}
   157  		includedTxs = append(includedTxs, tx)
   158  		if hashError != nil {
   159  			return nil, nil, NewError(ErrorMissingBlockhash, hashError)
   160  		}
   161  		gasUsed += msgResult.UsedGas
   162  
   163  		// Receipt:
   164  		{
   165  			var root []byte
   166  			if chainConfig.IsByzantium(vmContext.BlockNumber) {
   167  				statedb.Finalise(true)
   168  			} else {
   169  				root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes()
   170  			}
   171  
   172  			// Create a new receipt for the transaction, storing the intermediate root and
   173  			// gas used by the tx.
   174  			receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: gasUsed}
   175  			if msgResult.Failed() {
   176  				receipt.Status = types.ReceiptStatusFailed
   177  			} else {
   178  				receipt.Status = types.ReceiptStatusSuccessful
   179  			}
   180  			receipt.TxHash = tx.Hash()
   181  			receipt.GasUsed = msgResult.UsedGas
   182  
   183  			// If the transaction created a contract, store the creation address in the receipt.
   184  			if msg.To() == nil {
   185  				receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   186  			}
   187  
   188  			// Set the receipt logs and create the bloom filter.
   189  			receipt.Logs = statedb.GetLogs(tx.Hash())
   190  			receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   191  			// These three are non-consensus fields:
   192  			//receipt.BlockHash
   193  			//receipt.BlockNumber
   194  			receipt.TransactionIndex = uint(txIndex)
   195  			receipts = append(receipts, receipt)
   196  		}
   197  
   198  		txIndex++
   199  	}
   200  	statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber))
   201  	// Add mining reward?
   202  	if miningReward > 0 {
   203  		// Add mining reward. The mining reward may be `0`, which only makes a difference in the cases
   204  		// where
   205  		// - the coinbase suicided, or
   206  		// - there are only 'bad' transactions, which aren't executed. In those cases,
   207  		//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
   208  		var (
   209  			blockReward = big.NewInt(miningReward)
   210  			minerReward = new(big.Int).Set(blockReward)
   211  			perOmmer    = new(big.Int).Div(blockReward, big.NewInt(32))
   212  		)
   213  		for _, ommer := range pre.Env.Ommers {
   214  			// Add 1/32th for each ommer included
   215  			minerReward.Add(minerReward, perOmmer)
   216  			// Add (8-delta)/8
   217  			reward := big.NewInt(8)
   218  			reward.Sub(reward, big.NewInt(0).SetUint64(ommer.Delta))
   219  			reward.Mul(reward, blockReward)
   220  			reward.Div(reward, big.NewInt(8))
   221  			statedb.AddBalance(ommer.Address, reward)
   222  		}
   223  		statedb.AddBalance(pre.Env.Coinbase, minerReward)
   224  	}
   225  	// Commit block
   226  	root, _, err := statedb.Commit(chainConfig.IsEIP158(vmContext.BlockNumber))
   227  	if err != nil {
   228  		fmt.Fprintf(os.Stderr, "Could not commit state: %v", err)
   229  		return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not commit state: %v", err))
   230  	}
   231  	execRs := &ExecutionResult{
   232  		StateRoot:   root,
   233  		TxRoot:      types.DeriveSha(includedTxs, trie.NewStackTrie(nil)),
   234  		ReceiptRoot: types.DeriveSha(receipts, trie.NewStackTrie(nil)),
   235  		Bloom:       types.CreateBloom(receipts),
   236  		LogsHash:    rlpHash(statedb.Logs()),
   237  		Receipts:    receipts,
   238  		Rejected:    rejectedTxs,
   239  	}
   240  	return statedb, execRs, nil
   241  }
   242  
   243  func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
   244  	sdb := state.NewDatabase(db)
   245  	statedb, _ := state.New(common.Hash{}, sdb, nil)
   246  	for addr, a := range accounts {
   247  		statedb.SetCode(addr, a.Code)
   248  		statedb.SetNonce(addr, a.Nonce)
   249  		statedb.SetBalance(addr, a.Balance)
   250  		for k, v := range a.Storage {
   251  			statedb.SetState(addr, k, v)
   252  		}
   253  	}
   254  	// Commit and re-open to start with a clean state.
   255  	root, _, _ := statedb.Commit(false)
   256  	statedb, _ = state.New(root, sdb, nil)
   257  	return statedb
   258  }
   259  
   260  func rlpHash(x interface{}) (h common.Hash) {
   261  	hw := sha3.NewLegacyKeccak256()
   262  	rlp.Encode(hw, x)
   263  	hw.Sum(h[:0])
   264  	return h
   265  }