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