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