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