github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/miner/worker.go (about) 1 // Copyright 2015 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 "bytes" 21 "errors" 22 "math/big" 23 "sync" 24 "sync/atomic" 25 "time" 26 27 mapset "github.com/deckarep/golang-set" 28 "github.com/CommerciumBlockchain/go-commercium/common" 29 "github.com/CommerciumBlockchain/go-commercium/consensus" 30 "github.com/CommerciumBlockchain/go-commercium/consensus/misc" 31 "github.com/CommerciumBlockchain/go-commercium/core" 32 "github.com/CommerciumBlockchain/go-commercium/core/state" 33 "github.com/CommerciumBlockchain/go-commercium/core/types" 34 "github.com/CommerciumBlockchain/go-commercium/event" 35 "github.com/CommerciumBlockchain/go-commercium/log" 36 "github.com/CommerciumBlockchain/go-commercium/params" 37 "github.com/CommerciumBlockchain/go-commercium/trie" 38 ) 39 40 const ( 41 // resultQueueSize is the size of channel listening to sealing result. 42 resultQueueSize = 10 43 44 // txChanSize is the size of channel listening to NewTxsEvent. 45 // The number is referenced from the size of tx pool. 46 txChanSize = 4096 47 48 // chainHeadChanSize is the size of channel listening to ChainHeadEvent. 49 chainHeadChanSize = 10 50 51 // chainSideChanSize is the size of channel listening to ChainSideEvent. 52 chainSideChanSize = 10 53 54 // resubmitAdjustChanSize is the size of resubmitting interval adjustment channel. 55 resubmitAdjustChanSize = 10 56 57 // miningLogAtDepth is the number of confirmations before logging successful mining. 58 miningLogAtDepth = 7 59 60 // minRecommitInterval is the minimal time interval to recreate the mining block with 61 // any newly arrived transactions. 62 minRecommitInterval = 1 * time.Second 63 64 // maxRecommitInterval is the maximum time interval to recreate the mining block with 65 // any newly arrived transactions. 66 maxRecommitInterval = 15 * time.Second 67 68 // intervalAdjustRatio is the impact a single interval adjustment has on sealing work 69 // resubmitting interval. 70 intervalAdjustRatio = 0.1 71 72 // intervalAdjustBias is applied during the new resubmit interval calculation in favor of 73 // increasing upper limit or decreasing lower limit so that the limit can be reachable. 74 intervalAdjustBias = 200 * 1000.0 * 1000.0 75 76 // staleThreshold is the maximum depth of the acceptable stale block. 77 staleThreshold = 7 78 ) 79 80 // environment is the worker's current environment and holds all of the current state information. 81 type environment struct { 82 signer types.Signer 83 84 state *state.StateDB // apply state changes here 85 ancestors mapset.Set // ancestor set (used for checking uncle parent validity) 86 family mapset.Set // family set (used for checking uncle invalidity) 87 uncles mapset.Set // uncle set 88 tcount int // tx count in cycle 89 90 header *types.Header 91 txs []*types.Transaction 92 receipts []*types.Receipt 93 } 94 95 // task contains all information for consensus engine sealing and result submitting. 96 type task struct { 97 receipts []*types.Receipt 98 state *state.StateDB 99 block *types.Block 100 createdAt time.Time 101 } 102 103 const ( 104 commitInterruptNone int32 = iota 105 commitInterruptNewHead 106 commitInterruptResubmit 107 ) 108 109 // newWorkReq represents a request for new sealing work submitting with relative interrupt notifier. 110 type newWorkReq struct { 111 interrupt *int32 112 noempty bool 113 timestamp int64 114 } 115 116 // intervalAdjust represents a resubmitting interval adjustment. 117 type intervalAdjust struct { 118 ratio float64 119 inc bool 120 } 121 122 // worker is the main object which takes care of submitting new work to consensus engine 123 // and gathering the sealing result. 124 type worker struct { 125 config *Config 126 chainConfig *params.ChainConfig 127 engine consensus.Engine 128 eth Backend 129 chain *core.BlockChain 130 131 // Feeds 132 pendingLogsFeed event.Feed 133 134 // Subscriptions 135 mux *event.TypeMux 136 txsCh chan core.NewTxsEvent 137 txsSub event.Subscription 138 chainHeadCh chan core.ChainHeadEvent 139 chainHeadSub event.Subscription 140 chainSideCh chan core.ChainSideEvent 141 chainSideSub event.Subscription 142 143 // Channels 144 newWorkCh chan *newWorkReq 145 taskCh chan *task 146 resultCh chan *types.Block 147 startCh chan struct{} 148 exitCh chan struct{} 149 resubmitIntervalCh chan time.Duration 150 resubmitAdjustCh chan *intervalAdjust 151 152 current *environment // An environment for current running cycle. 153 localUncles map[common.Hash]*types.Block // A set of side blocks generated locally as the possible uncle blocks. 154 remoteUncles map[common.Hash]*types.Block // A set of side blocks as the possible uncle blocks. 155 unconfirmed *unconfirmedBlocks // A set of locally mined blocks pending canonicalness confirmations. 156 157 mu sync.RWMutex // The lock used to protect the coinbase and extra fields 158 coinbase common.Address 159 extra []byte 160 161 pendingMu sync.RWMutex 162 pendingTasks map[common.Hash]*task 163 164 snapshotMu sync.RWMutex // The lock used to protect the block snapshot and state snapshot 165 snapshotBlock *types.Block 166 snapshotState *state.StateDB 167 168 // atomic status counters 169 running int32 // The indicator whether the consensus engine is running or not. 170 newTxs int32 // New arrival transaction count since last sealing work submitting. 171 172 // noempty is the flag used to control whether the feature of pre-seal empty 173 // block is enabled. The default value is false(pre-seal is enabled by default). 174 // But in some special scenario the consensus engine will seal blocks instantaneously, 175 // in this case this feature will add all empty blocks into canonical chain 176 // non-stop and no real transaction will be included. 177 noempty uint32 178 179 // External functions 180 isLocalBlock func(block *types.Block) bool // Function used to determine whether the specified block is mined by local miner. 181 182 // Test hooks 183 newTaskHook func(*task) // Method to call upon receiving a new sealing task. 184 skipSealHook func(*task) bool // Method to decide whether skipping the sealing. 185 fullTaskHook func() // Method to call before pushing the full sealing task. 186 resubmitHook func(time.Duration, time.Duration) // Method to call upon updating resubmitting interval. 187 } 188 189 func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus.Engine, eth Backend, mux *event.TypeMux, isLocalBlock func(*types.Block) bool, init bool) *worker { 190 worker := &worker{ 191 config: config, 192 chainConfig: chainConfig, 193 engine: engine, 194 eth: eth, 195 mux: mux, 196 chain: eth.BlockChain(), 197 isLocalBlock: isLocalBlock, 198 localUncles: make(map[common.Hash]*types.Block), 199 remoteUncles: make(map[common.Hash]*types.Block), 200 unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth), 201 pendingTasks: make(map[common.Hash]*task), 202 txsCh: make(chan core.NewTxsEvent, txChanSize), 203 chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize), 204 chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize), 205 newWorkCh: make(chan *newWorkReq), 206 taskCh: make(chan *task), 207 resultCh: make(chan *types.Block, resultQueueSize), 208 exitCh: make(chan struct{}), 209 startCh: make(chan struct{}, 1), 210 resubmitIntervalCh: make(chan time.Duration), 211 resubmitAdjustCh: make(chan *intervalAdjust, resubmitAdjustChanSize), 212 } 213 // Subscribe NewTxsEvent for tx pool 214 worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh) 215 // Subscribe events for blockchain 216 worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh) 217 worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh) 218 219 // Sanitize recommit interval if the user-specified one is too short. 220 recommit := worker.config.Recommit 221 if recommit < minRecommitInterval { 222 log.Warn("Sanitizing miner recommit interval", "provided", recommit, "updated", minRecommitInterval) 223 recommit = minRecommitInterval 224 } 225 226 go worker.mainLoop() 227 go worker.newWorkLoop(recommit) 228 go worker.resultLoop() 229 go worker.taskLoop() 230 231 // Submit first work to initialize pending state. 232 if init { 233 worker.startCh <- struct{}{} 234 } 235 return worker 236 } 237 238 // setEtherbase sets the etherbase used to initialize the block coinbase field. 239 func (w *worker) setEtherbase(addr common.Address) { 240 w.mu.Lock() 241 defer w.mu.Unlock() 242 w.coinbase = addr 243 } 244 245 // setExtra sets the content used to initialize the block extra field. 246 func (w *worker) setExtra(extra []byte) { 247 w.mu.Lock() 248 defer w.mu.Unlock() 249 w.extra = extra 250 } 251 252 // setRecommitInterval updates the interval for miner sealing work recommitting. 253 func (w *worker) setRecommitInterval(interval time.Duration) { 254 w.resubmitIntervalCh <- interval 255 } 256 257 // disablePreseal disables pre-sealing mining feature 258 func (w *worker) disablePreseal() { 259 atomic.StoreUint32(&w.noempty, 1) 260 } 261 262 // enablePreseal enables pre-sealing mining feature 263 func (w *worker) enablePreseal() { 264 atomic.StoreUint32(&w.noempty, 0) 265 } 266 267 // pending returns the pending state and corresponding block. 268 func (w *worker) pending() (*types.Block, *state.StateDB) { 269 // return a snapshot to avoid contention on currentMu mutex 270 w.snapshotMu.RLock() 271 defer w.snapshotMu.RUnlock() 272 if w.snapshotState == nil { 273 return nil, nil 274 } 275 return w.snapshotBlock, w.snapshotState.Copy() 276 } 277 278 // pendingBlock returns pending block. 279 func (w *worker) pendingBlock() *types.Block { 280 // return a snapshot to avoid contention on currentMu mutex 281 w.snapshotMu.RLock() 282 defer w.snapshotMu.RUnlock() 283 return w.snapshotBlock 284 } 285 286 // start sets the running status as 1 and triggers new work submitting. 287 func (w *worker) start() { 288 atomic.StoreInt32(&w.running, 1) 289 w.startCh <- struct{}{} 290 } 291 292 // stop sets the running status as 0. 293 func (w *worker) stop() { 294 atomic.StoreInt32(&w.running, 0) 295 } 296 297 // isRunning returns an indicator whether worker is running or not. 298 func (w *worker) isRunning() bool { 299 return atomic.LoadInt32(&w.running) == 1 300 } 301 302 // close terminates all background threads maintained by the worker. 303 // Note the worker does not support being closed multiple times. 304 func (w *worker) close() { 305 atomic.StoreInt32(&w.running, 0) 306 close(w.exitCh) 307 } 308 309 // recalcRecommit recalculates the resubmitting interval upon feedback. 310 func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration { 311 var ( 312 prevF = float64(prev.Nanoseconds()) 313 next float64 314 ) 315 if inc { 316 next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias) 317 max := float64(maxRecommitInterval.Nanoseconds()) 318 if next > max { 319 next = max 320 } 321 } else { 322 next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias) 323 min := float64(minRecommit.Nanoseconds()) 324 if next < min { 325 next = min 326 } 327 } 328 return time.Duration(int64(next)) 329 } 330 331 // newWorkLoop is a standalone goroutine to submit new mining work upon received events. 332 func (w *worker) newWorkLoop(recommit time.Duration) { 333 var ( 334 interrupt *int32 335 minRecommit = recommit // minimal resubmit interval specified by user. 336 timestamp int64 // timestamp for each round of mining. 337 ) 338 339 timer := time.NewTimer(0) 340 defer timer.Stop() 341 <-timer.C // discard the initial tick 342 343 // commit aborts in-flight transaction execution with given signal and resubmits a new one. 344 commit := func(noempty bool, s int32) { 345 if interrupt != nil { 346 atomic.StoreInt32(interrupt, s) 347 } 348 interrupt = new(int32) 349 select { 350 case w.newWorkCh <- &newWorkReq{interrupt: interrupt, noempty: noempty, timestamp: timestamp}: 351 case <-w.exitCh: 352 return 353 } 354 timer.Reset(recommit) 355 atomic.StoreInt32(&w.newTxs, 0) 356 } 357 // clearPending cleans the stale pending tasks. 358 clearPending := func(number uint64) { 359 w.pendingMu.Lock() 360 for h, t := range w.pendingTasks { 361 if t.block.NumberU64()+staleThreshold <= number { 362 delete(w.pendingTasks, h) 363 } 364 } 365 w.pendingMu.Unlock() 366 } 367 368 for { 369 select { 370 case <-w.startCh: 371 clearPending(w.chain.CurrentBlock().NumberU64()) 372 timestamp = time.Now().Unix() 373 commit(false, commitInterruptNewHead) 374 375 case head := <-w.chainHeadCh: 376 clearPending(head.Block.NumberU64()) 377 timestamp = time.Now().Unix() 378 commit(false, commitInterruptNewHead) 379 380 case <-timer.C: 381 // If mining is running resubmit a new work cycle periodically to pull in 382 // higher priced transactions. Disable this overhead for pending blocks. 383 if w.isRunning() && (w.chainConfig.Clique == nil || w.chainConfig.Clique.Period > 0) { 384 // Short circuit if no new transaction arrives. 385 if atomic.LoadInt32(&w.newTxs) == 0 { 386 timer.Reset(recommit) 387 continue 388 } 389 commit(true, commitInterruptResubmit) 390 } 391 392 case interval := <-w.resubmitIntervalCh: 393 // Adjust resubmit interval explicitly by user. 394 if interval < minRecommitInterval { 395 log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval) 396 interval = minRecommitInterval 397 } 398 log.Info("Miner recommit interval update", "from", minRecommit, "to", interval) 399 minRecommit, recommit = interval, interval 400 401 if w.resubmitHook != nil { 402 w.resubmitHook(minRecommit, recommit) 403 } 404 405 case adjust := <-w.resubmitAdjustCh: 406 // Adjust resubmit interval by feedback. 407 if adjust.inc { 408 before := recommit 409 target := float64(recommit.Nanoseconds()) / adjust.ratio 410 recommit = recalcRecommit(minRecommit, recommit, target, true) 411 log.Trace("Increase miner recommit interval", "from", before, "to", recommit) 412 } else { 413 before := recommit 414 recommit = recalcRecommit(minRecommit, recommit, float64(minRecommit.Nanoseconds()), false) 415 log.Trace("Decrease miner recommit interval", "from", before, "to", recommit) 416 } 417 418 if w.resubmitHook != nil { 419 w.resubmitHook(minRecommit, recommit) 420 } 421 422 case <-w.exitCh: 423 return 424 } 425 } 426 } 427 428 // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event. 429 func (w *worker) mainLoop() { 430 defer w.txsSub.Unsubscribe() 431 defer w.chainHeadSub.Unsubscribe() 432 defer w.chainSideSub.Unsubscribe() 433 434 for { 435 select { 436 case req := <-w.newWorkCh: 437 w.commitNewWork(req.interrupt, req.noempty, req.timestamp) 438 439 case ev := <-w.chainSideCh: 440 // Short circuit for duplicate side blocks 441 if _, exist := w.localUncles[ev.Block.Hash()]; exist { 442 continue 443 } 444 if _, exist := w.remoteUncles[ev.Block.Hash()]; exist { 445 continue 446 } 447 // Add side block to possible uncle block set depending on the author. 448 if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) { 449 w.localUncles[ev.Block.Hash()] = ev.Block 450 } else { 451 w.remoteUncles[ev.Block.Hash()] = ev.Block 452 } 453 // If our mining block contains less than 2 uncle blocks, 454 // add the new uncle block if valid and regenerate a mining block. 455 if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 { 456 start := time.Now() 457 if err := w.commitUncle(w.current, ev.Block.Header()); err == nil { 458 var uncles []*types.Header 459 w.current.uncles.Each(func(item interface{}) bool { 460 hash, ok := item.(common.Hash) 461 if !ok { 462 return false 463 } 464 uncle, exist := w.localUncles[hash] 465 if !exist { 466 uncle, exist = w.remoteUncles[hash] 467 } 468 if !exist { 469 return false 470 } 471 uncles = append(uncles, uncle.Header()) 472 return false 473 }) 474 w.commit(uncles, nil, true, start) 475 } 476 } 477 478 case ev := <-w.txsCh: 479 // Apply transactions to the pending state if we're not mining. 480 // 481 // Note all transactions received may not be continuous with transactions 482 // already included in the current mining block. These transactions will 483 // be automatically eliminated. 484 if !w.isRunning() && w.current != nil { 485 w.mu.RLock() 486 coinbase := w.coinbase 487 w.mu.RUnlock() 488 489 txs := make(map[common.Address]types.Transactions) 490 for _, tx := range ev.Txs { 491 acc, _ := types.Sender(w.current.signer, tx) 492 txs[acc] = append(txs[acc], tx) 493 } 494 txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs) 495 tcount := w.current.tcount 496 w.commitTransactions(txset, coinbase, nil) 497 // Only update the snapshot if any new transactons were added 498 // to the pending block 499 if tcount != w.current.tcount { 500 w.updateSnapshot() 501 } 502 } else { 503 // Special case, if the consensus engine is 0 period clique(dev mode), 504 // submit mining work here since all empty submission will be rejected 505 // by clique. Of course the advance sealing(empty submission) is disabled. 506 if w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0 { 507 w.commitNewWork(nil, true, time.Now().Unix()) 508 } 509 } 510 atomic.AddInt32(&w.newTxs, int32(len(ev.Txs))) 511 512 // System stopped 513 case <-w.exitCh: 514 return 515 case <-w.txsSub.Err(): 516 return 517 case <-w.chainHeadSub.Err(): 518 return 519 case <-w.chainSideSub.Err(): 520 return 521 } 522 } 523 } 524 525 // taskLoop is a standalone goroutine to fetch sealing task from the generator and 526 // push them to consensus engine. 527 func (w *worker) taskLoop() { 528 var ( 529 stopCh chan struct{} 530 prev common.Hash 531 ) 532 533 // interrupt aborts the in-flight sealing task. 534 interrupt := func() { 535 if stopCh != nil { 536 close(stopCh) 537 stopCh = nil 538 } 539 } 540 for { 541 select { 542 case task := <-w.taskCh: 543 if w.newTaskHook != nil { 544 w.newTaskHook(task) 545 } 546 // Reject duplicate sealing work due to resubmitting. 547 sealHash := w.engine.SealHash(task.block.Header()) 548 if sealHash == prev { 549 continue 550 } 551 // Interrupt previous sealing operation 552 interrupt() 553 stopCh, prev = make(chan struct{}), sealHash 554 555 if w.skipSealHook != nil && w.skipSealHook(task) { 556 continue 557 } 558 w.pendingMu.Lock() 559 w.pendingTasks[sealHash] = task 560 w.pendingMu.Unlock() 561 562 if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil { 563 log.Warn("Block sealing failed", "err", err) 564 } 565 case <-w.exitCh: 566 interrupt() 567 return 568 } 569 } 570 } 571 572 // resultLoop is a standalone goroutine to handle sealing result submitting 573 // and flush relative data to the database. 574 func (w *worker) resultLoop() { 575 for { 576 select { 577 case block := <-w.resultCh: 578 // Short circuit when receiving empty result. 579 if block == nil { 580 continue 581 } 582 // Short circuit when receiving duplicate result caused by resubmitting. 583 if w.chain.HasBlock(block.Hash(), block.NumberU64()) { 584 continue 585 } 586 var ( 587 sealhash = w.engine.SealHash(block.Header()) 588 hash = block.Hash() 589 ) 590 w.pendingMu.RLock() 591 task, exist := w.pendingTasks[sealhash] 592 w.pendingMu.RUnlock() 593 if !exist { 594 log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash) 595 continue 596 } 597 // Different block could share same sealhash, deep copy here to prevent write-write conflict. 598 var ( 599 receipts = make([]*types.Receipt, len(task.receipts)) 600 logs []*types.Log 601 ) 602 for i, receipt := range task.receipts { 603 // add block location fields 604 receipt.BlockHash = hash 605 receipt.BlockNumber = block.Number() 606 receipt.TransactionIndex = uint(i) 607 608 receipts[i] = new(types.Receipt) 609 *receipts[i] = *receipt 610 // Update the block hash in all logs since it is now available and not when the 611 // receipt/log of individual transactions were created. 612 for _, log := range receipt.Logs { 613 log.BlockHash = hash 614 } 615 logs = append(logs, receipt.Logs...) 616 } 617 // Commit block and state to database. 618 _, err := w.chain.WriteBlockWithState(block, receipts, logs, task.state, true) 619 if err != nil { 620 log.Error("Failed writing block to chain", "err", err) 621 continue 622 } 623 log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash, 624 "elapsed", common.PrettyDuration(time.Since(task.createdAt))) 625 626 // Broadcast the block and announce chain insertion event 627 w.mux.Post(core.NewMinedBlockEvent{Block: block}) 628 629 // Insert the block into the set of pending ones to resultLoop for confirmations 630 w.unconfirmed.Insert(block.NumberU64(), block.Hash()) 631 632 case <-w.exitCh: 633 return 634 } 635 } 636 } 637 638 // makeCurrent creates a new environment for the current cycle. 639 func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error { 640 state, err := w.chain.StateAt(parent.Root()) 641 if err != nil { 642 return err 643 } 644 env := &environment{ 645 signer: types.NewEIP155Signer(w.chainConfig.ChainID), 646 state: state, 647 ancestors: mapset.NewSet(), 648 family: mapset.NewSet(), 649 uncles: mapset.NewSet(), 650 header: header, 651 } 652 653 // when 08 is processed ancestors contain 07 (quick block) 654 for _, ancestor := range w.chain.GetBlocksFromHash(parent.Hash(), 7) { 655 for _, uncle := range ancestor.Uncles() { 656 env.family.Add(uncle.Hash()) 657 } 658 env.family.Add(ancestor.Hash()) 659 env.ancestors.Add(ancestor.Hash()) 660 } 661 662 // Keep track of transactions which return errors so they can be removed 663 env.tcount = 0 664 w.current = env 665 return nil 666 } 667 668 // commitUncle adds the given block to uncle block set, returns error if failed to add. 669 func (w *worker) commitUncle(env *environment, uncle *types.Header) error { 670 hash := uncle.Hash() 671 if env.uncles.Contains(hash) { 672 return errors.New("uncle not unique") 673 } 674 if env.header.ParentHash == uncle.ParentHash { 675 return errors.New("uncle is sibling") 676 } 677 if !env.ancestors.Contains(uncle.ParentHash) { 678 return errors.New("uncle's parent unknown") 679 } 680 if env.family.Contains(hash) { 681 return errors.New("uncle already included") 682 } 683 env.uncles.Add(uncle.Hash()) 684 return nil 685 } 686 687 // updateSnapshot updates pending snapshot block and state. 688 // Note this function assumes the current variable is thread safe. 689 func (w *worker) updateSnapshot() { 690 w.snapshotMu.Lock() 691 defer w.snapshotMu.Unlock() 692 693 var uncles []*types.Header 694 w.current.uncles.Each(func(item interface{}) bool { 695 hash, ok := item.(common.Hash) 696 if !ok { 697 return false 698 } 699 uncle, exist := w.localUncles[hash] 700 if !exist { 701 uncle, exist = w.remoteUncles[hash] 702 } 703 if !exist { 704 return false 705 } 706 uncles = append(uncles, uncle.Header()) 707 return false 708 }) 709 710 w.snapshotBlock = types.NewBlock( 711 w.current.header, 712 w.current.txs, 713 uncles, 714 w.current.receipts, 715 new(trie.Trie), 716 ) 717 718 w.snapshotState = w.current.state.Copy() 719 } 720 721 func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) { 722 snap := w.current.state.Snapshot() 723 724 receipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, w.current.state, w.current.header, tx, &w.current.header, *w.chain.GetVMConfig()) 725 if err != nil { 726 w.current.state.RevertToSnapshot(snap) 727 return nil, err 728 } 729 w.current.txs = append(w.current.txs, tx) 730 w.current.receipts = append(w.current.receipts, receipt) 731 732 return receipt.Logs, nil 733 } 734 735 func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool { 736 // Short circuit if current is nil 737 if w.current == nil { 738 return true 739 } 740 741 742 var coalescedLogs []*types.Log 743 744 for { 745 // In the following three cases, we will interrupt the execution of the transaction. 746 // (1) new head block event arrival, the interrupt signal is 1 747 // (2) worker start or restart, the interrupt signal is 1 748 // (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2. 749 // For the first two cases, the semi-finished work will be discarded. 750 // For the third case, the semi-finished work will be submitted to the consensus engine. 751 if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone { 752 // Notify resubmit loop to increase resubmitting interval due to too frequent commits. 753 return atomic.LoadInt32(interrupt) == commitInterruptNewHead 754 } 755 756 // Retrieve the next transaction and abort if all done 757 tx := txs.Peek() 758 if tx == nil { 759 break 760 } 761 // Error may be ignored here. The error has already been checked 762 // during transaction acceptance is the transaction pool. 763 // 764 // We use the eip155 signer regardless of the current hf. 765 from, _ := types.Sender(w.current.signer, tx) 766 // Check whether the tx is replay protected. If we're not in the EIP155 hf 767 // phase, start ignoring the sender until we do. 768 if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) { 769 log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block) 770 771 txs.Pop() 772 continue 773 } 774 // Start executing the transaction 775 w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount) 776 777 logs, err := w.commitTransaction(tx, coinbase) 778 switch { 779 780 case errors.Is(err, core.ErrNonceTooLow): 781 // New head notification data race between the transaction pool and miner, shift 782 log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce()) 783 txs.Shift() 784 785 case errors.Is(err, core.ErrNonceTooHigh): 786 // Reorg notification data race between the transaction pool and miner, skip account = 787 log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce()) 788 txs.Pop() 789 790 case errors.Is(err, nil): 791 // Everything ok, collect the logs and shift in the next transaction from the same account 792 coalescedLogs = append(coalescedLogs, logs...) 793 w.current.tcount++ 794 txs.Shift() 795 796 default: 797 // Strange error, discard the transaction and get the next in line (note, the 798 // nonce-too-high clause will prevent us from executing in vain). 799 log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err) 800 txs.Shift() 801 } 802 } 803 804 if !w.isRunning() && len(coalescedLogs) > 0 { 805 // We don't push the pendingLogsEvent while we are mining. The reason is that 806 // when we are mining, the worker will regenerate a mining block every 3 seconds. 807 // In order to avoid pushing the repeated pendingLog, we disable the pending log pushing. 808 809 // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined 810 // logs by filling in the block hash when the block was mined by the local miner. This can 811 // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed. 812 cpy := make([]*types.Log, len(coalescedLogs)) 813 for i, l := range coalescedLogs { 814 cpy[i] = new(types.Log) 815 *cpy[i] = *l 816 } 817 w.pendingLogsFeed.Send(cpy) 818 } 819 // Notify resubmit loop to decrease resubmitting interval if current interval is larger 820 // than the user-specified one. 821 if interrupt != nil { 822 w.resubmitAdjustCh <- &intervalAdjust{inc: false} 823 } 824 return false 825 } 826 827 // commitNewWork generates several new sealing tasks based on the parent block. 828 func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) { 829 w.mu.RLock() 830 defer w.mu.RUnlock() 831 832 tstart := time.Now() 833 parent := w.chain.CurrentBlock() 834 835 if parent.Time() >= uint64(timestamp) { 836 timestamp = int64(parent.Time() + 1) 837 } 838 // this will ensure we're not going off too far in the future 839 if now := time.Now().Unix(); timestamp > now+1 { 840 wait := time.Duration(timestamp-now) * time.Second 841 log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait)) 842 time.Sleep(wait) 843 } 844 845 num := parent.Number() 846 header := &types.Header{ 847 ParentHash: parent.Hash(), 848 Number: num.Add(num, common.Big1), 849 Extra: w.extra, 850 Time: uint64(timestamp), 851 } 852 // Only set the coinbase if our consensus engine is running (avoid spurious block rewards) 853 if w.isRunning() { 854 if w.coinbase == (common.Address{}) { 855 log.Error("Refusing to mine without etherbase") 856 return 857 } 858 header.Coinbase = w.coinbase 859 } 860 if err := w.engine.Prepare(w.chain, header); err != nil { 861 log.Error("Failed to prepare header for mining", "err", err) 862 return 863 } 864 // If we are care about TheDAO hard-fork check whether to override the extra-data or not 865 if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil { 866 // Check whether the block is among the fork extra-override range 867 limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange) 868 if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 { 869 // Depending whether we support or oppose the fork, override differently 870 if w.chainConfig.DAOForkSupport { 871 header.Extra = common.CopyBytes(params.DAOForkBlockExtra) 872 } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) { 873 header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data 874 } 875 } 876 } 877 // Could potentially happen if starting to mine in an odd state. 878 err := w.makeCurrent(parent, header) 879 if err != nil { 880 log.Error("Failed to create mining context", "err", err) 881 return 882 } 883 // Create the current work task and check any fork transitions needed 884 env := w.current 885 if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 { 886 misc.ApplyDAOHardFork(env.state) 887 } 888 // Accumulate the uncles for the current block 889 uncles := make([]*types.Header, 0, 2) 890 commitUncles := func(blocks map[common.Hash]*types.Block) { 891 // Clean up stale uncle blocks first 892 for hash, uncle := range blocks { 893 if uncle.NumberU64()+staleThreshold <= header.Number.Uint64() { 894 delete(blocks, hash) 895 } 896 } 897 for hash, uncle := range blocks { 898 if len(uncles) == 2 { 899 break 900 } 901 if err := w.commitUncle(env, uncle.Header()); err != nil { 902 log.Trace("Possible uncle rejected", "hash", hash, "reason", err) 903 } else { 904 log.Debug("Committing new uncle to block", "hash", hash) 905 uncles = append(uncles, uncle.Header()) 906 } 907 } 908 } 909 // Prefer to locally generated uncle 910 commitUncles(w.localUncles) 911 commitUncles(w.remoteUncles) 912 913 // Create an empty block based on temporary copied state for 914 // sealing in advance without waiting block execution finished. 915 if !noempty && atomic.LoadUint32(&w.noempty) == 0 { 916 w.commit(uncles, nil, false, tstart) 917 } 918 919 // Fill the block with all available pending transactions. 920 pending, err := w.eth.TxPool().Pending() 921 if err != nil { 922 log.Error("Failed to fetch pending transactions", "err", err) 923 return 924 } 925 // Short circuit if there is no available pending transactions. 926 // But if we disable empty precommit already, ignore it. Since 927 // empty block is necessary to keep the liveness of the network. 928 if len(pending) == 0 && atomic.LoadUint32(&w.noempty) == 0 { 929 w.updateSnapshot() 930 return 931 } 932 // Split the pending transactions into locals and remotes 933 localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending 934 for _, account := range w.eth.TxPool().Locals() { 935 if txs := remoteTxs[account]; len(txs) > 0 { 936 delete(remoteTxs, account) 937 localTxs[account] = txs 938 } 939 } 940 if len(localTxs) > 0 { 941 txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs) 942 if w.commitTransactions(txs, w.coinbase, interrupt) { 943 return 944 } 945 } 946 if len(remoteTxs) > 0 { 947 txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs) 948 if w.commitTransactions(txs, w.coinbase, interrupt) { 949 return 950 } 951 } 952 w.commit(uncles, w.fullTaskHook, true, tstart) 953 } 954 955 // commit runs any post-transaction state modifications, assembles the final block 956 // and commits new work if consensus engine is running. 957 func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error { 958 // Deep copy receipts here to avoid interaction between different tasks. 959 receipts := copyReceipts(w.current.receipts) 960 s := w.current.state.Copy() 961 block, err := w.engine.FinalizeAndAssemble(w.chain, w.current.header, s, w.current.txs, uncles, receipts) 962 if err != nil { 963 return err 964 } 965 if w.isRunning() { 966 if interval != nil { 967 interval() 968 } 969 select { 970 case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}: 971 w.unconfirmed.Shift(block.NumberU64() - 1) 972 log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()), 973 "uncles", len(uncles), "txs", w.current.tcount, 974 "elapsed", common.PrettyDuration(time.Since(start))) 975 976 case <-w.exitCh: 977 log.Info("Worker has exited") 978 } 979 } 980 if update { 981 w.updateSnapshot() 982 } 983 return nil 984 } 985 986 // copyReceipts makes a deep copy of the given receipts. 987 func copyReceipts(receipts []*types.Receipt) []*types.Receipt { 988 result := make([]*types.Receipt, len(receipts)) 989 for i, l := range receipts { 990 cpy := *l 991 result[i] = &cpy 992 } 993 return result 994 } 995 996 // postSideBlock fires a side chain event, only use it for testing. 997 func (w *worker) postSideBlock(event core.ChainSideEvent) { 998 select { 999 case w.chainSideCh <- event: 1000 case <-w.exitCh: 1001 } 1002 }