@@ -109,13 +109,15 @@ class PivotBlockSelector(
109109 timeout : Cancellable ,
110110 headers : Map [ByteString , BlockHeaderWithVotes ]
111111 ): Unit = {
112- val BlockHeaderWithVotes (mostPopularBlockHeader, updatedVotes) = headers.mostVotedHeader
112+ // most voted header can return empty if we asked one peer and it returned us non expected block. Then headers map is empty
113+ // so there is no most voted header
114+ val maybeBlockHeaderWithVotes = headers.mostVotedHeader
113115 // All peers responded - consensus reached
114- if (peersToAsk.isEmpty && updatedVotes > = minPeersToChoosePivotBlock) {
116+ if (peersToAsk.isEmpty && maybeBlockHeaderWithVotes.exists(hWv => hWv.votes > = minPeersToChoosePivotBlock) ) {
115117 timeout.cancel()
116- sendResponseAndCleanup(mostPopularBlockHeader )
118+ sendResponseAndCleanup(maybeBlockHeaderWithVotes.get.header )
117119 // Consensus could not be reached - ask additional peer if available
118- } else if (! isPossibleToReachConsensus(peersToAsk.size, updatedVotes )) {
120+ } else if (! isPossibleToReachConsensus(peersToAsk.size, maybeBlockHeaderWithVotes.map(_.votes).getOrElse( 0 ) )) {
119121 timeout.cancel()
120122 if (waitingPeers.nonEmpty) { // There are more peers to ask
121123 val newTimeout = scheduler.scheduleOnce(peerResponseTimeout, self, ElectionPivotBlockTimeout )
@@ -206,11 +208,11 @@ object PivotBlockSelector {
206208 case class BlockHeaderWithVotes (header : BlockHeader , votes : Int = 1 ) {
207209 def vote : BlockHeaderWithVotes = copy(votes = votes + 1 )
208210 }
209-
211+ import cats . implicits . _
210212 implicit class SortableHeadersMap (headers : Map [ByteString , BlockHeaderWithVotes ]) {
211- def mostVotedHeader : BlockHeaderWithVotes = headers.maxBy { case (_, headerWithVotes) =>
212- headerWithVotes.votes
213- }._2
213+ def mostVotedHeader : Option [ BlockHeaderWithVotes ] = {
214+ headers.toList.maximumByOption { case (_, headerWithVotes) => headerWithVotes .votes }.map(_._2)
215+ }
214216 }
215217
216218 case class ElectionDetails (participants : List [Peer ], expectedPivotBlock : BigInt ) {
0 commit comments