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