Skip to content

Commit 1e28e0b

Browse files
authored
eth/gasestimator, internal/ethapi: move gas estimator out of rpc (#28600)
1 parent 333dd95 commit 1e28e0b

File tree

3 files changed

+222
-129
lines changed

3 files changed

+222
-129
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/ethereum/go-ethereum/common"
27+
"github.com/ethereum/go-ethereum/core"
28+
"github.com/ethereum/go-ethereum/core/state"
29+
"github.com/ethereum/go-ethereum/core/types"
30+
"github.com/ethereum/go-ethereum/core/vm"
31+
"github.com/ethereum/go-ethereum/log"
32+
"github.com/ethereum/go-ethereum/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, 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, 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))
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: 24 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import (
4040
"github.com/ethereum/go-ethereum/core/types"
4141
"github.com/ethereum/go-ethereum/core/vm"
4242
"github.com/ethereum/go-ethereum/crypto"
43+
"github.com/ethereum/go-ethereum/eth/gasestimator"
4344
"github.com/ethereum/go-ethereum/eth/tracers/logger"
4445
"github.com/ethereum/go-ethereum/log"
4546
"github.com/ethereum/go-ethereum/p2p"
@@ -1120,15 +1121,16 @@ func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash
11201121
return doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap)
11211122
}
11221123

1123-
func newRevertError(result *core.ExecutionResult) *revertError {
1124-
reason, errUnpack := abi.UnpackRevert(result.Revert())
1125-
err := errors.New("execution reverted")
1124+
func newRevertError(revert []byte) *revertError {
1125+
err := vm.ErrExecutionReverted
1126+
1127+
reason, errUnpack := abi.UnpackRevert(revert)
11261128
if errUnpack == nil {
1127-
err = fmt.Errorf("execution reverted: %v", reason)
1129+
err = fmt.Errorf("%w: %v", vm.ErrExecutionReverted, reason)
11281130
}
11291131
return &revertError{
11301132
error: err,
1131-
reason: hexutil.Encode(result.Revert()),
1133+
reason: hexutil.Encode(revert),
11321134
}
11331135
}
11341136

@@ -1167,147 +1169,44 @@ func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrO
11671169
}
11681170
// If the result contains a revert reason, try to unpack and return it.
11691171
if len(result.Revert()) > 0 {
1170-
return nil, newRevertError(result)
1172+
return nil, newRevertError(result.Revert())
11711173
}
11721174
return result.Return(), result.Err
11731175
}
11741176

