execution.go 12.8 KB
Newer Older
1
// Copyright 2020 The go-ethereum Authors
2
// This file is part of go-ethereum.
3
//
4 5
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
6 7 8
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// go-ethereum is distributed in the hope that it will be useful,
10 11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
// GNU General Public License for more details.
13
//
14 15
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16 17 18 19 20 21 22 23 24

package t8ntool

import (
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/math"
25
	"github.com/ethereum/go-ethereum/consensus/ethash"
26 27 28 29 30 31 32 33 34 35 36
	"github.com/ethereum/go-ethereum/consensus/misc"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/rawdb"
	"github.com/ethereum/go-ethereum/core/state"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/core/vm"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/params"
	"github.com/ethereum/go-ethereum/rlp"
37
	"github.com/ethereum/go-ethereum/trie"
38 39 40 41 42 43 44 45 46 47 48
	"golang.org/x/crypto/sha3"
)

type Prestate struct {
	Env stEnv             `json:"env"`
	Pre core.GenesisAlloc `json:"pre"`
}

// ExecutionResult contains the execution status after running a state test, any
// error that might have occurred and a dump of the final state if requested.
type ExecutionResult struct {
49 50 51 52 53 54 55 56 57 58 59
	StateRoot       common.Hash           `json:"stateRoot"`
	TxRoot          common.Hash           `json:"txRoot"`
	ReceiptRoot     common.Hash           `json:"receiptsRoot"`
	LogsHash        common.Hash           `json:"logsHash"`
	Bloom           types.Bloom           `json:"logsBloom"        gencodec:"required"`
	Receipts        types.Receipts        `json:"receipts"`
	Rejected        []*rejectedTx         `json:"rejected,omitempty"`
	Difficulty      *math.HexOrDecimal256 `json:"currentDifficulty" gencodec:"required"`
	GasUsed         math.HexOrDecimal64   `json:"gasUsed"`
	BaseFee         *math.HexOrDecimal256 `json:"currentBaseFee,omitempty"`
	WithdrawalsRoot *common.Hash          `json:"withdrawalsRoot,omitempty"`
60 61 62 63 64 65 66
}

type ommer struct {
	Delta   uint64         `json:"delta"`
	Address common.Address `json:"address"`
}

67
//go:generate go run github.com/fjl/gencodec -type stEnv -field-override stEnvMarshaling -out gen_stenv.go
68
type stEnv struct {
69 70
	Coinbase         common.Address                      `json:"currentCoinbase"   gencodec:"required"`
	Difficulty       *big.Int                            `json:"currentDifficulty"`
71
	Random           *big.Int                            `json:"currentRandom"`
72
	ParentDifficulty *big.Int                            `json:"parentDifficulty"`
73 74 75
	ParentBaseFee    *big.Int                            `json:"parentBaseFee,omitempty"`
	ParentGasUsed    uint64                              `json:"parentGasUsed,omitempty"`
	ParentGasLimit   uint64                              `json:"parentGasLimit,omitempty"`
76 77 78 79 80 81
	GasLimit         uint64                              `json:"currentGasLimit"   gencodec:"required"`
	Number           uint64                              `json:"currentNumber"     gencodec:"required"`
	Timestamp        uint64                              `json:"currentTimestamp"  gencodec:"required"`
	ParentTimestamp  uint64                              `json:"parentTimestamp,omitempty"`
	BlockHashes      map[math.HexOrDecimal64]common.Hash `json:"blockHashes,omitempty"`
	Ommers           []ommer                             `json:"ommers,omitempty"`
82
	Withdrawals      []*types.Withdrawal                 `json:"withdrawals,omitempty"`
83 84
	BaseFee          *big.Int                            `json:"currentBaseFee,omitempty"`
	ParentUncleHash  common.Hash                         `json:"parentUncleHash"`
85 86 87
}

