github.com/JFJun/bsc@v1.0.0/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/JFJun/bsc/accounts" 27 "github.com/JFJun/bsc/common" 28 "github.com/JFJun/bsc/consensus" 29 "github.com/JFJun/bsc/consensus/clique" 30 "github.com/JFJun/bsc/consensus/ethash" 31 "github.com/JFJun/bsc/core" 32 "github.com/JFJun/bsc/core/rawdb" 33 "github.com/JFJun/bsc/core/types" 34 "github.com/JFJun/bsc/core/vm" 35 "github.com/JFJun/bsc/crypto" 36 "github.com/JFJun/bsc/ethdb" 37 "github.com/JFJun/bsc/event" 38 "github.com/JFJun/bsc/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 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 = ¶ms.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) 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 // Arch64 unit tests are running in a VM on travis, they must 289 // be given more time to execute. 290 time.Sleep(time.Second) 291 } 292 w.start() // Start mining! 293 for i := 0; i < 2; i += 1 { 294 select { 295 case <-taskCh: 296 case <-time.NewTimer(3 * time.Second).C: 297 t.Error("new task timeout") 298 } 299 } 300 } 301 302 func TestStreamUncleBlock(t *testing.T) { 303 ethash := ethash.NewFaker() 304 defer ethash.Close() 305 306 w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1) 307 defer w.close() 308 309 var taskCh = make(chan struct{}) 310 311 taskIndex := 0 312 w.newTaskHook = func(task *task) { 313 if task.block.NumberU64() == 2 { 314 // The first task is an empty task, the second 315 // one has 1 pending tx, the third one has 1 tx 316 // and 1 uncle. 317 if taskIndex == 2 { 318 have := task.block.Header().UncleHash 319 want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()}) 320 if have != want { 321 t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex()) 322 } 323 } 324 taskCh <- struct{}{} 325 taskIndex += 1 326 } 327 } 328 w.skipSealHook = func(task *task) bool { 329 return true 330 } 331 w.fullTaskHook = func() { 332 time.Sleep(100 * time.Millisecond) 333 } 334 w.start() 335 336 for i := 0; i < 2; i += 1 { 337 select { 338 case <-taskCh: 339 case <-time.NewTimer(time.Second).C: 340 t.Error("new task timeout") 341 } 342 } 343 344 w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock}) 345 346 select { 347 case <-taskCh: 348 case <-time.NewTimer(time.Second).C: 349 t.Error("new task timeout") 350 } 351 } 352 353 func TestRegenerateMiningBlockEthash(t *testing.T) { 354 testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker()) 355 } 356 357 func TestRegenerateMiningBlockClique(t *testing.T) { 358 testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 359 } 360 361 func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 362 defer engine.Close() 363 364 w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 365 defer w.close() 366 367 var taskCh = make(chan struct{}) 368 369 taskIndex := 0 370 w.newTaskHook = func(task *task) { 371 if task.block.NumberU64() == 1 { 372 // The first task is an empty task, the second 373 // one has 1 pending tx, the third one has 2 txs 374 if taskIndex == 2 { 375 receiptLen, balance := 2, big.NewInt(2000) 376 if len(task.receipts) != receiptLen { 377 t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen) 378 } 379 if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 { 380 t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance) 381 } 382 } 383 taskCh <- struct{}{} 384 taskIndex += 1 385 } 386 } 387 w.skipSealHook = func(task *task) bool { 388 return true 389 } 390 w.fullTaskHook = func() { 391 time.Sleep(100 * time.Millisecond) 392 } 393 394 w.start() 395 // Ignore the first two works 396 for i := 0; i < 2; i += 1 { 397 select { 398 case <-taskCh: 399 case <-time.NewTimer(time.Second).C: 400 t.Error("new task timeout") 401 } 402 } 403 b.txPool.AddLocals(newTxs) 404 time.Sleep(time.Second) 405 406 select { 407 case <-taskCh: 408 case <-time.NewTimer(time.Second).C: 409 t.Error("new task timeout") 410 } 411 } 412 413 func TestAdjustIntervalEthash(t *testing.T) { 414 testAdjustInterval(t, ethashChainConfig, ethash.NewFaker()) 415 } 416 417 func TestAdjustIntervalClique(t *testing.T) { 418 testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 419 } 420 421 func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 422 defer engine.Close() 423 424 w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 425 defer w.close() 426 427 w.skipSealHook = func(task *task) bool { 428 return true 429 } 430 w.fullTaskHook = func() { 431 time.Sleep(100 * time.Millisecond) 432 } 433 var ( 434 progress = make(chan struct{}, 10) 435 result = make([]float64, 0, 10) 436 index = 0 437 start uint32 438 ) 439 w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) { 440 // Short circuit if interval checking hasn't started. 441 if atomic.LoadUint32(&start) == 0 { 442 return 443 } 444 var wantMinInterval, wantRecommitInterval time.Duration 445 446 switch index { 447 case 0: 448 wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second 449 case 1: 450 origin := float64(3 * time.Second.Nanoseconds()) 451 estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias) 452 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 453 case 2: 454 estimate := result[index-1] 455 min := float64(3 * time.Second.Nanoseconds()) 456 estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias) 457 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 458 case 3: 459 wantMinInterval, wantRecommitInterval = time.Second, time.Second 460 } 461 462 // Check interval 463 if minInterval != wantMinInterval { 464 t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval) 465 } 466 if recommitInterval != wantRecommitInterval { 467 t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval) 468 } 469 result = append(result, float64(recommitInterval.Nanoseconds())) 470 index += 1 471 progress <- struct{}{} 472 } 473 w.start() 474 475 time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt 476 atomic.StoreUint32(&start, 1) 477 478 w.setRecommitInterval(3 * time.Second) 479 select { 480 case <-progress: 481 case <-time.NewTimer(time.Second).C: 482 t.Error("interval reset timeout") 483 } 484 485 w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8} 486 select { 487 case <-progress: 488 case <-time.NewTimer(time.Second).C: 489 t.Error("interval reset timeout") 490 } 491 492 w.resubmitAdjustCh <- &intervalAdjust{inc: false} 493 select { 494 case <-progress: 495 case <-time.NewTimer(time.Second).C: 496 t.Error("interval reset timeout") 497 } 498 499 w.setRecommitInterval(500 * time.Millisecond) 500 select { 501 case <-progress: 502 case <-time.NewTimer(time.Second).C: 503 t.Error("interval reset timeout") 504 } 505 }