1175-
// executeEstimate is a helper that executes the transaction under a given gas limit and returns
1176-
// true if the transaction fails for a reason that might be related to not enough gas. A non-nil
1177-
// error means execution failed due to reasons unrelated to the gas limit.
1178-
func executeEstimate(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, gasCap uint64, gasLimit uint64) (bool, *core.ExecutionResult, error) {
1179-
args.Gas = (*hexutil.Uint64)(&gasLimit)
1180-
result, err := doCall(ctx, b, args, state, header, nil, nil, 0, gasCap)
1181-
if err != nil {
1182-
if errors.Is(err, core.ErrIntrinsicGas) {
1183-
return true, nil, nil // Special case, raise gas limit
1184-
}
1185-
return true, nil, err // Bail out
1186-
}
1187-
return result.Failed(), result, nil
1188-
}
1189-
11901177
// DoEstimateGas returns the lowest possible gas limit that allows the transaction to run
11911178
// successfully at block `blockNrOrHash`. It returns error if the transaction would revert, or if
11921179
// there are unexpected failures. The gas limit is capped by both `args.Gas` (if non-nil &
11931180
// non-zero) and `gasCap` (if non-zero).
11941181
func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, gasCap uint64) (hexutil.Uint64, error) {
1195-
// Binary search the gas limit, as it may need to be higher than the amount used
1196-
var (
1197-
lo uint64 // lowest-known gas limit where tx execution fails
1198-
hi uint64 // lowest-known gas limit where tx execution succeeds
1199-
)
1200-
// Use zero address if sender unspecified.
1201-
if args.From == nil {
1202-
args.From = new(common.Address)
1203-
}
1204-
// Determine the highest gas limit can be used during the estimation.
1205-
if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
1206-
hi = uint64(*args.Gas)
1207-
} else {
1208-
// Retrieve the block to act as the gas ceiling
1209-
block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
1210-
if err != nil {
1211-
return 0, err
1212-
}
1213-
if block == nil {
1214-
return 0, errors.New("block not found")
1215-
}
1216-
hi = block.GasLimit()
1217-
}
1218-
// Normalize the max fee per gas the call is willing to spend.
1219-
var feeCap *big.Int
1220-
if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
1221-
return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
1222-
} else if args.GasPrice != nil {
1223-
feeCap = args.GasPrice.ToInt()
1224-
} else if args.MaxFeePerGas != nil {
1225-
feeCap = args.MaxFeePerGas.ToInt()
1226-
} else {
1227-
feeCap = common.Big0
1228-
}
1229-
1182+
// Retrieve the base state and mutate it with any overrides
12301183
state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
12311184
if state == nil || err != nil {
12321185
return 0, err
12331186
}
1234-
if err := overrides.Apply(state); err != nil {
1187+
if err = overrides.Apply(state); err != nil {
12351188
return 0, err
12361189
}
1237-
1238-
// Recap the highest gas limit with account's available balance.
1239-
if feeCap.BitLen() != 0 {
1240-
balance := state.GetBalance(*args.From) // from can't be nil
1241-
available := new(big.Int).Set(balance)
1242-
if args.Value != nil {
1243-
if args.Value.ToInt().Cmp(available) >= 0 {
1244-
return 0, core.ErrInsufficientFundsForTransfer
1245-
}
1246-
available.Sub(available, args.Value.ToInt())
1247-
}
1248-
allowance := new(big.Int).Div(available, feeCap)
1249-
1250-
// If the allowance is larger than maximum uint64, skip checking
1251-
if allowance.IsUint64() && hi > allowance.Uint64() {
1252-
transfer := args.Value
1253-
if transfer == nil {
1254-
transfer = new(hexutil.Big)
1255-
}
1256-
log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
1257-
"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
1258-
hi = allowance.Uint64()
1259-
}
1190+
// Construct the gas estimator option from the user input
1191+
opts := &gasestimator.Options{
1192+
Config: b.ChainConfig(),
1193+
Chain: NewChainContext(ctx, b),
1194+
Header: header,
1195+
State: state,
12601196
}
1261-
// Recap the highest gas allowance with specified gascap.
1262-
if gasCap != 0 && hi > gasCap {
1263-
log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
1264-
hi = gasCap
1265-
}
1266-
1267-
// We first execute the transaction at the highest allowable gas limit, since if this fails we
1268-
// can return error immediately.
1269-
failed, result, err := executeEstimate(ctx, b, args, state.Copy(), header, gasCap, hi)
1197+
// Run the gas estimation andwrap any revertals into a custom return
1198+
call, err := args.ToMessage(gasCap, header.BaseFee)
12701199
if err != nil {
12711200
return 0, err
12721201
}
1273-
if failed {
1274-
if result != nil && !errors.Is(result.Err, vm.ErrOutOfGas) {
1275-
if len(result.Revert()) > 0 {
1276-
return 0, newRevertError(result)
1277-
}
1278-
return 0, result.Err
1279-
}
1280-
return 0, fmt.Errorf("gas required exceeds allowance (%d)", hi)
1281-
}
1282-
// For almost any transaction, the gas consumed by the unconstrained execution above
1283-
// lower-bounds the gas limit required for it to succeed. One exception is those txs that
1284-
// explicitly check gas remaining in order to successfully execute within a given limit, but we
1285-
// probably don't want to return a lowest possible gas limit for these cases anyway.
1286-
lo = result.UsedGas - 1
1287-
1288-
// Binary search for the smallest gas limit that allows the tx to execute successfully.
1289-
for lo+1 < hi {
1290-
mid := (hi + lo) / 2
1291-
if mid > lo*2 {
1292-
// Most txs don't need much higher gas limit than their gas used, and most txs don't
1293-
// require near the full block limit of gas, so the selection of where to bisect the
1294-
// range here is skewed to favor the low side.
1295-
mid = lo * 2
1296-
}
1297-
failed, _, err = executeEstimate(ctx, b, args, state.Copy(), header, gasCap, mid)
1298-
if err != nil {
1299-
// This should not happen under normal conditions since if we make it this far the
1300-
// transaction had run without error at least once before.
1301-
log.Error("execution error in estimate gas", "err", err)
1302-
return 0, err
1303-
}
1304-
if failed {
1305-
lo = mid
1306-
} else {
1307-
hi = mid
1202+
estimate, revert, err := gasestimator.Estimate(ctx, call, opts, gasCap)
1203+
if err != nil {
1204+
if len(revert) > 0 {
1205+
return 0, newRevertError(revert)
13081206
}
1207+
return 0, err
13091208
}
1310-
return hexutil.Uint64(hi), nil
1209+
return hexutil.Uint64(estimate), nil
13111210
}
13121211

13131212
// EstimateGas returns the lowest possible gas limit that allows the transaction to run

0 commit comments

Comments
 (0)