{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}

-- | The votes the node has accepted, from whichever peer.
--
-- Each LeiosNotify client already holds its own upstream peer to one vote per
-- seat in an election. But the node relays what it accepts from all its peers,
-- and a downstream peer holds the node to the same, and to having relayed the
-- announcement a vote is for. So the node decides once, here, whether a vote
-- is new and valid, and only then relays it.
--
-- A vote is relayed only to be aggregated into a certificate, which the
-- earliest block that can carry it needs in the first slot at or after the
-- vote's deadline, the end of its diffusion period ('voteUntil'). The node
-- neither keeps nor relays a vote it has only after its deadline. Such a vote
-- could still complete a certificate for a later block, but a quorum that late
-- is no evidence that the endorser block's data diffused in time, so the node
-- deliberately gives up that throughput rather than endanger safety.
--
-- So the node aggregates the votes for an announcement into its certificate as
-- soon as they reach quorum, which is before 'pruneVotes' passes their
-- deadline, or never. It keeps the
-- certificate until the announcing block is immutable, long after it forgot
-- the votes, for whichever block comes to certify it.
module Ouroboros.Consensus.Leios.VoteState
  ( VoteState
  , newVoteState
  , TraceLeiosVoteState (..)

    -- * Votes
  , currentVotes
  , addVote
  , AddVoteResult (..)
  , validateVote
  , ValidatedVote (..)
  , recordVote
  , pruneVotes

    -- * Certificates
  , getCertificate
  , pruneCertificates
  ) where

import Cardano.Crypto.DSIGN.Class (verifyDSIGN)
import Cardano.Crypto.Leios
  ( AggregationError
  , LeiosCert
  , LeiosSeat (..)
  , LeiosSeatId
  , LeiosSignature
  , Weight
  , aggregateLeiosCert
  , leiosSignContext
  , resolveLeiosSeat
  )
import Cardano.Prelude (isJust, unlessM)
import Control.Monad (when)
import Control.Tracer (Tracer, traceWith)
import Data.Foldable (for_)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (..))
import qualified Data.Text as Text
import Data.Time.Clock (NominalDiffTime)
import GHC.Generics (Generic)
import NoThunks.Class (NoThunks)
import Ouroboros.Consensus.Block (ConvertRawHash, GetHeader, SlotNo)
import Ouroboros.Consensus.BlockchainTime.WallClock.Types
  ( RelativeTime (..)
  , SystemTime (..)
  , diffRelTime
  )
import Ouroboros.Consensus.Leios.AnnounceState (AnnounceState, hasAnnouncement)
import Ouroboros.Consensus.Leios.NotifyLog
  ( Notification (..)
  , NotifyLog
  , appendNotifyLog
  )
import Ouroboros.Consensus.Leios.Types (LeiosVote (..), RankingBlockHash)
import Ouroboros.Consensus.MiniProtocol.LeiosNotify.Client.State
  ( AcceptedVote (..)
  , InvalidVoteReason (..)
  , VoteWindow (..)
  )
import Ouroboros.Consensus.Util.IOLike
  ( IOLike
  , MonadDelay (threadDelay)
  , MonadSTM
  , STM
  , StrictTVar
  , atomically
  , modifyTVar
  , newTVarIO
  , readTVar
  , writeTVar
  )
import Ouroboros.Consensus.Util.Time (nominalDelay)

-- | The node's votes, and where it learns which announcements it relays and
-- relays the votes.
data VoteState m blk = MkVoteState
  { forall (m :: * -> *) blk. VoteState m blk -> StrictTVar m Votes
votes :: !(StrictTVar m Votes)
  , forall (m :: * -> *) blk. VoteState m blk -> AnnounceState m blk
announceState :: !(AnnounceState m blk)
  -- ^ Which announcements the node relays, as it relays only votes for those.
  , forall (m :: * -> *) blk. VoteState m blk -> NotifyLog m blk
relayLog :: !(NotifyLog m blk)
  -- ^ Where the node relays the votes it adds.
  , forall (m :: * -> *) blk.
VoteState m blk -> StrictTVar m Certificates
certificates :: !(StrictTVar m Certificates)
  , forall (m :: * -> *) blk.
VoteState m blk -> Tracer m TraceLeiosVoteState
tracer :: !(Tracer m TraceLeiosVoteState)
  }

-- | The first valid vote of each seat, per election slot, for every election
-- slot whose deadline had not passed when the votes were last pruned.
data Votes = MkVotes
  { Votes -> RelativeTime
votesPrunedAt :: !RelativeTime
  -- ^ When the votes were last pruned. The node may have forgotten whether it
  -- has a vote whose deadline is before this.
  , Votes -> Map SlotNo SlotVotes
votesBySlot :: !(Map SlotNo SlotVotes)
  }
  deriving stock (Votes -> Votes -> Bool
(Votes -> Votes -> Bool) -> (Votes -> Votes -> Bool) -> Eq Votes
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Votes -> Votes -> Bool
== :: Votes -> Votes -> Bool
$c/= :: Votes -> Votes -> Bool
/= :: Votes -> Votes -> Bool
Eq, Int -> Votes -> ShowS
[Votes] -> ShowS
Votes -> String
(Int -> Votes -> ShowS)
-> (Votes -> String) -> ([Votes] -> ShowS) -> Show Votes
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Votes -> ShowS
showsPrec :: Int -> Votes -> ShowS
$cshow :: Votes -> String
show :: Votes -> String
$cshowList :: [Votes] -> ShowS
showList :: [Votes] -> ShowS
Show, (forall x. Votes -> Rep Votes x)
-> (forall x. Rep Votes x -> Votes) -> Generic Votes
forall x. Rep Votes x -> Votes
forall x. Votes -> Rep Votes x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Votes -> Rep Votes x
from :: forall x. Votes -> Rep Votes x
$cto :: forall x. Rep Votes x -> Votes
to :: forall x. Rep Votes x -> Votes
Generic)
  deriving anyclass Context -> Votes -> IO (Maybe ThunkInfo)
