gasprice.go 7.0 KB

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