github.com/phillinzzz/newBsc@v1.1.6/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/phillinzzz/newBsc/accounts" 27 "github.com/phillinzzz/newBsc/common" 28 "github.com/phillinzzz/newBsc/consensus" 29 "github.com/phillinzzz/newBsc/consensus/clique" 30 "github.com/phillinzzz/newBsc/consensus/ethash" 31 "github.com/phillinzzz/newBsc/core" 32 "github.com/phillinzzz/newBsc/core/rawdb" 33 "github.com/phillinzzz/newBsc/core/types" 34 "github.com/phillinzzz/newBsc/core/vm" 35 "github.com/phillinzzz/newBsc/crypto" 36 "github.com/phillinzzz/newBsc/ethdb" 37 "github.com/phillinzzz/newBsc/event" 38 "github.com/phillinzzz/newBsc/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 85 signer := types.LatestSigner(params.TestChainConfig) 86 tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{ 87 ChainID: params.TestChainConfig.ChainID, 88 Nonce: 0, 89 To: &testUserAddress, 90 Value: big.NewInt(1000), 91 Gas: params.TxGas, 92 }) 93 pendingTxs = append(pendingTxs, tx1) 94 95 tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{ 96 Nonce: 1, 97 To: &testUserAddress, 98 Value: big.NewInt(1000), 99 Gas: params.TxGas, 100 }) 101 newTxs = append(newTxs, tx2) 102 103 rand.Seed(time.Now().UnixNano()) 104 } 105 106 // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing. 107 type testWorkerBackend struct { 108 db ethdb.Database 109 txPool *core.TxPool 110 chain *core.BlockChain 111 testTxFeed event.Feed 112 genesis *core.Genesis 113 uncleBlock *types.Block 114 } 115 116 func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend { 117 var gspec = core.Genesis{ 118 Config: chainConfig, 119 Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, 120 } 121 122 switch e := engine.(type) { 123 case *clique.Clique: 124 gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength) 125 copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes()) 126 e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) { 127 return crypto.Sign(crypto.Keccak256(data), testBankKey) 128 }) 129 case *ethash.Ethash: 130 default: 131 t.Fatalf("unexpected consensus engine type: %T", engine) 132 } 133 genesis := gspec.MustCommit(db) 134 135 chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil) 136 txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain) 137 138 // Generate a small n-block chain and an uncle block for it 139 if n > 0 { 140 blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) { 141 gen.SetCoinbase(testBankAddress) 142 }) 143 if _, err := chain.InsertChain(blocks); err != nil { 144 t.Fatalf("failed to insert origin chain: %v", err) 145 } 146 } 147 parent := genesis 148 if n > 0 { 149 parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash()) 150 } 151 blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) { 152 gen.SetCoinbase(testUserAddress) 153 }) 154 155 return &testWorkerBackend{ 156 db: db, 157 chain: chain, 158 txPool: txpool, 159 genesis: &gspec, 160 uncleBlock: blocks[0], 161 } 162 } 163 164 func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain } 165 func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool } 166 167 func (b *testWorkerBackend) newRandomUncle() *types.Block { 168 var parent *types.Block 169 cur := b.chain.CurrentBlock() 170 if cur.NumberU64() == 0 { 171 parent = b.chain.Genesis() 172 } else { 173 parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash()) 174 } 175 blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) { 176 var addr = make([]byte, common.AddressLength) 177 rand.Read(addr) 178 gen.SetCoinbase(common.BytesToAddress(addr)) 179 }) 180 return blocks[0] 181 } 182 183 func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction { 184 var tx *types.Transaction 185 if creation { 186 tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, nil, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey) 187 } else { 188 tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey) 189 } 190 return tx 191 } 192 193 func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) { 194 backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks) 195 backend.txPool.AddLocals(pendingTxs) 196 w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false) 197 w.setEtherbase(testBankAddress) 198 return w, backend 199 } 200 201 func TestGenerateBlockAndImportEthash(t *testing.T) { 202 testGenerateBlockAndImport(t, false) 203 } 204 205 func TestGenerateBlockAndImportClique(t *testing.T) { 206 testGenerateBlockAndImport(t, true) 207 } 208 209 func testGenerateBlockAndImport(t *testing.T, isClique bool) { 210 var ( 211 engine consensus.Engine 212 chainConfig *params.ChainConfig 213 db = rawdb.NewMemoryDatabase() 214 ) 215 if isClique { 216 chainConfig = params.AllCliqueProtocolChanges 217 chainConfig.Clique = ¶ms.CliqueConfig{Period: 1, Epoch: 30000} 218 engine = clique.New(chainConfig.Clique, db) 219 } else { 220 chainConfig = params.AllEthashProtocolChanges 221 engine = ethash.NewFaker() 222 } 223 224 w, b := newTestWorker(t, chainConfig, engine, db, 0) 225 defer w.close() 226 227 // This test chain imports the mined blocks. 228 db2 := rawdb.NewMemoryDatabase() 229 b.genesis.MustCommit(db2) 230 chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil, nil) 231 defer chain.Stop() 232 233 // Ignore empty commit here for less noise. 234 w.skipSealHook = func(task *task) bool { 235 return len(task.receipts) == 0 236 } 237 238 // Wait for mined blocks. 239 sub := w.mux.Subscribe(core.NewMinedBlockEvent{}) 240 defer sub.Unsubscribe() 241 242 // Start mining! 243 w.start() 244 245 for i := 0; i < 5; i++ { 246 b.txPool.AddLocal(b.newRandomTx(true)) 247 b.txPool.AddLocal(b.newRandomTx(false)) 248 w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) 249 w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) 250 251 select { 252 case ev := <-sub.Chan(): 253 block := ev.Data.(core.NewMinedBlockEvent).Block 254 if _, err := chain.InsertChain([]*types.Block{block}); err != nil { 255 t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err) 256 } 257 case <-time.After(3 * time.Second): // Worker needs 1s to include new changes. 258 t.Fatalf("timeout") 259 } 260 } 261 } 262 263 func TestAdjustIntervalEthash(t *testing.T) { 264 testAdjustInterval(t, ethashChainConfig, ethash.NewFaker()) 265 } 266 267 func TestAdjustIntervalClique(t *testing.T) { 268 testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 269 } 270 271 func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 272 defer engine.Close() 273 274 w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 275 defer w.close() 276 277 w.skipSealHook = func(task *task) bool { 278 return true 279 } 280 w.fullTaskHook = func() { 281 time.Sleep(100 * time.Millisecond) 282 } 283 var ( 284 progress = make(chan struct{}, 10) 285 result = make([]float64, 0, 10) 286 index = 0 287 start uint32 288 ) 289 w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) { 290 // Short circuit if interval checking hasn't started. 291 if atomic.LoadUint32(&start) == 0 { 292 return 293 } 294 var wantMinInterval, wantRecommitInterval time.Duration 295 296 switch index { 297 case 0: 298 wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second 299 case 1: 300 origin := float64(3 * time.Second.Nanoseconds()) 301 estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias) 302 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 303 case 2: 304 estimate := result[index-1] 305 min := float64(3 * time.Second.Nanoseconds()) 306 estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias) 307 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 308 case 3: 309 wantMinInterval, wantRecommitInterval = time.Second, time.Second 310 } 311 312 // Check interval 313 if minInterval != wantMinInterval { 314 t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval) 315 } 316 if recommitInterval != wantRecommitInterval { 317 t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval) 318 } 319 result = append(result, float64(recommitInterval.Nanoseconds())) 320 index += 1 321 progress <- struct{}{} 322 } 323 w.start() 324 325 time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt 326 atomic.StoreUint32(&start, 1) 327 328 w.setRecommitInterval(3 * time.Second) 329 select { 330 case <-progress: 331 case <-time.NewTimer(time.Second).C: 332 t.Error("interval reset timeout") 333 } 334 335 w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8} 336 select { 337 case <-progress: 338 case <-time.NewTimer(time.Second).C: 339 t.Error("interval reset timeout") 340 } 341 342 w.resubmitAdjustCh <- &intervalAdjust{inc: false} 343 select { 344 case <-progress: 345 case <-time.NewTimer(time.Second).C: 346 t.Error("interval reset timeout") 347 } 348 349 w.setRecommitInterval(500 * time.Millisecond) 350 select { 351 case <-progress: 352 case <-time.NewTimer(time.Second).C: 353 t.Error("interval reset timeout") 354 } 355 }