accounts/abi/bind, internal/ethapi: binary search gas estimation (#3587)

Gas estimation currently mostly works, but can underestimate for more funky
refunds. This is because various ops (e.g. CALL) need more gas to run than they
actually consume (e.g. 2300 stipend that is refunded if not used). With more
intricate contract interplays, it becomes almost impossible to return a proper
value to the user.

This commit swaps out the simplistic gas estimation to a binary search approach,
honing in on the correct gas use. This does mean that gas estimation needs to
rerun the transaction log(max-price) times to measure whether it fails or not,
but it's a price paid by the transaction issuer, and it should be worth it to
support proper estimates.
This commit is contained in:
Péter Szilágyi
2017-01-21 00:39:16 +02:00
committed by Felix Lange
parent 0126d01435
commit 682875adff
3 changed files with 100 additions and 9 deletions

View File

@ -559,8 +559,34 @@ func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr r
// EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*hexutil.Big, error) {
_, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber)
return (*hexutil.Big)(gas), err
// Binary search the gas requirement, as it may be higher than the amount used
var lo, hi uint64
if (*big.Int)(&args.Gas).BitLen() > 0 {
hi = (*big.Int)(&args.Gas).Uint64()
} else {
// Retrieve the current pending block to act as the gas ceiling
block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber)
if err != nil {
return nil, err
}
hi = block.GasLimit().Uint64()
}
for lo+1 < hi {
// Take a guess at the gas, and check transaction validity
mid := (hi + lo) / 2
(*big.Int)(&args.Gas).SetUint64(mid)
_, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber)
// If the transaction became invalid or used all the gas (failed), raise the gas limit
if err != nil || gas.Cmp((*big.Int)(&args.Gas)) == 0 {
lo = mid
continue
}
// Otherwise assume the transaction succeeded, lower the gas limit
hi = mid
}
return (*hexutil.Big)(new(big.Int).SetUint64(hi)), nil
}
// ExecutionResult groups all structured logs emitted by the EVM