type stEnvMarshaling struct {
88 89
	Coinbase         common.UnprefixedAddress
	Difficulty       *math.HexOrDecimal256
90
	Random           *math.HexOrDecimal256
91
	ParentDifficulty *math.HexOrDecimal256
92 93 94
	ParentBaseFee    *math.HexOrDecimal256
	ParentGasUsed    math.HexOrDecimal64
	ParentGasLimit   math.HexOrDecimal64
95 96 97 98 99
	GasLimit         math.HexOrDecimal64
	Number           math.HexOrDecimal64
	Timestamp        math.HexOrDecimal64
	ParentTimestamp  math.HexOrDecimal64
	BaseFee          *math.HexOrDecimal256
100 101
}

102 103 104 105 106
type rejectedTx struct {
	Index int    `json:"index"`
	Err   string `json:"error"`
}

107 108 109
// Apply applies a set of transactions to a pre-state
func (pre *Prestate) Apply(vmConfig vm.Config, chainConfig *params.ChainConfig,
	txs types.Transactions, miningReward int64,
110
	getTracerFn func(txIndex int, txHash common.Hash) (tracer vm.EVMLogger, err error)) (*state.StateDB, *ExecutionResult, error) {
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	// Capture errors for BLOCKHASH operation, if we haven't been supplied the
	// required blockhashes
	var hashError error
	getHash := func(num uint64) common.Hash {
		if pre.Env.BlockHashes == nil {
			hashError = fmt.Errorf("getHash(%d) invoked, no blockhashes provided", num)
			return common.Hash{}
		}
		h, ok := pre.Env.BlockHashes[math.HexOrDecimal64(num)]
		if !ok {
			hashError = fmt.Errorf("getHash(%d) invoked, blockhash for that block not provided", num)
		}
		return h
	}
	var (
		statedb     = MakePreState(rawdb.NewMemoryDatabase(), pre.Pre)
127
		signer      = types.MakeSigner(chainConfig, new(big.Int).SetUint64(pre.Env.Number), pre.Env.Timestamp)
128 129
		gaspool     = new(core.GasPool)
		blockHash   = common.Hash{0x13, 0x37}
130
		rejectedTxs []*rejectedTx
131 132 133 134 135 136
		includedTxs types.Transactions
		gasUsed     = uint64(0)
		receipts    = make(types.Receipts, 0)
		txIndex     = 0
	)
	gaspool.AddGas(pre.Env.GasLimit)
137
	vmContext := vm.BlockContext{
138 139 140 141
		CanTransfer: core.CanTransfer,
		Transfer:    core.Transfer,
		Coinbase:    pre.Env.Coinbase,
		BlockNumber: new(big.Int).SetUint64(pre.Env.Number),
142
		Time:        pre.Env.Timestamp,
143 144 145 146
		Difficulty:  pre.Env.Difficulty,
		GasLimit:    pre.Env.GasLimit,
		GetHash:     getHash,
	}
147 148 149 150
	// If currentBaseFee is defined, add it to the vmContext.
	if pre.Env.BaseFee != nil {
		vmContext.BaseFee = new(big.Int).Set(pre.Env.BaseFee)
	}
151 152 153 154 155
	// If random is defined, add it to the vmContext.
	if pre.Env.Random != nil {
		rnd := common.BigToHash(pre.Env.Random)
		vmContext.Random = &rnd
	}
156 157 158 159 160 161 162 163 164
	// If DAO is supported/enabled, we need to handle it here. In geth 'proper', it's
	// done in StateProcessor.Process(block, ...), right before transactions are applied.
	if chainConfig.DAOForkSupport &&
		chainConfig.DAOForkBlock != nil &&
		chainConfig.DAOForkBlock.Cmp(new(big.Int).SetUint64(pre.Env.Number)) == 0 {
		misc.ApplyDAOHardFork(statedb)
	}

	for i, tx := range txs {
165
		msg, err := core.TransactionToMessage(tx, signer, pre.Env.BaseFee)
166
		if err != nil {
167 168
			log.Warn("rejected tx", "index", i, "hash", tx.Hash(), "error", err)
			rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
169 170
			continue
		}
171
		tracer, err := getTracerFn(txIndex, tx.Hash())
172 173 174 175
		if err != nil {
			return nil, nil, err
		}
		vmConfig.Tracer = tracer
176
		statedb.SetTxContext(tx.Hash(), txIndex)
177 178 179 180 181 182

		var (
			txContext = core.NewEVMTxContext(msg)
			snapshot  = statedb.Snapshot()
			prevGas   = gaspool.Gas()
		)
183 184
		evm := vm.NewEVM(vmContext, txContext, statedb, chainConfig, vmConfig)

185 186 187 188
		// (ret []byte, usedGas uint64, failed bool, err error)
		msgResult, err := core.ApplyMessage(evm, msg, gaspool)
		if err != nil {
			statedb.RevertToSnapshot(snapshot)
189
			log.Info("rejected tx", "index", i, "hash", tx.Hash(), "from", msg.From, "error", err)
190
			rejectedTxs = append(rejectedTxs, &rejectedTx{i, err.Error()})
191
			gaspool.SetGas(prevGas)
192 193 194 195 196 197 198
			continue
		}
		includedTxs = append(includedTxs, tx)
		if hashError != nil {
			return nil, nil, NewError(ErrorMissingBlockhash, hashError)
		}
		gasUsed += msgResult.UsedGas
199 200

		// Receipt:
201 202 203 204 205 206 207 208
		{
			var root []byte
			if chainConfig.IsByzantium(vmContext.BlockNumber) {
				statedb.Finalise(true)
			} else {
				root = statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber)).Bytes()
			}

209 210 211 212 213 214 215 216
			// Create a new receipt for the transaction, storing the intermediate root and
			// gas used by the tx.
			receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: gasUsed}
			if msgResult.Failed() {
				receipt.Status = types.ReceiptStatusFailed
			} else {
				receipt.Status = types.ReceiptStatusSuccessful
			}
