|
| 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 | +} |
0 commit comments