Skip to content

Commit

Permalink
optimize & clean up EstimateGas
Browse files Browse the repository at this point in the history
  • Loading branch information
roberto-bayardo committed Jul 12, 2023
1 parent 80b7bfe commit 9b8e908
Showing 1 changed file with 71 additions and 78 deletions.
149 changes: 71 additions & 78 deletions internal/ethapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1024,9 +1024,10 @@ func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *types.H
return header
}

func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
// doCall executes the given transaction and returns its execution result along with its gas used
func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.StateDB, header *types.Header, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, uint64, error) {
if err := overrides.Apply(state); err != nil {
return nil, err
return nil, 0, err
}
// Setup context so it may be cancelled the call has completed
// or, in case of unmetered gas, setup a context with a timeout.
Expand All @@ -1043,7 +1044,7 @@ func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.S
// Get a new instance of the EVM.
msg, err := args.ToMessage(globalGasCap, header.BaseFee)
if err != nil {
return nil, err
return nil, 0, err
}
blockCtx := core.NewEVMBlockContext(header, NewChainContext(ctx, b), nil)
if blockOverrides != nil {
Expand All @@ -1062,17 +1063,17 @@ func doCall(ctx context.Context, b Backend, args TransactionArgs, state *state.S
gp := new(core.GasPool).AddGas(math.MaxUint64)
result, err := core.ApplyMessage(evm, msg, gp)
if err := vmError(); err != nil {
return nil, err
return nil, 0, err
}

// If the timer caused an abort, return an appropriate error message
if evm.Cancelled() {
return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
return nil, 0, fmt.Errorf("execution aborted (timeout = %v)", timeout)
}
if err != nil {
return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.GasLimit)
return result, 0, fmt.Errorf("err: %w (supplied gas %d)", err, msg.GasLimit)
}
return result, nil
return result, math.MaxUint64 - gp.Gas(), nil
}

func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, blockOverrides *BlockOverrides, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
Expand All @@ -1083,37 +1084,16 @@ func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash
return nil, err
}

return doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap)
er, _, err := doCall(ctx, b, args, state, header, overrides, blockOverrides, timeout, globalGasCap)
return er, err
}

