github.com/jimmyx0x/go-ethereum@v1.10.28/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  	"errors"
    21  	"math/big"
    22  	"math/rand"
    23  	"sync/atomic"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/accounts"
    28  	"github.com/ethereum/go-ethereum/common"
    29  	"github.com/ethereum/go-ethereum/consensus"
    30  	"github.com/ethereum/go-ethereum/consensus/clique"
    31  	"github.com/ethereum/go-ethereum/consensus/ethash"
    32  	"github.com/ethereum/go-ethereum/core"
    33  	"github.com/ethereum/go-ethereum/core/rawdb"
    34  	"github.com/ethereum/go-ethereum/core/state"
    35  	"github.com/ethereum/go-ethereum/core/txpool"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/core/vm"
    38  	"github.com/ethereum/go-ethereum/crypto"
    39  	"github.com/ethereum/go-ethereum/ethdb"
    40  	"github.com/ethereum/go-ethereum/event"
    41  	"github.com/ethereum/go-ethereum/params"
    42  )
    43  
    44  const (
    45  	// testCode is the testing contract binary code which will initialises some
    46  	// variables in constructor
    47  	testCode = "0x60806040527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0060005534801561003457600080fd5b5060fc806100436000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c4dae8814603757806398a213cf146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506084565b005b60005481565b806000819055507fe9e44f9f7da8c559de847a3232b57364adc0354f15a2cd8dc636d54396f9587a6000546040518082815260200191505060405180910390a15056fea265627a7a723058208ae31d9424f2d0bc2a3da1a5dd659db2d71ec322a17db8f87e19e209e3a1ff4a64736f6c634300050a0032"
    48  
    49  	// testGas is the gas required for contract deployment.
    50  	testGas = 144109
    51  )
    52  
    53  var (
    54  	// Test chain configurations
    55  	testTxPoolConfig  txpool.Config
    56  	ethashChainConfig *params.ChainConfig
    57  	cliqueChainConfig *params.ChainConfig
    58  
    59  	// Test accounts
    60  	testBankKey, _  = crypto.GenerateKey()
    61  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    62  	testBankFunds   = big.NewInt(1000000000000000000)
    63  
    64  	testUserKey, _  = crypto.GenerateKey()
    65  	testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
    66  
    67  	// Test transactions
    68  	pendingTxs []*types.Transaction
    69  	newTxs     []*types.Transaction
    70  
    71  	testConfig = &Config{
    72  		Recommit: time.Second,
    73  		GasCeil:  params.GenesisGasLimit,
    74  	}
    75  )
    76  
    77  func init() {
    78  	testTxPoolConfig = txpool.DefaultConfig
    79  	testTxPoolConfig.Journal = ""
    80  	ethashChainConfig = new(params.ChainConfig)
    81  	*ethashChainConfig = *params.TestChainConfig
    82  	cliqueChainConfig = new(params.ChainConfig)
    83  	*cliqueChainConfig = *params.TestChainConfig
    84  	cliqueChainConfig.Clique = &params.CliqueConfig{
    85  		Period: 10,
    86  		Epoch:  30000,
    87  	}
    88  
    89  	signer := types.LatestSigner(params.TestChainConfig)
    90  	tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{
    91  		ChainID:  params.TestChainConfig.ChainID,
    92  		Nonce:    0,
    93  		To:       &testUserAddress,
    94  		Value:    big.NewInt(1000),
    95  		Gas:      params.TxGas,
    96  		GasPrice: big.NewInt(params.InitialBaseFee),
    97  	})
    98  	pendingTxs = append(pendingTxs, tx1)
    99  
   100  	tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{
   101  		Nonce:    1,
   102  		To:       &testUserAddress,
   103  		Value:    big.NewInt(1000),
   104  		Gas:      params.TxGas,
   105  		GasPrice: big.NewInt(params.InitialBaseFee),
   106  	})
   107  	newTxs = append(newTxs, tx2)
   108  
   109  	rand.Seed(time.Now().UnixNano())
   110  }
   111  
   112  // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
   113  type testWorkerBackend struct {
   114  	db         ethdb.Database
   115  	txPool     *txpool.TxPool
   116  	chain      *core.BlockChain
   117  	genesis    *core.Genesis
   118  	uncleBlock *types.Block
   119  }
   120  
   121  func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
   122  	var gspec = &core.Genesis{
   123  		Config: chainConfig,
   124  		Alloc:  core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
   125  	}
   126  	switch e := engine.(type) {
   127  	case *clique.Clique:
   128  		gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
   129  		copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes())
   130  		e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
   131  			return crypto.Sign(crypto.Keccak256(data), testBankKey)
   132  		})
   133  	case *ethash.Ethash:
   134  	default:
   135  		t.Fatalf("unexpected consensus engine type: %T", engine)
   136  	}
   137  	chain, err := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec, nil, engine, vm.Config{}, nil, nil)
   138  	if err != nil {
   139  		t.Fatalf("core.NewBlockChain failed: %v", err)
   140  	}
   141  	txpool := txpool.NewTxPool(testTxPoolConfig, chainConfig, chain)
   142  
   143  	// Generate a small n-block chain and an uncle block for it
   144  	var uncle *types.Block
   145  	if n > 0 {
   146  		genDb, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, n, func(i int, gen *core.BlockGen) {
   147  			gen.SetCoinbase(testBankAddress)
   148  		})
   149  		if _, err := chain.InsertChain(blocks); err != nil {
   150  			t.Fatalf("failed to insert origin chain: %v", err)
   151  		}
   152  		parent := chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
   153  		blocks, _ = core.GenerateChain(chainConfig, parent, engine, genDb, 1, func(i int, gen *core.BlockGen) {
   154  			gen.SetCoinbase(testUserAddress)
   155  		})
   156  		uncle = blocks[0]
   157  	} else {
   158  		_, blocks, _ := core.GenerateChainWithGenesis(gspec, engine, 1, func(i int, gen *core.BlockGen) {
   159  			gen.SetCoinbase(testUserAddress)
   160  		})
   161  		uncle = blocks[0]
   162  	}
   163  	return &testWorkerBackend{
   164  		db:         db,
   165  		chain:      chain,
   166  		txPool:     txpool,
   167  		genesis:    gspec,
   168  		uncleBlock: uncle,
   169  	}
   170  }
   171  
   172  func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
   173  func (b *testWorkerBackend) TxPool() *txpool.TxPool       { return b.txPool }
   174  func (b *testWorkerBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
   175  	return nil, errors.New("not supported")
   176  }
   177  
   178  func (b *testWorkerBackend) newRandomUncle() *types.Block {
   179  	var parent *types.Block
   180  	cur := b.chain.CurrentBlock()
   181  	if cur.NumberU64() == 0 {
   182  		parent = b.chain.Genesis()
   183  	} else {
   184  		parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
   185  	}
   186  	blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
   187  		var addr = make([]byte, common.AddressLength)
   188  		rand.Read(addr)
   189  		gen.SetCoinbase(common.BytesToAddress(addr))
   190  	})
   191  	return blocks[0]
   192  }
   193  
   194  func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
   195  	var tx *types.Transaction
   196  	gasPrice := big.NewInt(10 * params.InitialBaseFee)
   197  	if creation {
   198  		tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
   199  	} else {
   200  		tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey)
   201  	}
   202  	return tx
   203  }
   204  
   205  func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
   206  	backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
   207  	backend.txPool.AddLocals(pendingTxs)
   208  	w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
   209  	w.setEtherbase(testBankAddress)
   210  	return w, backend
   211  }
   212  
   213  func TestGenerateBlockAndImportEthash(t *testing.T) {
   214  	testGenerateBlockAndImport(t, false)
   215  }
   216  
   217  func TestGenerateBlockAndImportClique(t *testing.T) {
   218  	testGenerateBlockAndImport(t, true)
   219  }
   220  
   221  func testGenerateBlockAndImport(t *testing.T, isClique bool) {
   222  	var (
   223  		engine      consensus.Engine
   224  		chainConfig params.ChainConfig
   225  		db          = rawdb.NewMemoryDatabase()
   226  	)
   227  	if isClique {
   228  		chainConfig = *params.AllCliqueProtocolChanges
   229  		chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
   230  		engine = clique.New(chainConfig.Clique, db)
   231  	} else {
   232  		chainConfig = *params.AllEthashProtocolChanges
   233  		engine = ethash.NewFaker()
   234  	}
   235  	w, b := newTestWorker(t, &chainConfig, engine, db, 0)
   236  	defer w.close()
   237  
   238  	// This test chain imports the mined blocks.
   239  	chain, _ := core.NewBlockChain(rawdb.NewMemoryDatabase(), nil, b.genesis, nil, engine, vm.Config{}, nil, nil)
   240  	defer chain.Stop()
   241  
   242  	// Ignore empty commit here for less noise.
   243  	w.skipSealHook = func(task *task) bool {
   244  		return len(task.receipts) == 0
   245  	}
   246  
   247  	// Wait for mined blocks.
   248  	sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
   249  	defer sub.Unsubscribe()
   250  
   251  	// Start mining!
   252  	w.start()
   253  
   254  	for i := 0; i < 5; i++ {
   255  		b.txPool.AddLocal(b.newRandomTx(true))
   256  		b.txPool.AddLocal(b.newRandomTx(false))
   257  		w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
   258  		w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
   259  
   260  		select {
   261  		case ev := <-sub.Chan():
   262  			block := ev.Data.(core.NewMinedBlockEvent).Block
   263  			if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
   264  				t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err)
   265  			}
   266  		case <-time.After(3 * time.Second): // Worker needs 1s to include new changes.
   267  			t.Fatalf("timeout")
   268  		}
   269  	}
   270  }
   271  
   272  func TestEmptyWorkEthash(t *testing.T) {
   273  	testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
   274  }
   275  func TestEmptyWorkClique(t *testing.T) {
   276  	testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   277  }
   278  
   279  func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   280  	defer engine.Close()
   281  
   282  	w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   283  	defer w.close()
   284  
   285  	var (
   286  		taskIndex int
   287  		taskCh    = make(chan struct{}, 2)
   288  	)
   289  	checkEqual := func(t *testing.T, task *task, index int) {
   290  		// The first empty work without any txs included
   291  		receiptLen, balance := 0, big.NewInt(0)
   292  		if index == 1 {
   293  			// The second full work with 1 tx included
   294  			receiptLen, balance = 1, big.NewInt(1000)
   295  		}
   296  		if len(task.receipts) != receiptLen {
   297  			t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
   298  		}
   299  		if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
   300  			t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
   301  		}
   302  	}
   303  	w.newTaskHook = func(task *task) {
   304  		if task.block.NumberU64() == 1 {
   305  			checkEqual(t, task, taskIndex)
   306  			taskIndex += 1
   307  			taskCh <- struct{}{}
   308  		}
   309  	}
   310  	w.skipSealHook = func(task *task) bool { return true }
   311  	w.fullTaskHook = func() {
   312  		time.Sleep(100 * time.Millisecond)
   313  	}
   314  	w.start() // Start mining!
   315  	for i := 0; i < 2; i += 1 {
   316  		select {
   317  		case <-taskCh:
   318  		case <-time.NewTimer(3 * time.Second).C:
   319  			t.Error("new task timeout")
   320  		}
   321  	}
   322  }
   323  
   324  func TestStreamUncleBlock(t *testing.T) {
   325  	ethash := ethash.NewFaker()
   326  	defer ethash.Close()
   327  
   328  	w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
   329  	defer w.close()
   330  
   331  	var taskCh = make(chan struct{}, 3)
   332  
   333  	taskIndex := 0
   334  	w.newTaskHook = func(task *task) {
   335  		if task.block.NumberU64() == 2 {
   336  			// The first task is an empty task, the second
   337  			// one has 1 pending tx, the third one has 1 tx
   338  			// and 1 uncle.
   339  			if taskIndex == 2 {
   340  				have := task.block.Header().UncleHash
   341  				want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
   342  				if have != want {
   343  					t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
   344  				}
   345  			}
   346  			taskCh <- struct{}{}
   347  			taskIndex += 1
   348  		}
   349  	}
   350  	w.skipSealHook = func(task *task) bool {
   351  		return true
   352  	}
   353  	w.fullTaskHook = func() {
   354  		time.Sleep(100 * time.Millisecond)
   355  	}
   356  	w.start()
   357  
   358  	for i := 0; i < 2; i += 1 {
   359  		select {
   360  		case <-taskCh:
   361  		case <-time.NewTimer(time.Second).C:
   362  			t.Error("new task timeout")
   363  		}
   364  	}
   365  
   366  	w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
   367  
   368  	select {
   369  	case <-taskCh:
   370  	case <-time.NewTimer(time.Second).C:
   371  		t.Error("new task timeout")
   372  	}
   373  }
   374  
   375  func TestRegenerateMiningBlockEthash(t *testing.T) {
   376  	testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
   377  }
   378  
   379  func TestRegenerateMiningBlockClique(t *testing.T) {
   380  	testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   381  }
   382  
   383  func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   384  	defer engine.Close()
   385  
   386  	w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   387  	defer w.close()
   388  
   389  	var taskCh = make(chan struct{}, 3)
   390  
   391  	taskIndex := 0
   392  	w.newTaskHook = func(task *task) {
   393  		if task.block.NumberU64() == 1 {
   394  			// The first task is an empty task, the second
   395  			// one has 1 pending tx, the third one has 2 txs
   396  			if taskIndex == 2 {
   397  				receiptLen, balance := 2, big.NewInt(2000)
   398  				if len(task.receipts) != receiptLen {
   399  					t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
   400  				}
   401  				if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
   402  					t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
   403  				}
   404  			}
   405  			taskCh <- struct{}{}
   406  			taskIndex += 1
   407  		}
   408  	}
   409  	w.skipSealHook = func(task *task) bool {
   410  		return true
   411  	}
   412  	w.fullTaskHook = func() {
   413  		time.Sleep(100 * time.Millisecond)
   414  	}
   415  
   416  	w.start()
   417  	// Ignore the first two works
   418  	for i := 0; i < 2; i += 1 {
   419  		select {
   420  		case <-taskCh:
   421  		case <-time.NewTimer(time.Second).C:
   422  			t.Error("new task timeout")
   423  		}
   424  	}
   425  	b.txPool.AddLocals(newTxs)
   426  	time.Sleep(time.Second)
   427  
   428  	select {
   429  	case <-taskCh:
   430  	case <-time.NewTimer(time.Second).C:
   431  		t.Error("new task timeout")
   432  	}
   433  }
   434  
   435  func TestAdjustIntervalEthash(t *testing.T) {
   436  	testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
   437  }
   438  
   439  func TestAdjustIntervalClique(t *testing.T) {
   440  	testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   441  }
   442  
   443  func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   444  	defer engine.Close()
   445  
   446  	w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   447  	defer w.close()
   448  
   449  	w.skipSealHook = func(task *task) bool {
   450  		return true
   451  	}
   452  	w.fullTaskHook = func() {
   453  		time.Sleep(100 * time.Millisecond)
   454  	}
   455  	var (
   456  		progress = make(chan struct{}, 10)
   457  		result   = make([]float64, 0, 10)
   458  		index    = 0
   459  		start    uint32
   460  	)
   461  	w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
   462  		// Short circuit if interval checking hasn't started.
   463  		if atomic.LoadUint32(&start) == 0 {
   464  			return
   465  		}
   466  		var wantMinInterval, wantRecommitInterval time.Duration
   467  
   468  		switch index {
   469  		case 0:
   470  			wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
   471  		case 1:
   472  			origin := float64(3 * time.Second.Nanoseconds())
   473  			estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
   474  			wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
   475  		case 2:
   476  			estimate := result[index-1]
   477  			min := float64(3 * time.Second.Nanoseconds())
   478  			estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
   479  			wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
   480  		case 3:
   481  			wantMinInterval, wantRecommitInterval = time.Second, time.Second
   482  		}
   483  
   484  		// Check interval
   485  		if minInterval != wantMinInterval {
   486  			t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
   487  		}
   488  		if recommitInterval != wantRecommitInterval {
   489  			t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
   490  		}
   491  		result = append(result, float64(recommitInterval.Nanoseconds()))
   492  		index += 1
   493  		progress <- struct{}{}
   494  	}
   495  	w.start()
   496  
   497  	time.Sleep(time.Second) // Ensure two tasks have been submitted due to start opt
   498  	atomic.StoreUint32(&start, 1)
   499  
   500  	w.setRecommitInterval(3 * time.Second)
   501  	select {
   502  	case <-progress:
   503  	case <-time.NewTimer(time.Second).C:
   504  		t.Error("interval reset timeout")
   505  	}
   506  
   507  	w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
   508  	select {
   509  	case <-progress:
   510  	case <-time.NewTimer(time.Second).C:
   511  		t.Error("interval reset timeout")
   512  	}
   513  
   514  	w.resubmitAdjustCh <- &intervalAdjust{inc: false}
   515  	select {
   516  	case <-progress:
   517  	case <-time.NewTimer(time.Second).C:
   518  		t.Error("interval reset timeout")
   519  	}
   520  
   521  	w.setRecommitInterval(500 * time.Millisecond)
   522  	select {
   523  	case <-progress:
   524  	case <-time.NewTimer(time.Second).C:
   525  		t.Error("interval reset timeout")
   526  	}
   527  }
   528  
   529  func TestGetSealingWorkEthash(t *testing.T) {
   530  	testGetSealingWork(t, ethashChainConfig, ethash.NewFaker())
   531  }
   532  
   533  func TestGetSealingWorkClique(t *testing.T) {
   534  	testGetSealingWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
   535  }
   536  
   537  func TestGetSealingWorkPostMerge(t *testing.T) {
   538  	local := new(params.ChainConfig)
   539  	*local = *ethashChainConfig
   540  	local.TerminalTotalDifficulty = big.NewInt(0)
   541  	testGetSealingWork(t, local, ethash.NewFaker())
   542  }
   543  
   544  func testGetSealingWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
   545  	defer engine.Close()
   546  
   547  	w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
   548  	defer w.close()
   549  
   550  	w.setExtra([]byte{0x01, 0x02})
   551  	w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
   552  
   553  	w.skipSealHook = func(task *task) bool {
   554  		return true
   555  	}
   556  	w.fullTaskHook = func() {
   557  		time.Sleep(100 * time.Millisecond)
   558  	}
   559  	timestamp := uint64(time.Now().Unix())
   560  	assertBlock := func(block *types.Block, number uint64, coinbase common.Address, random common.Hash) {
   561  		if block.Time() != timestamp {
   562  			// Sometime the timestamp will be mutated if the timestamp
   563  			// is even smaller than parent block's. It's OK.
   564  			t.Logf("Invalid timestamp, want %d, get %d", timestamp, block.Time())
   565  		}
   566  		if len(block.Uncles()) != 0 {
   567  			t.Error("Unexpected uncle block")
   568  		}
   569  		_, isClique := engine.(*clique.Clique)
   570  		if !isClique {
   571  			if len(block.Extra()) != 2 {
   572  				t.Error("Unexpected extra field")
   573  			}
   574  			if block.Coinbase() != coinbase {
   575  				t.Errorf("Unexpected coinbase got %x want %x", block.Coinbase(), coinbase)
   576  			}
   577  		} else {
   578  			if block.Coinbase() != (common.Address{}) {
   579  				t.Error("Unexpected coinbase")
   580  			}
   581  		}
   582  		if !isClique {
   583  			if block.MixDigest() != random {
   584  				t.Error("Unexpected mix digest")
   585  			}
   586  		}
   587  		if block.Nonce() != 0 {
   588  			t.Error("Unexpected block nonce")
   589  		}
   590  		if block.NumberU64() != number {
   591  			t.Errorf("Mismatched block number, want %d got %d", number, block.NumberU64())
   592  		}
   593  	}
   594  	var cases = []struct {
   595  		parent       common.Hash
   596  		coinbase     common.Address
   597  		random       common.Hash
   598  		expectNumber uint64
   599  		expectErr    bool
   600  	}{
   601  		{
   602  			b.chain.Genesis().Hash(),
   603  			common.HexToAddress("0xdeadbeef"),
   604  			common.HexToHash("0xcafebabe"),
   605  			uint64(1),
   606  			false,
   607  		},
   608  		{
   609  			b.chain.CurrentBlock().Hash(),
   610  			common.HexToAddress("0xdeadbeef"),
   611  			common.HexToHash("0xcafebabe"),
   612  			b.chain.CurrentBlock().NumberU64() + 1,
   613  			false,
   614  		},
   615  		{
   616  			b.chain.CurrentBlock().Hash(),
   617  			common.Address{},
   618  			common.HexToHash("0xcafebabe"),
   619  			b.chain.CurrentBlock().NumberU64() + 1,
   620  			false,
   621  		},
   622  		{
   623  			b.chain.CurrentBlock().Hash(),
   624  			common.Address{},
   625  			common.Hash{},
   626  			b.chain.CurrentBlock().NumberU64() + 1,
   627  			false,
   628  		},
   629  		{
   630  			common.HexToHash("0xdeadbeef"),
   631  			common.HexToAddress("0xdeadbeef"),
   632  			common.HexToHash("0xcafebabe"),
   633  			0,
   634  			true,
   635  		},
   636  	}
   637  
   638  	// This API should work even when the automatic sealing is not enabled
   639  	for _, c := range cases {
   640  		block, _, err := w.getSealingBlock(c.parent, timestamp, c.coinbase, c.random, false)
   641  		if c.expectErr {
   642  			if err == nil {
   643  				t.Error("Expect error but get nil")
   644  			}
   645  		} else {
   646  			if err != nil {
   647  				t.Errorf("Unexpected error %v", err)
   648  			}
   649  			assertBlock(block, c.expectNumber, c.coinbase, c.random)
   650  		}
   651  	}
   652  
   653  	// This API should work even when the automatic sealing is enabled
   654  	w.start()
   655  	for _, c := range cases {
   656  		block, _, err := w.getSealingBlock(c.parent, timestamp, c.coinbase, c.random, false)
   657  		if c.expectErr {
   658  			if err == nil {
   659  				t.Error("Expect error but get nil")
   660  			}
   661  		} else {
   662  			if err != nil {
   663  				t.Errorf("Unexpected error %v", err)
   664  			}
   665  			assertBlock(block, c.expectNumber, c.coinbase, c.random)
   666  		}
   667  	}
   668  }