github.com/core-coin/go-core/v2@v2.1.9/miner/stress_clique.go (about)

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