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