github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/miner/worker_test.go (about) 1 // Copyright 2021 The adkgo Authors 2 // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8). 3 // 4 // the adkgo 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 adkgo 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 adkgo 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/aidoskuneen/adk-node/accounts" 27 "github.com/aidoskuneen/adk-node/common" 28 "github.com/aidoskuneen/adk-node/consensus" 29 "github.com/aidoskuneen/adk-node/consensus/clique" 30 "github.com/aidoskuneen/adk-node/consensus/ethash" 31 "github.com/aidoskuneen/adk-node/core" 32 "github.com/aidoskuneen/adk-node/core/rawdb" 33 "github.com/aidoskuneen/adk-node/core/types" 34 "github.com/aidoskuneen/adk-node/core/vm" 35 "github.com/aidoskuneen/adk-node/crypto" 36 "github.com/aidoskuneen/adk-node/ethdb" 37 "github.com/aidoskuneen/adk-node/event" 38 "github.com/aidoskuneen/adk-node/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 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 84 signer := types.LatestSigner(params.TestChainConfig) 85 tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{ 86 ChainID: params.TestChainConfig.ChainID, 87 Nonce: 0, 88 To: &testUserAddress, 89 Value: big.NewInt(1000), 90 Gas: params.TxGas, 91 GasPrice: big.NewInt(params.InitialBaseFee), 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 GasPrice: big.NewInt(params.InitialBaseFee), 101 }) 102 newTxs = append(newTxs, tx2) 103 104 rand.Seed(time.Now().UnixNano()) 105 } 106 107 // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing. 108 type testWorkerBackend struct { 109 db ethdb.Database 110 txPool *core.TxPool 111 chain *core.BlockChain 112 testTxFeed event.Feed 113 genesis *core.Genesis 114 uncleBlock *types.Block 115 } 116 117 func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend { 118 var gspec = core.Genesis{ 119 Config: chainConfig, 120 Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, 121 } 122 123 switch e := engine.(type) { 124 case *clique.Clique: 125 gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength) 126 copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes()) 127 e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) { 128 return crypto.Sign(crypto.Keccak256(data), testBankKey) 129 }) 130 case *ethash.Ethash: 131 default: 132 t.Fatalf("unexpected consensus engine type: %T", engine) 133 } 134 genesis := gspec.MustCommit(db) 135 136 chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil) 137 txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain) 138 139 // Generate a small n-block chain and an uncle block for it 140 if n > 0 { 141 blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) { 142 gen.SetCoinbase(testBankAddress) 143 }) 144 if _, err := chain.InsertChain(blocks); err != nil { 145 t.Fatalf("failed to insert origin chain: %v", err) 146 } 147 } 148 parent := genesis 149 if n > 0 { 150 parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash()) 151 } 152 blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) { 153 gen.SetCoinbase(testUserAddress) 154 }) 155 156 return &testWorkerBackend{ 157 db: db, 158 chain: chain, 159 txPool: txpool, 160 genesis: &gspec, 161 uncleBlock: blocks[0], 162 } 163 } 164 165 func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain } 166 func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool } 167 168 func (b *testWorkerBackend) newRandomUncle() *types.Block { 169 var parent *types.Block 170 cur := b.chain.CurrentBlock() 171 if cur.NumberU64() == 0 { 172 parent = b.chain.Genesis() 173 } else { 174 parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash()) 175 } 176 blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) { 177 var addr = make([]byte, common.AddressLength) 178 rand.Read(addr) 179 gen.SetCoinbase(common.BytesToAddress(addr)) 180 }) 181 return blocks[0] 182 } 183 184 func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction { 185 var tx *types.Transaction 186 gasPrice := big.NewInt(10 * params.InitialBaseFee) 187 if creation { 188 tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, gasPrice, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey) 189 } else { 190 tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, gasPrice, nil), types.HomesteadSigner{}, testBankKey) 191 } 192 return tx 193 } 194 195 func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) { 196 backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks) 197 backend.txPool.AddLocals(pendingTxs) 198 w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false) 199 w.setEtherbase(testBankAddress) 200 return w, backend 201 } 202 203 func TestGenerateBlockAndImportEthash(t *testing.T) { 204 testGenerateBlockAndImport(t, false) 205 } 206 207 func TestGenerateBlockAndImportClique(t *testing.T) { 208 testGenerateBlockAndImport(t, true) 209 } 210 211 func testGenerateBlockAndImport(t *testing.T, isClique bool) { 212 var ( 213 engine consensus.Engine 214 chainConfig *params.ChainConfig 215 db = rawdb.NewMemoryDatabase() 216 ) 217 if isClique { 218 chainConfig = params.AllCliqueProtocolChanges 219 chainConfig.Clique = ¶ms.CliqueConfig{Period: 1, Epoch: 30000} 220 engine = clique.New(chainConfig.Clique, db) 221 } else { 222 chainConfig = params.AllEthashProtocolChanges 223 engine = ethash.NewFaker() 224 } 225 226 chainConfig.LondonBlock = big.NewInt(0) 227 w, b := newTestWorker(t, chainConfig, engine, db, 0) 228 defer w.close() 229 230 // This test chain imports the mined blocks. 231 db2 := rawdb.NewMemoryDatabase() 232 b.genesis.MustCommit(db2) 233 chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil, nil) 234 defer chain.Stop() 235 236 // Ignore empty commit here for less noise. 237 w.skipSealHook = func(task *task) bool { 238 return len(task.receipts) == 0 239 } 240 241 // Wait for mined blocks. 242 sub := w.mux.Subscribe(core.NewMinedBlockEvent{}) 243 defer sub.Unsubscribe() 244 245 // Start mining! 246 w.start() 247 248 for i := 0; i < 5; i++ { 249 b.txPool.AddLocal(b.newRandomTx(true)) 250 b.txPool.AddLocal(b.newRandomTx(false)) 251 w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) 252 w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) 253 254 select { 255 case ev := <-sub.Chan(): 256 block := ev.Data.(core.NewMinedBlockEvent).Block 257 if _, err := chain.InsertChain([]*types.Block{block}); err != nil { 258 t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err) 259 } 260 case <-time.After(3 * time.Second): // Worker needs 1s to include new changes. 261 t.Fatalf("timeout") 262 } 263 } 264 } 265 266 func TestEmptyWorkEthash(t *testing.T) { 267 testEmptyWork(t, ethashChainConfig, ethash.NewFaker()) 268 } 269 func TestEmptyWorkClique(t *testing.T) { 270 testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 271 } 272 273 func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 274 defer engine.Close() 275 276 w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 277 defer w.close() 278 279 var ( 280 taskIndex int 281 taskCh = make(chan struct{}, 2) 282 ) 283 checkEqual := func(t *testing.T, task *task, index int) { 284 // The first empty work without any txs included 285 receiptLen, balance := 0, big.NewInt(0) 286 if index == 1 { 287 // The second full work with 1 tx included 288 receiptLen, balance = 1, big.NewInt(1000) 289 } 290 if len(task.receipts) != receiptLen { 291 t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen) 292 } 293 if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 { 294 t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance) 295 } 296 } 297 w.newTaskHook = func(task *task) { 298 if task.block.NumberU64() == 1 { 299 checkEqual(t, task, taskIndex) 300 taskIndex += 1 301 taskCh <- struct{}{} 302 } 303 } 304 w.skipSealHook = func(task *task) bool { return true } 305 w.fullTaskHook = func() { 306 time.Sleep(100 * time.Millisecond) 307 } 308 w.start() // Start mining! 309 for i := 0; i < 2; i += 1 { 310 select { 311 case <-taskCh: 312 case <-time.NewTimer(3 * time.Second).C: 313 t.Error("new task timeout") 314 } 315 } 316 } 317 318 func TestStreamUncleBlock(t *testing.T) { 319 ethash := ethash.NewFaker() 320 defer ethash.Close() 321 322 w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1) 323 defer w.close() 324 325 var taskCh = make(chan struct{}) 326 327 taskIndex := 0 328 w.newTaskHook = func(task *task) { 329 if task.block.NumberU64() == 2 { 330 // The first task is an empty task, the second 331 // one has 1 pending tx, the third one has 1 tx 332 // and 1 uncle. 333 if taskIndex == 2 { 334 have := task.block.Header().UncleHash 335 want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()}) 336 if have != want { 337 t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex()) 338 } 339 } 340 taskCh <- struct{}{} 341 taskIndex += 1 342 } 343 } 344 w.skipSealHook = func(task *task) bool { 345 return true 346 } 347 w.fullTaskHook = func() { 348 time.Sleep(100 * time.Millisecond) 349 } 350 w.start() 351 352 for i := 0; i < 2; i += 1 { 353 select { 354 case <-taskCh: 355 case <-time.NewTimer(time.Second).C: 356 t.Error("new task timeout") 357 } 358 } 359 360 w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock}) 361 362 select { 363 case <-taskCh: 364 case <-time.NewTimer(time.Second).C: 365 t.Error("new task timeout") 366 } 367 } 368 369 func TestRegenerateMiningBlockEthash(t *testing.T) { 370 testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker()) 371 } 372 373 func TestRegenerateMiningBlockClique(t *testing.T) { 374 testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 375 } 376 377 func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 378 defer engine.Close() 379 380 w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 381 defer w.close() 382 383 var taskCh = make(chan struct{}) 384 385 taskIndex := 0 386 w.newTaskHook = func(task *task) { 387 if task.block.NumberU64() == 1 { 388 // The first task is an empty task, the second 389 // one has 1 pending tx, the third one has 2 txs 390 if taskIndex == 2 { 391 receiptLen, balance := 2, big.NewInt(2000) 392 if len(task.receipts) != receiptLen { 393 t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen) 394 } 395 if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 { 396 t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance) 397 } 398 } 399 taskCh <- struct{}{} 400 taskIndex += 1 401 } 402 } 403 w.skipSealHook = func(task *task) bool { 404 return true 405 } 406 w.fullTaskHook = func() { 407 time.Sleep(100 * time.Millisecond) 408 } 409 410 w.start() 411 // Ignore the first two works 412 for i := 0; i < 2; i += 1 { 413 select { 414 case <-taskCh: 415 case <-time.NewTimer(time.Second).C: 416 t.Error("new task timeout") 417 } 418 } 419 b.txPool.AddLocals(newTxs) 420 time.Sleep(time.Second) 421 422 select { 423 case <-taskCh: 424 case <-time.NewTimer(time.Second).C: 425 t.Error("new task timeout") 426 } 427 } 428 429 func TestAdjustIntervalEthash(t *testing.T) { 430 testAdjustInterval(t, ethashChainConfig, ethash.NewFaker()) 431 } 432 433 func TestAdjustIntervalClique(t *testing.T) { 434 testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) 435 } 436 437 func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) { 438 defer engine.Close() 439 440 w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0) 441 defer w.close() 442 443 w.skipSealHook = func(task *task) bool { 444 return true 445 } 446 w.fullTaskHook = func() { 447 time.Sleep(100 * time.Millisecond) 448 } 449 var ( 450 progress = make(chan struct{}, 10) 451 result = make([]float64, 0, 10) 452 index = 0 453 start uint32 454 ) 455 w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) { 456 // Short circuit if interval checking hasn't started. 457 if atomic.LoadUint32(&start) == 0 { 458 return 459 } 460 var wantMinInterval, wantRecommitInterval time.Duration 461 462 switch index { 463 case 0: 464 wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second 465 case 1: 466 origin := float64(3 * time.Second.Nanoseconds()) 467 estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias) 468 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 469 case 2: 470 estimate := result[index-1] 471 min := float64(3 * time.Second.Nanoseconds()) 472 estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias) 473 wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond 474 case 3: 475 wantMinInterval, wantRecommitInterval = time.Second, time.Second 476 } 477 478 // Check interval 479 if minInterval != wantMinInterval { 480 t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval) 481 } 482 if recommitInterval != wantRecommitInterval { 483 t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval) 484 } 485 result = append(result, float64(recommitInterval.Nanoseconds())) 486 index += 1 487 progress <- struct{}{} 488 } 489 w.start() 490 491 time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt 492 atomic.StoreUint32(&start, 1) 493 494 w.setRecommitInterval(3 * time.Second) 495 select { 496 case <-progress: 497 case <-time.NewTimer(time.Second).C: 498 t.Error("interval reset timeout") 499 } 500 501 w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8} 502 select { 503 case <-progress: 504 case <-time.NewTimer(time.Second).C: 505 t.Error("interval reset timeout") 506 } 507 508 w.resubmitAdjustCh <- &intervalAdjust{inc: false} 509 select { 510 case <-progress: 511 case <-time.NewTimer(time.Second).C: 512 t.Error("interval reset timeout") 513 } 514 515 w.setRecommitInterval(500 * time.Millisecond) 516 select { 517 case <-progress: 518 case <-time.NewTimer(time.Second).C: 519 t.Error("interval reset timeout") 520 } 521 }