Skip to content

Commit dce7b37

Browse files
authored
eth/gasestimator, internal/ethapi: move gas estimator out of rpc ethereum#28600 (#1589)
1 parent afdb029 commit dce7b37

File tree

3 files changed

+236
-98
lines changed

3 files changed

+236
-98
lines changed

eth/gasestimator/gasestimator.go

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
// Copyright 2023 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 gasestimator
18+
19+
import (
20+
"context"
21+
"errors"
22+
"fmt"
23+
"math"
24+
"math/big"
25+
26+
"github.com/XinFinOrg/XDPoSChain/common"
27+
"github.com/XinFinOrg/XDPoSChain/core"
28+
"github.com/XinFinOrg/XDPoSChain/core/state"
29+
"github.com/XinFinOrg/XDPoSChain/core/types"
30+
"github.com/XinFinOrg/XDPoSChain/core/vm"
31+
"github.com/XinFinOrg/XDPoSChain/log"
32+
"github.com/XinFinOrg/XDPoSChain/params"
33+
)
34+
35+
// Options are the contextual parameters to execute the requested call.
36+
//
37+
// Whilst it would be possible to pass a blockchain object that aggregates all
38+
// these together, it would be excessively hard to test. Splitting the parts out
39+
// allows testing without needing a proper live chain.
40+
type Options struct {
41+
Config *params.ChainConfig // Chain configuration for hard fork selection
42+
Chain core.ChainContext // Chain context to access past block hashes
43+
Header *types.Header // Header defining the block context to execute in
44+
State *state.StateDB // Pre-state on top of which to estimate the gas
45+
}
46+
47+
// Estimate returns the lowest possible gas limit that allows the transaction to
48+
// run successfully with the provided context optons. It returns an error if the
49+
// transaction would always revert, or if there are unexpected failures.
50+
func Estimate(ctx context.Context, call *core.Message, opts *Options, gasCap uint64) (uint64, []byte, error) {
51+
// Binary search the gas limit, as it may need to be higher than the amount used
52+
var (
53+
lo uint64 // lowest-known gas limit where tx execution fails
54+
hi uint64 // lowest-known gas limit where tx execution succeeds
55+
)
56+
// Determine the highest gas limit can be used during the estimation.
57+
hi = opts.Header.GasLimit
58+
if call.GasLimit >= params.TxGas {
59+
hi = call.GasLimit
60+
}
61+
// Normalize the max fee per gas the call is willing to spend.
62+
var feeCap *big.Int
63+
if call.GasFeeCap != nil {
64+
feeCap = call.GasFeeCap
65+
} else if call.GasPrice != nil {
66+
feeCap = call.GasPrice
67+
} else {
68+
feeCap = common.Big0
69+
}
70+
// Recap the highest gas limit with account's available balance.
71+
if feeCap.BitLen() != 0 {
72+
balance := opts.State.GetBalance(call.From)
73+
74+
available := new(big.Int).Set(balance)
75+
if call.Value != nil {
76+
if call.Value.Cmp(available) >= 0 {
77+
return 0, nil, core.ErrInsufficientFundsForTransfer
78+
}
79+
available.Sub(available, call.Value)
80+
}
81+
allowance := new(big.Int).Div(available, feeCap)
82+
83+
// If the allowance is larger than maximum uint64, skip checking
84+
if allowance.IsUint64() && hi > allowance.Uint64() {
85+
transfer := call.Value
86+
if transfer == nil {
87+
transfer = new(big.Int)
88+
}
89+
log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
90+
"sent", transfer, "maxFeePerGas", feeCap, "fundable", allowance)
91+
hi = allowance.Uint64()
92+
}
93+
}
94+
// Recap the highest gas allowance with specified gascap.
95+
if gasCap != 0 && hi > gasCap {
96+
log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
97+
hi = gasCap
98+
}
99+
// We first execute the transaction at the highest allowable gas limit, since if this fails we
100+
// can return error immediately.
101+
failed, result, err := execute(ctx, call, opts, hi)
102+
if err != nil {
103+
return 0, nil, err
104+
}
105+
if failed {
106+
if result != nil && !errors.Is(result.Err, vm.ErrOutOfGas) {
107+
return 0, result.Revert(), result.Err
108+
}
109+
return 0, nil, fmt.Errorf("gas required exceeds allowance (%d)", hi)
110+
}
111+
// For almost any transaction, the gas consumed by the unconstrained execution
112+
// above lower-bounds the gas limit required for it to succeed. One exception
113+
// is those that explicitly check gas remaining in order to execute within a
114+
// given limit, but we probably don't want to return the lowest possible gas
115+
// limit for these cases anyway.
116+
lo = result.UsedGas - 1
117+
118+
// Binary search for the smallest gas limit that allows the tx to execute successfully.
119+
for lo+1 < hi {
120+
mid := (hi + lo) / 2
121+
if mid > lo*2 {
122+
// Most txs don't need much higher gas limit than their gas used, and most txs don't
123+
// require near the full block limit of gas, so the selection of where to bisect the
124+
// range here is skewed to favor the low side.
125+
mid = lo * 2
126+
}
127+
failed, _, err = execute(ctx, call, opts, mid)
128+
if err != nil {
129+
// This should not happen under normal conditions since if we make it this far the
130+
// transaction had run without error at least once before.
131+
log.Error("Execution error in estimate gas", "err", err)
132+
return 0, nil, err
133+
}
134+
if failed {
135+
lo = mid
136+
} else {
137+
hi = mid
138+
}
139+
}
140+
return hi, nil, nil
141+
}
142+
143+
// execute is a helper that executes the transaction under a given gas limit and
144+
// returns true if the transaction fails for a reason that might be related to
145+
// not enough gas. A non-nil error means execution failed due to reasons unrelated
146+
// to the gas limit.
147+
func execute(ctx context.Context, call *core.Message, opts *Options, gasLimit uint64) (bool, *core.ExecutionResult, error) {
148+
// Configure the call for this specific execution (and revert the change after)
149+
defer func(gas uint64) { call.GasLimit = gas }(call.GasLimit)
150+
call.GasLimit = gasLimit
151+
152+
// Execute the call and separate execution faults caused by a lack of gas or
153+
// other non-fixable conditions
154+
result, err := run(ctx, call, opts)
155+
if err != nil {
156+
if errors.Is(err, vm.ErrOutOfGas) || errors.Is(err, core.ErrIntrinsicGas) {
157+
return true, nil, nil // Special case, raise gas limit
158+
}
159+
return true, nil, err // Bail out
160+
}
161+
return result.Failed(), result, nil
162+
}
163+
164+
// run assembles the EVM as defined by the consensus rules and runs the requested
165+
// call invocation.
166+
func run(ctx context.Context, call *core.Message, opts *Options) (*core.ExecutionResult, error) {
167+
// Assemble the call and the call context
168+
var (
169+
msgContext = core.NewEVMTxContext(call)
170+
evmContext = core.NewEVMBlockContext(opts.Header, opts.Chain, nil)
171+
172+
dirtyState = opts.State.Copy()
173+
evm = vm.NewEVM(evmContext, msgContext, dirtyState, nil, opts.Config, vm.Config{NoBaseFee: true})
174+
)
175+
// Monitor the outer context and interrupt the EVM upon cancellation. To avoid
176+
// a dangling goroutine until the outer estimation finishes, create an internal
177+
// context for the lifetime of this method call.
178+
ctx, cancel := context.WithCancel(ctx)
179+
defer cancel()
180+
181+
go func() {
182+
<-ctx.Done()
183+
evm.Cancel()
184+
}()
185+
// Execute the call, returning a wrapped error or the result
186+
result, err := core.ApplyMessage(evm, call, new(core.GasPool).AddGas(math.MaxUint64), common.Address{})
187+
if vmerr := dirtyState.Error(); vmerr != nil {
188+
return nil, vmerr
189+
}
190+
if err != nil {
191+
return result, fmt.Errorf("failed with %d gas: %w", call.GasLimit, err)
192+
}
193+
return result, nil
194+
}