Proxy Votes -> String
(Context -> Votes -> IO (Maybe ThunkInfo))
-> (Context -> Votes -> IO (Maybe ThunkInfo))
-> (Proxy Votes -> String)
-> NoThunks Votes
forall a.
(Context -> a -> IO (Maybe ThunkInfo))
-> (Context -> a -> IO (Maybe ThunkInfo))
-> (Proxy a -> String)
-> NoThunks a
$cnoThunks :: Context -> Votes -> IO (Maybe ThunkInfo)
noThunks :: Context -> Votes -> IO (Maybe ThunkInfo)
$cwNoThunks :: Context -> Votes -> IO (Maybe ThunkInfo)
wNoThunks :: Context -> Votes -> IO (Maybe ThunkInfo)
$cshowTypeOf :: Proxy Votes -> String
showTypeOf :: Proxy Votes -> String
NoThunks

-- | The votes of one election slot, their deadline and their quorum.
data SlotVotes = MkSlotVotes
  { SlotVotes -> RelativeTime
slotRelayUntil :: !RelativeTime
  , SlotVotes -> Weight
slotQuorum :: !Weight
  , SlotVotes -> Map LeiosSeatId LeiosVote
slotVotes :: !(Map LeiosSeatId LeiosVote)
  -- ^ A seat votes once per election slot, whichever announcement it votes
  -- for.
  , SlotVotes -> Map RankingBlockHash Weight
slotTallies :: !(Map RankingBlockHash Weight)
  -- ^ INVARIANT: The weight of the votes in 'slotVotes' for each announcement.
  }
  deriving stock (SlotVotes -> SlotVotes -> Bool
(SlotVotes -> SlotVotes -> Bool)
-> (SlotVotes -> SlotVotes -> Bool) -> Eq SlotVotes
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SlotVotes -> SlotVotes -> Bool
== :: SlotVotes -> SlotVotes -> Bool
$c/= :: SlotVotes -> SlotVotes -> Bool
/= :: SlotVotes -> SlotVotes -> Bool
Eq, Int -> SlotVotes -> ShowS
[SlotVotes] -> ShowS
SlotVotes -> String
(Int -> SlotVotes -> ShowS)
-> (SlotVotes -> String)
-> ([SlotVotes] -> ShowS)
-> Show SlotVotes
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SlotVotes -> ShowS
showsPrec :: Int -> SlotVotes -> ShowS
$cshow :: SlotVotes -> String
show :: SlotVotes -> String
$cshowList :: [SlotVotes] -> ShowS
showList :: [SlotVotes] -> ShowS
Show, (forall x. SlotVotes -> Rep SlotVotes x)
-> (forall x. Rep SlotVotes x -> SlotVotes) -> Generic SlotVotes
forall x. Rep SlotVotes x -> SlotVotes
forall x. SlotVotes -> Rep SlotVotes x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. SlotVotes -> Rep SlotVotes x
from :: forall x. SlotVotes -> Rep SlotVotes x
$cto :: forall x. Rep SlotVotes x -> SlotVotes
to :: forall x. Rep SlotVotes x -> SlotVotes
Generic)
  deriving anyclass Context -> SlotVotes -> IO (Maybe ThunkInfo)
Proxy SlotVotes -> String
(Context -> SlotVotes -> IO (Maybe ThunkInfo))
-> (Context -> SlotVotes -> IO (Maybe ThunkInfo))
-> (Proxy SlotVotes -> String)
-> NoThunks SlotVotes
forall a.
(Context -> a -> IO (Maybe ThunkInfo))
-> (Context -> a -> IO (Maybe ThunkInfo))
-> (Proxy a -> String)
-> NoThunks a
$cnoThunks :: Context -> SlotVotes -> IO (Maybe ThunkInfo)
noThunks :: Context -> SlotVotes -> IO (Maybe ThunkInfo)
$cwNoThunks :: Context -> SlotVotes -> IO (Maybe ThunkInfo)
wNoThunks :: Context -> SlotVotes -> IO (Maybe ThunkInfo)
$cshowTypeOf :: Proxy SlotVotes -> String
showTypeOf :: Proxy SlotVotes -> String
NoThunks

newVoteState ::
  IOLike m =>
  Tracer m TraceLeiosVoteState -> AnnounceState m blk -> NotifyLog m blk -> m (VoteState m blk)
newVoteState :: forall (m :: * -> *) blk.
IOLike m =>
Tracer m TraceLeiosVoteState
-> AnnounceState m blk -> NotifyLog m blk -> m (VoteState m blk)
newVoteState Tracer m TraceLeiosVoteState
tracer' AnnounceState m blk
announceState' NotifyLog m blk
notifyLog =
  StrictTVar m Votes
-> AnnounceState m blk
-> NotifyLog m blk
-> StrictTVar m Certificates
-> Tracer m TraceLeiosVoteState
-> VoteState m blk
forall (m :: * -> *) blk.
StrictTVar m Votes
-> AnnounceState m blk
-> NotifyLog m blk
-> StrictTVar m Certificates
-> Tracer m TraceLeiosVoteState
-> VoteState m blk
MkVoteState
    (StrictTVar m Votes
 -> AnnounceState m blk
 -> NotifyLog m blk
 -> StrictTVar m Certificates
 -> Tracer m TraceLeiosVoteState
 -> VoteState m blk)
-> m (StrictTVar m Votes)
-> m (AnnounceState m blk
      -> NotifyLog m blk
      -> StrictTVar m Certificates
      -> Tracer m TraceLeiosVoteState
      -> VoteState m blk)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Votes -> m (StrictTVar m Votes)
