diff --git a/consensus/ibft/consensus_backend.go b/consensus/ibft/consensus_backend.go index e25ed19137..1d73ae1a85 100644 --- a/consensus/ibft/consensus_backend.go +++ b/consensus/ibft/consensus_backend.go @@ -221,8 +221,7 @@ func (i *backendIBFT) writeTransactions( } var ( - blockTimer = time.NewTimer(i.blockTime) - stopExecution = false + blockTimer = time.NewTimer(i.blockTime) successful = 0 failed = 0 @@ -230,8 +229,6 @@ func (i *backendIBFT) writeTransactions( ) defer func() { - blockTimer.Stop() - i.logger.Info( "executed txs", "successful", successful, @@ -243,16 +240,12 @@ func (i *backendIBFT) writeTransactions( i.txpool.Prepare() +write: for { select { case <-blockTimer.C: return default: - if stopExecution { - // wait for the timer to expire - continue - } - // execute transactions one by one result, ok := i.writeTransaction( i.txpool.Peek(), @@ -261,9 +254,7 @@ func (i *backendIBFT) writeTransactions( ) if !ok { - stopExecution = true - - continue + break write } tx := result.tx @@ -279,6 +270,11 @@ func (i *backendIBFT) writeTransactions( } } } + + // wait for the timer to expire + <-blockTimer.C + + return } func (i *backendIBFT) writeTransaction( diff --git a/consensus/ibft/ibft.go b/consensus/ibft/ibft.go index 16b081d596..306ecdd323 100644 --- a/consensus/ibft/ibft.go +++ b/consensus/ibft/ibft.go @@ -376,6 +376,11 @@ func (i *backendIBFT) startConsensus() { defer newBlockSub.Close() + var ( + sequenceCh = make(<-chan struct{}) + isValidator bool + ) + for { var ( latest = i.blockchain.Header().Number @@ -384,22 +389,23 @@ func (i *backendIBFT) startConsensus() { i.updateActiveValidatorSet(latest) - if !i.isActiveValidator() { - // we are not participating in consensus for this height - continue + isValidator = i.isActiveValidator() + + if isValidator { + sequenceCh = i.consensus.runSequence(pending) } select { - case <-i.consensus.runSequence(pending): - // consensus inserted block - continue case <-syncerBlockCh: - // syncer inserted block -> stop running consensus - i.consensus.stopSequence() - i.logger.Info("canceled sequence", "sequence", pending) + if isValidator { + i.consensus.stopSequence() + i.logger.Info("canceled sequence", "sequence", pending) + } + case <-sequenceCh: case <-i.closeCh: - // IBFT consensus stopped - i.consensus.stopSequence() + if isValidator { + i.consensus.stopSequence() + } return }