internal/ethapi/api.go

Lines changed: 42 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import (
4747
"github.com/XinFinOrg/XDPoSChain/core/types"
4848
"github.com/XinFinOrg/XDPoSChain/core/vm"
4949
"github.com/XinFinOrg/XDPoSChain/crypto"
50+
"github.com/XinFinOrg/XDPoSChain/eth/gasestimator"
5051
"github.com/XinFinOrg/XDPoSChain/eth/tracers/logger"
5152
"github.com/XinFinOrg/XDPoSChain/log"
5253
"github.com/XinFinOrg/XDPoSChain/p2p"
@@ -1203,15 +1204,16 @@ func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.S
12031204
return result, err
12041205
}
12051206

1206-
func newRevertError(result *core.ExecutionResult) *revertError {
1207-
reason, errUnpack := abi.UnpackRevert(result.Revert())
1208-
err := errors.New("execution reverted")
1207+
func newRevertError(revert []byte) *revertError {
1208+
err := vm.ErrExecutionReverted
1209+
1210+
reason, errUnpack := abi.UnpackRevert(revert)
12091211
if errUnpack == nil {
1210-
err = fmt.Errorf("execution reverted: %v", reason)
1212+
err = fmt.Errorf("%w: %v", vm.ErrExecutionReverted, reason)
12111213
}
12121214
return &revertError{
12131215
error: err,
1214-
reason: hexutil.Encode(result.Revert()),
1216+
reason: hexutil.Encode(revert),
12151217
}
12161218
}
12171219

@@ -1250,116 +1252,50 @@ func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrO
12501252
}
12511253
// If the result contains a revert reason, try to unpack and return it.
12521254
if len(result.Revert()) > 0 {
1253-
return nil, newRevertError(result)
1255+
return nil, newRevertError(result.Revert())
12541256
}
12551257
return result.Return(), result.Err
12561258
}
12571259

