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