github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/miner/stress/1559/main.go (about)

     1  // Copyright 2021 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  // This file contains a miner stress test for eip 1559.
    18  package main
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"math/big"
    23  	"math/rand"
    24  	"os"
    25  	"os/signal"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/common/fdlimit"
    30  	"github.com/ethereum/go-ethereum/consensus/ethash"
    31  	"github.com/ethereum/go-ethereum/core"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/crypto"
    34  	"github.com/ethereum/go-ethereum/eth"
    35  	"github.com/ethereum/go-ethereum/eth/downloader"
    36  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    37  	"github.com/ethereum/go-ethereum/log"
    38  	"github.com/ethereum/go-ethereum/miner"
    39  	"github.com/ethereum/go-ethereum/node"
    40  	"github.com/ethereum/go-ethereum/p2p"
    41  	"github.com/ethereum/go-ethereum/p2p/enode"
    42  	"github.com/ethereum/go-ethereum/params"
    43  )
    44  
    45  var (
    46  	londonBlock = big.NewInt(30) // Predefined london fork block for activating eip 1559.
    47  )
    48  
    49  func main() {
    50  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
    51  	fdlimit.Raise(2048)
    52  
    53  	// Generate a batch of accounts to seal and fund with
    54  	faucets := make([]*ecdsa.PrivateKey, 128)
    55  	for i := 0; i < len(faucets); i++ {
    56  		faucets[i], _ = crypto.GenerateKey()
    57  	}
    58  	// Pre-generate the ethash mining DAG so we don't race
    59  	ethash.MakeDataset(1, ethconfig.Defaults.Ethash.DatasetDir)
    60  
    61  	// Create an Ethash network based off of the Ropsten config
    62  	genesis := makeGenesis(faucets)
    63  
    64  	// Handle interrupts.
    65  	interruptCh := make(chan os.Signal, 5)
    66  	signal.Notify(interruptCh, os.Interrupt)
    67  
    68  	var (
    69  		stacks []*node.Node
    70  		nodes  []*eth.Ethereum
    71  		enodes []*enode.Node
    72  	)
    73  	for i := 0; i < 4; i++ {
    74  		// Start the node and wait until it's up
    75  		stack, ethBackend, err := makeMiner(genesis)
    76  		if err != nil {
    77  			panic(err)
    78  		}
    79  		defer stack.Close()
    80  
    81  		for stack.Server().NodeInfo().Ports.Listener == 0 {
    82  			time.Sleep(250 * time.Millisecond)
    83  		}
    84  		// Connect the node to all the previous ones
    85  		for _, n := range enodes {
    86  			stack.Server().AddPeer(n)
    87  		}
    88  		// Start tracking the node and its enode
    89  		nodes = append(nodes, ethBackend)
    90  		enodes = append(enodes, stack.Server().Self())
    91  	}
    92  
    93  	// Iterate over all the nodes and start mining
    94  	time.Sleep(3 * time.Second)
    95  	for _, node := range nodes {
    96  		if err := node.StartMining(1); err != nil {
    97  			panic(err)
    98  		}
    99  	}
   100  	time.Sleep(3 * time.Second)
   101  
   102  	// Start injecting transactions from the faucets like crazy
   103  	var (
   104  		nonces = make([]uint64, len(faucets))
   105  
   106  		// The signer activates the 1559 features even before the fork,
   107  		// so the new 1559 txs can be created with this signer.
   108  		signer = types.LatestSignerForChainID(genesis.Config.ChainID)
   109  	)
   110  	for {
   111  		// Stop when interrupted.
   112  		select {
   113  		case <-interruptCh:
   114  			for _, node := range stacks {
   115  				node.Close()
   116  			}
   117  			return
   118  		default:
   119  		}
   120  
   121  		// Pick a random mining node
   122  		index := rand.Intn(len(faucets))
   123  		backend := nodes[index%len(nodes)]
   124  
   125  		headHeader := backend.BlockChain().CurrentHeader()
   126  		baseFee := headHeader.BaseFee
   127  
   128  		// Create a self transaction and inject into the pool. The legacy
   129  		// and 1559 transactions can all be created by random even if the
   130  		// fork is not happened.
   131  		tx := makeTransaction(nonces[index], faucets[index], signer, baseFee)
   132  		if err := backend.TxPool().AddLocal(tx); err != nil {
   133  			continue
   134  		}
   135  		nonces[index]++
   136  
   137  		// Wait if we're too saturated
   138  		if pend, _ := backend.TxPool().Stats(); pend > 4192 {
   139  			time.Sleep(100 * time.Millisecond)
   140  		}
   141  
   142  		// Wait if the basefee is raised too fast
   143  		if baseFee != nil && baseFee.Cmp(new(big.Int).Mul(big.NewInt(100), big.NewInt(params.GWei))) > 0 {
   144  			time.Sleep(500 * time.Millisecond)
   145  		}
   146  	}
   147  }
   148  
   149  func makeTransaction(nonce uint64, privKey *ecdsa.PrivateKey, signer types.Signer, baseFee *big.Int) *types.Transaction {
   150  	// Generate legacy transaction
   151  	if rand.Intn(2) == 0 {
   152  		tx, err := types.SignTx(types.NewTransaction(nonce, crypto.PubkeyToAddress(privKey.PublicKey), new(big.Int), 21000, big.NewInt(100000000000+rand.Int63n(65536)), nil), signer, privKey)
   153  		if err != nil {
   154  			panic(err)
   155  		}
   156  		return tx
   157  	}
   158  	// Generate eip 1559 transaction
   159  	recipient := crypto.PubkeyToAddress(privKey.PublicKey)
   160  
   161  	// Feecap and feetip are limited to 32 bytes. Offer a sightly
   162  	// larger buffer for creating both valid and invalid transactions.
   163  	var buf = make([]byte, 32+5)
   164  	rand.Read(buf)
   165  	gasTipCap := new(big.Int).SetBytes(buf)
   166  
   167  	// If the given base fee is nil(the 1559 is still not available),
   168  	// generate a fake base fee in order to create 1559 tx forcibly.
   169  	if baseFee == nil {
   170  		baseFee = new(big.Int).SetInt64(int64(rand.Int31()))
   171  	}
   172  	// Generate the feecap, 75% valid feecap and 25% unguaranted.
   173  	var gasFeeCap *big.Int
   174  	if rand.Intn(4) == 0 {
   175  		rand.Read(buf)
   176  		gasFeeCap = new(big.Int).SetBytes(buf)
   177  	} else {
   178  		gasFeeCap = new(big.Int).Add(baseFee, gasTipCap)
   179  	}
   180  	return types.MustSignNewTx(privKey, signer, &types.DynamicFeeTx{
   181  		ChainID:    signer.ChainID(),
   182  		Nonce:      nonce,
   183  		GasTipCap:  gasTipCap,
   184  		GasFeeCap:  gasFeeCap,
   185  		Gas:        21000,
   186  		To:         &recipient,
   187  		Value:      big.NewInt(100),
   188  		Data:       nil,
   189  		AccessList: nil,
   190  	})
   191  }
   192  
   193  // makeGenesis creates a custom Ethash genesis block based on some pre-defined
   194  // faucet accounts.
   195  func makeGenesis(faucets []*ecdsa.PrivateKey) *core.Genesis {
   196  	genesis := core.DefaultRopstenGenesisBlock()
   197  
   198  	genesis.Config = params.AllEthashProtocolChanges
   199  	genesis.Config.LondonBlock = londonBlock
   200  	genesis.Difficulty = params.MinimumDifficulty
   201  
   202  	// Small gaslimit for easier basefee moving testing.
   203  	genesis.GasLimit = 8_000_000
   204  
   205  	genesis.Config.ChainID = big.NewInt(18)
   206  	genesis.Config.EIP150Hash = common.Hash{}
   207  
   208  	genesis.Alloc = core.GenesisAlloc{}
   209  	for _, faucet := range faucets {
   210  		genesis.Alloc[crypto.PubkeyToAddress(faucet.PublicKey)] = core.GenesisAccount{
   211  			Balance: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil),
   212  		}
   213  	}
   214  	if londonBlock.Sign() == 0 {
   215  		log.Info("Enabled the eip 1559 by default")
   216  	} else {
   217  		log.Info("Registered the london fork", "number", londonBlock)
   218  	}
   219  	return genesis
   220  }
   221  
   222  func makeMiner(genesis *core.Genesis) (*node.Node, *eth.Ethereum, error) {
   223  	// Define the basic configurations for the Ethereum node
   224  	datadir, _ := os.MkdirTemp("", "")
   225  
   226  	config := &node.Config{
   227  		Name:    "geth",
   228  		Version: params.Version,
   229  		DataDir: datadir,
   230  		P2P: p2p.Config{
   231  			ListenAddr:  "0.0.0.0:0",
   232  			NoDiscovery: true,
   233  			MaxPeers:    25,
   234  		},
   235  		UseLightweightKDF: true,
   236  	}
   237  	// Create the node and configure a full Ethereum node on it
   238  	stack, err := node.New(config)
   239  	if err != nil {
   240  		return nil, nil, err
   241  	}
   242  	ethBackend, err := eth.New(stack, &ethconfig.Config{
   243  		Genesis:         genesis,
   244  		NetworkId:       genesis.Config.ChainID.Uint64(),
   245  		SyncMode:        downloader.FullSync,
   246  		DatabaseCache:   256,
   247  		DatabaseHandles: 256,
   248  		TxPool:          core.DefaultTxPoolConfig,
   249  		GPO:             ethconfig.Defaults.GPO,
   250  		Ethash:          ethconfig.Defaults.Ethash,
   251  		Miner: miner.Config{
   252  			Etherbase: common.Address{1},
   253  			GasCeil:   genesis.GasLimit * 11 / 10,
   254  			GasPrice:  big.NewInt(1),
   255  			Recommit:  time.Second,
   256  		},
   257  	})
   258  	if err != nil {
   259  		return nil, nil, err
   260  	}
   261  	err = stack.Start()
   262  	return stack, ethBackend, err
   263  }