1260+
// DoEstimateGas returns the lowest possible gas limit that allows the transaction to run
1261+
// successfully at block `blockNrOrHash`. It returns error if the transaction would revert, or if
1262+
// there are unexpected failures. The gas limit is capped by both `args.Gas` (if non-nil &
1263+
// non-zero) and `gasCap` (if non-zero).
12581264
func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, gasCap uint64) (hexutil.Uint64, error) {
12591265
// Retrieve the base state and mutate it with any overrides
1260-
state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
1266+
state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
12611267
if state == nil || err != nil {
12621268
return 0, err
12631269
}
12641270
if err = overrides.Apply(state); err != nil {
12651271
return 0, err
12661272
}
1267-
// Binary search the gas requirement, as it may be higher than the amount used
1268-
var (
1269-
lo uint64 = params.TxGas - 1
1270-
hi uint64
1271-
cap uint64
1272-
)
1273-
// Use zero address if sender unspecified.
1274-
if args.From == nil {
1275-
args.From = new(common.Address)
1276-
}
1277-
// Determine the highest gas limit can be used during the estimation.
1278-
if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
1279-
hi = uint64(*args.Gas)
1280-
} else {
1281-
// Retrieve the current pending block to act as the gas ceiling
1282-
block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
1283-
if err != nil {
1284-
return 0, err
1285-
}
1286-
if block == nil {
1287-
return 0, errors.New("block not found")
1288-
}
1289-
hi = block.GasLimit()
1290-
}
1291-
// Recap the highest gas allowance with specified gascap.
1292-
if gasCap != 0 && hi > gasCap {
1293-
log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
1294-
hi = gasCap
1273+
// Construct the gas estimator option from the user input
1274+
opts := &gasestimator.Options{
1275+
Config: b.ChainConfig(),
1276+
Chain: NewChainContext(ctx, b),
1277+
Header: header,
1278+
State: state,
12951279
}
1296-
cap = hi
1297-
1298-
// Create a helper to check if a gas allowance results in an executable transaction
1299-
executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
1300-
args.Gas = (*hexutil.Uint64)(&gas)
1301-
1302-
result, err := DoCall(ctx, b, args, blockNrOrHash, nil, nil, 0, gasCap)
1303-
if err != nil {
1304-
if errors.Is(err, vm.ErrOutOfGas) || errors.Is(err, core.ErrIntrinsicGas) {
1305-
return true, nil, nil // Special case, raise gas limit
1306-
}
1307-
return true, nil, err // Bail out
1308-
}
1309-
return result.Failed(), result, nil
1310-
}
1311-
1312-
// If the transaction is a plain value transfer, short circuit estimation and
1313-
// directly try 21000. Returning 21000 without any execution is dangerous as
1314-
// some tx field combos might bump the price up even for plain transfers (e.g.
1315-
// unused access list items). Ever so slightly wasteful, but safer overall.
1316-
if args.Data == nil || len(*args.Data) == 0 {
1317-
if args.To != nil && state.GetCodeSize(*args.To) == 0 {
1318-
ok, _, err := executable(params.TxGas)
1319-
if ok && err == nil {
1320-
return hexutil.Uint64(params.TxGas), nil
1321-
}
1322-
}
1280+
// Set any required transaction default, but make sure the gas cap itself is not messed with
1281+
// if it was not specified in the original argument list.
1282+
if args.Gas == nil {
1283+
args.Gas = new(hexutil.Uint64)
13231284
}
1324-
1325-
// Execute the binary search and hone in on an executable gas limit
1326-
for lo+1 < hi {
1327-
mid := (hi + lo) / 2
1328-
failed, _, err := executable(mid)
1329-
1330-
// If the error is not nil(consensus error), it means the provided message
1331-
// call or transaction will never be accepted no matter how much gas it is
1332-
// assigned. Return the error directly, don't struggle any more.
1333-
if err != nil {
1334-
return 0, err
1335-
}
1336-
1337-
if failed {
1338-
lo = mid
1339-
} else {
1340-
hi = mid
1341-
}
1285+
if err := args.CallDefaults(gasCap, header.BaseFee, b.ChainConfig().ChainID); err != nil {
1286+
return 0, err
13421287
}
1288+
call := args.ToMessage(b, header.BaseFee)
13431289

1344-
// Reject the transaction as invalid if it still fails at the highest allowance
1345-
if hi == cap {
1346-
failed, result, err := executable(hi)
1347-
if err != nil {
1348-
return 0, err
1349-
}
1350-
1351-
if failed {
1352-
if result != nil && !errors.Is(result.Err, vm.ErrOutOfGas) {
1353-
if len(result.Revert()) > 0 {
1354-
return 0, newRevertError(result)
1355-
}
1356-
return 0, result.Err
1357-
}
1358-
// Otherwise, the specified gas cap is too low
1359-
return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
1290+
// Run the gas estimation andwrap any revertals into a custom return
1291+
estimate, revert, err := gasestimator.Estimate(ctx, call, opts, gasCap)
1292+
if err != nil {
1293+
if len(revert) > 0 {
1294+
return 0, newRevertError(revert)
13601295
}
1296+
return 0, err
13611297
}
1362-
return hexutil.Uint64(hi), nil
1298+
return hexutil.Uint64(estimate), nil
13631299
}
13641300

13651301
// EstimateGas returns an estimate of the amount of gas needed to execute the
@@ -1778,6 +1714,15 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH
17781714
if err := args.setDefaults(ctx, b, true); err != nil {
17791715
return nil, 0, nil, err
17801716
}
1717+
if args.Nonce == nil {
1718+
nonce := hexutil.Uint64(db.GetNonce(args.from()))
1719+
args.Nonce = &nonce
1720+
}
1721+
blockCtx := core.NewEVMBlockContext(header, NewChainContext(ctx, b), nil)
1722+
if err = args.CallDefaults(b.RPCGasCap(), blockCtx.BaseFee, b.ChainConfig().ChainID); err != nil {
1723+
return nil, 0, nil, err
1724+
}
1725+
17811726
var to common.Address
17821727
if args.To != nil {
17831728
to = *args.To

internal/ethapi/transaction_args.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,6 @@ func (args *TransactionArgs) ToMessage(b AccountBackend, baseFee *big.Int) *core
322322
}
323323
}
324324
}
325-
326325
return &core.Message{
327326
From: addr,
328327
To: args.To,

0 commit comments

Comments
 (0)