worker_test.go 20 KB

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