forall (m :: * -> *) a.
(HasCallStack, MonadSTM m, NoThunks a) =>
a -> m (StrictTVar m a)
newTVarIO (RelativeTime -> Map SlotNo SlotVotes -> Votes
MkVotes (NominalDiffTime -> RelativeTime
RelativeTime NominalDiffTime
0) Map SlotNo SlotVotes
forall k a. Map k a
Map.empty)
    m (AnnounceState m blk
   -> NotifyLog m blk
   -> StrictTVar m Certificates
   -> Tracer m TraceLeiosVoteState
   -> VoteState m blk)
-> m (AnnounceState m blk)
-> m (NotifyLog m blk
      -> StrictTVar m Certificates
      -> Tracer m TraceLeiosVoteState
      -> VoteState m blk)
forall a b. m (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> AnnounceState m blk -> m (AnnounceState m blk)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AnnounceState m blk
announceState'
    m (NotifyLog m blk
   -> StrictTVar m Certificates
   -> Tracer m TraceLeiosVoteState
   -> VoteState m blk)
-> m (NotifyLog m blk)
-> m (StrictTVar m Certificates
      -> Tracer m TraceLeiosVoteState -> VoteState m blk)
forall a b. m (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> NotifyLog m blk -> m (NotifyLog m blk)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure NotifyLog m blk
notifyLog
    m (StrictTVar m Certificates
   -> Tracer m TraceLeiosVoteState -> VoteState m blk)
-> m (StrictTVar m Certificates)
-> m (Tracer m TraceLeiosVoteState -> VoteState m blk)
forall a b. m (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Certificates -> m (StrictTVar m Certificates)
forall (m :: * -> *) a.
(HasCallStack, MonadSTM m, NoThunks a) =>
a -> m (StrictTVar m a)
newTVarIO (SlotNo -> Map RankingBlockHash (SlotNo, LeiosCert) -> Certificates
MkCertificates SlotNo
0 Map RankingBlockHash (SlotNo, LeiosCert)
forall k a. Map k a
Map.empty)
    m (Tracer m TraceLeiosVoteState -> VoteState m blk)
-> m (Tracer m TraceLeiosVoteState) -> m (VoteState m blk)
forall a b. m (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Tracer m TraceLeiosVoteState -> m (Tracer m TraceLeiosVoteState)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Tracer m TraceLeiosVoteState
tracer'

-- | Whether the node has a vote of this seat in this election.
hasSeenVote ::
  MonadSTM m =>
  VoteState m blk -> AcceptedVote -> STM m Bool
hasSeenVote :: forall (m :: * -> *) blk.
MonadSTM m =>
VoteState m blk -> AcceptedVote -> STM m Bool
hasSeenVote VoteState m blk
st AcceptedVote
accepted = do
  MkVotes{votesBySlot} <- StrictTVar m Votes -> STM m Votes
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Votes
forall (m :: * -> *) blk. VoteState m blk -> StrictTVar m Votes
votes VoteState m blk
st)
  pure $
    maybe
      False
      (Map.member voteSeatId . slotVotes)
      (Map.lookup voteElectionSlot votesBySlot)
 where
  MkAcceptedVote
    { acceptedVote :: AcceptedVote -> LeiosVote
acceptedVote = MkLeiosVote{LeiosSeatId
voteSeatId :: LeiosSeatId
voteSeatId :: LeiosVote -> LeiosSeatId
voteSeatId}
    , SlotNo
voteElectionSlot :: SlotNo
voteElectionSlot :: AcceptedVote -> SlotNo
voteElectionSlot
    } = AcceptedVote
accepted

-- | The votes the node keeps, by election slot and seat.
currentVotes ::
  IOLike m =>
  VoteState m blk -> STM m (Map SlotNo (Map LeiosSeatId LeiosVote))
currentVotes :: forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk -> STM m (Map SlotNo (Map LeiosSeatId LeiosVote))
currentVotes VoteState m blk
st = (SlotVotes -> Map LeiosSeatId LeiosVote)
-> Map SlotNo SlotVotes -> Map SlotNo (Map LeiosSeatId LeiosVote)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map SlotVotes -> Map LeiosSeatId LeiosVote
slotVotes (Map SlotNo SlotVotes -> Map SlotNo (Map LeiosSeatId LeiosVote))
-> (Votes -> Map SlotNo SlotVotes)
-> Votes
-> Map SlotNo (Map LeiosSeatId LeiosVote)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Votes -> Map SlotNo SlotVotes
votesBySlot (Votes -> Map SlotNo (Map LeiosSeatId LeiosVote))
-> STM m Votes -> STM m (Map SlotNo (Map LeiosSeatId LeiosVote))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StrictTVar m Votes -> STM m Votes
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Votes
forall (m :: * -> *) blk. VoteState m blk -> StrictTVar m Votes
votes VoteState m blk
st)

-- | What the node's 'VoteState' traces, for each vote it adds or does not, so
-- these are frequent. What 'addVote' did with a vote is up to its caller to
-- trace.
data TraceLeiosVoteState
  = -- | The node starts to add a vote, and to check whether it should.
    TraceLeiosVoteAdding !LeiosVote
  | -- | The vote arrived before its window opened, so the node waits this long
    -- before adding it.
    TraceLeiosVoteAwaitingWindow !LeiosVote !NominalDiffTime
  | -- | The node validated a vote, its seat and signature, and has yet to add it.
    TraceLeiosVoteValidated !LeiosVote
  | -- | The votes for this announcement reached quorum, and the node aggregated
    -- them into its certificate.
    TraceLeiosCertified !RankingBlockHash !LeiosCert
  | -- | The node could not aggregate the votes for this announcement, though
    -- they reached quorum.
    TraceLeiosAggregationFailed !RankingBlockHash !AggregationError
  | -- | The deadline of the votes for this announcement passed with only this
    -- much weight voting for it, short of quorum. Not traced for an announcement
    -- without any vote. Many of these, for announcements of valid endorser
    -- blocks, mean the diffusion period is too short for the network.
    TraceLeiosQuorumMissed !RankingBlockHash !Weight
  deriving Int -> TraceLeiosVoteState -> ShowS
[TraceLeiosVoteState] -> ShowS
TraceLeiosVoteState -> String
(Int -> TraceLeiosVoteState -> ShowS)
-> (TraceLeiosVoteState -> String)
-> ([TraceLeiosVoteState] -> ShowS)
-> Show TraceLeiosVoteState
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> TraceLeiosVoteState -> ShowS
showsPrec :: Int -> TraceLeiosVoteState -> ShowS
$cshow :: TraceLeiosVoteState -> String
show :: TraceLeiosVoteState -> String
$cshowList :: [TraceLeiosVoteState] -> ShowS
showList :: [TraceLeiosVoteState] -> ShowS
Show

-- | What 'addVote' did with a vote.
data AddVoteResult
  = -- | The node had it only after its deadline, or after it forgot its
    -- election.
    ArrivedTooLate
  | -- | We already saw a vote of its seat in its election.
    AlreadyKnown
  | -- | We did not relay the announcement it is for.
    NotAnnounced
  | -- | Its seat has no key in the committee, or its signature does not verify
    -- under it.
    VoteInvalid !InvalidVoteReason
  | -- | The node keeps the vote and relays it.
    Added
  deriving stock (AddVoteResult -> AddVoteResult -> Bool
(AddVoteResult -> AddVoteResult -> Bool)
-> (AddVoteResult -> AddVoteResult -> Bool) -> Eq AddVoteResult
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AddVoteResult -> AddVoteResult -> Bool
== :: AddVoteResult -> AddVoteResult -> Bool
$c/= :: AddVoteResult -> AddVoteResult -> Bool
/= :: AddVoteResult -> AddVoteResult -> Bool
Eq, Int -> AddVoteResult -> ShowS
[AddVoteResult] -> ShowS
AddVoteResult -> String
(Int -> AddVoteResult -> ShowS)
-> (AddVoteResult -> String)
-> ([AddVoteResult] -> ShowS)
-> Show AddVoteResult
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> AddVoteResult -> ShowS
showsPrec :: Int -> AddVoteResult -> ShowS
$cshow :: AddVoteResult -> String
show :: AddVoteResult -> String
$cshowList :: [AddVoteResult] -> ShowS
showList :: [AddVoteResult] -> ShowS
Show)

-- | Add a vote, if it is the first valid vote of its seat in its election, for
-- an announcement the node relays, and the node has it by its deadline.
--
-- NOTE: This will wait until the vote's window is open.
--
-- The signature is verified between two transactions, so that a retry does
-- not repeat a BLS verification. As verifying takes time, 'recordVote' checks
-- again whether the node has seen or forgotten the vote. The relay log stops
-- relaying it after its deadline.
addVote ::
  (IOLike m, ConvertRawHash blk, GetHeader blk) =>
  VoteState m blk -> SystemTime m -> AcceptedVote -> m AddVoteResult
addVote :: forall (m :: * -> *) blk.
(IOLike m, ConvertRawHash blk, GetHeader blk) =>
VoteState m blk -> SystemTime m -> AcceptedVote -> m AddVoteResult
addVote VoteState m blk
st SystemTime m
systemTime AcceptedVote
accepted = do
  Tracer m TraceLeiosVoteState -> TraceLeiosVoteState -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith (VoteState m blk -> Tracer m TraceLeiosVoteState
forall (m :: * -> *) blk.
VoteState m blk -> Tracer m TraceLeiosVoteState
tracer VoteState m blk
st) (LeiosVote -> TraceLeiosVoteState
TraceLeiosVoteAdding LeiosVote
acceptedVote)
  received <- SystemTime m -> m RelativeTime
forall (m :: * -> *). SystemTime m -> m RelativeTime
systemTimeCurrent SystemTime m
systemTime
  -- Wait for the window of a vote that 'checkLeiosVotes' accepted early.
  -- NOTE: 'checkLeiosVotes' just rejected votes earlier than the
  -- clock skew, so this waits at most 'InFutureCheck.ClockSkew'.
  let early = VoteWindow -> RelativeTime
voteFrom VoteWindow
voteWindow RelativeTime -> RelativeTime -> NominalDiffTime
`diffRelTime` RelativeTime
received
  when (early > 0) $ do
    traceWith (tracer st) (TraceLeiosVoteAwaitingWindow acceptedVote early)
    threadDelay (nominalDelay early)
  seen <- atomically $ hasSeenVote st accepted
  -- NOTE: The client only checked that its peer announced it, but the node
  -- does not relay a third announcement of an election, nor one of a stale
  -- OCIN, so it must not relay their votes either.
  announced <-
    atomically $
      hasAnnouncement (announceState st) voteElectionSlot (voteAnnouncingRbHash acceptedVote)
  (result, quorum) <-
    if
      | received > voteUntil voteWindow -> pure (ArrivedTooLate, Nothing)
      | not announced -> pure (NotAnnounced, Nothing)
      | seen -> pure (AlreadyKnown, Nothing)
      | otherwise ->
          -- NOTE: Verifying a signature is expensive, so this comes last.
          case validateVote accepted of
            Left InvalidVoteReason
reason -> (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
-> m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (InvalidVoteReason -> AddVoteResult
VoteInvalid InvalidVoteReason
reason, Maybe (Map LeiosSeatId LeiosSignature)
forall a. Maybe a
Nothing)
            Right ValidatedVote
validVote -> do
              Tracer m TraceLeiosVoteState -> TraceLeiosVoteState -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith (VoteState m blk -> Tracer m TraceLeiosVoteState
forall (m :: * -> *) blk.
VoteState m blk -> Tracer m TraceLeiosVoteState
tracer VoteState m blk
st) (LeiosVote -> TraceLeiosVoteState
TraceLeiosVoteValidated LeiosVote
acceptedVote)
              STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
-> m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
 -> m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature)))
-> STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
-> m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a b. (a -> b) -> a -> b
$
                VoteState m blk
-> ValidatedVote
-> STM
     m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk
-> ValidatedVote
-> STM
     m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
recordVote VoteState m blk
st ValidatedVote
validVote STM
  m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
-> (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature))
    -> STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature)))
-> STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a b. STM m a -> (a -> STM m b) -> STM m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                  Left AddVoteResult
notAdded -> (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
-> STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (AddVoteResult
notAdded, Maybe (Map LeiosSeatId LeiosSignature)
forall a. Maybe a
Nothing)
                  Right Maybe (Map LeiosSeatId LeiosSignature)
quorum -> (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
-> STM m (AddVoteResult, Maybe (Map LeiosSeatId LeiosSignature))
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (AddVoteResult
Added, Maybe (Map LeiosSeatId LeiosSignature)
quorum)
  -- Aggregate outside the STM transaction that recorded a vote. We often
  -- receive many votes in quick succession, even duplicates via different
  -- peers. Having it recorded early will not have them validated again. Every
  -- vote recorded at or above the threshold returns the signatures, but only
  -- aggregates them while there is no certificate yet, to be resilient against
  -- the thread dying between recording and aggregating (e.g. due to a
  -- connection reset). If that also was the last vote, we won't have a
  -- certificate, but with such a close quorum its for the better to skip this
  -- round.
  for_ quorum $ \Map LeiosSeatId LeiosSignature
signatures -> do
    -- Another vote may have been aggregated into the certificate since.
    m Bool -> m () -> m ()
forall (m :: * -> *). Monad m => m Bool -> m () -> m ()
unlessM (STM m Bool -> m Bool
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically STM m Bool
hasCertificate) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
      case LeiosCommittee
-> Map LeiosSeatId LeiosSignature
-> Either AggregationError LeiosCert
aggregateLeiosCert LeiosCommittee
voteCommittee Map LeiosSeatId LeiosSignature
signatures of
        Left AggregationError
err -> Tracer m TraceLeiosVoteState -> TraceLeiosVoteState -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith (VoteState m blk -> Tracer m TraceLeiosVoteState
forall (m :: * -> *) blk.
VoteState m blk -> Tracer m TraceLeiosVoteState
tracer VoteState m blk
st) (RankingBlockHash -> AggregationError -> TraceLeiosVoteState
TraceLeiosAggregationFailed RankingBlockHash
rbHash AggregationError
err)
        Right !LeiosCert
cert -> do
          --  ^ Make sure not to store a thunk
          inserted <- STM m Bool -> m Bool
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m Bool -> m Bool) -> STM m Bool -> m Bool
forall a b. (a -> b) -> a -> b
$ LeiosCert -> STM m Bool
recordCertificate LeiosCert
cert
          when inserted $
            traceWith (tracer st) (TraceLeiosCertified rbHash cert)
  pure result
 where
  hasCertificate :: STM m Bool
hasCertificate = Maybe LeiosCert -> Bool
forall a. Maybe a -> Bool
isJust (Maybe LeiosCert -> Bool) -> STM m (Maybe LeiosCert) -> STM m Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> VoteState m blk -> RankingBlockHash -> STM m (Maybe LeiosCert)
forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk -> RankingBlockHash -> STM m (Maybe LeiosCert)
getCertificate VoteState m blk
st RankingBlockHash
rbHash

  recordCertificate :: LeiosCert -> STM m Bool
recordCertificate LeiosCert
cert = do
    MkCertificates{certificatesPrunedAt, certificatesByRbHash} <- StrictTVar m Certificates -> STM m Certificates
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Certificates
forall (m :: * -> *) blk.
VoteState m blk -> StrictTVar m Certificates
certificates VoteState m blk
st)
    let new =
          SlotNo