func newRevertError(result *core.ExecutionResult) *revertError {
func newRevertError(result *core.ExecutionResult) error {
reason, errUnpack := abi.UnpackRevert(result.Revert())
err := errors.New("execution reverted")
if errUnpack == nil {
err = fmt.Errorf("execution reverted: %v", reason)
}
return &revertError{
error: err,
reason: hexutil.Encode(result.Revert()),
if errUnpack != nil {
return errors.New("execution reverted")
}
}

// revertError is an API error that encompasses an EVM revertal with JSON error
// code and a binary data blob.
type revertError struct {
error
reason string // revert reason hex encoded
}

// ErrorCode returns the JSON error code for a revertal.
// See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
func (e *revertError) ErrorCode() int {
return 3
}

// ErrorData returns the hex encoded revert reason.
func (e *revertError) ErrorData() interface{} {
return e.reason
return fmt.Errorf("execution reverted: %v", reason)
}

// Call executes the given transaction on the state for the given block number.
Expand All @@ -1134,12 +1114,16 @@ func (s *BlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrO
return result.Return(), result.Err
}

// DoEstimateGas returns the lowest possible gas limit that allows the transaction to run
// successfully at block `blockNrOrHash`. It returns error if the transaction would revert, or if
// there are unexpected failures. The gas limit is capped by both `args.Gas` (if non-nil &
// non-zero) and `gasCap` (if non-zero).
func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
// Binary search the gas requirement, as it may be higher than the amount used
// Binary search the gas limit, as it may need to be higher than the amount used
var (
lo uint64 = params.TxGas - 1
hi uint64
cap uint64
// `lo` and `hi` will define the current range of our binary search
lo uint64 // lowest-known gas limit where tx execution fails
hi uint64 // lowest-known gas limit where tx execution succeeds
)
// Use zero address if sender unspecified.
if args.From == nil {
Expand Down Expand Up @@ -1170,13 +1154,15 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
} else {
feeCap = common.Big0
}

st, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if st == nil || err != nil {
return 0, err
}

// Recap the highest gas limit with account's available balance.
if feeCap.BitLen() != 0 {
state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if err != nil {
return 0, err
}
balance := state.GetBalance(*args.From) // from can't be nil
balance := st.GetBalance(*args.From) // from can't be nil
available := new(big.Int).Set(balance)
if args.Value != nil {
if args.Value.ToInt().Cmp(available) >= 0 {
Expand All @@ -1202,35 +1188,56 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
hi = gasCap
}
cap = hi

// Create a helper to check if a gas allowance results in an executable transaction
executable := func(gas uint64, state *state.StateDB, header *types.Header) (bool, *core.ExecutionResult, error) {
// Create a helper that executes the transaction under a given gas limit and returns true
// if the transaction fails for a reason that might be related to not enough gas. A non-nil
// error means execution failed due to reasons unrelated to the gas limit.
executable := func(gas uint64, state *state.StateDB) (bool, *core.ExecutionResult, error, uint64) {
args.Gas = (*hexutil.Uint64)(&gas)

result, err := doCall(ctx, b, args, state, header, nil, nil, 0, gasCap)
result, gasUsed, err := doCall(ctx, b, args, state, header, nil, nil, 0, gasCap)
if err != nil {
if errors.Is(err, core.ErrIntrinsicGas) {
return true, nil, nil // Special case, raise gas limit
return true, nil, nil, 0 // Special case, raise gas limit
}
return true, nil, err // Bail out
return true, nil, err, 0 // Bail out
}
return result.Failed(), result, nil
return result.Failed(), result, nil, gasUsed
}
state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
if state == nil || err != nil {

// We first execute the transaction at the highest allowable gas limit, since if this fails we
// can return error immediately.
failed, result, err, gasUsed := executable(hi, st.Copy())
if err != nil {
return 0, err
}
// Execute the binary search and hone in on an executable gas limit
if failed {
if result != nil && result.Err != vm.ErrOutOfGas {
if len(result.Revert()) > 0 {
return 0, newRevertError(result)
}
return 0, result.Err
}
return 0, fmt.Errorf("gas required exceeds allowance (%d)", hi)
}
// For almost any transaction, the gas consumed by the unconstrained execution above
// lower-bounds the gas limit required for it to succeed. One exception is those txs that
// explicitly check gas remaining in order to successfully execute within a given limit, but we
// probably don't want to return a lowest possible gas limit for these cases anyway.
lo = gasUsed - 1

// Binary search for the smallest gas limit that allows the tx to execute successfully.
for lo+1 < hi {
s := state.Copy()
mid := (hi + lo) / 2
failed, _, err := executable(mid, s, header)

// If the error is not nil(consensus error), it means the provided message
// call or transaction will never be accepted no matter how much gas it is
// assigned. Return the error directly, don't struggle any more.
if mid > lo*2 {
// Bias the search towards lo since the initial lo value is rarely far off
mid = lo * 2
}
failed, _, err, _ = executable(mid, st.Copy())
if err != nil {
// This should not happen under normal conditions since if we make it this far the
// transaction had run without error at least once before.
log.Error("execution error in estimate gas", "err", err)
return 0, err
}
if failed {
Expand All @@ -1239,28 +1246,14 @@ func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNr
hi = mid
}
}
// Reject the transaction as invalid if it still fails at the highest allowance
if hi == cap {
failed, result, err := executable(hi, state, header)
if err != nil {
return 0, err
}
if failed {
if result != nil && result.Err != vm.ErrOutOfGas {
if len(result.Revert()) > 0 {
return 0, newRevertError(result)
}
return 0, result.Err
}
// Otherwise, the specified gas cap is too low
return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
}
}
return hexutil.Uint64(hi), nil
}

// EstimateGas returns an estimate of the amount of gas needed to execute the
// given transaction against the current pending block.
// EstimateGas returns the lowest possible gas limit that allows the transaction to run
// successfully at block `blockNrOrHash`, or the latest block if `blockNrOrHash` is unspecified. It
// returns error if the transaction would revert or if there are unexpected failures. The returned
// value is capped by both `args.Gas` (if non-nil & non-zero) and the backend's RPCGasCap
// configuration (if non-zero).
func (s *BlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
if blockNrOrHash != nil {
Expand Down

0 comments on commit 9b8e908

Please sign in to comment.