github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/kisexp/xdchain/common"
    25  	"github.com/kisexp/xdchain/common/math"
    26  	"github.com/kisexp/xdchain/consensus/misc"
    27  	"github.com/kisexp/xdchain/core"
    28  	"github.com/kisexp/xdchain/core/rawdb"
    29  	"github.com/kisexp/xdchain/core/state"
    30  	"github.com/kisexp/xdchain/core/types"
    31  	"github.com/kisexp/xdchain/core/vm"
    32  	"github.com/kisexp/xdchain/crypto"
    33  	"github.com/kisexp/xdchain/ethdb"
    34  	"github.com/kisexp/xdchain/log"
    35  	"github.com/kisexp/xdchain/params"
    36  	"github.com/kisexp/xdchain/rlp"
    37  	"github.com/kisexp/xdchain/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  		privateStatedb = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre) // Quorum private state db
   104  		signer         = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number))
   105  		gaspool        = new(core.GasPool)
   106  		blockHash      = common.Hash{0x13, 0x37}
   107  		rejectedTxs    []int
   108  		includedTxs    types.Transactions
   109  		gasUsed        = uint64(0)
   110  		receipts       = make(types.Receipts, 0)
   111  		txIndex        = 0
   112  	)
   113  	gaspool.AddGas(pre.Env.GasLimit)
   114  	vmContext := vm.BlockContext{
   115  		CanTransfer: core.CanTransfer,
   116  		Transfer:    core.Transfer,
   117  		Coinbase:    pre.Env.Coinbase,
   118  		BlockNumber: new(big.Int).SetUint64(pre.Env.Number),
   119  		Time:        new(big.Int).SetUint64(pre.Env.Timestamp),
   120  		Difficulty:  pre.Env.Difficulty,
   121  		GasLimit:    pre.Env.GasLimit,
   122  		GetHash:     getHash,
   123  	}
   124  	// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
   125  	// done in StateProcessor.Process(block, ...), right before transactions are applied.
   126  	if chainConfig.DAOForkSupport &&
   127  		chainConfig.DAOForkBlock != nil &&
   128  		chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 {
   129  		misc.ApplyDAOHardFork(statedb)
   130  	}
   131  
   132  	for i, tx := range txs {
   133  		msg, err := tx.AsMessage(signer)
   134  		if err != nil {
   135  			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
   136  			rejectedTxs = append(rejectedTxs, i)
   137  			continue
   138  		}
   139  		tracer, err := getTracerFn(txIndex, tx.Hash())
   140  		if err != nil {
   141  			return nil, nil, err
   142  		}
   143  		vmConfig.Tracer = tracer
   144  		vmConfig.Debug = (tracer != nil)
   145  		statedb.Prepare(tx.Hash(), blockHash, txIndex)
   146  		txContext := core.NewEVMTxContext(msg)
   147  
   148  		evm := vm.NewEVM(vmContext, txContext, statedb, privateStatedb, chainConfig, vmConfig)
   149  		if chainConfig.IsYoloV2(vmContext.BlockNumber) {
   150  			statedb.AddAddressToAccessList(msg.From())
   151  			if dst := msg.To(); dst != nil {
   152  				statedb.AddAddressToAccessList(*dst)
   153  				// If it's a create-tx, the destination will be added inside evm.create
   154  			}
   155  			for _, addr := range evm.ActivePrecompiles() {
   156  				statedb.AddAddressToAccessList(addr)
   157  			}
   158  		}
   159  		snapshot := statedb.Snapshot()
   160  		// (ret []byte, usedGas uint64, failed bool, err error)
   161  		msgResult, err := core.ApplyMessage(evm, msg, gaspool)
   162  		if err != nil {
   163  			statedb.RevertToSnapshot(snapshot)
   164  			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From(), "error", err)
   165  			rejectedTxs = append(rejectedTxs, i)
   166  			continue
   167  		}
   168  		includedTxs = append(includedTxs, tx)
   169  		if hashError != nil {
   170  			return nil, nil, NewError(ErrorMissingBlockhash, hashError)
   171  		}
   172  		gasUsed += msgResult.UsedGas
   173  		// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
   174  		{
   175  			var root []byte
   176  			if chainConfig.IsByzantium(vmContext.BlockNumber) {
   177  				statedb.Finalise(true)
   178  			} else {
   179  				root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes()
   180  			}
   181  
   182  			receipt := types.NewReceipt(root, msgResult.Failed(), gasUsed)
   183  			receipt.TxHash = tx.Hash()
   184  			receipt.GasUsed = msgResult.UsedGas
   185  			// if the transaction created a contract, store the creation address in the receipt.
   186  			if msg.To() == nil {
   187  				receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
   188  			}
   189  			// Set the receipt logs and create a bloom for filtering
   190  			receipt.Logs = statedb.GetLogs(tx.Hash())
   191  			receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
   192  			// These three are non-consensus fields
   193  			//receipt.BlockHash
   194  			//receipt.BlockNumber =
   195  			receipt.TransactionIndex = uint(txIndex)
   196  			receipts = append(receipts, receipt)
   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, new(trie.Trie)),
   234  		ReceiptRoot: types.DeriveSha(receipts, new(trie.Trie)),
   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  }