certificatesPrunedAt SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
<= SlotNo
voteElectionSlot
            Bool -> Bool -> Bool
&& RankingBlockHash
-> Map RankingBlockHash (SlotNo, LeiosCert) -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember RankingBlockHash
rbHash Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash
    when new $ do
      modifyTVar (certificates st) $ \Certificates
certs ->
        Certificates
certs
          { certificatesByRbHash =
              Map.insert rbHash (voteElectionSlot, cert) certificatesByRbHash
          }
    pure new

  MkAcceptedVote
    { LeiosVote
acceptedVote :: AcceptedVote -> LeiosVote
acceptedVote :: LeiosVote
acceptedVote
    , SlotNo
voteElectionSlot :: AcceptedVote -> SlotNo
voteElectionSlot :: SlotNo
voteElectionSlot
    , LeiosCommittee
voteCommittee :: LeiosCommittee
voteCommittee :: AcceptedVote -> LeiosCommittee
voteCommittee
    , VoteWindow
voteWindow :: VoteWindow
voteWindow :: AcceptedVote -> VoteWindow
voteWindow
    } = AcceptedVote
accepted

  rbHash :: RankingBlockHash
rbHash = LeiosVote -> RankingBlockHash
voteAnnouncingRbHash LeiosVote
acceptedVote

-- | A vote whose seat has a key in the committee, and whose signature verifies
-- under it.
data ValidatedVote = MkValidatedVote
  { ValidatedVote -> LeiosVote
validatedVote :: !LeiosVote
  , ValidatedVote -> SlotNo
validatedElectionSlot :: !SlotNo
  , ValidatedVote -> Weight
validatedSeatWeight :: !Weight
  -- ^ The weight of the vote's seat.
  , ValidatedVote -> Weight
validatedQuorum :: !Weight
  -- ^ See 'acceptedQuorum'.
  , ValidatedVote -> RelativeTime
voteValidUntil :: !RelativeTime
  -- ^ Until when the vote is relayed and considered valid.
  }

