consensus/misc: reduce allocations and improve comments in CalcBaseFee (#24958)

* consensus/misc: reduce allocations in CalcBaseFee

* consensus/misc: add formulas of CalcBaseFee
This commit is contained in:
Ivan Kuznetsov 2022-06-03 01:25:12 +07:00 committed by GitHub
parent 6f075bf6af
commit 490c45c70f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -58,36 +58,36 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int {
return new(big.Int).SetUint64(params.InitialBaseFee) return new(big.Int).SetUint64(params.InitialBaseFee)
} }
var ( parentGasTarget := parent.GasLimit / params.ElasticityMultiplier
parentGasTarget = parent.GasLimit / params.ElasticityMultiplier
parentGasTargetBig = new(big.Int).SetUint64(parentGasTarget)
baseFeeChangeDenominator = new(big.Int).SetUint64(params.BaseFeeChangeDenominator)
)
// If the parent gasUsed is the same as the target, the baseFee remains unchanged. // If the parent gasUsed is the same as the target, the baseFee remains unchanged.
if parent.GasUsed == parentGasTarget { if parent.GasUsed == parentGasTarget {
return new(big.Int).Set(parent.BaseFee) return new(big.Int).Set(parent.BaseFee)
} }
var (
num = new(big.Int)
denom = new(big.Int)
)
if parent.GasUsed > parentGasTarget { if parent.GasUsed > parentGasTarget {
// If the parent block used more gas than its target, the baseFee should increase. // If the parent block used more gas than its target, the baseFee should increase.
gasUsedDelta := new(big.Int).SetUint64(parent.GasUsed - parentGasTarget) // max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta) num.SetUint64(parent.GasUsed - parentGasTarget)
y := x.Div(x, parentGasTargetBig) num.Mul(num, parent.BaseFee)
baseFeeDelta := math.BigMax( num.Div(num, denom.SetUint64(parentGasTarget))
x.Div(y, baseFeeChangeDenominator), num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
common.Big1, baseFeeDelta := math.BigMax(num, common.Big1)
)
return x.Add(parent.BaseFee, baseFeeDelta) return num.Add(parent.BaseFee, baseFeeDelta)
} else { } else {
// Otherwise if the parent block used less gas than its target, the baseFee should decrease. // Otherwise if the parent block used less gas than its target, the baseFee should decrease.
gasUsedDelta := new(big.Int).SetUint64(parentGasTarget - parent.GasUsed) // max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta) num.SetUint64(parentGasTarget - parent.GasUsed)
y := x.Div(x, parentGasTargetBig) num.Mul(num, parent.BaseFee)
baseFeeDelta := x.Div(y, baseFeeChangeDenominator) num.Div(num, denom.SetUint64(parentGasTarget))
num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
baseFee := num.Sub(parent.BaseFee, num)
return math.BigMax( return math.BigMax(baseFee, common.Big0)
x.Sub(parent.BaseFee, baseFeeDelta),
common.Big0,
)
} }
} }