217 218
			receipt.TxHash = tx.Hash()
			receipt.GasUsed = msgResult.UsedGas
219 220

			// If the transaction created a contract, store the creation address in the receipt.
221
			if msg.To == nil {
222
				receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
223
			}
224 225

			// Set the receipt logs and create the bloom filter.
226
			receipt.Logs = statedb.GetLogs(tx.Hash(), vmContext.BlockNumber.Uint64(), blockHash)
227
			receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
228
			// These three are non-consensus fields:
229
			//receipt.BlockHash
230
			//receipt.BlockNumber
231 232 233
			receipt.TransactionIndex = uint(txIndex)
			receipts = append(receipts, receipt)
		}
234

235 236 237
		txIndex++
	}
	statedb.IntermediateRoot(chainConfig.IsEIP158(vmContext.BlockNumber))
238 239
	// Add mining reward? (-1 means rewards are disabled)
	if miningReward >= 0 {
240 241
		// Add mining reward. The mining reward may be `0`, which only makes a difference in the cases
		// where
242
		// - the coinbase self-destructed, or
243 244 245 246 247 248 249 250 251 252 253 254
		// - there are only 'bad' transactions, which aren't executed. In those cases,
		//   the coinbase gets no txfee, so isn't created, and thus needs to be touched
		var (
			blockReward = big.NewInt(miningReward)
			minerReward = new(big.Int).Set(blockReward)
			perOmmer    = new(big.Int).Div(blockReward, big.NewInt(32))
		)
		for _, ommer := range pre.Env.Ommers {
			// Add 1/32th for each ommer included
			minerReward.Add(minerReward, perOmmer)
			// Add (8-delta)/8
			reward := big.NewInt(8)
255
			reward.Sub(reward, new(big.Int).SetUint64(ommer.Delta))
256 257 258 259 260 261
			reward.Mul(reward, blockReward)
			reward.Div(reward, big.NewInt(8))
			statedb.AddBalance(ommer.Address, reward)
		}
		statedb.AddBalance(pre.Env.Coinbase, minerReward)
	}
