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