github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/eth/gasprice/feehistory.go (about)

     1  // Copyright 2021 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 gasprice
    18  
    19  import (
    20  	"context"
    21  	"encoding/binary"
    22  	"errors"
    23  	"fmt"
    24  	"math"
    25  	"math/big"
    26  	"sort"
    27  	"sync/atomic"
    28  
    29  	"github.com/ethw3/go-ethereuma/common"
    30  	"github.com/ethw3/go-ethereuma/consensus/misc"
    31  	"github.com/ethw3/go-ethereuma/core/types"
    32  	"github.com/ethw3/go-ethereuma/log"
    33  	"github.com/ethw3/go-ethereuma/rpc"
    34  )
    35  
    36  var (
    37  	errInvalidPercentile = errors.New("invalid reward percentile")
    38  	errRequestBeyondHead = errors.New("request beyond head block")
    39  )
    40  
    41  const (
    42  	// maxBlockFetchers is the max number of goroutines to spin up to pull blocks
    43  	// for the fee history calculation (mostly relevant for LES).
    44  	maxBlockFetchers = 4
    45  )
    46  
    47  // blockFees represents a single block for processing
    48  type blockFees struct {
    49  	// set by the caller
    50  	blockNumber uint64
    51  	header      *types.Header
    52  	block       *types.Block // only set if reward percentiles are requested
    53  	receipts    types.Receipts
    54  	// filled by processBlock
    55  	results processedFees
    56  	err     error
    57  }
    58  
    59  // processedFees contains the results of a processed block and is also used for caching
    60  type processedFees struct {
    61  	reward               []*big.Int
    62  	baseFee, nextBaseFee *big.Int
    63  	gasUsedRatio         float64
    64  }
    65  
    66  // txGasAndReward is sorted in ascending order based on reward
    67  type (
    68  	txGasAndReward struct {
    69  		gasUsed uint64
    70  		reward  *big.Int
    71  	}
    72  	sortGasAndReward []txGasAndReward
    73  )
    74  
    75  func (s sortGasAndReward) Len() int { return len(s) }
    76  func (s sortGasAndReward) Swap(i, j int) {
    77  	s[i], s[j] = s[j], s[i]
    78  }
    79  func (s sortGasAndReward) Less(i, j int) bool {
    80  	return s[i].reward.Cmp(s[j].reward) < 0
    81  }
    82  
    83  // processBlock takes a blockFees structure with the blockNumber, the header and optionally
    84  // the block field filled in, retrieves the block from the backend if not present yet and
    85  // fills in the rest of the fields.
    86  func (oracle *Oracle) processBlock(bf *blockFees, percentiles []float64) {
    87  	chainconfig := oracle.backend.ChainConfig()
    88  	if bf.results.baseFee = bf.header.BaseFee; bf.results.baseFee == nil {
    89  		bf.results.baseFee = new(big.Int)
    90  	}
    91  	if chainconfig.IsLondon(big.NewInt(int64(bf.blockNumber + 1))) {
    92  		bf.results.nextBaseFee = misc.CalcBaseFee(chainconfig, bf.header)
    93  	} else {
    94  		bf.results.nextBaseFee = new(big.Int)
    95  	}
    96  	bf.results.gasUsedRatio = float64(bf.header.GasUsed) / float64(bf.header.GasLimit)
    97  	if len(percentiles) == 0 {
    98  		// rewards were not requested, return null
    99  		return
   100  	}
   101  	if bf.block == nil || (bf.receipts == nil && len(bf.block.Transactions()) != 0) {
   102  		log.Error("Block or receipts are missing while reward percentiles are requested")
   103  		return
   104  	}
   105  
   106  	bf.results.reward = make([]*big.Int, len(percentiles))
   107  	if len(bf.block.Transactions()) == 0 {
   108  		// return an all zero row if there are no transactions to gather data from
   109  		for i := range bf.results.reward {
   110  			bf.results.reward[i] = new(big.Int)
   111  		}
   112  		return
   113  	}
   114  
   115  	sorter := make(sortGasAndReward, len(bf.block.Transactions()))
   116  	for i, tx := range bf.block.Transactions() {
   117  		reward, _ := tx.EffectiveGasTip(bf.block.BaseFee())
   118  		sorter[i] = txGasAndReward{gasUsed: bf.receipts[i].GasUsed, reward: reward}
   119  	}
   120  	sort.Stable(sorter)
   121  
   122  	var txIndex int
   123  	sumGasUsed := sorter[0].gasUsed
   124  
   125  	for i, p := range percentiles {
   126  		thresholdGasUsed := uint64(float64(bf.block.GasUsed()) * p / 100)
   127  		for sumGasUsed < thresholdGasUsed && txIndex < len(bf.block.Transactions())-1 {
   128  			txIndex++
   129  			sumGasUsed += sorter[txIndex].gasUsed
   130  		}
   131  		bf.results.reward[i] = sorter[txIndex].reward
   132  	}
   133  }
   134  
   135  // resolveBlockRange resolves the specified block range to absolute block numbers while also
   136  // enforcing backend specific limitations. The pending block and corresponding receipts are
   137  // also returned if requested and available.
   138  // Note: an error is only returned if retrieving the head header has failed. If there are no
   139  // retrievable blocks in the specified range then zero block count is returned with no error.
   140  func (oracle *Oracle) resolveBlockRange(ctx context.Context, reqEnd rpc.BlockNumber, blocks int) (*types.Block, []*types.Receipt, uint64, int, error) {
   141  	var (
   142  		headBlock       *types.Header
   143  		pendingBlock    *types.Block
   144  		pendingReceipts types.Receipts
   145  		err             error
   146  	)
   147  
   148  	// Get the chain's current head.
   149  	if headBlock, err = oracle.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber); err != nil {
   150  		return nil, nil, 0, 0, err
   151  	}
   152  	head := rpc.BlockNumber(headBlock.Number.Uint64())
   153  
   154  	// Fail if request block is beyond the chain's current head.
   155  	if head < reqEnd {
   156  		return nil, nil, 0, 0, fmt.Errorf("%w: requested %d, head %d", errRequestBeyondHead, reqEnd, head)
   157  	}
   158  
   159  	// Resolve block tag.
   160  	if reqEnd < 0 {
   161  		var (
   162  			resolved *types.Header
   163  			err      error
   164  		)
   165  		switch reqEnd {
   166  		case rpc.PendingBlockNumber:
   167  			if pendingBlock, pendingReceipts = oracle.backend.PendingBlockAndReceipts(); pendingBlock != nil {
   168  				resolved = pendingBlock.Header()
   169  			} else {
   170  				// Pending block not supported by backend, process only until latest block.
   171  				resolved = headBlock
   172  
   173  				// Update total blocks to return to account for this.
   174  				blocks--
   175  			}
   176  		case rpc.LatestBlockNumber:
   177  			// Retrieved above.
   178  			resolved = headBlock
   179  		case rpc.SafeBlockNumber:
   180  			resolved, err = oracle.backend.HeaderByNumber(ctx, rpc.SafeBlockNumber)
   181  		case rpc.FinalizedBlockNumber:
   182  			resolved, err = oracle.backend.HeaderByNumber(ctx, rpc.FinalizedBlockNumber)
   183  		case rpc.EarliestBlockNumber:
   184  			resolved, err = oracle.backend.HeaderByNumber(ctx, rpc.EarliestBlockNumber)
   185  		}
   186  		if resolved == nil || err != nil {
   187  			return nil, nil, 0, 0, err
   188  		}
   189  		// Absolute number resolved.
   190  		reqEnd = rpc.BlockNumber(resolved.Number.Uint64())
   191  	}
   192  
   193  	// If there are no blocks to return, short circuit.
   194  	if blocks == 0 {
   195  		return nil, nil, 0, 0, nil
   196  	}
   197  	// Ensure not trying to retrieve before genesis.
   198  	if int(reqEnd+1) < blocks {
   199  		blocks = int(reqEnd + 1)
   200  	}
   201  	return pendingBlock, pendingReceipts, uint64(reqEnd), blocks, nil
   202  }
   203  
   204  // FeeHistory returns data relevant for fee estimation based on the specified range of blocks.
   205  // The range can be specified either with absolute block numbers or ending with the latest
   206  // or pending block. Backends may or may not support gathering data from the pending block
   207  // or blocks older than a certain age (specified in maxHistory). The first block of the
   208  // actually processed range is returned to avoid ambiguity when parts of the requested range
   209  // are not available or when the head has changed during processing this request.
   210  // Three arrays are returned based on the processed blocks:
   211  // - reward: the requested percentiles of effective priority fees per gas of transactions in each
   212  //   block, sorted in ascending order and weighted by gas used.
   213  // - baseFee: base fee per gas in the given block
   214  // - gasUsedRatio: gasUsed/gasLimit in the given block
   215  // Note: baseFee includes the next block after the newest of the returned range, because this
   216  // value can be derived from the newest block.
   217  func (oracle *Oracle) FeeHistory(ctx context.Context, blocks int, unresolvedLastBlock rpc.BlockNumber, rewardPercentiles []float64) (*big.Int, [][]*big.Int, []*big.Int, []float64, error) {
   218  	if blocks < 1 {
   219  		return common.Big0, nil, nil, nil, nil // returning with no data and no error means there are no retrievable blocks
   220  	}
   221  	maxFeeHistory := oracle.maxHeaderHistory
   222  	if len(rewardPercentiles) != 0 {
   223  		maxFeeHistory = oracle.maxBlockHistory
   224  	}
   225  	if blocks > maxFeeHistory {
   226  		log.Warn("Sanitizing fee history length", "requested", blocks, "truncated", maxFeeHistory)
   227  		blocks = maxFeeHistory
   228  	}
   229  	for i, p := range rewardPercentiles {
   230  		if p < 0 || p > 100 {
   231  			return common.Big0, nil, nil, nil, fmt.Errorf("%w: %f", errInvalidPercentile, p)
   232  		}
   233  		if i > 0 && p < rewardPercentiles[i-1] {
   234  			return common.Big0, nil, nil, nil, fmt.Errorf("%w: #%d:%f > #%d:%f", errInvalidPercentile, i-1, rewardPercentiles[i-1], i, p)
   235  		}
   236  	}
   237  	var (
   238  		pendingBlock    *types.Block
   239  		pendingReceipts []*types.Receipt
   240  		err             error
   241  	)
   242  	pendingBlock, pendingReceipts, lastBlock, blocks, err := oracle.resolveBlockRange(ctx, unresolvedLastBlock, blocks)
   243  	if err != nil || blocks == 0 {
   244  		return common.Big0, nil, nil, nil, err
   245  	}
   246  	oldestBlock := lastBlock + 1 - uint64(blocks)
   247  
   248  	var (
   249  		next    = oldestBlock
   250  		results = make(chan *blockFees, blocks)
   251  	)
   252  	percentileKey := make([]byte, 8*len(rewardPercentiles))
   253  	for i, p := range rewardPercentiles {
   254  		binary.LittleEndian.PutUint64(percentileKey[i*8:(i+1)*8], math.Float64bits(p))
   255  	}
   256  	for i := 0; i < maxBlockFetchers && i < blocks; i++ {
   257  		go func() {
   258  			for {
   259  				// Retrieve the next block number to fetch with this goroutine
   260  				blockNumber := atomic.AddUint64(&next, 1) - 1
   261  				if blockNumber > lastBlock {
   262  					return
   263  				}
   264  
   265  				fees := &blockFees{blockNumber: blockNumber}
   266  				if pendingBlock != nil && blockNumber >= pendingBlock.NumberU64() {
   267  					fees.block, fees.receipts = pendingBlock, pendingReceipts
   268  					fees.header = fees.block.Header()
   269  					oracle.processBlock(fees, rewardPercentiles)
   270  					results <- fees
   271  				} else {
   272  					cacheKey := struct {
   273  						number      uint64
   274  						percentiles string
   275  					}{blockNumber, string(percentileKey)}
   276  
   277  					if p, ok := oracle.historyCache.Get(cacheKey); ok {
   278  						fees.results = p.(processedFees)
   279  						results <- fees
   280  					} else {
   281  						if len(rewardPercentiles) != 0 {
   282  							fees.block, fees.err = oracle.backend.BlockByNumber(ctx, rpc.BlockNumber(blockNumber))
   283  							if fees.block != nil && fees.err == nil {
   284  								fees.receipts, fees.err = oracle.backend.GetReceipts(ctx, fees.block.Hash())
   285  								fees.header = fees.block.Header()
   286  							}
   287  						} else {
   288  							fees.header, fees.err = oracle.backend.HeaderByNumber(ctx, rpc.BlockNumber(blockNumber))
   289  						}
   290  						if fees.header != nil && fees.err == nil {
   291  							oracle.processBlock(fees, rewardPercentiles)
   292  							if fees.err == nil {
   293  								oracle.historyCache.Add(cacheKey, fees.results)
   294  							}
   295  						}
   296  						// send to results even if empty to guarantee that blocks items are sent in total
   297  						results <- fees
   298  					}
   299  				}
   300  			}
   301  		}()
   302  	}
   303  	var (
   304  		reward       = make([][]*big.Int, blocks)
   305  		baseFee      = make([]*big.Int, blocks+1)
   306  		gasUsedRatio = make([]float64, blocks)
   307  		firstMissing = blocks
   308  	)
   309  	for ; blocks > 0; blocks-- {
   310  		fees := <-results
   311  		if fees.err != nil {
   312  			return common.Big0, nil, nil, nil, fees.err
   313  		}
   314  		i := int(fees.blockNumber - oldestBlock)
   315  		if fees.results.baseFee != nil {
   316  			reward[i], baseFee[i], baseFee[i+1], gasUsedRatio[i] = fees.results.reward, fees.results.baseFee, fees.results.nextBaseFee, fees.results.gasUsedRatio
   317  		} else {
   318  			// getting no block and no error means we are requesting into the future (might happen because of a reorg)
   319  			if i < firstMissing {
   320  				firstMissing = i
   321  			}
   322  		}
   323  	}
   324  	if firstMissing == 0 {
   325  		return common.Big0, nil, nil, nil, nil
   326  	}
   327  	if len(rewardPercentiles) != 0 {
   328  		reward = reward[:firstMissing]
   329  	} else {
   330  		reward = nil
   331  	}
   332  	baseFee, gasUsedRatio = baseFee[:firstMissing+1], gasUsedRatio[:firstMissing]
   333  	return new(big.Int).SetUint64(oldestBlock), reward, baseFee, gasUsedRatio, nil
   334  }