github.com/juliankolbe/go-ethereum@v1.9.992/miner/worker_test.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  package miner
    18  
    19  import (
    20  	"math/big"
    21  	"math/rand"
    22  	"sync/atomic"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/juliankolbe/go-ethereum/accounts"
    27  	"github.com/juliankolbe/go-ethereum/common"
    28  	"github.com/juliankolbe/go-ethereum/consensus"
    29  	"github.com/juliankolbe/go-ethereum/consensus/clique"
    30  	"github.com/juliankolbe/go-ethereum/consensus/ethash"
    31  	"github.com/juliankolbe/go-ethereum/core"
    32  	"github.com/juliankolbe/go-ethereum/core/rawdb"
    33  	"github.com/juliankolbe/go-ethereum/core/types"
    34  	"github.com/juliankolbe/go-ethereum/core/vm"
    35  	"github.com/juliankolbe/go-ethereum/crypto"
    36  	"github.com/juliankolbe/go-ethereum/ethdb"
    37  	"github.com/juliankolbe/go-ethereum/event"
    38  	"github.com/juliankolbe/go-ethereum/params"
    39  )
    40  
    41  const (
    42  	// testCode is the testing contract binary code which will initialises some
    43  	// variables in constructor
    44  	testCode = "0x60806040527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0060005534801561003457600080fd5b5060fc806100436000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c4dae8814603757806398a213cf146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506084565b005b60005481565b806000819055507fe9e44f9f7da8c559de847a3232b57364adc0354f15a2cd8dc636d54396f9587a6000546040518082815260200191505060405180910390a15056fea265627a7a723058208ae31d9424f2d0bc2a3da1a5dd659db2d71ec322a17db8f87e19e209e3a1ff4a64736f6c634300050a0032"
    45  
    46  	// testGas is the gas required for contract deployment.
    47  	testGas = 144109
    48  )
    49  
    50  var (
    51  	// Test chain configurations
    52  	testTxPoolConfig  core.TxPoolConfig
    53  	ethashChainConfig *params.ChainConfig
    54  	cliqueChainConfig *params.ChainConfig
    55  
    56  	// Test accounts
    57  	testBankKey, _  = crypto.GenerateKey()
    58  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    59  	testBankFunds   = big.NewInt(1000000000000000000)
    60  
    61  	testUserKey, _  = crypto.GenerateKey()
    62  	testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
    63  
    64  	// Test transactions
    65  	pendingTxs []*types.Transaction
    66  	newTxs     []*types.Transaction
    67  
    68  	testConfig = &Config{
    69  		Recommit: time.Second,
    70  		GasFloor: params.GenesisGasLimit,
    71  		GasCeil:  params.GenesisGasLimit,
    72  	}
    73  )
    74  
    75  func init() {
    76  	testTxPoolConfig = core.DefaultTxPoolConfig
    77  	testTxPoolConfig.Journal = ""
    78  	ethashChainConfig = params.TestChainConfig
    79  	cliqueChainConfig = params.TestChainConfig
    80  	cliqueChainConfig.Clique = &params.CliqueConfig{
    81  		Period: 10,
    82  		Epoch:  30000,
    83  	}
    84  
    85  	signer := types.LatestSigner(params.TestChainConfig)
    86  	tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{
    87  		ChainID: params.TestChainConfig.ChainID,
    88  		Nonce:   0,
    89  		To:      &testUserAddress,
    90  		Value:   big.NewInt(1000),
    91  		Gas:     params.TxGas,
    92  	})
    93  	pendingTxs = append(pendingTxs, tx1)
    94  
    95  	tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{
    96  		Nonce: 1,
    97  		To:    &testUserAddress,
    98  		Value: big.NewInt(1000),
    99  		Gas:   params.TxGas,
   100  	})
   101  	newTxs = append(newTxs, tx2)
   102  
   103  	rand.Seed(time.Now().UnixNano())
   104  }
   105  
   106  // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
   107  type testWorkerBackend struct {
   108  	db         ethdb.Database
   109  	txPool     *core.TxPool
   110  	chain      *core.BlockChain
   111  	testTxFeed event.Feed
   112  	genesis    *core.Genesis
   113  	uncleBlock *types.Block
   114  }
   115  
   116  func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
   117  	var gspec = core.Genesis{
   118  		Config: chainConfig,
   119  		Alloc:  core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
   120  	}
   121  
   122  	switch e := engine.(type) {
   123  	case *clique.Clique:
   124  		gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
   125  		copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes())
   126  		e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
   127  			return crypto.Sign(crypto.Keccak256(data), testBankKey)
   128  		})
   129  	case *ethash.Ethash:
   130  	default:
   131  		t.Fatalf("unexpected consensus engine type: %T", engine)
   132  	}
   133  	genesis := gspec.MustCommit(db)
   134  
   135  	chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil)
   136  	txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
   137  
   138  	// Generate a small n-block chain and an uncle block for it
   139  	if n > 0 {
   140  		blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) {
   141  			gen.SetCoinbase(testBankAddress)
   142  		})
   143  		if _, err := chain.InsertChain(blocks); err != nil {
   144  			t.Fatalf("failed to insert origin chain: %v", err)
   145  		}
   146  	}
   147  	parent := genesis
   148  	if n > 0 {
   149  		parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
   150  	}
   151  	blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) {
   152  		gen.SetCoinbase(testUserAddress)
   153  	})
   154  
   155  	return &testWorkerBackend{
   156  		db:         db,
   157  		chain:      chain,
   158  		txPool:     txpool,
   159  		genesis:    &gspec,
   160  		uncleBlock: blocks[0],
   161  	}
   162  }
   163  
   164  func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
   165  func (b *testWorkerBackend) TxPool() *core.TxPool         { return b.txPool }
   166  
   167  func (b *testWorkerBackend) newRandomUncle() *types.Block {
   168  	var parent *types.Block
   169  	cur := b.chain.CurrentBlock()
   170  	if cur.NumberU64() == 0 {
   171  		parent = b.chain.Genesis()
   172  	} else {
   173  		parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
   174  	}
   175  	blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
   176  		var addr = make([]byte, common.AddressLength)
   177  		rand.Read(addr)
   178  		gen.SetCoinbase(common.BytesToAddress(addr))
   179  	})
   180  	return blocks[0]
   181  }
   182  
   183  func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
   184  	var tx *types.Transaction
   185  	if creation {
   186  		tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, nil, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
   187  	} else {
   188  		tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
   189  	}
   190  	return tx
   191  }
   192  
   193  func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
   194  	backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
   195  	backend.txPool.AddLocals(pendingTxs)
   196  	w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
   197  	w.setEtherbase(testBankAddress)
   198  	return w, backend
   199  }
   200  
   201  func TestGenerateBlockAndImportEthash(t *testing.T) {
   202  	testGenerateBlockAndImport(t, false)
   203  }
   204  
   205  func TestGenerateBlockAndImportClique(t *testing.T) {
   206  	testGenerateBlockAndImport(t, true)
   207  }
   208  
   209  func testGenerateBlockAndImport(t *testing.T, isClique bool) {
   210  	var (
   211  		engine      consensus.Engine
   212  		chainConfig *params.ChainConfig
   213  		db          = rawdb.NewMemoryDatabase()
   214  	)
   215  	if isClique {
   216  		chainConfig = params.AllCliqueProtocolChanges
   217  		chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
   218  		engine = clique.New(chainConfig.Clique, db)
   219  	} else {
   220  		chainConfig = params.AllEthashProtocolChanges
   221  		engine = ethash.NewFaker()
   222  	}
   223  
   224  	w, b := newTestWorker(t, chainConfig, engine, db, 0)
   225  	defer w.close()
   226  
   227  	// This test chain imports the mined blocks.
   228  	db2 := rawdb.NewMemoryDatabase()
   229  	b.genesis.MustCommit(db2)
   230  	chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil, nil)
   231  	defer chain.Stop()
   232  
   233  	// Ignore empty commit here for less noise.
   234  	w.skipSealHook = func(task *task) bool {
   235  		return len(task.receipts) == 0
   236  	}
   237  
   238  	// Wait for mined blocks.
   239  	sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
   240  	defer sub.Unsubscribe()
   241  
   242  	// Start mining!
   243  	w.start()
   244  
   245  	for i := 0; i < 5; i++ {
   246  		b.txPool.AddLocal(b.newRandomTx(true))
   247  		b.txPool.AddLocal(b.newRandomTx(false))
   248  		w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
   249  		w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
   250  
   251  		select {
   252  		case ev := <-sub.Chan():
   253  			block := ev.Data.(core.NewMinedBlockEvent).Block
   254  			if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
   255  				t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err)
   256  			}
   257  		case <-time.After(3 * time.Second): // Worker needs 1s to include new changes.
   258  			t.Fatalf("timeout")
   259  		}
   260  	}
   261  }
   262  
   263  func TestEmptyWorkEthash(t *testing.T) {
   264  	testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
   265  }
   266  func TestEmptyWorkClique(t *testing.T) {
   267  	testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   268  }
   269  
   270  func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   271  	defer engine.Close()
   272  
   273  	w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   274  	defer w.close()
   275  
   276  	var (
   277  		taskIndex int
   278  		taskCh    = make(chan struct{}, 2)
   279  	)
   280  	checkEqual := func(t *testing.T, task *task, index int) {
   281  		// The first empty work without any txs included
   282  		receiptLen, balance := 0, big.NewInt(0)
   283  		if index == 1 {
   284  			// The second full work with 1 tx included
   285  			receiptLen, balance = 1, big.NewInt(1000)
   286  		}
   287  		if len(task.receipts) != receiptLen {
   288  			t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
   289  		}
   290  		if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
   291  			t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
   292  		}
   293  	}
   294  	w.newTaskHook = func(task *task) {
   295  		if task.block.NumberU64() == 1 {
   296  			checkEqual(t, task, taskIndex)
   297  			taskIndex += 1
   298  			taskCh <- struct{}{}
   299  		}
   300  	}
   301  	w.skipSealHook = func(task *task) bool { return true }
   302  	w.fullTaskHook = func() {
   303  		time.Sleep(100 * time.Millisecond)
   304  	}
   305  	w.start() // Start mining!
   306  	for i := 0; i < 2; i += 1 {
   307  		select {
   308  		case <-taskCh:
   309  		case <-time.NewTimer(3 * time.Second).C:
   310  			t.Error("new task timeout")
   311  		}
   312  	}
   313  }
   314  
   315  func TestStreamUncleBlock(t *testing.T) {
   316  	ethash := ethash.NewFaker()
   317  	defer ethash.Close()
   318  
   319  	w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
   320  	defer w.close()
   321  
   322  	var taskCh = make(chan struct{})
   323  
   324  	taskIndex := 0
   325  	w.newTaskHook = func(task *task) {
   326  		if task.block.NumberU64() == 2 {
   327  			// The first task is an empty task, the second
   328  			// one has 1 pending tx, the third one has 1 tx
   329  			// and 1 uncle.
   330  			if taskIndex == 2 {
   331  				have := task.block.Header().UncleHash
   332  				want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
   333  				if have != want {
   334  					t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
   335  				}
   336  			}
   337  			taskCh <- struct{}{}
   338  			taskIndex += 1
   339  		}
   340  	}
   341  	w.skipSealHook = func(task *task) bool {
   342  		return true
   343  	}
   344  	w.fullTaskHook = func() {
   345  		time.Sleep(100 * time.Millisecond)
   346  	}
   347  	w.start()
   348  
   349  	for i := 0; i < 2; i += 1 {
   350  		select {
   351  		case <-taskCh:
   352  		case <-time.NewTimer(time.Second).C:
   353  			t.Error("new task timeout")
   354  		}
   355  	}
   356  
   357  	w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
   358  
   359  	select {
   360  	case <-taskCh:
   361  	case <-time.NewTimer(time.Second).C:
   362  		t.Error("new task timeout")
   363  	}
   364  }
   365  
   366  func TestRegenerateMiningBlockEthash(t *testing.T) {
   367  	testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
   368  }
   369  
   370  func TestRegenerateMiningBlockClique(t *testing.T) {
   371  	testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   372  }
   373  
   374  func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   375  	defer engine.Close()
   376  
   377  	w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   378  	defer w.close()
   379  
   380  	var taskCh = make(chan struct{})
   381  
   382  	taskIndex := 0
   383  	w.newTaskHook = func(task *task) {
   384  		if task.block.NumberU64() == 1 {
   385  			// The first task is an empty task, the second
   386  			// one has 1 pending tx, the third one has 2 txs
   387  			if taskIndex == 2 {
   388  				receiptLen, balance := 2, big.NewInt(2000)
   389  				if len(task.receipts) != receiptLen {
   390  					t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
   391  				}
   392  				if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
   393  					t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
   394  				}
   395  			}
   396  			taskCh <- struct{}{}
   397  			taskIndex += 1
   398  		}
   399  	}
   400  	w.skipSealHook = func(task *task) bool {
   401  		return true
   402  	}
   403  	w.fullTaskHook = func() {
   404  		time.Sleep(100 * time.Millisecond)
   405  	}
   406  
   407  	w.start()
   408  	// Ignore the first two works
   409  	for i := 0; i < 2; i += 1 {
   410  		select {
   411  		case <-taskCh:
   412  		case <-time.NewTimer(time.Second).C:
   413  			t.Error("new task timeout")
   414  		}
   415  	}
   416  	b.txPool.AddLocals(newTxs)
   417  	time.Sleep(time.Second)
   418  
   419  	select {
   420  	case <-taskCh:
   421  	case <-time.NewTimer(time.Second).C:
   422  		t.Error("new task timeout")
   423  	}
   424  }
   425  
   426  func TestAdjustIntervalEthash(t *testing.T) {
   427  	testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
   428  }
   429  
   430  func TestAdjustIntervalClique(t *testing.T) {
   431  	testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   432  }
   433  
   434  func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   435  	defer engine.Close()
   436  
   437  	w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   438  	defer w.close()
   439  
   440  	w.skipSealHook = func(task *task) bool {
   441  		return true
   442  	}
   443  	w.fullTaskHook = func() {
   444  		time.Sleep(100 * time.Millisecond)
   445  	}
   446  	var (
   447  		progress = make(chan struct{}, 10)
   448  		result   = make([]float64, 0, 10)
   449  		index    = 0
   450  		start    uint32
   451  	)
   452  	w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
   453  		// Short circuit if interval checking hasn't started.
   454  		if atomic.LoadUint32(&start) == 0 {
   455  			return
   456  		}
   457  		var wantMinInterval, wantRecommitInterval time.Duration
   458  
   459  		switch index {
   460  		case 0:
   461  			wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
   462  		case 1:
   463  			origin := float64(3 * time.Second.Nanoseconds())
   464  			estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
   465  			wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
   466  		case 2:
   467  			estimate := result[index-1]
   468  			min := float64(3 * time.Second.Nanoseconds())
   469  			estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
   470  			wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
   471  		case 3:
   472  			wantMinInterval, wantRecommitInterval = time.Second, time.Second
   473  		}
   474  
   475  		// Check interval
   476  		if minInterval != wantMinInterval {
   477  			t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
   478  		}
   479  		if recommitInterval != wantRecommitInterval {
   480  			t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
   481  		}
   482  		result = append(result, float64(recommitInterval.Nanoseconds()))
   483  		index += 1
   484  		progress <- struct{}{}
   485  	}
   486  	w.start()
   487  
   488  	time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
   489  	atomic.StoreUint32(&start, 1)
   490  
   491  	w.setRecommitInterval(3 * time.Second)
   492  	select {
   493  	case <-progress:
   494  	case <-time.NewTimer(time.Second).C:
   495  		t.Error("interval reset timeout")
   496  	}
   497  
   498  	w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
   499  	select {
   500  	case <-progress:
   501  	case <-time.NewTimer(time.Second).C:
   502  		t.Error("interval reset timeout")
   503  	}
   504  
   505  	w.resubmitAdjustCh <- &intervalAdjust{inc: false}
   506  	select {
   507  	case <-progress:
   508  	case <-time.NewTimer(time.Second).C:
   509  		t.Error("interval reset timeout")
   510  	}
   511  
   512  	w.setRecommitInterval(500 * time.Millisecond)
   513  	select {
   514  	case <-progress:
   515  	case <-time.NewTimer(time.Second).C:
   516  		t.Error("interval reset timeout")
   517  	}
   518  }