gasprice.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. package gasprice
  17. import (
  18. "context"
  19. "math/big"
  20. "sort"
  21. "sync"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/log"
  25. "github.com/ethereum/go-ethereum/params"
  26. "github.com/ethereum/go-ethereum/rpc"
  27. )
  28. const sampleNumber = 3 // Number of transactions sampled in a block
  29. var DefaultMaxPrice = big.NewInt(500 * params.GWei)
  30. type Config struct {
  31. Blocks int
  32. Percentile int
  33. Default *big.Int `toml:",omitempty"`
  34. MaxPrice *big.Int `toml:",omitempty"`
  35. OracleThreshold int `toml:",omitempty"`
  36. }
  37. // OracleBackend includes all necessary background APIs for oracle.
  38. type OracleBackend interface {
  39. HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
  40. BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
  41. ChainConfig() *params.ChainConfig
  42. }
  43. // Oracle recommends gas prices based on the content of recent
  44. // blocks. Suitable for both light and full clients.
  45. type Oracle struct {
  46. backend OracleBackend
  47. lastHead common.Hash
  48. lastPrice *big.Int
  49. maxPrice *big.Int
  50. cacheLock sync.RWMutex
  51. fetchLock sync.Mutex
  52. defaultPrice *big.Int
  53. sampleTxThreshold int
  54. checkBlocks int
  55. percentile int
  56. }
  57. // NewOracle returns a new gasprice oracle which can recommend suitable
  58. // gasprice for newly created transaction.
  59. func NewOracle(backend OracleBackend, params Config) *Oracle {
  60. blocks := params.Blocks
  61. if blocks < 1 {
  62. blocks = 1
  63. log.Warn("Sanitizing invalid gasprice oracle sample blocks", "provided", params.Blocks, "updated", blocks)
  64. }
  65. percent := params.Percentile
  66. if percent < 0 {
  67. percent = 0
  68. log.Warn("Sanitizing invalid gasprice oracle sample percentile", "provided", params.Percentile, "updated", percent)
  69. }
  70. if percent > 100 {
  71. percent = 100
  72. log.Warn("Sanitizing invalid gasprice oracle sample percentile", "provided", params.Percentile, "updated", percent)
  73. }
  74. maxPrice := params.MaxPrice
  75. if maxPrice == nil || maxPrice.Int64() <= 0 {
  76. maxPrice = DefaultMaxPrice
  77. log.Warn("Sanitizing invalid gasprice oracle price cap", "provided", params.MaxPrice, "updated", maxPrice)
  78. }
  79. return &Oracle{
  80. backend: backend,
  81. lastPrice: params.Default,
  82. maxPrice: maxPrice,
  83. checkBlocks: blocks,
  84. percentile: percent,
  85. defaultPrice: params.Default,
  86. sampleTxThreshold: params.OracleThreshold,
  87. }
  88. }
  89. // SuggestPrice returns a gasprice so that newly created transaction can
  90. // have a very high chance to be included in the following blocks.
  91. func (gpo *Oracle) SuggestPrice(ctx context.Context) (*big.Int, error) {
  92. head, _ := gpo.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
  93. headHash := head.Hash()
  94. // If the latest gasprice is still available, return it.
  95. gpo.cacheLock.RLock()
  96. lastHead, lastPrice := gpo.lastHead, gpo.lastPrice
  97. gpo.cacheLock.RUnlock()
  98. if headHash == lastHead {
  99. return lastPrice, nil
  100. }
  101. gpo.fetchLock.Lock()
  102. defer gpo.fetchLock.Unlock()
  103. // Try checking the cache again, maybe the laest fetch fetched what we need
  104. gpo.cacheLock.RLock()
  105. lastHead, lastPrice = gpo.lastHead, gpo.lastPrice
  106. gpo.cacheLock.RUnlock()
  107. if headHash == lastHead {
  108. return lastPrice, nil
  109. }
  110. var (
  111. sent, exp int
  112. number = head.Number.Uint64()
  113. result = make(chan getBlockPricesResult, gpo.checkBlocks)
  114. quit = make(chan struct{})
  115. txPrices []*big.Int
  116. totalTxSamples int
  117. )
  118. for sent < gpo.checkBlocks && number > 0 {
  119. go gpo.getBlockPrices(ctx, types.MakeSigner(gpo.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, result, quit)
  120. sent++
  121. exp++
  122. number--
  123. }
  124. for exp > 0 {
  125. res := <-result
  126. if res.err != nil {
  127. close(quit)
  128. return lastPrice, res.err
  129. }
  130. exp--
  131. // Nothing returned. There are two special cases here:
  132. // - The block is empty
  133. // - All the transactions included are sent by the miner itself.
  134. // In these cases, use the latest calculated price for samping.
  135. if len(res.prices) == 0 {
  136. res.prices = []*big.Int{lastPrice}
  137. } else {
  138. totalTxSamples = totalTxSamples + res.number
  139. }
  140. // Besides, in order to collect enough data for sampling, if nothing
  141. // meaningful returned, try to query more blocks. But the maximum
  142. // is 2*checkBlocks.
  143. if len(res.prices) == 1 && len(txPrices)+1+exp < gpo.checkBlocks*2 && number > 0 {
  144. go gpo.getBlockPrices(ctx, types.MakeSigner(gpo.backend.ChainConfig(), big.NewInt(int64(number))), number, sampleNumber, result, quit)
  145. sent++
  146. exp++
  147. number--
  148. }
  149. txPrices = append(txPrices, res.prices...)
  150. }
  151. price := lastPrice
  152. if len(txPrices) > 0 && totalTxSamples > gpo.sampleTxThreshold {
  153. sort.Sort(bigIntArray(txPrices))
  154. price = txPrices[(len(txPrices)-1)*gpo.percentile/100]
  155. } else {
  156. price = gpo.defaultPrice
  157. }
  158. if price.Cmp(gpo.maxPrice) > 0 {
  159. price = new(big.Int).Set(gpo.maxPrice)
  160. }
  161. gpo.cacheLock.Lock()
  162. gpo.lastHead = headHash
  163. gpo.lastPrice = price
  164. gpo.cacheLock.Unlock()
  165. return price, nil
  166. }
  167. type getBlockPricesResult struct {
  168. number int
  169. prices []*big.Int
  170. err error
  171. }
  172. type transactionsByGasPrice []*types.Transaction
  173. func (t transactionsByGasPrice) Len() int { return len(t) }
  174. func (t transactionsByGasPrice) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
  175. func (t transactionsByGasPrice) Less(i, j int) bool { return t[i].GasPriceCmp(t[j]) < 0 }
  176. // getBlockPrices calculates the lowest transaction gas price in a given block
  177. // and sends it to the result channel. If the block is empty or all transactions
  178. // are sent by the miner itself(it doesn't make any sense to include this kind of
  179. // transaction prices for sampling), nil gasprice is returned.
  180. func (gpo *Oracle) getBlockPrices(ctx context.Context, signer types.Signer, blockNum uint64, limit int, result chan getBlockPricesResult, quit chan struct{}) {
  181. block, err := gpo.backend.BlockByNumber(ctx, rpc.BlockNumber(blockNum))
  182. if block == nil {
  183. select {
  184. case result <- getBlockPricesResult{0, nil, err}:
  185. case <-quit:
  186. }
  187. return
  188. }
  189. blockTxs := block.Transactions()
  190. txs := make([]*types.Transaction, len(blockTxs))
  191. copy(txs, blockTxs)
  192. sort.Sort(transactionsByGasPrice(txs))
  193. var prices []*big.Int
  194. for _, tx := range txs {
  195. if tx.GasPriceIntCmp(common.Big1) <= 0 {
  196. continue
  197. }
  198. sender, err := types.Sender(signer, tx)
  199. if err == nil && sender != block.Coinbase() {
  200. prices = append(prices, tx.GasPrice())
  201. if len(prices) >= limit {
  202. break
  203. }
  204. }
  205. }
  206. select {
  207. case result <- getBlockPricesResult{len(prices), prices, nil}:
  208. case <-quit:
  209. }
  210. }
  211. type bigIntArray []*big.Int
  212. func (s bigIntArray) Len() int { return len(s) }
  213. func (s bigIntArray) Less(i, j int) bool { return s[i].Cmp(s[j]) < 0 }
  214. func (s bigIntArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] }