github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/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/ethw3/go-ethereuma/accounts"
    28  	"github.com/ethw3/go-ethereuma/common"
    29  	"github.com/ethw3/go-ethereuma/consensus"
    30  	"github.com/ethw3/go-ethereuma/consensus/clique"
    31  	"github.com/ethw3/go-ethereuma/consensus/ethash"
    32  	"github.com/ethw3/go-ethereuma/core"
    33  	"github.com/ethw3/go-ethereuma/core/rawdb"
    34  	"github.com/ethw3/go-ethereuma/core/state"
    35  	"github.com/ethw3/go-ethereuma/core/types"
    36  	"github.com/ethw3/go-ethereuma/core/vm"
    37  	"github.com/ethw3/go-ethereuma/crypto"
    38  	"github.com/ethw3/go-ethereuma/ethdb"
    39  	"github.com/ethw3/go-ethereuma/event"
    40  	"github.com/ethw3/go-ethereuma/params"
    41  )
    42  
    43  const (
    44  	// testCode is the testing contract binary code which will initialises some
    45  	// variables in constructor
    46  	testCode = "0x60806040527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0060005534801561003457600080fd5b5060fc806100436000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c4dae8814603757806398a213cf146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506084565b005b60005481565b806000819055507fe9e44f9f7da8c559de847a3232b57364adc0354f15a2cd8dc636d54396f9587a6000546040518082815260200191505060405180910390a15056fea265627a7a723058208ae31d9424f2d0bc2a3da1a5dd659db2d71ec322a17db8f87e19e209e3a1ff4a64736f6c634300050a0032"
    47  
    48  	// testGas is the gas required for contract deployment.
    49  	testGas = 144109
    50  )
    51  
    52  var (
    53  	// Test chain configurations
    54  	testTxPoolConfig  core.TxPoolConfig
    55  	ethashChainConfig *params.ChainConfig
    56  	cliqueChainConfig *params.ChainConfig
    57  
    58  	// Test accounts
    59  	testBankKey, _  = crypto.GenerateKey()
    60  	testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
    61  	testBankFunds   = big.NewInt(1000000000000000000)
    62  
    63  	testUserKey, _  = crypto.GenerateKey()
    64  	testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
    65  
    66  	// Test transactions
    67  	pendingTxs []*types.Transaction
    68  	newTxs     []*types.Transaction
    69  
    70  	testConfig = &Config{
    71  		Recommit: time.Second,
    72  		GasCeil:  params.GenesisGasLimit,
    73  	}
    74  )
    75  
    76  func init() {
    77  	testTxPoolConfig = core.DefaultTxPoolConfig
    78  	testTxPoolConfig.Journal = ""
    79  	ethashChainConfig = new(params.ChainConfig)
    80  	*ethashChainConfig = *params.TestChainConfig
    81  	cliqueChainConfig = new(params.ChainConfig)
    82  	*cliqueChainConfig = *params.TestChainConfig
    83  	cliqueChainConfig.Clique = &params.CliqueConfig{
    84  		Period: 10,
    85  		Epoch:  30000,
    86  	}
    87  
    88  	signer := types.LatestSigner(params.TestChainConfig)
    89  	tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{
    90  		ChainID:  params.TestChainConfig.ChainID,
    91  		Nonce:    0,
    92  		To:       &testUserAddress,
    93  		Value:    big.NewInt(1000),
    94  		Gas:      params.TxGas,
    95  		GasPrice: big.NewInt(params.InitialBaseFee),
    96  	})
    97  	pendingTxs = append(pendingTxs, tx1)
    98  
    99  	tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{
   100  		Nonce:    1,
   101  		To:       &testUserAddress,
   102  		Value:    big.NewInt(1000),
   103  		Gas:      params.TxGas,
   104  		GasPrice: big.NewInt(params.InitialBaseFee),
   105  	})
   106  	newTxs = append(newTxs, tx2)
   107  
   108  	rand.Seed(time.Now().UnixNano())
   109  }
   110  
   111  // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
   112  type testWorkerBackend struct {
   113  	db         ethdb.Database
   114  	txPool     *core.TxPool
   115  	chain      *core.BlockChain
   116  	genesis    *core.Genesis
   117  	uncleBlock *types.Block
   118  }
   119  
   120  func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
   121  	var gspec = core.Genesis{
   122  		Config: chainConfig,
   123  		Alloc:  core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
   124  	}
   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  	genesis := gspec.MustCommit(db)
   138  
   139  	chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil)
   140  	txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
   141  
   142  	// Generate a small n-block chain and an uncle block for it
   143  	if n > 0 {
   144  		blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) {
   145  			gen.SetCoinbase(testBankAddress)
   146  		})
   147  		if _, err := chain.InsertChain(blocks); err != nil {
   148  			t.Fatalf("failed to insert origin chain: %v", err)
   149  		}
   150  	}
   151  	parent := genesis
   152  	if n > 0 {
   153  		parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
   154  	}
   155  	blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) {
   156  		gen.SetCoinbase(testUserAddress)
   157  	})
   158  
   159  	return &testWorkerBackend{
   160  		db:         db,
   161  		chain:      chain,
   162  		txPool:     txpool,
   163  		genesis:    &gspec,
   164  		uncleBlock: blocks[0],
   165  	}
   166  }
   167  
   168  func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
   169  func (b *testWorkerBackend) TxPool() *core.TxPool         { return b.txPool }
   170  func (b *testWorkerBackend) StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error) {
   171  	return nil, errors.New("not supported")
   172  }
   173  
   174  func (b *testWorkerBackend) newRandomUncle() *types.Block {
   175  	var parent *types.Block
   176  	cur := b.chain.CurrentBlock()
   177  	if cur.NumberU64() == 0 {
   178  		parent = b.chain.Genesis()
   179  	} else {
   180  		parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
   181  	}
   182  	blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
   183  		var addr = make([]byte, common.AddressLength)
   184  		rand.Read(addr)
   185  		gen.SetCoinbase(common.BytesToAddress(addr))
   186  	})
   187  	return blocks[0]
   188  }
   189  
   190  func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
   191  	var tx *types.Transaction
   192  	gasPrice := big.NewInt(10 * params.InitialBaseFee)
   193  	if creation {
   194  		tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
   195  	} else {
   196  		tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey)
   197  	}
   198  	return tx
   199  }
   200  
   201  func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
   202  	backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
   203  	backend.txPool.AddLocals(pendingTxs)
   204  	w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
   205  	w.setEtherbase(testBankAddress)
   206  	return w, backend
   207  }
   208  
   209  func TestGenerateBlockAndImportEthash(t *testing.T) {
   210  	testGenerateBlockAndImport(t, false)
   211  }
   212  
   213  func TestGenerateBlockAndImportClique(t *testing.T) {
   214  	testGenerateBlockAndImport(t, true)
   215  }
   216  
   217  func testGenerateBlockAndImport(t *testing.T, isClique bool) {
   218  	var (
   219  		engine      consensus.Engine
   220  		chainConfig *params.ChainConfig
   221  		db          = rawdb.NewMemoryDatabase()
   222  	)
   223  	if isClique {
   224  		chainConfig = params.AllCliqueProtocolChanges
   225  		chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
   226  		engine = clique.New(chainConfig.Clique, db)
   227  	} else {
   228  		chainConfig = params.AllEthashProtocolChanges
   229  		engine = ethash.NewFaker()
   230  	}
   231  
   232  	chainConfig.LondonBlock = big.NewInt(0)
   233  	w, b := newTestWorker(t, chainConfig, engine, db, 0)
   234  	defer w.close()
   235  
   236  	// This test chain imports the mined blocks.
   237  	db2 := rawdb.NewMemoryDatabase()
   238  	b.genesis.MustCommit(db2)
   239  	chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), 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{})
   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(), false)
   531  }
   532  
   533  func TestGetSealingWorkClique(t *testing.T) {
   534  	testGetSealingWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()), false)
   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(), true)
   542  }
   543  
   544  func testGetSealingWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, postMerge bool) {
   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()) != 0 {
   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  		resChan, errChan, _ := w.getSealingBlock(c.parent, timestamp, c.coinbase, c.random, false)
   641  		block := <-resChan
   642  		err := <-errChan
   643  		if c.expectErr {
   644  			if err == nil {
   645  				t.Error("Expect error but get nil")
   646  			}
   647  		} else {
   648  			if err != nil {
   649  				t.Errorf("Unexpected error %v", err)
   650  			}
   651  			assertBlock(block, c.expectNumber, c.coinbase, c.random)
   652  		}
   653  	}
   654  
   655  	// This API should work even when the automatic sealing is enabled
   656  	w.start()
   657  	for _, c := range cases {
   658  		resChan, errChan, _ := w.getSealingBlock(c.parent, timestamp, c.coinbase, c.random, false)
   659  		block := <-resChan
   660  		err := <-errChan
   661  		if c.expectErr {
   662  			if err == nil {
   663  				t.Error("Expect error but get nil")
   664  			}
   665  		} else {
   666  			if err != nil {
   667  				t.Errorf("Unexpected error %v", err)
   668  			}
   669  			assertBlock(block, c.expectNumber, c.coinbase, c.random)
   670  		}
   671  	}
   672  }