github.com/DxChainNetwork/dxc@v0.8.1-0.20220824085222-1162e304b6e7/eth/gasprice/gasprice.go (about)

     1  // Copyright 2015 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  	"math/big"
    22  	"sort"
    23  	"sync"
    24  
    25  	"github.com/DxChainNetwork/dxc/common"
    26  	"github.com/DxChainNetwork/dxc/core"
    27  	"github.com/DxChainNetwork/dxc/core/types"
    28  	"github.com/DxChainNetwork/dxc/event"
    29  	"github.com/DxChainNetwork/dxc/log"
    30  	"github.com/DxChainNetwork/dxc/params"
    31  	"github.com/DxChainNetwork/dxc/rpc"
    32  	lru "github.com/hashicorp/golang-lru"
    33  )
    34  
    35  const sampleNumber = 3 // Number of transactions sampled in a block
    36  
    37  var (
    38  	DefaultMaxPrice    = big.NewInt(500 * params.GWei)
    39  	DefaultIgnorePrice = big.NewInt(2 * params.Wei)
    40  )
    41  
    42  type Config struct {
    43  	Blocks           int
    44  	Percentile       int
    45  	MaxHeaderHistory int
    46  	MaxBlockHistory  int
    47  	Default          *big.Int `toml:",omitempty"`
    48  	MaxPrice         *big.Int `toml:",omitempty"`
    49  	IgnorePrice      *big.Int `toml:",omitempty"`
    50  
    51  	PredConfig
    52  }
    53  
    54  // OracleBackend includes all necessary background APIs for oracle.
    55  type OracleBackend interface {
    56  	HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
    57  	BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
    58  	GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error)
    59  	PendingBlockAndReceipts() (*types.Block, types.Receipts)
    60  	ChainConfig() *params.ChainConfig
    61  	SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
    62  }
    63  
    64  // Oracle recommends gas prices based on the content of recent
    65  // blocks. Suitable for both light and full clients.
    66  type Oracle struct {
    67  	backend     OracleBackend
    68  	lastHead    common.Hash
    69  	lastPrice   *big.Int
    70  	maxPrice    *big.Int
    71  	ignorePrice *big.Int
    72  	cacheLock   sync.RWMutex
    73  	fetchLock   sync.Mutex
    74  
    75  	checkBlocks, percentile           int
    76  	maxHeaderHistory, maxBlockHistory int
    77  	historyCache                      *lru.Cache
    78  }
    79  
    80  // NewOracle returns a new gasprice oracle which can recommend suitable
    81  // gasprice for newly created transaction.
    82  func NewOracle(backend OracleBackend, params Config) *Oracle {
    83  	blocks := params.Blocks
    84  	if blocks < 1 {
    85  		blocks = 1
    86  		log.Warn("Sanitizing invalid gasprice oracle sample blocks", "provided", params.Blocks, "updated", blocks)
    87  	}
    88  	percent := params.Percentile
    89  	if percent < 0 {
    90  		percent = 0
    91  		log.Warn("Sanitizing invalid gasprice oracle sample percentile", "provided", params.Percentile, "updated", percent)
    92  	}
    93  	if percent > 100 {
    94  		percent = 100
    95  		log.Warn("Sanitizing invalid gasprice oracle sample percentile", "provided", params.Percentile, "updated", percent)
    96  	}
    97  	maxPrice := params.MaxPrice
    98  	if maxPrice == nil || maxPrice.Int64() <= 0 {
    99  		maxPrice = DefaultMaxPrice
   100  		log.Warn("Sanitizing invalid gasprice oracle price cap", "provided", params.MaxPrice, "updated", maxPrice)
   101  	}
   102  	ignorePrice := params.IgnorePrice
   103  	if ignorePrice == nil || ignorePrice.Int64() <= 0 {
   104  		ignorePrice = DefaultIgnorePrice
   105  		log.Warn("Sanitizing invalid gasprice oracle ignore price", "provided", params.IgnorePrice, "updated", ignorePrice)
   106  	} else if ignorePrice.Int64() > 0 {
   107  		log.Info("Gasprice oracle is ignoring threshold set", "threshold", ignorePrice)
   108  	}
   109  
   110  	cache, _ := lru.New(2048)
   111  	headEvent := make(chan core.ChainHeadEvent, 1)
   112  	backend.SubscribeChainHeadEvent(headEvent)
   113  	go func() {
   114  		var lastHead common.Hash
   115  		for ev := range headEvent {
   116  			if ev.Block.ParentHash() != lastHead {
   117  				cache.Purge()
   118  			}
   119  			lastHead = ev.Block.Hash()
   120  		}
   121  	}()
   122  
   123  	return &Oracle{
   124  		backend:          backend,
   125  		lastPrice:        params.Default,
   126  		maxPrice:         maxPrice,
   127  		ignorePrice:      ignorePrice,
   128  		checkBlocks:      blocks,
   129  		percentile:       percent,
   130  		maxHeaderHistory: params.MaxHeaderHistory,
   131  		maxBlockHistory:  params.MaxBlockHistory,
   132  		historyCache:     cache,
   133  	}
   134  }
   135  
   136  // SuggestTipCap returns a tip cap so that newly created transaction can have a
   137  // very high chance to be included in the following blocks.
   138  //
   139  // Note, for legacy transactions and the legacy eth_gasPrice RPC call, it will be
   140  // necessary to add the basefee to the returned number to fall back to the legacy
   141  // behavior.
   142  func (oracle *Oracle) SuggestTipCap(ctx context.Context) (*big.Int, error) {
   143  	head, _ := oracle.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
   144  	headHash := head.Hash()
   145  
   146  	// If the latest gasprice is still available, return it.
   147  	oracle.cacheLock.RLock()
   148  	lastHead, lastPrice := oracle.lastHead, oracle.lastPrice
   149  	oracle.cacheLock.RUnlock()
   150  	if headHash == lastHead {
   151  		return new(big.Int).Set(lastPrice), nil
   152  	}
   153  	oracle.fetchLock.Lock()
   154  	defer oracle.fetchLock.Unlock()
   155  
   156  	// Try checking the cache again, maybe the last fetch fetched what we need
   157  	oracle.cacheLock.RLock()
   158  	lastHead, lastPrice = oracle.lastHead, oracle.lastPrice
   159  	oracle.cacheLock.RUnlock()
   160  	if headHash == lastHead {
   161  		return new(big.Int).Set(lastPrice), nil
   162  	}
   163  	var (
   164  		sent, exp int
   165  		number    = head.Number.Uint64()
   166  		result    = make(chan results, oracle.checkBlocks)
   167  		quit      = make(chan struct{})
   168  		results   []*big.Int
   169  	)
   170  	for sent < oracle.checkBlocks && number > 0 {
   171  		go oracle.getBlockValues(ctx, types.MakeSigner(oracle.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, oracle.ignorePrice, result, quit)
   172  		sent++
   173  		exp++
   174  		number--
   175  	}
   176  	for exp > 0 {
   177  		res := <-result
   178  		if res.err != nil {
   179  			close(quit)
   180  			return new(big.Int).Set(lastPrice), res.err
   181  		}
   182  		exp--
   183  		// Nothing returned. There are two special cases here:
   184  		// - The block is empty
   185  		// - All the transactions included are sent by the miner itself.
   186  		// In these cases, use the latest calculated price for sampling.
   187  		if len(res.values) == 0 {
   188  			res.values = []*big.Int{lastPrice}
   189  		}
   190  		// Besides, in order to collect enough data for sampling, if nothing
   191  		// meaningful returned, try to query more blocks. But the maximum
   192  		// is 2*checkBlocks.
   193  		if len(res.values) == 1 && len(results)+1+exp < oracle.checkBlocks*2 && number > 0 {
   194  			go oracle.getBlockValues(ctx, types.MakeSigner(oracle.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, oracle.ignorePrice, result, quit)
   195  			sent++
   196  			exp++
   197  			number--
   198  		}
   199  		results = append(results, res.values...)
   200  	}
   201  	price := lastPrice
   202  	if len(results) > 0 {
   203  		sort.Sort(bigIntArray(results))
   204  		price = results[(len(results)-1)*oracle.percentile/100]
   205  	}
   206  	if price.Cmp(oracle.maxPrice) > 0 {
   207  		price = new(big.Int).Set(oracle.maxPrice)
   208  	}
   209  	oracle.cacheLock.Lock()
   210  	oracle.lastHead = headHash
   211  	oracle.lastPrice = price
   212  	oracle.cacheLock.Unlock()
   213  
   214  	return new(big.Int).Set(price), nil
   215  }
   216  
   217  type results struct {
   218  	values []*big.Int
   219  	err    error
   220  }
   221  
   222  type txSorter struct {
   223  	txs     []*types.Transaction
   224  	baseFee *big.Int
   225  }
   226  
   227  func newSorter(txs []*types.Transaction, baseFee *big.Int) *txSorter {
   228  	return &txSorter{
   229  		txs:     txs,
   230  		baseFee: baseFee,
   231  	}
   232  }
   233  
   234  func (s *txSorter) Len() int { return len(s.txs) }
   235  func (s *txSorter) Swap(i, j int) {
   236  	s.txs[i], s.txs[j] = s.txs[j], s.txs[i]
   237  }
   238  func (s *txSorter) Less(i, j int) bool {
   239  	// It's okay to discard the error because a tx would never be
   240  	// accepted into a block with an invalid effective tip.
   241  	tip1, _ := s.txs[i].EffectiveGasTip(s.baseFee)
   242  	tip2, _ := s.txs[j].EffectiveGasTip(s.baseFee)
   243  	return tip1.Cmp(tip2) < 0
   244  }
   245  
   246  // getBlockPrices calculates the lowest transaction gas price in a given block
   247  // and sends it to the result channel. If the block is empty or all transactions
   248  // are sent by the miner itself(it doesn't make any sense to include this kind of
   249  // transaction prices for sampling), nil gasprice is returned.
   250  func (oracle *Oracle) getBlockValues(ctx context.Context, signer types.Signer, blockNum uint64, limit int, ignoreUnder *big.Int, result chan results, quit chan struct{}) {
   251  	block, err := oracle.backend.BlockByNumber(ctx, rpc.BlockNumber(blockNum))
   252  	if block == nil {
   253  		select {
   254  		case result <- results{nil, err}:
   255  		case <-quit:
   256  		}
   257  		return
   258  	}
   259  	// Sort the transaction by effective tip in ascending sort.
   260  	txs := make([]*types.Transaction, len(block.Transactions()))
   261  	copy(txs, block.Transactions())
   262  	sorter := newSorter(txs, block.BaseFee())
   263  	sort.Sort(sorter)
   264  
   265  	var prices []*big.Int
   266  	for _, tx := range sorter.txs {
   267  		tip, _ := tx.EffectiveGasTip(block.BaseFee())
   268  		if ignoreUnder != nil && tip.Cmp(ignoreUnder) == -1 {
   269  			continue
   270  		}
   271  		sender, err := types.Sender(signer, tx)
   272  		if err == nil && sender != block.Coinbase() {
   273  			prices = append(prices, tip)
   274  			if len(prices) >= limit {
   275  				break
   276  			}
   277  		}
   278  	}
   279  	select {
   280  	case result <- results{prices, nil}:
   281  	case <-quit:
   282  	}
   283  }
   284  
   285  type bigIntArray []*big.Int
   286  
   287  func (s bigIntArray) Len() int           { return len(s) }
   288  func (s bigIntArray) Less(i, j int) bool { return s[i].Cmp(s[j]) < 0 }
   289  func (s bigIntArray) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }