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