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