Skip to content

Commit 3c48a25

Browse files
authored
Merge pull request #15014 from rjl493456442/metropolis-eip658
core: add status as a consensus field in receipt
2 parents 286ec5d + 4ee92f2 commit 3c48a25

18 files changed

Lines changed: 87 additions & 50 deletions

File tree

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,8 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
253253
// about the transaction and calling mechanisms.
254254
vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{})
255255
gaspool := new(core.GasPool).AddGas(math.MaxBig256)
256-
ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
256+
// TODO utilize returned failed flag to help gas estimation.
257+
ret, gasUsed, _, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
257258
return ret, gasUsed, err
258259
}
259260

‎common/bytes.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ func FromHex(s string) []byte {
4747
//
4848
// Returns an exact copy of the provided bytes
4949
func CopyBytes(b []byte) (copiedBytes []byte) {
50+
if b == nil {
51+
return nil
52+
}
5053
copiedBytes = make([]byte, len(b))
5154
copy(copiedBytes, b)
5255

‎core/database_util_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,12 +461,12 @@ func TestMipmapChain(t *testing.T) {
461461
var receipts types.Receipts
462462
switch i {
463463
case 1:
464-
receipt := types.NewReceipt(nil, new(big.Int))
464+
receipt := types.NewReceipt(nil, false, new(big.Int))
465465
receipt.Logs = []*types.Log{{Address: addr, Topics: []common.Hash{hash1}}}
466466
gen.AddUncheckedReceipt(receipt)
467467
receipts = types.Receipts{receipt}
468468
case 1000:
469-
receipt := types.NewReceipt(nil, new(big.Int))
469+
receipt := types.NewReceipt(nil, false, new(big.Int))
470470
receipt.Logs = []*types.Log{{Address: addr2}}
471471
gen.AddUncheckedReceipt(receipt)
472472
receipts = types.Receipts{receipt}

‎core/state_processor.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, author *common
9898
// about the transaction and calling mechanisms.
9999
vmenv := vm.NewEVM(context, statedb, config, cfg)
100100
// Apply the transaction to the current state (included in the env)
101-
_, gas, err := ApplyMessage(vmenv, msg, gp)
101+
_, gas, failed, err := ApplyMessage(vmenv, msg, gp)
102102
if err != nil {
103103
return nil, nil, err
104104
}
@@ -114,7 +114,7 @@ func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, author *common
114114

115115
// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
116116
// based on the eip phase, we're passing wether the root touch-delete accounts.
117-
receipt := types.NewReceipt(root, usedGas)
117+
receipt := types.NewReceipt(root, failed, usedGas)
118118
receipt.TxHash = tx.Hash()
119119
receipt.GasUsed = new(big.Int).Set(gas)
120120
// if the transaction created a contract, store the creation address in the receipt.

‎core/state_transition.go‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,7 @@ type StateTransition struct {
5959
value *big.Int
6060
data []byte
6161
state vm.StateDB
62-
63-
evm *vm.EVM
62+
evm *vm.EVM
6463
}
6564

6665
// Message represents a message sent to a contract.
@@ -127,11 +126,11 @@ func NewStateTransition(evm *vm.EVM, msg Message, gp *GasPool) *StateTransition
127126
// the gas used (which includes gas refunds) and an error if it failed. An error always
128127
// indicates a core error meaning that the message would always fail for that particular
129128
// state and would never be accepted within a block.
130-
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, error) {
129+
func ApplyMessage(evm *vm.EVM, msg Message, gp *GasPool) ([]byte, *big.Int, bool, error) {
131130
st := NewStateTransition(evm, msg, gp)
132131

133-
ret, _, gasUsed, err := st.TransitionDb()
134-
return ret, gasUsed, err
132+
ret, _, gasUsed, failed, err := st.TransitionDb()
133+
return ret, gasUsed, failed, err
135134
}
136135

137136
func (st *StateTransition) from() vm.AccountRef {
@@ -208,7 +207,7 @@ func (st *StateTransition) preCheck() error {
208207
// TransitionDb will transition the state by applying the current message and returning the result
209208
// including the required gas for the operation as well as the used gas. It returns an error if it
210209
// failed. An error indicates a consensus issue.
211-
func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, err error) {
210+
func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big.Int, failed bool, err error) {
212211
if err = st.preCheck(); err != nil {
213212
return
214213
}
@@ -222,10 +221,10 @@ func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big
222221
// TODO convert to uint64
223222
intrinsicGas := IntrinsicGas(st.data, contractCreation, homestead)
224223
if intrinsicGas.BitLen() > 64 {
225-
return nil, nil, nil, vm.ErrOutOfGas
224+
return nil, nil, nil, false, vm.ErrOutOfGas
226225
}
227226
if err = st.useGas(intrinsicGas.Uint64()); err != nil {
228-
return nil, nil, nil, err
227+
return nil, nil, nil, false, err
229228
}
230229

231230
var (
@@ -248,15 +247,15 @@ func (st *StateTransition) TransitionDb() (ret []byte, requiredGas, usedGas *big
248247
// sufficient balance to make the transfer happen. The first
249248
// balance transfer may never fail.
250249
if vmerr == vm.ErrInsufficientBalance {
251-
return nil, nil, nil, vmerr
250+
return nil, nil, nil, false, vmerr
252251
}
253252
}
254253
requiredGas = new(big.Int).Set(st.gasUsed())
255254

256255
st.refundGas()
257256
st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(st.gasUsed(), st.gasPrice))
258257

259-
return ret, requiredGas, st.gasUsed(), err
258+
return ret, requiredGas, st.gasUsed(), vmerr != nil, err
260259
}
261260

262261
func (st *StateTransition) refundGas() {

‎core/types/gen_receipt_json.go‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎core/types/receipt.go‎

Lines changed: 36 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,16 @@ import (
2828

2929
//go:generate gencodec -type Receipt -field-override receiptMarshaling -out gen_receipt_json.go
3030

31+
const (
32+
receiptStatusSuccessful = byte(0x01)
33+
receiptStatusFailed = byte(0x00)
34+
)
35+
3136
// Receipt represents the results of a transaction.
3237
type Receipt struct {
3338
// Consensus fields
3439
PostState []byte `json:"root"`
40+
Failed bool `json:"failed"`
3541
CumulativeGasUsed *big.Int `json:"cumulativeGasUsed" gencodec:"required"`
3642
Bloom Bloom `json:"logsBloom" gencodec:"required"`
3743
Logs []*Log `json:"logs" gencodec:"required"`
@@ -60,21 +66,26 @@ type homesteadReceiptRLP struct {
6066
// metropolisReceiptRLP contains the receipt's Metropolis consensus fields, used
6167
// during RLP serialization.
6268
type metropolisReceiptRLP struct {
69+
Status byte
6370
CumulativeGasUsed *big.Int
6471
Bloom Bloom
6572
Logs []*Log
6673
}
6774

6875
// NewReceipt creates a barebone transaction receipt, copying the init fields.
69-
func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt {
70-
return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)}
76+
func NewReceipt(root []byte, failed bool, cumulativeGasUsed *big.Int) *Receipt {
77+
return &Receipt{PostState: common.CopyBytes(root), Failed: failed, CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)}
7178
}
7279

7380
// EncodeRLP implements rlp.Encoder, and flattens the consensus fields of a receipt
7481
// into an RLP stream. If no post state is present, metropolis fork is assumed.
7582
func (r *Receipt) EncodeRLP(w io.Writer) error {
7683
if r.PostState == nil {
77-
return rlp.Encode(w, &metropolisReceiptRLP{r.CumulativeGasUsed, r.Bloom, r.Logs})
84+
status := receiptStatusSuccessful
85+
if r.Failed {
86+
status = receiptStatusFailed
87+
}
88+
return rlp.Encode(w, &metropolisReceiptRLP{status, r.CumulativeGasUsed, r.Bloom, r.Logs})
7889
}
7990
return rlp.Encode(w, &homesteadReceiptRLP{r.PostState, r.CumulativeGasUsed, r.Bloom, r.Logs})
8091
}
@@ -87,29 +98,38 @@ func (r *Receipt) DecodeRLP(s *rlp.Stream) error {
8798
if err != nil {
8899
return err
89100
}
90-
list, _, err := rlp.SplitList(raw)
101+
content, _, err := rlp.SplitList(raw)
91102
if err != nil {
92103
return err
93104
}
94-
items, err := rlp.CountValues(list)
105+
kind, cnt, _, err := rlp.Split(content)
95106
if err != nil {
96107
return err
97108
}
98-
// Deserialize based on the number of content items
99-
switch items {
100-
case 3:
101-
// Metropolis receipts have 3 components
109+
// Deserialize based on the first component type.
110+
switch {
111+
case kind == rlp.Byte || (kind == rlp.String && len(cnt) == 0):
112+
// The first component of metropolis receipts is Byte (0x01), or the empty
113+
// string (0x80, decoded as a byte with 0x00 value).
102114
var metro metropolisReceiptRLP
103115
if err := rlp.DecodeBytes(raw, &metro); err != nil {
104116
return err
105117
}
118+
switch metro.Status {
119+
case receiptStatusSuccessful:
120+
r.Failed = false
121+
case receiptStatusFailed:
122+
r.Failed = true
123+
default:
124+
return fmt.Errorf("invalid status byte: 0x%x", metro.Status)
125+
}
106126
r.CumulativeGasUsed = metro.CumulativeGasUsed
107127
r.Bloom = metro.Bloom
108128
r.Logs = metro.Logs
109129
return nil
110130

111-
case 4:
112-
// Homestead receipts have 4 components
131+
case kind == rlp.String:
132+
// The first component of homestead receipts is non-empty String.
113133
var home homesteadReceiptRLP
114134
if err := rlp.DecodeBytes(raw, &home); err != nil {
115135
return err
@@ -121,14 +141,14 @@ func (r *Receipt) DecodeRLP(s *rlp.Stream) error {
121141
return nil
122142

123143
default:
124-
return fmt.Errorf("invalid receipt components: %v", items)
144+
return fmt.Errorf("invalid first receipt component: %v", kind)
125145
}
126146
}
127147

128148
// String implements the Stringer interface.
129149
func (r *Receipt) String() string {
130150
if r.PostState == nil {
131-
return fmt.Sprintf("receipt{cgas=%v bloom=%x logs=%v}", r.CumulativeGasUsed, r.Bloom, r.Logs)
151+
return fmt.Sprintf("receipt{failed=%t cgas=%v bloom=%x logs=%v}", r.Failed, r.CumulativeGasUsed, r.Bloom, r.Logs)
132152
}
133153
return fmt.Sprintf("receipt{med=%x cgas=%v bloom=%x logs=%v}", r.PostState, r.CumulativeGasUsed, r.Bloom, r.Logs)
134154
}
@@ -144,14 +164,15 @@ func (r *ReceiptForStorage) EncodeRLP(w io.Writer) error {
144164
for i, log := range r.Logs {
145165
logs[i] = (*LogForStorage)(log)
146166
}
147-
return rlp.Encode(w, []interface{}{r.PostState, r.CumulativeGasUsed, r.Bloom, r.TxHash, r.ContractAddress, logs, r.GasUsed})
167+
return rlp.Encode(w, []interface{}{r.PostState, r.Failed, r.CumulativeGasUsed, r.Bloom, r.TxHash, r.ContractAddress, logs, r.GasUsed})
148168
}
149169

150170
// DecodeRLP implements rlp.Decoder, and loads both consensus and implementation
151171
// fields of a receipt from an RLP stream.
152172
func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error {
153173
var receipt struct {
154174
PostState []byte
175+
Failed bool
155176
CumulativeGasUsed *big.Int
156177
Bloom Bloom
157178
TxHash common.Hash
@@ -163,7 +184,7 @@ func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error {
163184
return err
164185
}
165186
// Assign the consensus fields
166-
r.PostState, r.CumulativeGasUsed, r.Bloom = receipt.PostState, receipt.CumulativeGasUsed, receipt.Bloom
187+
r.PostState, r.Failed, r.CumulativeGasUsed, r.Bloom = receipt.PostState, receipt.Failed, receipt.CumulativeGasUsed, receipt.Bloom
167188
r.Logs = make([]*Log, len(receipt.Logs))
168189
for i, log := range receipt.Logs {
169190
r.Logs[i] = (*Log)(log)

‎core/vm/evm.go‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
158158
evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value)
159159

160160
// initialise a new contract and set the code that is to be used by the
161-
// E The contract is a scoped evmironment for this execution context
161+
// E The contract is a scoped environment for this execution context
162162
// only.
163163
contract := NewContract(caller, to, value, gas)
164164
contract.SetCallCode(&addr, evm.StateDB.GetCodeHash(addr), evm.StateDB.GetCode(addr))
@@ -351,6 +351,10 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
351351
contract.UseGas(contract.Gas)
352352
}
353353
}
354+
// Assign err if contract code size exceeds the max while the err is still empty.
355+
if maxCodeSizeExceeded && err == nil {
356+
err = errMaxCodeSizeExceeded
357+
}
354358
return ret, contractAddr, contract.Gas, err
355359
}
356360

‎core/vm/instructions.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ var (
3333
errWriteProtection = errors.New("evm: write protection")
3434
errReturnDataOutOfBounds = errors.New("evm: return data out of bounds")
3535
errExecutionReverted = errors.New("evm: execution reverted")
36+
errMaxCodeSizeExceeded = errors.New("evm: max code size exceeded")
3637
)
3738

3839
func opAdd(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
@@ -619,7 +620,6 @@ func opCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Sta
619620
if value.Sign() != 0 {
620621
gas += params.CallStipend
621622
}
622-
623623
ret, returnGas, err := evm.Call(contract, address, args, gas, value)
624624
if err != nil {
625625
stack.push(new(big.Int))

‎eth/api.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,8 @@ func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.
523523

524524
// Run the transaction with tracing enabled.
525525
vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
526-
ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
526+
// TODO utilize failed flag
527+
ret, gas, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
527528
if err != nil {
528529
return nil, fmt.Errorf("tracing failed: %v", err)
529530
}
@@ -570,7 +571,7 @@ func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (co
570571

571572
vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
572573
gp := new(core.GasPool).AddGas(tx.Gas())
573-
_, _, err := core.ApplyMessage(vmenv, msg, gp)
574+
_, _, _, err := core.ApplyMessage(vmenv, msg, gp)
574575
if err != nil {
575576
return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
576577
}

0 commit comments

Comments
 (0)