github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/miner/worker_test.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package miner 19 20 import ( 21 "math/big" 22 "math/rand" 23 "testing" 24 "time" 25 26 "github.com/AigarNetwork/aigar/accounts" 27 "github.com/AigarNetwork/aigar/common" 28 "github.com/AigarNetwork/aigar/consensus" 29 "github.com/AigarNetwork/aigar/consensus/clique" 30 "github.com/AigarNetwork/aigar/consensus/ethash" 31 "github.com/AigarNetwork/aigar/core" 32 "github.com/AigarNetwork/aigar/core/rawdb" 33 "github.com/AigarNetwork/aigar/core/types" 34 "github.com/AigarNetwork/aigar/core/vm" 35 "github.com/AigarNetwork/aigar/crypto" 36 "github.com/AigarNetwork/aigar/ethdb" 37 "github.com/AigarNetwork/aigar/event" 38 "github.com/AigarNetwork/aigar/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 = ¶ms.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) 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 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 // Aarch64 unit tests are running in a VM on travis, they must 345 // be given more time to execute. 346 time.Sleep(time.Second) 347 } 348 349 // Ensure worker has finished initialization 350 for { 351 b := w.pendingBlock() 352 if b != nil && b.NumberU64() == 1 { 353 break 354 } 355 } 356 357 w.start() 358 for i := 0; i < 2; i += 1 { 359 select { 360 case <-taskCh: 361 case <-time.NewTimer(30 * time.Second).C: 362 t.Error("new task timeout") 363 } 364 } 365 } 366 367 func TestStreamUncleBlock(t *testing.T) { 368 ethash := ethash.NewFaker() 369 defer ethash.Close() 370 371 w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1) 372 defer w.close() 373 374 var taskCh = make(chan struct{}) 375 376 taskIndex := 0 377 w.newTaskHook = func(task *task) { 378 if task.block.NumberU64() == 2 { 379 if taskIndex == 2 { 380 have := task.block.Header().UncleHash 381 want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()}) 382 if have != want { 383 t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex()) 384 } 385 } 386 taskCh <- struct{}{} 387 taskIndex += 1 388 } 389 } 390 w.skipSealHook = func(task *task) bool { 391 return true 392 } 393 w.fullTaskHook = func() { 394 time.Sleep(100 * time.Millisecond) 395 } 396 397 // Ensure worker has finished initialization 398 for { 399 b := w.pendingBlock() 400 if b != nil && b.NumberU64() == 2 { 401 break 402 } 403 } 404 w.start() 405 406 // Ignore the first two works 407 for i := 0; i < 2; i += 1 { 408 select { 409 case <-taskCh: 410 case <-time.NewTimer(time.Second).C: 411 t.Error("new task timeout") 412 } 413 } 414 b.PostChainEvents([]interface{}{core.ChainSideEvent{Block: b.uncleBlock}}) 415 416 select { 417 case <-taskCh: 418 case <-time.NewTimer(time.Second).C: 419 t.Error("new task timeout") 420 } 421 } 422 423 func TestRegenerateMiningBlockEthash(t *testing.T) { 424 testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker()) 425 } 426 427 func TestRegenerateMiningBlockClique(t *testing.T) { 428 testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 429 } 430 431 func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 432 defer engine.Close() 433 434 w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 435 defer w.close() 436 437 var taskCh = make(chan struct{}) 438 439 taskIndex := 0 440 w.newTaskHook = func(task *task) { 441 if task.block.NumberU64() == 1 { 442 if taskIndex == 2 { 443 receiptLen, balance := 2, big.NewInt(2000) 444 if len(task.receipts) != receiptLen { 445 t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen) 446 } 447 if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 { 448 t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance) 449 } 450 } 451 taskCh <- struct{}{} 452 taskIndex += 1 453 } 454 } 455 w.skipSealHook = func(task *task) bool { 456 return true 457 } 458 w.fullTaskHook = func() { 459 time.Sleep(100 * time.Millisecond) 460 } 461 // Ensure worker has finished initialization 462 for { 463 b := w.pendingBlock() 464 if b != nil && b.NumberU64() == 1 { 465 break 466 } 467 } 468 469 w.start() 470 // Ignore the first two works 471 for i := 0; i < 2; i += 1 { 472 select { 473 case <-taskCh: 474 case <-time.NewTimer(time.Second).C: 475 t.Error("new task timeout") 476 } 477 } 478 b.txPool.AddLocals(newTxs) 479 time.Sleep(time.Second) 480 481 select { 482 case <-taskCh: 483 case <-time.NewTimer(time.Second).C: 484 t.Error("new task timeout") 485 } 486 } 487 488 func TestAdjustIntervalEthash(t *testing.T) { 489 testAdjustInterval(t, ethashChainConfig, ethash.NewFaker()) 490 } 491 492 func TestAdjustIntervalClique(t *testing.T) { 493 testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 494 } 495 496 func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 497 defer engine.Close() 498 499 w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 500 defer w.close() 501 502 w.skipSealHook = func(task *task) bool { 503 return true 504 } 505 w.fullTaskHook = func() { 506 time.Sleep(100 * time.Millisecond) 507 } 508 var ( 509 progress = make(chan struct{}, 10) 510 result = make([]float64, 0, 10) 511 index = 0 512 start = false 513 ) 514 w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) { 515 // Short circuit if interval checking hasn't started. 516 if !start { 517 return 518 } 519 var wantMinInterval, wantRecommitInterval time.Duration 520 521 switch index { 522 case 0: 523 wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second 524 case 1: 525 origin := float64(3 * time.Second.Nanoseconds()) 526 estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias) 527 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 528 case 2: 529 estimate := result[index-1] 530 min := float64(3 * time.Second.Nanoseconds()) 531 estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias) 532 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 533 case 3: 534 wantMinInterval, wantRecommitInterval = time.Second, time.Second 535 } 536 537 // Check interval 538 if minInterval != wantMinInterval { 539 t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval) 540 } 541 if recommitInterval != wantRecommitInterval { 542 t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval) 543 } 544 result = append(result, float64(recommitInterval.Nanoseconds())) 545 index += 1 546 progress <- struct{}{} 547 } 548 // Ensure worker has finished initialization 549 for { 550 b := w.pendingBlock() 551 if b != nil && b.NumberU64() == 1 { 552 break 553 } 554 } 555 556 w.start() 557 558 time.Sleep(time.Second) 559 560 start = true 561 w.setRecommitInterval(3 * time.Second) 562 select { 563 case <-progress: 564 case <-time.NewTimer(time.Second).C: 565 t.Error("interval reset timeout") 566 } 567 568 w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8} 569 select { 570 case <-progress: 571 case <-time.NewTimer(time.Second).C: 572 t.Error("interval reset timeout") 573 } 574 575 w.resubmitAdjustCh <- &intervalAdjust{inc: false} 576 select { 577 case <-progress: 578 case <-time.NewTimer(time.Second).C: 579 t.Error("interval reset timeout") 580 } 581 582 w.setRecommitInterval(500 * time.Millisecond) 583 select { 584 case <-progress: 585 case <-time.NewTimer(time.Second).C: 586 t.Error("interval reset timeout") 587 } 588 }