Skip to content

Commit b9df7ec

Browse files
authored
all: seperate consensus error and evm internal error (#20830)
* all: seperate consensus error and evm internal error There are actually two types of error will be returned when a tranaction/message call is executed: (a) consensus error (b) evm internal error. The former should be converted to a consensus issue, e.g. The sender doesn't enough asset to purchase the gas it specifies. The latter is allowed since evm itself is a blackbox and internal error is allowed to happen. This PR emphasizes the difference by introducing a executionResult structure. The evm error is embedded inside. So if any error returned, it indicates consensus issue happens. And also this PR improve the `EstimateGas` API to return the concrete revert reason if the transaction always fails * all: polish * accounts/abi/bind/backends: add tests * accounts/abi/bind/backends, internal: cleanup error message * all: address comments * core: fix lint * accounts, core, eth, internal: address comments * accounts, internal: resolve revert reason if possible * accounts, internal: address comments
1 parent c60c0c9 commit b9df7ec

33 files changed

Lines changed: 550 additions & 238 deletions

‎accounts/abi/abi.go‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"io"
2525

2626
"github.com/ethereum/go-ethereum/common"
27+
"github.com/ethereum/go-ethereum/crypto"
2728
)
2829

2930
// The ABI holds information about a contract's context and available
@@ -234,3 +235,25 @@ func (abi *ABI) HasFallback() bool {
234235
func (abi *ABI) HasReceive() bool {
235236
return abi.Receive.Type == Receive
236237
}
238+
239+
// revertSelector is a special function selector for revert reason unpacking.
240+
var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
241+
242+
// UnpackRevert resolves the abi-encoded revert reason. According to the solidity
243+
// spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
244+
// the provided revert reason is abi-encoded as if it were a call to a function
245+
// `Error(string)`. So it's a special tool for it.
246+
func UnpackRevert(data []byte) (string, error) {
247+
if len(data) < 4 {
248+
return "", errors.New("invalid data for unpacking")
249+
}
250+
if !bytes.Equal(data[:4], revertSelector) {
251+
return "", errors.New("invalid data for unpacking")
252+
}
253+
var reason string
254+
typ, _ := NewType("string", "", nil)
255+
if err := (Arguments{{Type: typ}}).Unpack(&reason, data[4:]); err != nil {
256+
return "", err
257+
}
258+
return reason, nil
259+
}

‎accounts/abi/abi_test.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package abi
1919
import (
2020
"bytes"
2121
"encoding/hex"
22+
"errors"
2223
"fmt"
2324
"math/big"
2425
"reflect"
@@ -1070,3 +1071,34 @@ func TestUnnamedEventParam(t *testing.T) {
10701071
t.Fatalf("Could not find input")
10711072
}
10721073
}
1074+
1075+
func TestUnpackRevert(t *testing.T) {
1076+
t.Parallel()
1077+
1078+
var cases = []struct {
1079+
input string
1080+
expect string
1081+
expectErr error
1082+
}{
1083+
{"", "", errors.New("invalid data for unpacking")},
1084+
{"08c379a1", "", errors.New("invalid data for unpacking")},
1085+
{"08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000d72657665727420726561736f6e00000000000000000000000000000000000000", "revert reason", nil},
1086+
}
1087+
for index, c := range cases {
1088+
t.Run(fmt.Sprintf("case %d", index), func(t *testing.T) {
1089+
got, err := UnpackRevert(common.Hex2Bytes(c.input))
1090+
if c.expectErr != nil {
1091+
if err == nil {
1092+
t.Fatalf("Expected non-nil error")
1093+
}
1094+
if err.Error() != c.expectErr.Error() {
1095+
t.Fatalf("Expected error mismatch, want %v, got %v", c.expectErr, err)
1096+
}
1097+
return
1098+
}
1099+
if c.expect != got {
1100+
t.Fatalf("Output mismatch, want %v, got %v", c.expect, got)
1101+
}
1102+
})
1103+
}
1104+
}

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

Lines changed: 48 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"time"
2626

2727
"github.com/ethereum/go-ethereum"
28+
"github.com/ethereum/go-ethereum/accounts/abi"
2829
"github.com/ethereum/go-ethereum/accounts/abi/bind"
2930
"github.com/ethereum/go-ethereum/common"
3031
"github.com/ethereum/go-ethereum/common/math"
@@ -49,7 +50,6 @@ var (
4950
errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block")
5051
errBlockDoesNotExist = errors.New("block does not exist in blockchain")
5152
errTransactionDoesNotExist = errors.New("transaction does not exist")
52-
errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction")
5353
)
5454

5555
// SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
@@ -349,8 +349,11 @@ func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallM
349349
if err != nil {
350350
return nil, err
351351
}
352-
rval, _, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
353-
return rval, err
352+
res, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
353+
if err != nil {
354+
return nil, err
355+
}
356+
return res.Return(), nil
354357
}
355358

