@@ -72,6 +72,9 @@ const (
7272 // intervalAdjustBias is applied during the new resubmit interval calculation in favor of
7373 // increasing upper limit or decreasing lower limit so that the limit can be reachable.
7474 intervalAdjustBias = 200 * 1000.0 * 1000.0
75+
76+ // staleThreshold is the maximum distance of the acceptable stale block.
77+ staleThreshold = 7
7578)
7679
7780// environment is the worker's current environment and holds all of the current state information.
@@ -150,6 +153,9 @@ type worker struct {
150153 coinbase common.Address
151154 extra []byte
152155
156+ pendingMu sync.RWMutex
157+ pendingTasks map [common.Hash ]* task
158+
153159 snapshotMu sync.RWMutex // The lock used to protect the block snapshot and state snapshot
154160 snapshotBlock * types.Block
155161 snapshotState * state.StateDB
@@ -174,6 +180,7 @@ func newWorker(config *params.ChainConfig, engine consensus.Engine, eth Backend,
174180 chain : eth .BlockChain (),
175181 possibleUncles : make (map [common.Hash ]* types.Block ),
176182 unconfirmed : newUnconfirmedBlocks (eth .BlockChain (), miningLogAtDepth ),
183+ pendingTasks : make (map [common.Hash ]* task ),
177184 txsCh : make (chan core.NewTxsEvent , txChanSize ),
178185 chainHeadCh : make (chan core.ChainHeadEvent , chainHeadChanSize ),
179186 chainSideCh : make (chan core.ChainSideEvent , chainSideChanSize ),
@@ -317,13 +324,25 @@ func (w *worker) newWorkLoop(recommit time.Duration) {
317324 }
318325 recommit = time .Duration (int64 (next ))
319326 }
327+ // clearPending cleans the stale pending tasks.
328+ clearPending := func (number uint64 ) {
329+ w .pendingMu .Lock ()
330+ for h , t := range w .pendingTasks {
331+ if t .block .NumberU64 ()+ staleThreshold <= number {
332+ delete (w .pendingTasks , h )
333+ }
334+ }
335+ w .pendingMu .Unlock ()
336+ }
320337
321338 for {
322339 select {
323340 case <- w .startCh :
341+ clearPending (w .chain .CurrentBlock ().NumberU64 ())
324342 commit (false , commitInterruptNewHead )
325343
326- case <- w .chainHeadCh :
344+ case head := <- w .chainHeadCh :
345+ clearPending (head .Block .NumberU64 ())
327346 commit (false , commitInterruptNewHead )
328347
329348 case <- timer .C :
@@ -454,28 +473,37 @@ func (w *worker) mainLoop() {
454473
455474// seal pushes a sealing task to consensus engine and submits the result.
456475func (w * worker ) seal (t * task , stop <- chan struct {}) {
457- var (
458- err error
459- res * task
460- )
461-
462476 if w .skipSealHook != nil && w .skipSealHook (t ) {
463477 return
464478 }
465-
466- if t .block , err = w .engine .Seal (w .chain , t .block , stop ); t .block != nil {
467- log .Info ("Successfully sealed new block" , "number" , t .block .Number (), "hash" , t .block .Hash (),
468- "elapsed" , common .PrettyDuration (time .Since (t .createdAt )))
469- res = t
470- } else {
471- if err != nil {
472- log .Warn ("Block sealing failed" , "err" , err )
479+ // The reason for caching task first is:
480+ // A previous sealing action will be canceled by subsequent actions,
481+ // however, remote miner may submit a result based on the cancelled task.
482+ // So we should only submit the pending state corresponding to the seal result.
483+ // TODO(rjl493456442) Replace the seal-wait logic structure
484+ w .pendingMu .Lock ()
485+ w .pendingTasks [w .engine .SealHash (t .block .Header ())] = t
486+ w .pendingMu .Unlock ()
487+
488+ if block , err := w .engine .Seal (w .chain , t .block , stop ); block != nil {
489+ sealhash := w .engine .SealHash (block .Header ())
490+ w .pendingMu .RLock ()
491+ task , exist := w .pendingTasks [sealhash ]
492+ w .pendingMu .RUnlock ()
493+ if ! exist {
494+ log .Error ("Block found but no relative pending task" , "number" , block .Number (), "sealhash" , sealhash , "hash" , block .Hash ())
495+ return
473496 }
474- res = nil
475- }
476- select {
477- case w .resultCh <- res :
478- case <- w .exitCh :
497+ // Assemble sealing result
498+ task .block = block
499+ log .Info ("Successfully sealed new block" , "number" , block .Number (), "sealhash" , sealhash , "hash" , block .Hash (),
500+ "elapsed" , common .PrettyDuration (time .Since (task .createdAt )))
501+ select {
502+ case w .resultCh <- task :
503+ case <- w .exitCh :
504+ }
505+ } else if err != nil {
506+ log .Warn ("Block sealing failed" , "err" , err )
479507 }
480508}
481509
@@ -501,12 +529,13 @@ func (w *worker) taskLoop() {
501529 w .newTaskHook (task )
502530 }
503531 // Reject duplicate sealing work due to resubmitting.
504- if task .block .HashNoNonce () == prev {
532+ sealHash := w .engine .SealHash (task .block .Header ())
533+ if sealHash == prev {
505534 continue
506535 }
507536 interrupt ()
508537 stopCh = make (chan struct {})
509- prev = task . block . HashNoNonce ()
538+ prev = sealHash
510539 go w .seal (task , stopCh )
511540 case <- w .exitCh :
512541 interrupt ()
@@ -928,8 +957,8 @@ func (w *worker) commit(uncles []*types.Header, interval func(), update bool, st
928957 }
929958 feesEth := new (big.Float ).Quo (new (big.Float ).SetInt (feesWei ), new (big.Float ).SetInt (big .NewInt (params .Ether )))
930959
931- log .Info ("Commit new mining work" , "number" , block .Number (), "uncles " , len ( uncles ), "txs" , w . current . tcount ,
932- "gas" , block .GasUsed (), "fees" , feesEth , "elapsed" , common .PrettyDuration (time .Since (start )))
960+ log .Info ("Commit new mining work" , "number" , block .Number (), "sealhash " , w . engine . SealHash ( block . Header ()) ,
961+ "uncles" , len ( uncles ), "txs" , w . current . tcount , " gas" , block .GasUsed (), "fees" , feesEth , "elapsed" , common .PrettyDuration (time .Since (start )))
933962
934963 case <- w .exitCh :
935964 log .Info ("Worker has exited" )
0 commit comments