-- | Validate a vote against its election's committee, or say why it is invalid.
validateVote :: AcceptedVote -> Either InvalidVoteReason ValidatedVote
validateVote :: AcceptedVote -> Either InvalidVoteReason ValidatedVote
validateVote AcceptedVote
acceptedVote =
  case LeiosCommittee -> LeiosSeatId -> Maybe LeiosSeat
resolveLeiosSeat LeiosCommittee
voteCommittee LeiosSeatId
voteSeatId of
    Maybe LeiosSeat
Nothing -> InvalidVoteReason -> Either InvalidVoteReason ValidatedVote
forall a b. a -> Either a b
Left InvalidVoteReason
SeatNotResolvable
    Just LeiosSeat{seatVKey :: LeiosSeat -> StrictMaybe LeiosVerificationKey
seatVKey = StrictMaybe LeiosVerificationKey
SNothing} -> InvalidVoteReason -> Either InvalidVoteReason ValidatedVote
forall a b. a -> Either a b
Left InvalidVoteReason
SeatHasNoKey
    Just LeiosSeat{seatVKey :: LeiosSeat -> StrictMaybe LeiosVerificationKey
seatVKey = SJust LeiosVerificationKey
vk, Weight
seatWeight :: Weight
seatWeight :: LeiosSeat -> Weight
seatWeight} ->
      case ContextDSIGN LeiosDSIGN
-> LeiosVerificationKey
-> RankingBlockHash
-> LeiosSignature
-> Either String ()
forall v a.
(DSIGNAlgorithm v, Signable v a, HasCallStack) =>
ContextDSIGN v
-> VerKeyDSIGN v -> a -> SigDSIGN v -> Either String ()
forall a.
(Signable LeiosDSIGN a, HasCallStack) =>
ContextDSIGN LeiosDSIGN
-> LeiosVerificationKey -> a -> LeiosSignature -> Either String ()
verifyDSIGN ContextDSIGN LeiosDSIGN
BLS12381SignContext
leiosSignContext LeiosVerificationKey
vk RankingBlockHash
voteAnnouncingRbHash LeiosSignature
voteSignature of
        Left String
err -> InvalidVoteReason -> Either InvalidVoteReason ValidatedVote
forall a b. a -> Either a b
Left (InvalidVoteReason -> Either InvalidVoteReason ValidatedVote)
-> (Text -> InvalidVoteReason)
-> Text
-> Either InvalidVoteReason ValidatedVote
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> InvalidVoteReason
BadSignature (Text -> Either InvalidVoteReason ValidatedVote)
-> Text -> Either InvalidVoteReason ValidatedVote
forall a b. (a -> b) -> a -> b
$ String -> Text
Text.pack String
err
        Right () -> ValidatedVote -> Either InvalidVoteReason ValidatedVote
forall a b. b -> Either a b
Right (ValidatedVote -> Either InvalidVoteReason ValidatedVote)
-> ValidatedVote -> Either InvalidVoteReason ValidatedVote
forall a b. (a -> b) -> a -> b
$ Weight -> ValidatedVote
mkValidated Weight
seatWeight
 where
  MkAcceptedVote
    { acceptedVote :: AcceptedVote -> LeiosVote
acceptedVote = vote :: LeiosVote
vote@MkLeiosVote{RankingBlockHash
voteAnnouncingRbHash :: LeiosVote -> RankingBlockHash
voteAnnouncingRbHash :: RankingBlockHash
voteAnnouncingRbHash, LeiosSeatId
voteSeatId :: LeiosVote -> LeiosSeatId
voteSeatId :: LeiosSeatId
voteSeatId, LeiosSignature
voteSignature :: LeiosSignature
voteSignature :: LeiosVote -> LeiosSignature
voteSignature}
    , SlotNo
voteElectionSlot :: AcceptedVote -> SlotNo
voteElectionSlot :: SlotNo
voteElectionSlot
    , LeiosCommittee
voteCommittee :: AcceptedVote -> LeiosCommittee
voteCommittee :: LeiosCommittee
voteCommittee
    , Weight
acceptedQuorum :: AcceptedVote -> Weight
acceptedQuorum :: Weight
acceptedQuorum
    , VoteWindow
voteWindow :: AcceptedVote -> VoteWindow
voteWindow :: VoteWindow
voteWindow
    } = AcceptedVote
acceptedVote

  mkValidated :: Weight -> ValidatedVote
mkValidated Weight
seatWeight =
    MkValidatedVote
      { validatedVote :: LeiosVote
validatedVote = LeiosVote
vote
      , validatedElectionSlot :: SlotNo
validatedElectionSlot = SlotNo
voteElectionSlot
      , validatedSeatWeight :: Weight
validatedSeatWeight = Weight
seatWeight
      , validatedQuorum :: Weight
validatedQuorum = Weight
acceptedQuorum
      , voteValidUntil :: RelativeTime
voteValidUntil = VoteWindow -> RelativeTime
voteUntil VoteWindow
voteWindow
      }

-- | Keep and relay a vote the node has neither seen nor forgotten, as it was
-- pruned past the vote's deadline already. If the votes for its announcement
-- reach quorum, return their signatures.
recordVote ::
  IOLike m =>
  VoteState m blk ->
  ValidatedVote ->
  STM m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
recordVote :: forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk
-> ValidatedVote
-> STM
     m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
recordVote VoteState m blk
st ValidatedVote
validatedVote = do
  vs <- StrictTVar m Votes -> STM m Votes
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Votes
forall (m :: * -> *) blk. VoteState m blk -> StrictTVar m Votes
votes VoteState m blk
st)
  let before = SlotNo -> Map SlotNo SlotVotes -> Maybe SlotVotes
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup SlotNo
validatedElectionSlot (Votes -> Map SlotNo SlotVotes
votesBySlot Votes
vs)
      after = SlotVotes