356359
// PendingCallContract executes a contract call on the pending state.
@@ -359,8 +362,11 @@ func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereu
359362
defer b.mu.Unlock()
360363
defer b.pendingState.RevertToSnapshot(b.pendingState.Snapshot())
361364

362-
rval, _, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
363-
return rval, err
365+
res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
366+
if err != nil {
367+
return nil, err
368+
}
369+
return res.Return(), nil
364370
}
365371

366372
// PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
@@ -398,39 +404,67 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
398404
cap = hi
399405

400406
// Create a helper to check if a gas allowance results in an executable transaction
401-
executable := func(gas uint64) bool {
407+
executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
402408
call.Gas = gas
403409

404410
snapshot := b.pendingState.Snapshot()
405-
_, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
411+
res, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState)
406412
b.pendingState.RevertToSnapshot(snapshot)
407413

408-
if err != nil || failed {
409-
return false
414+
if err != nil {
415+
if err == core.ErrIntrinsicGas {
416+
return true, nil, nil // Special case, raise gas limit
417+
}
418+
return true, nil, err // Bail out
410419
}
411-
return true
420+
return res.Failed(), res, nil
412421
}
413422
// Execute the binary search and hone in on an executable gas limit
414423
for lo+1 < hi {
415424
mid := (hi + lo) / 2
416-
if !executable(mid) {
425+
failed, _, err := executable(mid)
426+
427+
// If the error is not nil(consensus error), it means the provided message
428+
// call or transaction will never be accepted no matter how much gas it is
429+
// assigned. Return the error directly, don't struggle any more
430+
if err != nil {
431+
return 0, err
432+
}
433+
if failed {
417434
lo = mid
418435
} else {
419436
hi = mid
420437
}
421438
}
422439
// Reject the transaction as invalid if it still fails at the highest allowance
423440
if hi == cap {
424-
if !executable(hi) {
425-
return 0, errGasEstimationFailed
441+
failed, result, err := executable(hi)
442+
if err != nil {
443+
return 0, err
444+
}
445+
if failed {
446+
if result != nil && result.Err != vm.ErrOutOfGas {
447+
errMsg := fmt.Sprintf("always failing transaction (%v)", result.Err)
448+
if len(result.Revert()) > 0 {
449+
ret, err := abi.UnpackRevert(result.Revert())
450+
if err != nil {
451+
errMsg += fmt.Sprintf(" (%#x)", result.Revert())
452+
} else {
453+
errMsg += fmt.Sprintf(" (%s)", ret)
454+
}
455+
}
456+
return 0, errors.New(errMsg)
457+
}
458+
// Otherwise, the specified gas cap is too low
459+
return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
426460
}
427461
}
428462
return hi, nil
429463
}
430464

431465
// callContract implements common code between normal and pending contract calls.
432466
// state is modified during execution, make sure to copy it if necessary.
433-
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
467+
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) (*core.ExecutionResult, error) {
434468
// Ensure message is initialized properly.
435469
if call.GasPrice == nil {
436470
call.GasPrice = big.NewInt(1)

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

Lines changed: 104 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package backends
1919
import (
2020
"bytes"
2121
"context"
22+
"errors"
2223
"math/big"
2324
"strings"
2425
"testing"
@@ -356,25 +357,112 @@ func TestSimulatedBackend_TransactionByHash(t *testing.T) {
356357
}
357358

358359
func TestSimulatedBackend_EstimateGas(t *testing.T) {
359-
sim := NewSimulatedBackend(
360-
core.GenesisAlloc{}, 10000000,
361-
)
360+
/*
361+
pragma solidity ^0.6.4;
362+
contract GasEstimation {
363+
function PureRevert() public { revert(); }
364+
function Revert() public { revert("revert reason");}
365+
function OOG() public { for (uint i = 0; ; i++) {}}
366+
function Assert() public { assert(false);}
367+
function Valid() public {}
368+
}*/
369+
const contractAbi = "[{\"inputs\":[],\"name\":\"Assert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"OOG\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PureRevert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Revert\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"Valid\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
370+
const contractBin = "0x60806040523480156100115760006000fd5b50610017565b61016e806100266000396000f3fe60806040523480156100115760006000fd5b506004361061005c5760003560e01c806350f6fe3414610062578063aa8b1d301461006c578063b9b046f914610076578063d8b9839114610080578063e09fface1461008a5761005c565b60006000fd5b61006a610094565b005b6100746100ad565b005b61007e6100b5565b005b6100886100c2565b005b610092610135565b005b6000600090505b5b808060010191505061009b565b505b565b60006000fd5b565b600015156100bf57fe5b5b565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f72657665727420726561736f6e0000000000000000000000000000000000000081526020015060200191505060405180910390fd5b565b5b56fea2646970667358221220345bbcbb1a5ecf22b53a78eaebf95f8ee0eceff6d10d4b9643495084d2ec934a64736f6c63430006040033"
371+
372+
key, _ := crypto.GenerateKey()
373+
addr := crypto.PubkeyToAddress(key.PublicKey)
374+
opts := bind.NewKeyedTransactor(key)
375+
376+
sim := NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(params.Ether)}}, 10000000)
362377
defer sim.Close()
363-
bgCtx := context.Background()
364-
testAddr := crypto.PubkeyToAddress(testKey.PublicKey)
365378

366-
gas, err := sim.EstimateGas(bgCtx, ethereum.CallMsg{
367-
From: testAddr,
368-
To: &testAddr,
369-
Value: big.NewInt(1000),
370-
Data: []byte{},
371-
})
372-
if err != nil {
373-
t.Errorf("could not estimate gas: %v", err)
374-
}
379+
parsed, _ := abi.JSON(strings.NewReader(contractAbi))
380+
contractAddr, _, _, _ := bind.DeployContract(opts, parsed, common.FromHex(contractBin), sim)
381+
sim.Commit()
375382

376-
if gas != params.TxGas {
377-
t.Errorf("expected 21000 gas cost for a transaction got %v", gas)
383+
var cases = []struct {
384+
name string
385+
message ethereum.CallMsg
386+
expect uint64
387+
expectError error
388+
}{
389+
{"plain transfer(valid)", ethereum.CallMsg{
390+
From: addr,
391+
To: &addr,
392+
Gas: 0,
393+
GasPrice: big.NewInt(0),
394+
Value: big.NewInt(1),
395+
Data: nil,
396+
}, params.TxGas, nil},
397+
398+
{"plain transfer(invalid)", ethereum.CallMsg{
399+
From: addr,
400+
To: &contractAddr,
401+
Gas: 0,
402+
GasPrice: big.NewInt(0),
403+
Value: big.NewInt(1),
404+
Data: nil,
405+
}, 0, errors.New("always failing transaction (execution reverted)")},
406+
407+
{"Revert", ethereum.CallMsg{
408+
From: addr,
409+
To: &contractAddr,
410+
Gas: 0,
411+
GasPrice: big.NewInt(0),
412+
Value: nil,
413+
Data: common.Hex2Bytes("d8b98391"),
414+
}, 0, errors.New("always failing transaction (execution reverted) (revert reason)")},
415+
416+
{"PureRevert", ethereum.CallMsg{
417+
From: addr,
418+
To: &contractAddr,
419+
Gas: 0,
420+
GasPrice: big.NewInt(0),
421+
Value: nil,
422+
Data: common.Hex2Bytes("aa8b1d30"),
423+
}, 0, errors.New("always failing transaction (execution reverted)")},
424+
425+
{"OOG", ethereum.CallMsg{
426+
From: addr,
427+
To: &contractAddr,
428+
Gas: 100000,
429+
GasPrice: big.NewInt(0),
430+
Value: nil,
431+
Data: common.Hex2Bytes("50f6fe34"),
432+
}, 0, errors.New("gas required exceeds allowance (100000)")},
433+
434+
{"Assert", ethereum.CallMsg{
435+
From: addr,
436+
To: &contractAddr,
437+
Gas: 100000,
438+
GasPrice: big.NewInt(0),
439+
Value: nil,
440+
Data: common.Hex2Bytes("b9b046f9"),
441+
}, 0, errors.New("always failing transaction (invalid opcode: opcode 0xfe not defined)")},
442+
443+
{"Valid", ethereum.CallMsg{
444+
From: addr,
445+
To: &contractAddr,
446+
Gas: 100000,
447+
GasPrice: big.NewInt(0),
448+
Value: nil,
449+
Data: common.Hex2Bytes("e09fface"),
450+
}, 21275, nil},
451+
}
452+
for _, c := range cases {
453+
got, err := sim.EstimateGas(context.Background(), c.message)
454+
if c.expectError != nil {
455+
if err == nil {
456+
t.Fatalf("Expect error, got nil")
457+
}
458+
if c.expectError.Error() != err.Error() {
459+
t.Fatalf("Expect error, want %v, got %v", c.expectError, err)
460+
}
461+
continue
462+
}
463+
if got != c.expect {
464+
t.Fatalf("Gas estimation mismatch, want %d, got %d", c.expect, got)
465+
}
378466
}
379467
}
380468

‎cmd/geth/retesteth.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -678,7 +678,7 @@ func (api *RetestethAPI) AccountRange(ctx context.Context,
678678
context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
679679
// Not yet the searched for transaction, execute on top of the current state
680680
vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
681-
if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
681+
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
682682
return AccountRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
683683
}
684684
// Ensure any modifications are committed to the state
@@ -788,7 +788,7 @@ func (api *RetestethAPI) StorageRangeAt(ctx context.Context,
788788
context := core.NewEVMContext(msg, block.Header(), api.blockchain, nil)
789789
// Not yet the searched for transaction, execute on top of the current state
790790
vmenv := vm.NewEVM(context, statedb, api.blockchain.Config(), vm.Config{})
791-
if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
791+
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
792792
return StorageRangeResult{}, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
793793
}
794794
// Ensure any modifications are committed to the state

0 commit comments

Comments
 (0)