1// Copyright 2015 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
17package core
18
19import (
20	"fmt"
21	"math/big"
22
23	"github.com/ethereum/go-ethereum/common"
24	"github.com/ethereum/go-ethereum/consensus"
25	"github.com/ethereum/go-ethereum/consensus/misc"
26	"github.com/ethereum/go-ethereum/core/state"
27	"github.com/ethereum/go-ethereum/core/types"
28	"github.com/ethereum/go-ethereum/core/vm"
29	"github.com/ethereum/go-ethereum/crypto"
30	"github.com/ethereum/go-ethereum/params"
31)
32
33// StateProcessor is a basic Processor, which takes care of transitioning
34// state from one point to another.
35//
36// StateProcessor implements Processor.
37type StateProcessor struct {
38	config *params.ChainConfig // Chain configuration options
39	bc     *BlockChain         // Canonical block chain
40	engine consensus.Engine    // Consensus engine used for block rewards
41}
42
43// NewStateProcessor initialises a new StateProcessor.
44func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor {
45	return &StateProcessor{
46		config: config,
47		bc:     bc,
48		engine: engine,
49	}
50}
51
52// Process processes the state changes according to the Ethereum rules by running
53// the transaction messages using the statedb and applying any rewards to both
54// the processor (coinbase) and any included uncles.
55//
56// Process returns the receipts and logs accumulated during the process and
57// returns the amount of gas that was used in the process. If any of the
58// transactions failed to execute due to insufficient gas it will return an error.
59func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
60	var (
61		receipts    types.Receipts
62		usedGas     = new(uint64)
63		header      = block.Header()
64		blockHash   = block.Hash()
65		blockNumber = block.Number()
66		allLogs     []*types.Log
67		gp          = new(GasPool).AddGas(block.GasLimit())
68	)
69	// Mutate the block and state according to any hard-fork specs
70	if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
71		misc.ApplyDAOHardFork(statedb)
72	}
73	blockContext := NewEVMBlockContext(header, p.bc, nil)
74	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
75	// Iterate over and process the individual transactions
76	for i, tx := range block.Transactions() {
77		msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number), header.BaseFee)
78		if err != nil {
79			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
80		}
81		statedb.Prepare(tx.Hash(), i)
82		receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
83		if err != nil {
84			return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
85		}
86		receipts = append(receipts, receipt)
87		allLogs = append(allLogs, receipt.Logs...)
88	}
89	// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
90	p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
91
92	return receipts, allLogs, *usedGas, nil
93}
94
95func applyTransaction(msg types.Message, config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, blockNumber *big.Int, blockHash common.Hash, tx *types.Transaction, usedGas *uint64, evm *vm.EVM) (*types.Receipt, error) {
96	// Create a new context to be used in the EVM environment.
97	txContext := NewEVMTxContext(msg)
98	evm.Reset(txContext, statedb)
99
100	// Apply the transaction to the current state (included in the env).
101	result, err := ApplyMessage(evm, msg, gp)
102	if err != nil {
103		return nil, err
104	}
105
106	// Update the state with pending changes.
107	var root []byte
108	if config.IsByzantium(blockNumber) {
109		statedb.Finalise(true)
110	} else {
111		root = statedb.IntermediateRoot(config.IsEIP158(blockNumber)).Bytes()
112	}
113	*usedGas += result.UsedGas
114
115	// Create a new receipt for the transaction, storing the intermediate root and gas used
116	// by the tx.
117	receipt := &types.Receipt{Type: tx.Type(), PostState: root, CumulativeGasUsed: *usedGas}
118	if result.Failed() {
119		receipt.Status = types.ReceiptStatusFailed
120	} else {
121		receipt.Status = types.ReceiptStatusSuccessful
122	}
123	receipt.TxHash = tx.Hash()
124	receipt.GasUsed = result.UsedGas
125
126	// If the transaction created a contract, store the creation address in the receipt.
127	if msg.To() == nil {
128		receipt.ContractAddress = crypto.CreateAddress(evm.TxContext.Origin, tx.Nonce())
129	}
130
131	// Set the receipt logs and create the bloom filter.
132	receipt.Logs = statedb.GetLogs(tx.Hash(), blockHash)
133	receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
134	receipt.BlockHash = blockHash
135	receipt.BlockNumber = blockNumber
136	receipt.TransactionIndex = uint(statedb.TxIndex())
137	return receipt, err
138}
139
140// ApplyTransaction attempts to apply a transaction to the given state database
141// and uses the input parameters for its environment. It returns the receipt
142// for the transaction, gas used and an error if the transaction failed,
143// indicating the block was invalid.
144func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
145	msg, err := tx.AsMessage(types.MakeSigner(config, header.Number), header.BaseFee)
146	if err != nil {
147		return nil, err
148	}
149	// Create a new context to be used in the EVM environment
150	blockContext := NewEVMBlockContext(header, bc, author)
151	vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
152	return applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
153}
154