-> (SlotVotes -> SlotVotes) -> Maybe SlotVotes -> SlotVotes
forall b a. b -> (a -> b) -> Maybe a -> b
maybe SlotVotes
slotVotes' (SlotVotes -> SlotVotes -> SlotVotes
mergeNonEquivocations SlotVotes
slotVotes') Maybe SlotVotes
before
      weightOfAfter = Weight -> RankingBlockHash -> Map RankingBlockHash Weight -> Weight
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Weight
0 RankingBlockHash
rbHash (SlotVotes -> Map RankingBlockHash Weight
slotTallies SlotVotes
after)
  if
    | voteValidUntil < votesPrunedAt vs -> pure (Left ArrivedTooLate)
    | maybe False voteIn before -> pure (Left AlreadyKnown)
    | otherwise -> do
        writeTVar (votes st) vs{votesBySlot = Map.insert validatedElectionSlot after (votesBySlot vs)}
        appendNotifyLog (relayLog st) (NotifyVote vote) voteValidUntil
        pure . Right $
          if validatedQuorum <= weightOfAfter
            then
              Just $
                Map.fromList
                  [ (voteSeatId v, voteSignature v)
                  | v <- Map.elems (slotVotes after)
                  , voteAnnouncingRbHash v == rbHash
                  ]
            else Nothing
 where
  voteIn :: SlotVotes -> Bool
voteIn = LeiosSeatId -> Map LeiosSeatId LeiosVote -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member (LeiosVote -> LeiosSeatId
voteSeatId LeiosVote
vote) (Map LeiosSeatId LeiosVote -> Bool)
-> (SlotVotes -> Map LeiosSeatId LeiosVote) -> SlotVotes -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SlotVotes -> Map LeiosSeatId LeiosVote
slotVotes

  MkValidatedVote
    { validatedVote :: ValidatedVote -> LeiosVote
validatedVote = LeiosVote
vote
    , SlotNo
validatedElectionSlot :: ValidatedVote -> SlotNo
validatedElectionSlot :: SlotNo
validatedElectionSlot
    , Weight
validatedSeatWeight :: ValidatedVote -> Weight
validatedSeatWeight :: Weight
validatedSeatWeight
    , Weight
validatedQuorum :: ValidatedVote -> Weight
validatedQuorum :: Weight
validatedQuorum
    , RelativeTime
voteValidUntil :: ValidatedVote -> RelativeTime
voteValidUntil :: RelativeTime
voteValidUntil
    } = ValidatedVote
validatedVote

  rbHash :: RankingBlockHash
rbHash = LeiosVote -> RankingBlockHash
voteAnnouncingRbHash LeiosVote
vote

  slotVotes' :: SlotVotes
slotVotes' =
    RelativeTime
-> Weight
-> Map LeiosSeatId LeiosVote
-> Map RankingBlockHash Weight
-> SlotVotes
MkSlotVotes
      RelativeTime
voteValidUntil
      Weight
validatedQuorum
      (LeiosSeatId -> LeiosVote -> Map LeiosSeatId LeiosVote
forall k a. k -> a -> Map k a
Map.singleton (LeiosVote -> LeiosSeatId
voteSeatId LeiosVote
vote) LeiosVote
vote)
      (RankingBlockHash -> Weight -> Map RankingBlockHash Weight
forall k a. k -> a -> Map k a
Map.singleton RankingBlockHash
rbHash Weight
validatedSeatWeight)

  -- The 'AlreadyKnown' guard keeps an equivocation from reaching this.
  mergeNonEquivocations :: SlotVotes -> SlotVotes -> SlotVotes
mergeNonEquivocations SlotVotes
new SlotVotes
old =
    SlotVotes
old
      { slotVotes = Map.union (slotVotes old) (slotVotes new)
      , slotTallies = Map.unionWith (+) (slotTallies old) (slotTallies new)
      }

-- | Forget the votes of every election slot whose deadline has passed at the
-- given time, and trace the announcements among them that missed their quorum.
--
-- 'recordVote' then finds any later copy of their votes 'ArrivedTooLate'.
pruneVotes ::
  IOLike m =>
  VoteState m blk -> RelativeTime -> m ()
pruneVotes :: forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk -> RelativeTime -> m ()
pruneVotes VoteState m blk
st RelativeTime
now = do
  missed <- STM m [(RankingBlockHash, Weight)]
-> m [(RankingBlockHash, Weight)]
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m [(RankingBlockHash, Weight)]
 -> m [(RankingBlockHash, Weight)])
