github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/miner/stress_clique.go (about)

     1  // Copyright 2018 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  // +build none
    18  
    19  // This file contains a miner stress test based on the Clique consensus engine.
    20  package main
    21  
    22  import (
    23  	"bytes"
    24  	"crypto/ecdsa"
    25  	"io/ioutil"
    26  	"math/big"
    27  	"math/rand"
    28  	"os"
    29  	"time"
    30  
    31  	"github.com/kisexp/xdchain/accounts/keystore"
    32  	"github.com/kisexp/xdchain/common"
    33  	"github.com/kisexp/xdchain/common/fdlimit"
    34  	"github.com/kisexp/xdchain/core"
    35  	"github.com/kisexp/xdchain/core/types"
    36  	"github.com/kisexp/xdchain/crypto"
    37  	"github.com/kisexp/xdchain/eth"
    38  	"github.com/kisexp/xdchain/eth/downloader"
    39  	"github.com/kisexp/xdchain/log"
    40  	"github.com/kisexp/xdchain/miner"
    41  	"github.com/kisexp/xdchain/node"
    42  	"github.com/kisexp/xdchain/p2p"
    43  	"github.com/kisexp/xdchain/p2p/enode"
    44  	"github.com/kisexp/xdchain/params"
    45  )
    46  
    47  func main() {
    48  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
    49  	fdlimit.Raise(2048)
    50  
    51  	// Generate a batch of accounts to seal and fund with
    52  	faucets := make([]*ecdsa.PrivateKey, 128)
    53  	for i := 0; i < len(faucets); i++ {
    54  		faucets[i], _ = crypto.GenerateKey()
    55  	}
    56  	sealers := make([]*ecdsa.PrivateKey, 4)
    57  	for i := 0; i < len(sealers); i++ {
    58  		sealers[i], _ = crypto.GenerateKey()
    59  	}
    60  	// Create a Clique network based off of the Rinkeby config
    61  	genesis := makeGenesis(faucets, sealers)
    62  
    63  	var (
    64  		nodes  []*eth.Ethereum
    65  		enodes []*enode.Node
    66  	)
    67  
    68  	for _, sealer := range sealers {
    69  		// Start the node and wait until it's up
    70  		stack, ethBackend, err := makeSealer(genesis)
    71  		if err != nil {
    72  			panic(err)
    73  		}
    74  		defer stack.Close()
    75  
    76  		for stack.Server().NodeInfo().Ports.Listener == 0 {
    77  			time.Sleep(250 * time.Millisecond)
    78  		}
    79  		// Connect the node to all the previous ones
    80  		for _, n := range enodes {
    81  			stack.Server().AddPeer(n)
    82  		}
    83  		// Start tracking the node and its enode
    84  		nodes = append(nodes, ethBackend)
    85  		enodes = append(enodes, stack.Server().Self())
    86  
    87  		// Inject the signer key and start sealing with it
    88  		store := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
    89  		signer, err := store.ImportECDSA(sealer, "")
    90  		if err != nil {
    91  			panic(err)
    92  		}
    93  		if err := store.Unlock(signer, ""); err != nil {
    94  			panic(err)
    95  		}
    96  	}
    97  
    98  	// Iterate over all the nodes and start signing on them
    99  	time.Sleep(3 * time.Second)
   100  	for _, node := range nodes {
   101  		if err := node.StartMining(1); err != nil {
   102  			panic(err)
   103  		}
   104  	}
   105  	time.Sleep(3 * time.Second)
   106  
   107  	// Start injecting transactions from the faucet like crazy
   108  	nonces := make([]uint64, len(faucets))
   109  	for {
   110  		// Pick a random signer node
   111  		index := rand.Intn(len(faucets))
   112  		backend := nodes[index%len(nodes)]
   113  
   114  		// Create a self transaction and inject into the pool
   115  		tx, err := types.SignTx(types.NewTransaction(nonces[index], crypto.PubkeyToAddress(faucets[index].PublicKey), new(big.Int), 21000, big.NewInt(100000000000), nil), types.HomesteadSigner{}, faucets[index])
   116  		if err != nil {
   117  			panic(err)
   118  		}
   119  		if err := backend.TxPool().AddLocal(tx); err != nil {
   120  			panic(err)
   121  		}
   122  		nonces[index]++
   123  
   124  		// Wait if we're too saturated
   125  		if pend, _ := backend.TxPool().Stats(); pend > 2048 {
   126  			time.Sleep(100 * time.Millisecond)
   127  		}
   128  	}
   129  }
   130  
   131  // makeGenesis creates a custom Clique genesis block based on some pre-defined
   132  // signer and faucet accounts.
   133  func makeGenesis(faucets []*ecdsa.PrivateKey, sealers []*ecdsa.PrivateKey) *core.Genesis {
   134  	// Create a Clique network based off of the Rinkeby config
   135  	genesis := core.DefaultRinkebyGenesisBlock()
   136  	genesis.GasLimit = 25000000
   137  
   138  	genesis.Config.ChainID = big.NewInt(18)
   139  	genesis.Config.Clique.Period = 1
   140  	genesis.Config.EIP150Hash = common.Hash{}
   141  
   142  	genesis.Alloc = core.GenesisAlloc{}
   143  	for _, faucet := range faucets {
   144  		genesis.Alloc[crypto.PubkeyToAddress(faucet.PublicKey)] = core.GenesisAccount{
   145  			Balance: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil),
   146  		}
   147  	}
   148  	// Sort the signers and embed into the extra-data section
   149  	signers := make([]common.Address, len(sealers))
   150  	for i, sealer := range sealers {
   151  		signers[i] = crypto.PubkeyToAddress(sealer.PublicKey)
   152  	}
   153  	for i := 0; i < len(signers); i++ {
   154  		for j := i + 1; j < len(signers); j++ {
   155  			if bytes.Compare(signers[i][:], signers[j][:]) > 0 {
   156  				signers[i], signers[j] = signers[j], signers[i]
   157  			}
   158  		}
   159  	}
   160  	genesis.ExtraData = make([]byte, 32+len(signers)*common.AddressLength+65)
   161  	for i, signer := range signers {
   162  		copy(genesis.ExtraData[32+i*common.AddressLength:], signer[:])
   163  	}
   164  	// Return the genesis block for initialization
   165  	return genesis
   166  }
   167  
   168  func makeSealer(genesis *core.Genesis) (*node.Node, *eth.Ethereum, error) {
   169  	// Define the basic configurations for the Ethereum node
   170  	datadir, _ := ioutil.TempDir("", "")
   171  
   172  	config := &node.Config{
   173  		Name:    "geth",
   174  		Version: params.Version,
   175  		DataDir: datadir,
   176  		P2P: p2p.Config{
   177  			ListenAddr:  "0.0.0.0:0",
   178  			NoDiscovery: true,
   179  			MaxPeers:    25,
   180  		},
   181  		NoUSB: true,
   182  	}
   183  	// Start the node and configure a full Ethereum node on it
   184  	stack, err := node.New(config)
   185  	if err != nil {
   186  		return nil, nil, err
   187  	}
   188  	// Create and register the backend
   189  	ethBackend, err := eth.New(stack, &eth.Config{
   190  		Genesis:         genesis,
   191  		NetworkId:       genesis.Config.ChainID.Uint64(),
   192  		SyncMode:        downloader.FullSync,
   193  		DatabaseCache:   256,
   194  		DatabaseHandles: 256,
   195  		TxPool:          core.DefaultTxPoolConfig,
   196  		GPO:             eth.DefaultConfig.GPO,
   197  		Miner: miner.Config{
   198  			GasFloor: genesis.GasLimit * 9 / 10,
   199  			GasCeil:  genesis.GasLimit * 11 / 10,
   200  			GasPrice: big.NewInt(1),
   201  			Recommit: time.Second,
   202  		},
   203  	})
   204  	if err != nil {
   205  		return nil, nil, err
   206  	}
   207  
   208  	err = stack.Start()
   209  	return stack, ethBackend, err
   210  }