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