-> STM m [(RankingBlockHash, Weight)]
-> m [(RankingBlockHash, Weight)]
forall a b. (a -> b) -> a -> b
$ do
    MkVotes{votesPrunedAt, votesBySlot} <- StrictTVar m Votes -> STM m Votes
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Votes
forall (m :: * -> *) blk. VoteState m blk -> StrictTVar m Votes
votes VoteState m blk
st)
    -- Every slot kept has not expired at 'votesPrunedAt', so pruning at or
    -- before it forgets nothing.
    if now <= votesPrunedAt
      then pure []
      else do
        let (unexpired, expired) = Map.partition ((now <=) . slotRelayUntil) votesBySlot
        writeTVar (votes st) (MkVotes now unexpired)
        pure
          [ (rbHash, weight)
          | slotVotes' <- Map.elems expired
          , (rbHash, weight) <- Map.toList (slotTallies slotVotes')
          , weight < slotQuorum slotVotes'
          ]
  for_ missed $ \(RankingBlockHash
rbHash, Weight
weight) ->
    Tracer m TraceLeiosVoteState -> TraceLeiosVoteState -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith (VoteState m blk -> Tracer m TraceLeiosVoteState
forall (m :: * -> *) blk.
VoteState m blk -> Tracer m TraceLeiosVoteState
tracer VoteState m blk
st) (RankingBlockHash -> Weight -> TraceLeiosVoteState
TraceLeiosQuorumMissed RankingBlockHash
rbHash Weight
weight)

{-------------------------------------------------------------------------------
  Certificates
-------------------------------------------------------------------------------}

-- | The certificate of each announcement whose votes reached quorum, with its
-- election slot, for every election slot not before the immutable tip when the
-- certificates were last pruned.
data Certificates = MkCertificates
  { Certificates -> SlotNo
certificatesPrunedAt :: !SlotNo
  -- ^ The immutable tip's slot when the certificates were last pruned. The node
  -- keeps no certificate of an election slot before it.
  , Certificates -> Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash :: !(Map RankingBlockHash (SlotNo, LeiosCert))
  }
  deriving stock (forall x. Certificates -> Rep Certificates x)
-> (forall x. Rep Certificates x -> Certificates)
-> Generic Certificates
forall x. Rep Certificates x -> Certificates
forall x. Certificates -> Rep Certificates x
forall a.
(forall x. a -> Rep a x) -> (forall x. Rep a x -> a) -> Generic a
$cfrom :: forall x. Certificates -> Rep Certificates x
from :: forall x. Certificates -> Rep Certificates x
$cto :: forall x. Rep Certificates x -> Certificates
to :: forall x. Rep Certificates x -> Certificates
Generic
  deriving anyclass Context -> Certificates -> IO (Maybe ThunkInfo)
Proxy Certificates -> String
(Context -> Certificates -> IO (Maybe ThunkInfo))
-> (Context -> Certificates -> IO (Maybe ThunkInfo))
-> (Proxy Certificates -> String)
-> NoThunks Certificates
forall a.
(Context -> a -> IO (Maybe ThunkInfo))
-> (Context -> a -> IO (Maybe ThunkInfo))
-> (Proxy a -> String)
-> NoThunks a
$cnoThunks :: Context -> Certificates -> IO (Maybe ThunkInfo)
noThunks :: Context -> Certificates -> IO (Maybe ThunkInfo)
$cwNoThunks :: Context -> Certificates -> IO (Maybe ThunkInfo)
wNoThunks :: Context -> Certificates -> IO (Maybe ThunkInfo)
$cshowTypeOf :: Proxy Certificates -> String
showTypeOf :: Proxy Certificates -> String
NoThunks

-- | The certificate of this announcement, if the votes for it reached quorum
-- before 'pruneVotes' passed their deadline.
getCertificate ::
  IOLike m =>
  VoteState m blk -> RankingBlockHash -> STM m (Maybe LeiosCert)
getCertificate :: forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk -> RankingBlockHash -> STM m (Maybe LeiosCert)
getCertificate VoteState m blk
st RankingBlockHash
rbHash =
  ((SlotNo, LeiosCert) -> LeiosCert)
-> Maybe (SlotNo, LeiosCert) -> Maybe LeiosCert
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (SlotNo, LeiosCert) -> LeiosCert
forall a b. (a, b) -> b
snd (Maybe (SlotNo, LeiosCert) -> Maybe LeiosCert)
-> (Certificates -> Maybe (SlotNo, LeiosCert))
-> Certificates
-> Maybe LeiosCert
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RankingBlockHash
-> Map RankingBlockHash (SlotNo, LeiosCert)
-> Maybe (SlotNo, LeiosCert)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup RankingBlockHash
rbHash (Map RankingBlockHash (SlotNo, LeiosCert)
 -> Maybe (SlotNo, LeiosCert))
-> (Certificates -> Map RankingBlockHash (SlotNo, LeiosCert))
-> Certificates
-> Maybe (SlotNo, LeiosCert)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Certificates -> Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash (Certificates -> Maybe LeiosCert)
-> STM m Certificates -> STM m (Maybe LeiosCert)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StrictTVar m Certificates -> STM m Certificates
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (VoteState m blk -> StrictTVar m Certificates
forall (m :: * -> *) blk.
VoteState m blk -> StrictTVar m Certificates
certificates VoteState m blk
st)

-- | Forget the certificates of every election slot before the given slot, the
-- immutable tip's.
--
-- The announcing block of such a certificate is immutable, and all of its
-- successors are either also immutable or unreachable from the immutable tip.
-- Until then, a certificate is kept for whichever block comes to certify it,
-- however late.
pruneCertificates ::
  IOLike m =>
  VoteState m blk -> SlotNo -> STM m ()
pruneCertificates :: forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk -> SlotNo -> STM m ()
pruneCertificates VoteState m blk
st SlotNo
immTipSlot =
  StrictTVar m Certificates
-> (Certificates -> Certificates) -> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar (VoteState m blk -> StrictTVar m Certificates
forall (m :: * -> *) blk.
VoteState m blk -> StrictTVar m Certificates
certificates VoteState m blk
st) ((Certificates -> Certificates) -> STM m ())
-> (Certificates -> Certificates) -> STM m ()
forall a b. (a -> b) -> a -> b
$ \MkCertificates{SlotNo
certificatesPrunedAt :: Certificates -> SlotNo
certificatesPrunedAt :: SlotNo
certificatesPrunedAt, Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash :: Certificates -> Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash :: Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash} ->
    let prunedAt :: SlotNo
prunedAt = SlotNo -> SlotNo -> SlotNo
forall a. Ord a => a -> a -> a
max SlotNo
immTipSlot SlotNo
certificatesPrunedAt
     in SlotNo -> Map RankingBlockHash (SlotNo, LeiosCert) -> Certificates
MkCertificates SlotNo
prunedAt (((SlotNo, LeiosCert) -> Bool)
-> Map RankingBlockHash (SlotNo, LeiosCert)
-> Map RankingBlockHash (SlotNo, LeiosCert)
forall a k. (a -> Bool) -> Map k a -> Map k a
Map.filter ((SlotNo
prunedAt SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
<=) (SlotNo -> Bool)
-> ((SlotNo, LeiosCert) -> SlotNo) -> (SlotNo, LeiosCert) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SlotNo, LeiosCert) -> SlotNo
forall a b. (a, b) -> a
fst) Map RankingBlockHash (SlotNo, LeiosCert)
certificatesByRbHash)