github.com/ethereum/go-ethereum@v1.16.1/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  	"crypto/sha256"
    22  	"fmt"
    23  	"math"
    24  	"math/big"
    25  	"testing"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/consensus/beacon"
    29  	"github.com/ethereum/go-ethereum/consensus/ethash"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/crypto"
    34  	"github.com/ethereum/go-ethereum/crypto/kzg4844"
    35  	"github.com/ethereum/go-ethereum/event"
    36  	"github.com/ethereum/go-ethereum/params"
    37  	"github.com/ethereum/go-ethereum/rpc"
    38  	"github.com/holiman/uint256"
    39  )
    40  
    41  const testHead = 32
    42  
    43  type testBackend struct {
    44  	chain   *core.BlockChain
    45  	pending bool // pending block available
    46  }
    47  
    48  func (b *testBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
    49  	if number > testHead {
    50  		return nil, nil
    51  	}
    52  	if number == rpc.EarliestBlockNumber {
    53  		number = 0
    54  	}
    55  	if number == rpc.FinalizedBlockNumber {
    56  		return b.chain.CurrentFinalBlock(), nil
    57  	}
    58  	if number == rpc.SafeBlockNumber {
    59  		return b.chain.CurrentSafeBlock(), nil
    60  	}
    61  	if number == rpc.LatestBlockNumber {
    62  		number = testHead
    63  	}
    64  	if number == rpc.PendingBlockNumber {
    65  		if b.pending {
    66  			number = testHead + 1
    67  		} else {
    68  			return nil, nil
    69  		}
    70  	}
    71  	return b.chain.GetHeaderByNumber(uint64(number)), nil
    72  }
    73  
    74  func (b *testBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
    75  	if number > testHead {
    76  		return nil, nil
    77  	}
    78  	if number == rpc.EarliestBlockNumber {
    79  		number = 0
    80  	}
    81  	if number == rpc.FinalizedBlockNumber {
    82  		number = rpc.BlockNumber(b.chain.CurrentFinalBlock().Number.Uint64())
    83  	}
    84  	if number == rpc.SafeBlockNumber {
    85  		number = rpc.BlockNumber(b.chain.CurrentSafeBlock().Number.Uint64())
    86  	}
    87  	if number == rpc.LatestBlockNumber {
    88  		number = testHead
    89  	}
    90  	if number == rpc.PendingBlockNumber {
    91  		if b.pending {
    92  			number = testHead + 1
    93  		} else {
    94  			return nil, nil
    95  		}
    96  	}
    97  	return b.chain.GetBlockByNumber(uint64(number)), nil
    98  }
    99  
   100  func (b *testBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
   101  	return b.chain.GetReceiptsByHash(hash), nil
   102  }
   103  
   104  func (b *testBackend) Pending() (*types.Block, types.Receipts, *state.StateDB) {
   105  	if b.pending {
   106  		block := b.chain.GetBlockByNumber(testHead + 1)
   107  		state, _ := b.chain.StateAt(block.Root())
   108  		return block, b.chain.GetReceiptsByHash(block.Hash()), state
   109  	}
   110  	return nil, nil, nil
   111  }
   112  
   113  func (b *testBackend) ChainConfig() *params.ChainConfig {
   114  	return b.chain.Config()
   115  }
   116  
   117  func (b *testBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
   118  	return nil
   119  }
   120  
   121  func (b *testBackend) teardown() {
   122  	b.chain.Stop()
   123  }
   124  
   125  // newTestBackend creates a test backend. OBS: don't forget to invoke tearDown
   126  // after use, otherwise the blockchain instance will mem-leak via goroutines.
   127  func newTestBackend(t *testing.T, londonBlock *big.Int, cancunBlock *big.Int, pending bool) *testBackend {
   128  	if londonBlock != nil && cancunBlock != nil && londonBlock.Cmp(cancunBlock) == 1 {
   129  		panic("cannot define test backend with cancun before london")
   130  	}
   131  	var (
   132  		key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
   133  		addr   = crypto.PubkeyToAddress(key.PublicKey)
   134  		config = *params.TestChainConfig // needs copy because it is modified below
   135  		gspec  = &core.Genesis{
   136  			Config: &config,
   137  			Alloc:  types.GenesisAlloc{addr: {Balance: big.NewInt(math.MaxInt64)}},
   138  		}
   139  		signer = types.LatestSigner(gspec.Config)
   140  
   141  		// Compute empty blob hash.
   142  		emptyBlob          = kzg4844.Blob{}
   143  		emptyBlobCommit, _ = kzg4844.BlobToCommitment(&emptyBlob)
   144  		emptyBlobVHash     = kzg4844.CalcBlobHashV1(sha256.New(), &emptyBlobCommit)
   145  	)
   146  	config.LondonBlock = londonBlock
   147  	config.ArrowGlacierBlock = londonBlock
   148  	config.GrayGlacierBlock = londonBlock
   149  	if cancunBlock != nil {
   150  		// Enable the merge with cancun fork.
   151  		config.MergeNetsplitBlock = cancunBlock
   152  	}
   153  	engine := beacon.New(ethash.NewFaker())
   154  
   155  	if cancunBlock != nil {
   156  		ts := gspec.Timestamp + cancunBlock.Uint64()*10 // fixed 10 sec block time in blockgen
   157  		config.ShanghaiTime = &ts
   158  		config.CancunTime = &ts
   159  		config.BlobScheduleConfig = params.DefaultBlobSchedule
   160  		signer = types.LatestSigner(gspec.Config)
   161  	}
   162  
   163  	// Generate testing blocks
   164  	db, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, testHead+1, func(i int, b *core.BlockGen) {
   165  		b.SetCoinbase(common.Address{1})
   166  
   167  		var txdata types.TxData
   168  		if londonBlock != nil && b.Number().Cmp(londonBlock) >= 0 {
   169  			txdata = &types.DynamicFeeTx{
   170  				ChainID:   gspec.Config.ChainID,
   171  				Nonce:     b.TxNonce(addr),
   172  				To:        &common.Address{},
   173  				Gas:       30000,
   174  				GasFeeCap: big.NewInt(100 * params.GWei),
   175  				GasTipCap: big.NewInt(int64(i+1) * params.GWei),
   176  				Data:      []byte{},
   177  			}
   178  		} else {
   179  			txdata = &types.LegacyTx{
   180  				Nonce:    b.TxNonce(addr),
   181  				To:       &common.Address{},
   182  				Gas:      21000,
   183  				GasPrice: big.NewInt(int64(i+1) * params.GWei),
   184  				Value:    big.NewInt(100),
   185  				Data:     []byte{},
   186  			}
   187  		}
   188  		b.AddTx(types.MustSignNewTx(key, signer, txdata))
   189  
   190  		if cancunBlock != nil && b.Number().Cmp(cancunBlock) >= 0 {
   191  			b.SetPoS()
   192  
   193  			// put more blobs in each new block
   194  			for j := 0; j < i && j < 6; j++ {
   195  				blobTx := &types.BlobTx{
   196  					ChainID:    uint256.MustFromBig(gspec.Config.ChainID),
   197  					Nonce:      b.TxNonce(addr),
   198  					To:         common.Address{},
   199  					Gas:        30000,
   200  					GasFeeCap:  uint256.NewInt(100 * params.GWei),
   201  					GasTipCap:  uint256.NewInt(uint64(i+1) * params.GWei),
   202  					Data:       []byte{},
   203  					BlobFeeCap: uint256.NewInt(1),
   204  					BlobHashes: []common.Hash{emptyBlobVHash},
   205  					Value:      uint256.NewInt(100),
   206  					Sidecar:    nil,
   207  				}
   208  				b.AddTx(types.MustSignNewTx(key, signer, blobTx))
   209  			}
   210  		}
   211  	})
   212  
   213  	// Construct testing chain
   214  	chain, err := core.NewBlockChain(db, gspec, engine, &core.BlockChainConfig{NoPrefetch: true})
   215  	if err != nil {
   216  		t.Fatalf("Failed to create local chain, %v", err)
   217  	}
   218  	if i, err := chain.InsertChain(blocks); err != nil {
   219  		panic(fmt.Errorf("error inserting block %d: %w", i, err))
   220  	}
   221  	chain.SetFinalized(chain.GetBlockByNumber(25).Header())
   222  	chain.SetSafe(chain.GetBlockByNumber(25).Header())
   223  
   224  	return &testBackend{chain: chain, pending: pending}
   225  }
   226  
   227  func (b *testBackend) CurrentHeader() *types.Header {
   228  	return b.chain.CurrentHeader()
   229  }
   230  
   231  func (b *testBackend) GetBlockByNumber(number uint64) *types.Block {
   232  	return b.chain.GetBlockByNumber(number)
   233  }
   234  
   235  func TestSuggestTipCap(t *testing.T) {
   236  	config := Config{
   237  		Blocks:     3,
   238  		Percentile: 60,
   239  	}
   240  	var cases = []struct {
   241  		fork   *big.Int // London fork number
   242  		expect *big.Int // Expected gasprice suggestion
   243  	}{
   244  		{nil, big.NewInt(params.GWei * int64(30))},
   245  		{big.NewInt(0), big.NewInt(params.GWei * int64(30))},  // Fork point in genesis
   246  		{big.NewInt(1), big.NewInt(params.GWei * int64(30))},  // Fork point in first block
   247  		{big.NewInt(32), big.NewInt(params.GWei * int64(30))}, // Fork point in last block
   248  		{big.NewInt(33), big.NewInt(params.GWei * int64(30))}, // Fork point in the future
   249  	}
   250  	for _, c := range cases {
   251  		backend := newTestBackend(t, c.fork, nil, false)
   252  		oracle := NewOracle(backend, config, big.NewInt(params.GWei))
   253  
   254  		// The gas price sampled is: 32G, 31G, 30G, 29G, 28G, 27G
   255  		got, err := oracle.SuggestTipCap(context.Background())
   256  		backend.teardown()
   257  		if err != nil {
   258  			t.Fatalf("Failed to retrieve recommended gas price: %v", err)
   259  		}
   260  		if got.Cmp(c.expect) != 0 {
   261  			t.Fatalf("Gas price mismatch, want %d, got %d", c.expect, got)
   262  		}
   263  	}
   264  }