github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/eth/gasprice/gasprice_test.go (about)

     1  // Copyright 2020 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"
    22  	"math/big"
    23  	"testing"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/consensus/ethash"
    27  	"github.com/ethereum/go-ethereum/core"
    28  	"github.com/ethereum/go-ethereum/core/rawdb"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/core/vm"
    31  	"github.com/ethereum/go-ethereum/crypto"
    32  	"github.com/ethereum/go-ethereum/event"
    33  	"github.com/ethereum/go-ethereum/params"
    34  	"github.com/ethereum/go-ethereum/rpc"
    35  )
    36  
    37  const testHead = 32
    38  
    39  type testBackend struct {
    40  	chain   *core.BlockChain
    41  	pending bool // pending block available
    42  }
    43  
    44  func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
    45  	if number > testHead {
    46  		return nil, nil
    47  	}
    48  	if number == rpc.EarliestBlockNumber {
    49  		number = 0
    50  	}
    51  	if number == rpc.FinalizedBlockNumber {
    52  		return b.chain.CurrentFinalizedBlock().Header(), nil
    53  	}
    54  	if number == rpc.SafeBlockNumber {
    55  		return b.chain.CurrentSafeBlock().Header(), nil
    56  	}
    57  	if number == rpc.LatestBlockNumber {
    58  		number = testHead
    59  	}
    60  	if number == rpc.PendingBlockNumber {
    61  		if b.pending {
    62  			number = testHead + 1
    63  		} else {
    64  			return nil, nil
    65  		}
    66  	}
    67  	return b.chain.GetHeaderByNumber(uint64(number)), nil
    68  }
    69  
    70  func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
    71  	if number > testHead {
    72  		return nil, nil
    73  	}
    74  	if number == rpc.EarliestBlockNumber {
    75  		number = 0
    76  	}
    77  	if number == rpc.FinalizedBlockNumber {
    78  		return b.chain.CurrentFinalizedBlock(), nil
    79  	}
    80  	if number == rpc.SafeBlockNumber {
    81  		return b.chain.CurrentSafeBlock(), nil
    82  	}
    83  	if number == rpc.LatestBlockNumber {
    84  		number = testHead
    85  	}
    86  	if number == rpc.PendingBlockNumber {
    87  		if b.pending {
    88  			number = testHead + 1
    89  		} else {
    90  			return nil, nil
    91  		}
    92  	}
    93  	return b.chain.GetBlockByNumber(uint64(number)), nil
    94  }
    95  
    96  func (b *testBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
    97  	return b.chain.GetReceiptsByHash(hash), nil
    98  }
    99  
   100  func (b *testBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   101  	if b.pending {
   102  		block := b.chain.GetBlockByNumber(testHead + 1)
   103  		return block, b.chain.GetReceiptsByHash(block.Hash())
   104  	}
   105  	return nil, nil
   106  }
   107  
   108  func (b *testBackend) ChainConfig() *params.ChainConfig {
   109  	return b.chain.Config()
   110  }
   111  
   112  func (b *testBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   113  	return nil
   114  }
   115  
   116  func newTestBackend(t *testing.T, londonBlock *big.Int, pending bool) *testBackend {
   117  	var (
   118  		key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   119  		addr   = crypto.PubkeyToAddress(key.PublicKey)
   120  		config = *params.TestChainConfig // needs copy because it is modified below
   121  		gspec  = &core.Genesis{
   122  			Config: &config,
   123  			Alloc:  core.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}},
   124  		}
   125  		signer = types.LatestSigner(gspec.Config)
   126  	)
   127  	config.LondonBlock = londonBlock
   128  	config.ArrowGlacierBlock = londonBlock
   129  	config.GrayGlacierBlock = londonBlock
   130  	config.TerminalTotalDifficulty = common.Big0
   131  	engine := ethash.NewFaker()
   132  
   133  	// Generate testing blocks
   134  	_, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, testHead+1, func(i int, b *core.BlockGen) {
   135  		b.SetCoinbase(common.Address{1})
   136  
   137  		var txdata types.TxData
   138  		if londonBlock != nil && b.Number().Cmp(londonBlock) >= 0 {
   139  			txdata = &types.DynamicFeeTx{
   140  				ChainID:   gspec.Config.ChainID,
   141  				Nonce:     b.TxNonce(addr),
   142  				To:        &common.Address{},
   143  				Gas:       30000,
   144  				GasFeeCap: big.NewInt(100 * params.GWei),
   145  				GasTipCap: big.NewInt(int64(i+1) * params.GWei),
   146  				Data:      []byte{},
   147  			}
   148  		} else {
   149  			txdata = &types.LegacyTx{
   150  				Nonce:    b.TxNonce(addr),
   151  				To:       &common.Address{},
   152  				Gas:      21000,
   153  				GasPrice: big.NewInt(int64(i+1) * params.GWei),
   154  				Value:    big.NewInt(100),
   155  				Data:     []byte{},
   156  			}
   157  		}
   158  		b.AddTx(types.MustSignNewTx(key, signer, txdata))
   159  	})
   160  	// Construct testing chain
   161  	chain, err := core.NewBlockChain(rawdb.NewMemoryDatabase(), &core.CacheConfig{TrieCleanNoPrefetch: true}, gspec, nil, engine, vm.Config{}, nil, nil)
   162  	if err != nil {
   163  		t.Fatalf("Failed to create local chain, %v", err)
   164  	}
   165  	chain.InsertChain(blocks)
   166  	chain.SetFinalized(chain.GetBlockByNumber(25))
   167  	chain.SetSafe(chain.GetBlockByNumber(25))
   168  	return &testBackend{chain: chain, pending: pending}
   169  }
   170  
   171  func (b *testBackend) CurrentHeader() *types.Header {
   172  	return b.chain.CurrentHeader()
   173  }
   174  
   175  func (b *testBackend) GetBlockByNumber(number uint64) *types.Block {
   176  	return b.chain.GetBlockByNumber(number)
   177  }
   178  
   179  func TestSuggestTipCap(t *testing.T) {
   180  	config := Config{
   181  		Blocks:     3,
   182  		Percentile: 60,
   183  		Default:    big.NewInt(params.GWei),
   184  	}
   185  	var cases = []struct {
   186  		fork   *big.Int // London fork number
   187  		expect *big.Int // Expected gasprice suggestion
   188  	}{
   189  		{nil, big.NewInt(params.GWei * int64(30))},
   190  		{big.NewInt(0), big.NewInt(params.GWei * int64(30))},  // Fork point in genesis
   191  		{big.NewInt(1), big.NewInt(params.GWei * int64(30))},  // Fork point in first block
   192  		{big.NewInt(32), big.NewInt(params.GWei * int64(30))}, // Fork point in last block
   193  		{big.NewInt(33), big.NewInt(params.GWei * int64(30))}, // Fork point in the future
   194  	}
   195  	for _, c := range cases {
   196  		backend := newTestBackend(t, c.fork, false)
   197  		oracle := NewOracle(backend, config)
   198  
   199  		// The gas price sampled is: 32G, 31G, 30G, 29G, 28G, 27G
   200  		got, err := oracle.SuggestTipCap(context.Background())
   201  		if err != nil {
   202  			t.Fatalf("Failed to retrieve recommended gas price: %v", err)
   203  		}
   204  		if got.Cmp(c.expect) != 0 {
   205  			t.Fatalf("Gas price mismatch, want %d, got %d", c.expect, got)
   206  		}
   207  	}
   208  }