eth/gasprice: add generic LRU implementation (#26162)

This commit is contained in:
Daniel Liu 2024-11-13 09:30:54 +08:00
parent 179185438f
commit f9e431888e
2 changed files with 12 additions and 9 deletions

View file

@ -56,7 +56,12 @@ type blockFees struct {
err error
}
// processedFees contains the results of a processed block and is also used for caching
type cacheKey struct {
number uint64
percentiles string
}
// processedFees contains the results of a processed block.
type processedFees struct {
reward []*big.Int
baseFee, nextBaseFee *big.Int
@ -268,13 +273,10 @@ func (oracle *Oracle) FeeHistory(ctx context.Context, blocks uint64, unresolvedL
oracle.processBlock(fees, rewardPercentiles)
results <- fees
} else {
cacheKey := struct {
number uint64
percentiles string
}{blockNumber, string(percentileKey)}
cacheKey := cacheKey{number: blockNumber, percentiles: string(percentileKey)}
if p, ok := oracle.historyCache.Get(cacheKey); ok {
fees.results = p.(processedFees)
fees.results = p
results <- fees
} else {
if len(rewardPercentiles) != 0 {

View file

@ -29,7 +29,7 @@ import (
"github.com/XinFinOrg/XDPoSChain/log"
"github.com/XinFinOrg/XDPoSChain/params"
"github.com/XinFinOrg/XDPoSChain/rpc"
lru "github.com/hashicorp/golang-lru"
"github.com/XinFinOrg/XDPoSChain/common/lru"
)
const sampleNumber = 3 // Number of transactions sampled in a block
@ -72,7 +72,8 @@ type Oracle struct {
checkBlocks, percentile int
maxHeaderHistory, maxBlockHistory uint64
historyCache *lru.Cache
historyCache *lru.Cache[cacheKey, processedFees]
}
// NewOracle returns a new gasprice oracle which can recommend suitable
@ -114,7 +115,7 @@ func NewOracle(backend OracleBackend, params Config) *Oracle {
log.Warn("Sanitizing invalid gasprice oracle max block history", "provided", params.MaxBlockHistory, "updated", maxBlockHistory)
}
cache, _ := lru.New(2048)
cache := lru.NewCache[cacheKey, processedFees](2048)
headEvent := make(chan core.ChainHeadEvent, 1)
backend.SubscribeChainHeadEvent(headEvent)
go func() {