github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/eth/gasprice/gasprice.go (about) 1 // Copyright 2021 The adkgo Authors 2 // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8). 3 // 4 // the adkgo 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 adkgo 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 adkgo 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/aidoskuneen/adk-node/common" 26 "github.com/aidoskuneen/adk-node/core" 27 "github.com/aidoskuneen/adk-node/core/types" 28 "github.com/aidoskuneen/adk-node/event" 29 "github.com/aidoskuneen/adk-node/log" 30 "github.com/aidoskuneen/adk-node/params" 31 "github.com/aidoskuneen/adk-node/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 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 headEvent := make(chan core.ChainHeadEvent, 1) 110 backend.SubscribeChainHeadEvent(headEvent) 111 go func() { 112 var lastHead common.Hash 113 for ev := range headEvent { 114 if ev.Block.ParentHash() != lastHead { 115 cache.Purge() 116 } 117 lastHead = ev.Block.Hash() 118 } 119 }() 120 121 return &Oracle{ 122 backend: backend, 123 lastPrice: params.Default, 124 maxPrice: maxPrice, 125 ignorePrice: ignorePrice, 126 checkBlocks: blocks, 127 percentile: percent, 128 maxHeaderHistory: params.MaxHeaderHistory, 129 maxBlockHistory: params.MaxBlockHistory, 130 historyCache: cache, 131 } 132 } 133 134 // SuggestTipCap returns a tip cap so that newly created transaction can have a 135 // very high chance to be included in the following blocks. 136 // 137 // Note, for legacy transactions and the legacy eth_gasPrice RPC call, it will be 138 // necessary to add the basefee to the returned number to fall back to the legacy 139 // behavior. 140 func (oracle *Oracle) SuggestTipCap(ctx context.Context) (*big.Int, error) { 141 head, _ := oracle.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber) 142 headHash := head.Hash() 143 144 // If the latest gasprice is still available, return it. 145 oracle.cacheLock.RLock() 146 lastHead, lastPrice := oracle.lastHead, oracle.lastPrice 147 oracle.cacheLock.RUnlock() 148 if headHash == lastHead { 149 return new(big.Int).Set(lastPrice), nil 150 } 151 oracle.fetchLock.Lock() 152 defer oracle.fetchLock.Unlock() 153 154 // Try checking the cache again, maybe the last fetch fetched what we need 155 oracle.cacheLock.RLock() 156 lastHead, lastPrice = oracle.lastHead, oracle.lastPrice 157 oracle.cacheLock.RUnlock() 158 if headHash == lastHead { 159 return new(big.Int).Set(lastPrice), nil 160 } 161 var ( 162 sent, exp int 163 number = head.Number.Uint64() 164 result = make(chan results, oracle.checkBlocks) 165 quit = make(chan struct{}) 166 results []*big.Int 167 ) 168 for sent < oracle.checkBlocks && number > 0 { 169 go oracle.getBlockValues(ctx, types.MakeSigner(oracle.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, oracle.ignorePrice, result, quit) 170 sent++ 171 exp++ 172 number-- 173 } 174 for exp > 0 { 175 res := <-result 176 if res.err != nil { 177 close(quit) 178 return new(big.Int).Set(lastPrice), res.err 179 } 180 exp-- 181 // Nothing returned. There are two special cases here: 182 // - The block is empty 183 // - All the transactions included are sent by the miner itself. 184 // In these cases, use the latest calculated price for sampling. 185 if len(res.values) == 0 { 186 res.values = []*big.Int{lastPrice} 187 } 188 // Besides, in order to collect enough data for sampling, if nothing 189 // meaningful returned, try to query more blocks. But the maximum 190 // is 2*checkBlocks. 191 if len(res.values) == 1 && len(results)+1+exp < oracle.checkBlocks*2 && number > 0 { 192 go oracle.getBlockValues(ctx, types.MakeSigner(oracle.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, oracle.ignorePrice, result, quit) 193 sent++ 194 exp++ 195 number-- 196 } 197 results = append(results, res.values...) 198 } 199 price := lastPrice 200 if len(results) > 0 { 201 sort.Sort(bigIntArray(results)) 202 price = results[(len(results)-1)*oracle.percentile/100] 203 } 204 if price.Cmp(oracle.maxPrice) > 0 { 205 price = new(big.Int).Set(oracle.maxPrice) 206 } 207 oracle.cacheLock.Lock() 208 oracle.lastHead = headHash 209 oracle.lastPrice = price 210 oracle.cacheLock.Unlock() 211 212 return new(big.Int).Set(price), nil 213 } 214 215 type results struct { 216 values []*big.Int 217 err error 218 } 219 220 type txSorter struct { 221 txs []*types.Transaction 222 baseFee *big.Int 223 } 224 225 func newSorter(txs []*types.Transaction, baseFee *big.Int) *txSorter { 226 return &txSorter{ 227 txs: txs, 228 baseFee: baseFee, 229 } 230 } 231 232 func (s *txSorter) Len() int { return len(s.txs) } 233 func (s *txSorter) Swap(i, j int) { 234 s.txs[i], s.txs[j] = s.txs[j], s.txs[i] 235 } 236 func (s *txSorter) Less(i, j int) bool { 237 // It's okay to discard the error because a tx would never be 238 // accepted into a block with an invalid effective tip. 239 tip1, _ := s.txs[i].EffectiveGasTip(s.baseFee) 240 tip2, _ := s.txs[j].EffectiveGasTip(s.baseFee) 241 return tip1.Cmp(tip2) < 0 242 } 243 244 // getBlockPrices calculates the lowest transaction gas price in a given block 245 // and sends it to the result channel. If the block is empty or all transactions 246 // are sent by the miner itself(it doesn't make any sense to include this kind of 247 // transaction prices for sampling), nil gasprice is returned. 248 func (oracle *Oracle) getBlockValues(ctx context.Context, signer types.Signer, blockNum uint64, limit int, ignoreUnder *big.Int, result chan results, quit chan struct{}) { 249 block, err := oracle.backend.BlockByNumber(ctx, rpc.BlockNumber(blockNum)) 250 if block == nil { 251 select { 252 case result <- results{nil, err}: 253 case <-quit: 254 } 255 return 256 } 257 // Sort the transaction by effective tip in ascending sort. 258 txs := make([]*types.Transaction, len(block.Transactions())) 259 copy(txs, block.Transactions()) 260 sorter := newSorter(txs, block.BaseFee()) 261 sort.Sort(sorter) 262 263 var prices []*big.Int 264 for _, tx := range sorter.txs { 265 tip, _ := tx.EffectiveGasTip(block.BaseFee()) 266 if ignoreUnder != nil && tip.Cmp(ignoreUnder) == -1 { 267 continue 268 } 269 sender, err := types.Sender(signer, tx) 270 if err == nil && sender != block.Coinbase() { 271 prices = append(prices, tip) 272 if len(prices) >= limit { 273 break 274 } 275 } 276 } 277 select { 278 case result <- results{prices, nil}: 279 case <-quit: 280 } 281 } 282 283 type bigIntArray []*big.Int 284 285 func (s bigIntArray) Len() int { return len(s) } 286 func (s bigIntArray) Less(i, j int) bool { return s[i].Cmp(s[j]) < 0 } 287 func (s bigIntArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] }