262 263 264 265 266 267
	// Apply withdrawals
	for _, w := range pre.Env.Withdrawals {
		// Amount is in gwei, turn into wei
		amount := new(big.Int).Mul(new(big.Int).SetUint64(w.Amount), big.NewInt(params.GWei))
		statedb.AddBalance(w.Address, amount)
	}
268 269 270 271 272 273 274
	// Commit block
	root, err := statedb.Commit(chainConfig.IsEIP158(vmContext.BlockNumber))
	if err != nil {
		return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not commit state: %v", err))
	}
	execRs := &ExecutionResult{
		StateRoot:   root,
275 276
		TxRoot:      types.DeriveSha(includedTxs, trie.NewStackTrie(nil)),
		ReceiptRoot: types.DeriveSha(receipts, trie.NewStackTrie(nil)),
277 278 279 280
		Bloom:       types.CreateBloom(receipts),
		LogsHash:    rlpHash(statedb.Logs()),
		Receipts:    receipts,
		Rejected:    rejectedTxs,
281
		Difficulty:  (*math.HexOrDecimal256)(vmContext.Difficulty),
282
		GasUsed:     (math.HexOrDecimal64)(gasUsed),
283
		BaseFee:     (*math.HexOrDecimal256)(vmContext.BaseFee),
284
	}
285 286 287 288
	if pre.Env.Withdrawals != nil {
		h := types.DeriveSha(types.Withdrawals(pre.Env.Withdrawals), trie.NewStackTrie(nil))
		execRs.WithdrawalsRoot = &h
	}
289 290 291 292 293 294
	// Re-create statedb instance with new root upon the updated database
	// for accessing latest states.
	statedb, err = state.New(root, statedb.Database(), nil)
	if err != nil {
		return nil, nil, NewError(ErrorEVM, fmt.Errorf("could not reopen state: %v", err))
	}
295 296 297 298
	return statedb, execRs, nil
}

func MakePreState(db ethdb.Database, accounts core.GenesisAlloc) *state.StateDB {
299
	sdb := state.NewDatabaseWithConfig(db, &trie.Config{Preimages: true})
300
	statedb, _ := state.New(types.EmptyRootHash, sdb, nil)
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	for addr, a := range accounts {
		statedb.SetCode(addr, a.Code)
		statedb.SetNonce(addr, a.Nonce)
		statedb.SetBalance(addr, a.Balance)
		for k, v := range a.Storage {
			statedb.SetState(addr, k, v)
		}
	}
	// Commit and re-open to start with a clean state.
	root, _ := statedb.Commit(false)
	statedb, _ = state.New(root, sdb, nil)
	return statedb
}

func rlpHash(x interface{}) (h common.Hash) {
	hw := sha3.NewLegacyKeccak256()
	rlp.Encode(hw, x)
	hw.Sum(h[:0])
	return h
}
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

// calcDifficulty is based on ethash.CalcDifficulty. This method is used in case
// the caller does not provide an explicit difficulty, but instead provides only
// parent timestamp + difficulty.
// Note: this method only works for ethash engine.
func calcDifficulty(config *params.ChainConfig, number, currentTime, parentTime uint64,
	parentDifficulty *big.Int, parentUncleHash common.Hash) *big.Int {
	uncleHash := parentUncleHash
	if uncleHash == (common.Hash{}) {
		uncleHash = types.EmptyUncleHash
	}
	parent := &types.Header{
		ParentHash: common.Hash{},
		UncleHash:  uncleHash,
		Difficulty: parentDifficulty,
		Number:     new(big.Int).SetUint64(number - 1),
		Time:       parentTime,
	}
	return ethash.CalcDifficulty(config, currentTime, parent)
}