github.com/etclabscore/ethereum.go-ethereum@v1.8.15/miner/stress_ethash.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 Ethash consensus engine.
    20  package main
    21  
    22  import (
    23  	"crypto/ecdsa"
    24  	"fmt"
    25  	"io/ioutil"
    26  	"math/big"
    27  	"math/rand"
    28  	"os"
    29  	"path/filepath"
    30  	"time"
    31  
    32  	"github.com/ethereum/go-ethereum/accounts/keystore"
    33  	"github.com/ethereum/go-ethereum/common"
    34  	"github.com/ethereum/go-ethereum/common/fdlimit"
    35  	"github.com/ethereum/go-ethereum/consensus/ethash"
    36  	"github.com/ethereum/go-ethereum/core"
    37  	"github.com/ethereum/go-ethereum/core/types"
    38  	"github.com/ethereum/go-ethereum/crypto"
    39  	"github.com/ethereum/go-ethereum/eth"
    40  	"github.com/ethereum/go-ethereum/eth/downloader"
    41  	"github.com/ethereum/go-ethereum/log"
    42  	"github.com/ethereum/go-ethereum/node"
    43  	"github.com/ethereum/go-ethereum/p2p"
    44  	"github.com/ethereum/go-ethereum/p2p/discover"
    45  	"github.com/ethereum/go-ethereum/params"
    46  )
    47  
    48  func main() {
    49  	log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
    50  	fdlimit.Raise(2048)
    51  
    52  	// Generate a batch of accounts to seal and fund with
    53  	faucets := make([]*ecdsa.PrivateKey, 128)
    54  	for i := 0; i < len(faucets); i++ {
    55  		faucets[i], _ = crypto.GenerateKey()
    56  	}
    57  	// Pre-generate the ethash mining DAG so we don't race
    58  	ethash.MakeDataset(1, filepath.Join(os.Getenv("HOME"), ".ethash"))
    59  
    60  	// Create an Ethash network based off of the Ropsten config
    61  	genesis := makeGenesis(faucets)
    62  
    63  	var (
    64  		nodes  []*node.Node
    65  		enodes []string
    66  	)
    67  	for i := 0; i < 4; i++ {
    68  		// Start the node and wait until it's up
    69  		node, err := makeMiner(genesis, enodes)
    70  		if err != nil {
    71  			panic(err)
    72  		}
    73  		defer node.Stop()
    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 _, enode := range enodes {
    80  			enode, err := discover.ParseNode(enode)
    81  			if err != nil {
    82  				panic(err)
    83  			}
    84  			node.Server().AddPeer(enode)
    85  		}
    86  		// Start tracking the node and it's enode url
    87  		nodes = append(nodes, node)
    88  
    89  		enode := fmt.Sprintf("enode://%s@127.0.0.1:%d", node.Server().NodeInfo().ID, node.Server().NodeInfo().Ports.Listener)
    90  		enodes = append(enodes, enode)
    91  
    92  		// Inject the signer key and start sealing with it
    93  		store := node.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
    94  		if _, err := store.NewAccount(""); err != nil {
    95  			panic(err)
    96  		}
    97  	}
    98  	// Iterate over all the nodes and start signing with them
    99  	time.Sleep(3 * time.Second)
   100  
   101  	for _, node := range nodes {
   102  		var ethereum *eth.Ethereum
   103  		if err := node.Service(&ethereum); err != nil {
   104  			panic(err)
   105  		}
   106  		if err := ethereum.StartMining(1); err != nil {
   107  			panic(err)
   108  		}
   109  	}
   110  	time.Sleep(3 * time.Second)
   111  
   112  	// Start injecting transactions from the faucets like crazy
   113  	nonces := make([]uint64, len(faucets))
   114  	for {
   115  		index := rand.Intn(len(faucets))
   116  
   117  		// Fetch the accessor for the relevant signer
   118  		var ethereum *eth.Ethereum
   119  		if err := nodes[index%len(nodes)].Service(&ethereum); err != nil {
   120  			panic(err)
   121  		}
   122  		// Create a self transaction and inject into the pool
   123  		tx, err := types.SignTx(types.NewTransaction(nonces[index], crypto.PubkeyToAddress(faucets[index].PublicKey), new(big.Int), 21000, big.NewInt(100000000000+rand.Int63n(65536)), nil), types.HomesteadSigner{}, faucets[index])
   124  		if err != nil {
   125  			panic(err)
   126  		}
   127  		if err := ethereum.TxPool().AddLocal(tx); err != nil {
   128  			panic(err)
   129  		}
   130  		nonces[index]++
   131  
   132  		// Wait if we're too saturated
   133  		if pend, _ := ethereum.TxPool().Stats(); pend > 2048 {
   134  			time.Sleep(100 * time.Millisecond)
   135  		}
   136  	}
   137  }
   138  
   139  // makeGenesis creates a custom Ethash genesis block based on some pre-defined
   140  // faucet accounts.
   141  func makeGenesis(faucets []*ecdsa.PrivateKey) *core.Genesis {
   142  	genesis := core.DefaultTestnetGenesisBlock()
   143  	genesis.Difficulty = params.MinimumDifficulty
   144  	genesis.GasLimit = 25000000
   145  
   146  	genesis.Config.ChainID = big.NewInt(18)
   147  	genesis.Config.EIP150Hash = common.Hash{}
   148  
   149  	genesis.Alloc = core.GenesisAlloc{}
   150  	for _, faucet := range faucets {
   151  		genesis.Alloc[crypto.PubkeyToAddress(faucet.PublicKey)] = core.GenesisAccount{
   152  			Balance: new(big.Int).Exp(big.NewInt(2), big.NewInt(128), nil),
   153  		}
   154  	}
   155  	return genesis
   156  }
   157  
   158  func makeMiner(genesis *core.Genesis, nodes []string) (*node.Node, error) {
   159  	// Define the basic configurations for the Ethereum node
   160  	datadir, _ := ioutil.TempDir("", "")
   161  
   162  	config := &node.Config{
   163  		Name:    "geth",
   164  		Version: params.Version,
   165  		DataDir: datadir,
   166  		P2P: p2p.Config{
   167  			ListenAddr:  "0.0.0.0:0",
   168  			NoDiscovery: true,
   169  			MaxPeers:    25,
   170  		},
   171  		NoUSB:             true,
   172  		UseLightweightKDF: true,
   173  	}
   174  	// Start the node and configure a full Ethereum node on it
   175  	stack, err := node.New(config)
   176  	if err != nil {
   177  		return nil, err
   178  	}
   179  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   180  		return eth.New(ctx, &eth.Config{
   181  			Genesis:         genesis,
   182  			NetworkId:       genesis.Config.ChainID.Uint64(),
   183  			SyncMode:        downloader.FullSync,
   184  			DatabaseCache:   256,
   185  			DatabaseHandles: 256,
   186  			TxPool:          core.DefaultTxPoolConfig,
   187  			GPO:             eth.DefaultConfig.GPO,
   188  			Ethash:          eth.DefaultConfig.Ethash,
   189  			MinerGasFloor:   genesis.GasLimit * 9 / 10,
   190  			MinerGasCeil:    genesis.GasLimit * 11 / 10,
   191  			MinerGasPrice:   big.NewInt(1),
   192  			MinerRecommit:   time.Second,
   193  		})
   194  	}); err != nil {
   195  		return nil, err
   196  	}
   197  	// Start the node and return if successful
   198  	return stack, stack.Start()
   199  }