{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

-- | The node's LeiosFetch state, which all its LeiosFetch clients share, and
-- the threads that maintain it: the decision loop, which assigns the peers'
-- offers to requests, and the worker that acts on new announcements.
module Ouroboros.Consensus.MiniProtocol.LeiosFetch.Kernel
  ( LeiosFetchKernel (..)
  , LeiosFetchPeer (..)
  , LeiosPeerLifetimeId (..)
  , newLeiosFetchKernel
  , withLeiosFetchPeer
  , recordLeiosOffer
  , recordLeiosCertOffer
  , recordLeiosJumpOffers
  , ExnLeiosTwoCertificationClaims (..)
  , enqueueLeiosAnnouncement
  , leiosFetchAnnouncementFocuser
  , onForgedLeiosEb
  , leiosFetchCertificateFocuser
  , leiosFetchDecisionLoop
  , pruneLeiosFetchToImmTip
  ) where

import Control.Monad (forM_, forever, unless, void, when)
import Control.Monad.Except (runExcept)
import qualified Data.Foldable as F
import Data.List.NonEmpty (NonEmpty)
import qualified Data.Map.NonEmpty as NEMap
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (..))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import qualified Data.Sequence.NonEmpty as NESeq
import Data.Void (Void)
import Data.Word (Word64)
import Ouroboros.Consensus.Block
  ( BlockProtocol
  , BlockSupportsProtocol (..)
  , Header
  , Point (GenesisPoint)
  , Proxy (..)
  , SlotNo (..)
  , WithOrigin (..)
  , blockPoint
  , castPoint
  , pointSlot
  , withOrigin
  )
import Ouroboros.Consensus.BlockchainTime (BlockchainTime (..), CurrentSlot (..))
import Ouroboros.Consensus.Config (TopLevelConfig, configBlock, configLedger)
import Ouroboros.Consensus.Forecast (forecastFor)
import Ouroboros.Consensus.HardFork.Abstract (HasHardForkHistory (..))
import qualified Ouroboros.Consensus.HardFork.History as HardFork
import Ouroboros.Consensus.HeaderStateHistory
  ( HeaderStateHistory (..)
  , HeaderStateWithTime (..)
  )
import Ouroboros.Consensus.HeaderValidation
  ( AnnTip (..)
  , HeaderState (..)
  , HeaderWithTime (..)
  , headerStatePoint
  )
import Ouroboros.Consensus.Ledger.Abstract (getTipSlot)
import Ouroboros.Consensus.Ledger.Extended (ledgerState)
import Ouroboros.Consensus.Ledger.SupportsProtocol (LedgerSupportsProtocol (..))
import Ouroboros.Consensus.Leios.Cert (LeiosClaim (..))
import Ouroboros.Consensus.Leios.Protocol
  ( LeiosAnnouncement (..)
  , LeiosLedgerView (..)
  , LeiosProtocol (..)
  , leiosEbByteSizeBounds
  )
import Ouroboros.Consensus.Leios.TxCache.API (evictOlderThan)
import Ouroboros.Consensus.Leios.Types
  ( ElectionId (..)
  , EndorserBlockHash
  , ForgedEndorserBlock
  , LeiosEbByteSizes (..)
  , LeiosPoint (..)
  , minCertificationSlot
  )
import Ouroboros.Consensus.MiniProtocol.ChainSync.Client.State (JumpInfo (..))
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Client.Replies
  ( LeiosFetchClientContext (..)
  , acquireForgedEb
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision
  ( LeiosFetchRequest
  , LeiosOutstanding (..)
  , OfferedHalves (..)
  , PeerOffer (..)
  , focusCertifiedEb
  , focusElectionIfUnfocused
  , initializeLeiosOutstanding
  , leiosFetchLogicIteration
  , pruneOffers
  , pruneOutstandingToImmTip
  , recordReferencedPoint
  , removePeerFromOutstanding
  )
import Ouroboros.Consensus.MiniProtocol.LeiosNotify.Client.Announcements.Validation
  ( AnnouncingHeader (..)
  , ValidAnnouncement (..)
  )
import Ouroboros.Consensus.Storage.ChainDB.API (ChainDB)
import qualified Ouroboros.Consensus.Storage.ChainDB.API as ChainDB
import Ouroboros.Consensus.Storage.LeiosDB.API
  ( LeiosDbHandle
  , LeiosDbReader (..)
  , withReader
  )
import Ouroboros.Consensus.Util.IOLike
  ( DiffTime
  , Exception
  , IOLike
  , STM
  , StrictMVar
  , StrictTVar
  , TQueue
  , atomically
  , bracket
  , diffTime
  , getMonotonicTime
  , modifyMVar
  , modifyMVar_
  , modifyTVar
  , newTQueueIO
  , readTQueue
  , readTVar
  , readTVarIO
  , takeMVar
  , threadDelay
  , throwIO
  , tryPutMVar
  , uncheckedNewEmptyMVar
  , uncheckedNewMVar
  , uncheckedNewTVarM
  , writeTQueue
  , writeTVar
  )
import qualified Ouroboros.Network.AnchoredFragment as AF
import qualified Ouroboros.Network.AnchoredSeq as AS
import Ouroboros.Network.PeerSelection.LedgerPeers.Type (IsBigLedgerPeer)
import System.Random (StdGen)

-- | The node's LeiosFetch state, which all its LeiosFetch clients share.
data LeiosFetchKernel m peer blk = MkLeiosFetchKernel
  { forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: !(LeiosFetchClientContext m (LeiosPeerLifetimeId peer))
  , forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> StrictTVar
     m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: !(StrictTVar m (Map.Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)))
  -- ^ The upstream peers the decision loop assigns requests to, each
  -- registered at most once at a time; see 'withLeiosFetchPeer'.
  , forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m Word64
lfkNextLifetimeId :: !(StrictTVar m Word64)
  -- ^ What tells the next registration's 'LeiosPeerLifetimeId' apart from
  -- every earlier one.
  , forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
lfkPrunedSlot :: !(StrictTVar m SlotNo)
  -- ^ The slot 'pruneLeiosFetchToImmTip' has most recently pruned the peers'
  -- offers and claims to. Nothing older is recorded afterwards, so that an
  -- offer or claim that arrives after the pruning cannot undo it.
  , forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> TQueue m (ValidAnnouncement blk)
lfkAnnouncements :: !(TQueue m (ValidAnnouncement blk))
  -- ^ The announcements 'leiosFetchAnnouncementFocuser' has yet to act on; see
  -- 'enqueueLeiosAnnouncement'.
  }

-- | Identifies one registration of an upstream peer with the decision loop,
-- from when the first of its mini-protocols registers it until it is
-- unregistered; see 'withLeiosFetchPeer'. The decision loop's state is keyed
-- by it rather than by the peer, which the peer's later registrations share.
--
-- The peer alone would not do, even though connections whose mini-protocols
-- run at the same time have different @ConnectionId@s: that covers only the
-- mini-protocols' own threads. The LeiosDB writes asynchronously, so for each
-- reply a LeiosFetch client forks a thread that waits for the write and then
-- updates the decision loop's state for the peer, and that thread may outlive
-- the client. By then the peer may have registered again, after the mux
-- restarted its mini-protocols or after it reconnected with the same
-- @ConnectionId@, and the update would act on that registration instead.
data LeiosPeerLifetimeId peer = MkLeiosPeerLifetimeId !peer !Word64
  deriving (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
(LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> Eq (LeiosPeerLifetimeId peer)
forall peer.
Eq peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall peer.
Eq peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
== :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
$c/= :: forall peer.
Eq peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
/= :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
Eq, Eq (LeiosPeerLifetimeId peer)
Eq (LeiosPeerLifetimeId peer) =>
(LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Ordering)
-> (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> (LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool)
-> (LeiosPeerLifetimeId peer
    -> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer)
-> (LeiosPeerLifetimeId peer
    -> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer)
-> Ord (LeiosPeerLifetimeId peer)
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Ordering
LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
forall peer. Ord peer => Eq (LeiosPeerLifetimeId peer)
forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Ordering
forall peer.
Ord peer =>
LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
$ccompare :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Ordering
compare :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Ordering
$c< :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
< :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
$c<= :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
<= :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
$c> :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
> :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
$c>= :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
>= :: LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer -> Bool
$cmax :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
max :: LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
$cmin :: forall peer.
Ord peer =>
LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
min :: LeiosPeerLifetimeId peer
-> LeiosPeerLifetimeId peer -> LeiosPeerLifetimeId peer
Ord, Int -> LeiosPeerLifetimeId peer -> ShowS
[LeiosPeerLifetimeId peer] -> ShowS
LeiosPeerLifetimeId peer -> String
(Int -> LeiosPeerLifetimeId peer -> ShowS)
-> (LeiosPeerLifetimeId peer -> String)
-> ([LeiosPeerLifetimeId peer] -> ShowS)
-> Show (LeiosPeerLifetimeId peer)
forall peer. Show peer => Int -> LeiosPeerLifetimeId peer -> ShowS
forall peer. Show peer => [LeiosPeerLifetimeId peer] -> ShowS
forall peer. Show peer => LeiosPeerLifetimeId peer -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall peer. Show peer => Int -> LeiosPeerLifetimeId peer -> ShowS
showsPrec :: Int -> LeiosPeerLifetimeId peer -> ShowS
$cshow :: forall peer. Show peer => LeiosPeerLifetimeId peer -> String
show :: LeiosPeerLifetimeId peer -> String
$cshowList :: forall peer. Show peer => [LeiosPeerLifetimeId peer] -> ShowS
showList :: [LeiosPeerLifetimeId peer] -> ShowS
Show)

-- | What the node's LeiosFetch state holds about one upstream peer.
data LeiosFetchPeer m blk = MkLeiosFetchPeer
  { forall (m :: * -> *) blk. LeiosFetchPeer m blk -> IsBigLedgerPeer
lfpIsBigLedgerPeer :: !IsBigLedgerPeer
  -- ^ Fixed for the connection's lifetime. The decision logic fetches more
  -- aggressively from a big-ledger peer.
  , forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings :: !(StrictTVar m (Map.Map LeiosPoint PeerOffer))
  -- ^ The peer's current offers, keyed by point. Written only by the
  -- LeiosNotify and ChainSync clients, as the peer offers, and by the decision
  -- loop and the pruner, as offers go dead.
  , forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Seq LeiosFetchRequest)
lfpRequestsToSend :: !(StrictTVar m (Seq LeiosFetchRequest))
  -- ^ The requests the decision loop assigned to this peer that its LeiosFetch
  -- client has not sent yet.
  , forall (m :: * -> *) blk.
LeiosFetchPeer m blk
-> StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims :: !(StrictTVar m (Map.Map ElectionId EndorserBlockHash))
  -- ^ The endorser block the peer's ChainSync roll-forwards claim is certified,
  -- per election; see 'recordLeiosCertOffer'.
  , forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Point blk)
lfpJumpedThrough :: !(StrictTVar m (Point blk))
  -- ^ The newest header of the latest ChainSync jump the peer accepted; see
  -- 'recordLeiosJumpOffers'.
  }

-- | The node's LeiosFetch state, seeded with the complete closures its LeiosDB
-- holds whose announcements the immutable tip has not passed, so that it
-- neither fetches them nor emits their acquisitions again.
newLeiosFetchKernel ::
  (IOLike m, LedgerSupportsProtocol blk) =>
  ChainDB m blk ->
  LeiosDbHandle m ->
  -- | Seeds the decision loop's PRNG.
  StdGen ->
  -- | Everything of the clients' context but the state this creates.
  ( StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer)) ->
    StrictMVar m () ->
    LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
  ) ->
  m (LeiosFetchKernel m peer blk)
newLeiosFetchKernel :: forall (m :: * -> *) blk peer.
(IOLike m, LedgerSupportsProtocol blk) =>
ChainDB m blk
-> LeiosDbHandle m
-> StdGen
-> (StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
    -> StrictMVar m ()
    -> LeiosFetchClientContext m (LeiosPeerLifetimeId peer))
-> m (LeiosFetchKernel m peer blk)
newLeiosFetchKernel ChainDB m blk
chainDB LeiosDbHandle m
leiosDb StdGen
prng StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
-> StrictMVar m ()
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
mkContext = do
  immTipSlot <-
    STM m SlotNo -> m SlotNo
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m SlotNo -> m SlotNo) -> STM m SlotNo -> m SlotNo
forall a b. (a -> b) -> a -> b
$
      SlotNo -> (SlotNo -> SlotNo) -> WithOrigin SlotNo -> SlotNo
forall b t. b -> (t -> b) -> WithOrigin t -> b
withOrigin (Word64 -> SlotNo
SlotNo Word64
0) SlotNo -> SlotNo
forall a. a -> a
id (WithOrigin SlotNo -> SlotNo)
-> (ExtLedgerState blk EmptyMK -> WithOrigin SlotNo)
-> ExtLedgerState blk EmptyMK
-> SlotNo
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LedgerState blk EmptyMK -> WithOrigin SlotNo
forall (l :: LedgerStateKind) (mk :: MapKind).
GetTip l =>
l mk -> WithOrigin SlotNo
getTipSlot (LedgerState blk EmptyMK -> WithOrigin SlotNo)
-> (ExtLedgerState blk EmptyMK -> LedgerState blk EmptyMK)
-> ExtLedgerState blk EmptyMK
-> WithOrigin SlotNo
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ExtLedgerState blk EmptyMK -> LedgerState blk EmptyMK
forall blk (mk :: MapKind).
ExtLedgerState blk mk -> LedgerState blk mk
ledgerState (ExtLedgerState blk EmptyMK -> SlotNo)
-> STM m (ExtLedgerState blk EmptyMK) -> STM m SlotNo
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ChainDB m blk -> STM m (ExtLedgerState blk EmptyMK)
forall (m :: * -> *) blk.
ChainDB m blk -> STM m (ExtLedgerState blk EmptyMK)
ChainDB.getImmutableLedger ChainDB m blk
chainDB
  acquired <- withReader leiosDb $ \LeiosDbReader m
reader ->
    LeiosDbReader m -> HasCallStack => SlotNo -> m [LeiosPoint]
forall (m :: * -> *).
LeiosDbReader m -> HasCallStack => SlotNo -> m [LeiosPoint]
scanCompleteEbClosuresNotOlderThanSlot LeiosDbReader m
reader SlotNo
immTipSlot
  outstanding <- uncheckedNewMVar $ initializeLeiosOutstanding prng acquired immTipSlot
  ready <- uncheckedNewEmptyMVar
  lfkPeers <- uncheckedNewTVarM Map.empty
  lfkNextLifetimeId <- uncheckedNewTVarM 0
  lfkPrunedSlot <- uncheckedNewTVarM immTipSlot
  lfkAnnouncements <- newTQueueIO
  pure
    MkLeiosFetchKernel
      { lfkContext = mkContext outstanding ready
      , lfkPeers
      , lfkNextLifetimeId
      , lfkPrunedSlot
      , lfkAnnouncements
      }

-- | Run the action with this peer's LeiosFetch state and the
-- 'LeiosPeerLifetimeId' of its registration, registering it with the decision
-- loop if no other mini-protocol of the peer has.
--
-- There is no reference count: the first of the peer's mini-protocols to end
-- unregisters it, and cancels what it had in flight, so that other peers are
-- asked instead. Any of its mini-protocols still running keep their state, but
-- the decision loop no longer assigns them anything.
--
-- A connection's mini-protocols find its registration by @peer@, so
-- connections whose mini-protocols run at the same time must have different
-- @peer@s. Their @ConnectionId@s differ, by the exclusivity of @ConnectionId@s
-- (see "Ouroboros.Network.ConnectionId#exclusivity").
withLeiosFetchPeer ::
  (IOLike m, Ord peer) =>
  LeiosFetchKernel m peer blk ->
  peer ->
  IsBigLedgerPeer ->
  (LeiosPeerLifetimeId peer -> LeiosFetchPeer m blk -> m a) ->
  m a
withLeiosFetchPeer :: forall (m :: * -> *) peer blk a.
(IOLike m, Ord peer) =>
LeiosFetchKernel m peer blk
-> peer
-> IsBigLedgerPeer
-> (LeiosPeerLifetimeId peer -> LeiosFetchPeer m blk -> m a)
-> m a
withLeiosFetchPeer LeiosFetchKernel m peer blk
kernel peer
peer IsBigLedgerPeer
isBig LeiosPeerLifetimeId peer -> LeiosFetchPeer m blk -> m a
k = m (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
-> ((LeiosPeerLifetimeId peer, LeiosFetchPeer m blk) -> m ())
-> ((LeiosPeerLifetimeId peer, LeiosFetchPeer m blk) -> m a)
-> m a
forall a b c. m a -> (a -> m b) -> (a -> m c) -> m c
forall (m :: * -> *) a b c.
MonadThrow m =>
m a -> (a -> m b) -> (a -> m c) -> m c
bracket m (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
register (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk) -> m ()
forall {b}. (LeiosPeerLifetimeId peer, b) -> m ()
unregister ((LeiosPeerLifetimeId peer -> LeiosFetchPeer m blk -> m a)
-> (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk) -> m a
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry LeiosPeerLifetimeId peer -> LeiosFetchPeer m blk -> m a
k)
 where
  MkLeiosFetchKernel{LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext, StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> StrictTVar
     m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers, StrictTVar m Word64
lfkNextLifetimeId :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m Word64
lfkNextLifetimeId :: StrictTVar m Word64
lfkNextLifetimeId} = LeiosFetchKernel m peer blk
kernel

  register :: m (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
register = do
    fresh <-
      IsBigLedgerPeer
-> StrictTVar m (Map LeiosPoint PeerOffer)
-> StrictTVar m (Seq LeiosFetchRequest)
-> StrictTVar m (Map ElectionId EndorserBlockHash)
-> StrictTVar m (Point blk)
-> LeiosFetchPeer m blk
forall (m :: * -> *) blk.
IsBigLedgerPeer
-> StrictTVar m (Map LeiosPoint PeerOffer)
-> StrictTVar m (Seq LeiosFetchRequest)
-> StrictTVar m (Map ElectionId EndorserBlockHash)
-> StrictTVar m (Point blk)
-> LeiosFetchPeer m blk
MkLeiosFetchPeer IsBigLedgerPeer
isBig
        (StrictTVar m (Map LeiosPoint PeerOffer)
 -> StrictTVar m (Seq LeiosFetchRequest)
 -> StrictTVar m (Map ElectionId EndorserBlockHash)
 -> StrictTVar m (Point blk)
 -> LeiosFetchPeer m blk)
-> m (StrictTVar m (Map LeiosPoint PeerOffer))
-> m (StrictTVar m (Seq LeiosFetchRequest)
      -> StrictTVar m (Map ElectionId EndorserBlockHash)
      -> StrictTVar m (Point blk)
      -> LeiosFetchPeer m blk)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Map LeiosPoint PeerOffer
-> m (StrictTVar m (Map LeiosPoint PeerOffer))
forall (m :: * -> *) a. MonadSTM m => a -> m (StrictTVar m a)
uncheckedNewTVarM Map LeiosPoint PeerOffer
forall k a. Map k a
Map.empty
        m (StrictTVar m (Seq LeiosFetchRequest)
   -> StrictTVar m (Map ElectionId EndorserBlockHash)
   -> StrictTVar m (Point blk)
   -> LeiosFetchPeer m blk)
-> m (StrictTVar m (Seq LeiosFetchRequest))
-> m (StrictTVar m (Map ElectionId EndorserBlockHash)
      -> StrictTVar m (Point blk) -> LeiosFetchPeer 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
<*> Seq LeiosFetchRequest -> m (StrictTVar m (Seq LeiosFetchRequest))
forall (m :: * -> *) a. MonadSTM m => a -> m (StrictTVar m a)
uncheckedNewTVarM Seq LeiosFetchRequest
forall a. Seq a
Seq.empty
        m (StrictTVar m (Map ElectionId EndorserBlockHash)
   -> StrictTVar m (Point blk) -> LeiosFetchPeer m blk)
-> m (StrictTVar m (Map ElectionId EndorserBlockHash))
-> m (StrictTVar m (Point blk) -> LeiosFetchPeer 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
<*> Map ElectionId EndorserBlockHash
-> m (StrictTVar m (Map ElectionId EndorserBlockHash))
forall (m :: * -> *) a. MonadSTM m => a -> m (StrictTVar m a)
uncheckedNewTVarM Map ElectionId EndorserBlockHash
forall k a. Map k a
Map.empty
        m (StrictTVar m (Point blk) -> LeiosFetchPeer m blk)
-> m (StrictTVar m (Point blk)) -> m (LeiosFetchPeer 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
<*> Point blk -> m (StrictTVar m (Point blk))
forall (m :: * -> *) a. MonadSTM m => a -> m (StrictTVar m a)
uncheckedNewTVarM Point blk
forall {k} (block :: k). Point block
GenesisPoint
    atomically $ do
      peers <- readTVar lfkPeers
      -- 'LeiosPeerLifetimeId's order by their peer first, so this finds the
      -- peer's registration if it has one.
      case Map.lookupGE (MkLeiosPeerLifetimeId peer 0) peers of
        Just (lifetimeId :: LeiosPeerLifetimeId peer
lifetimeId@(MkLeiosPeerLifetimeId peer
peer' Word64
_), LeiosFetchPeer m blk
existing)
          | peer
peer' peer -> peer -> Bool
forall a. Eq a => a -> a -> Bool
== peer
peer -> (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
-> STM m (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosPeerLifetimeId peer
lifetimeId, LeiosFetchPeer m blk
existing)
        Maybe (LeiosPeerLifetimeId peer, LeiosFetchPeer m blk)
_ -> do
          n <- StrictTVar m Word64 -> STM m Word64
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar m Word64
lfkNextLifetimeId
          writeTVar lfkNextLifetimeId (n + 1)
          let lifetimeId = peer -> Word64 -> LeiosPeerLifetimeId peer
forall peer. peer -> Word64 -> LeiosPeerLifetimeId peer
MkLeiosPeerLifetimeId peer
peer Word64
n
          writeTVar lfkPeers (Map.insert lifetimeId fresh peers)
          pure (lifetimeId, fresh)

  -- The decision loop reads the registered peers within the same critical
  -- section in which it assigns requests, so it cannot assign this peer
  -- anything after its requests are cancelled here. It then runs again, to ask
  -- other peers for what this one had in flight.
  unregister :: (LeiosPeerLifetimeId peer, b) -> m ()
unregister (LeiosPeerLifetimeId peer
lifetimeId, b
_) = do
    StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> m ()
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m a) -> m ()
modifyMVar_ (LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
-> StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext) ((LeiosOutstanding (LeiosPeerLifetimeId peer)
  -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
 -> m ())
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> m ()
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding -> do
      STM m () -> m ()
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m () -> m ()) -> STM m () -> m ()
forall a b. (a -> b) -> a -> b
$ StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
-> (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
    -> Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
-> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers (LeiosPeerLifetimeId peer
-> Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
-> Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete LeiosPeerLifetimeId peer
lifetimeId)
      LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding (LeiosPeerLifetimeId peer)
 -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall a b. (a -> b) -> a -> b
$! LeiosPeerLifetimeId peer
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall peer.
Ord peer =>
peer -> LeiosOutstanding peer -> LeiosOutstanding peer
removePeerFromOutstanding LeiosPeerLifetimeId peer
lifetimeId LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding
    m Bool -> m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (m Bool -> m ()) -> m Bool -> m ()
forall a b. (a -> b) -> a -> b
$ StrictMVar m () -> () -> m Bool
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> a -> m Bool
tryPutMVar (LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
-> StrictMVar m ()
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext) ()

-- | Record a peer's offer, which an earlier offer of the same point merges
-- with, unless the point is older than what has been pruned, and wake the
-- decision loop.
recordLeiosOffer ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  LeiosFetchPeer m blk ->
  LeiosPoint ->
  PeerOffer ->
  m ()
recordLeiosOffer :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> LeiosPoint -> PeerOffer -> m ()
recordLeiosOffer LeiosFetchKernel m peer blk
kernel MkLeiosFetchPeer{StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings :: forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings :: StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings} LeiosPoint
point PeerOffer
offer = do
  STM m () -> m ()
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m () -> m ()) -> STM m () -> m ()
forall a b. (a -> b) -> a -> b
$ do
    prunedSlot <- StrictTVar m SlotNo -> STM m SlotNo
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
lfkPrunedSlot LeiosFetchKernel m peer blk
kernel)
    unless (pointSlotNo point < prunedSlot) $
      modifyTVar lfpOfferings (Map.insertWith (<>) point offer)
  m Bool -> m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (m Bool -> m ()) -> m Bool -> m ()
forall a b. (a -> b) -> a -> b
$ StrictMVar m () -> () -> m Bool
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> a -> m Bool
tryPutMVar (LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
-> StrictMVar m ()
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady (LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext LeiosFetchKernel m peer blk
kernel)) ()

-- | Record the offer a peer makes by rolling forward a header that claims its
-- block contains a Leios certificate: the endorser block the certificate
-- certifies, both its body, at the size its announcement names, and its
-- closure.
--
-- That endorser block is read from the state as of the header's predecessor,
-- which announced it, so the peer chose which header to roll forward but not
-- what its predecessor announced. The certificate has not been verified yet, so
-- this only offers: what the node fetches is still up to each election's focus.
recordLeiosCertOffer ::
  forall m peer blk.
  (IOLike m, BlockSupportsProtocol blk) =>
  TopLevelConfig blk ->
  LeiosFetchKernel m peer blk ->
  LeiosFetchPeer m blk ->
  Header blk ->
  -- | The state as of the header's predecessor
  HeaderStateWithTime blk ->
  m ()
recordLeiosCertOffer :: forall (m :: * -> *) peer blk.
(IOLike m, BlockSupportsProtocol blk) =>
TopLevelConfig blk
-> LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk
-> Header blk
-> HeaderStateWithTime blk
-> m ()
recordLeiosCertOffer TopLevelConfig blk
cfg LeiosFetchKernel m peer blk
kernel LeiosFetchPeer m blk
peerVars Header blk
hdr HeaderStateWithTime blk
predState =
  Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Proxy (BlockProtocol blk)
-> ValidateView (BlockProtocol blk) -> Bool
forall p (proxy :: * -> *).
LeiosProtocol p =>
proxy p -> ValidateView p -> Bool
forall (proxy :: * -> *).
proxy (BlockProtocol blk)
-> ValidateView (BlockProtocol blk) -> Bool
getContainsLeiosCert Proxy (BlockProtocol blk)
p (BlockConfig blk -> Header blk -> ValidateView (BlockProtocol blk)
forall blk.
BlockSupportsProtocol blk =>
BlockConfig blk -> Header blk -> ValidateView (BlockProtocol blk)
validateView (TopLevelConfig blk -> BlockConfig blk
forall blk. TopLevelConfig blk -> BlockConfig blk
configBlock TopLevelConfig blk
cfg) Header blk
hdr)) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
    -- The predecessor of a valid header that claims its block contains a
    -- certificate announced an endorser block, in an era with Leios, so the
    -- other cases cannot arise. Ignoring the header then would be harmless.
    case ( HeaderState blk -> WithOrigin (AnnTip blk)
forall blk. HeaderState blk -> WithOrigin (AnnTip blk)
headerStateTip HeaderState blk
predHeaderState
         , Proxy (BlockProtocol blk)
-> ChainDepState (BlockProtocol blk) -> Maybe LeiosAnnouncement
forall p (proxy :: * -> *).
LeiosProtocol p =>
proxy p -> ChainDepState p -> Maybe LeiosAnnouncement
forall (proxy :: * -> *).
proxy (BlockProtocol blk)
-> ChainDepState (BlockProtocol blk) -> Maybe LeiosAnnouncement
getCertifiableLeiosAnnouncement Proxy (BlockProtocol blk)
p (HeaderState blk -> ChainDepState (BlockProtocol blk)
forall blk. HeaderState blk -> ChainDepState (BlockProtocol blk)
headerStateChainDep HeaderState blk
predHeaderState)
         , HeaderStateWithTime blk -> StrictMaybe LeiosLedgerView
forall blk. HeaderStateWithTime blk -> StrictMaybe LeiosLedgerView
hswtLeiosLedgerView HeaderStateWithTime blk
predState
         ) of
      (NotOrigin AnnTip blk
predTip, Just LeiosAnnouncement
announcement, SJust LeiosLedgerView
llv) -> do
        let slot :: SlotNo
slot = AnnTip blk -> SlotNo
forall blk. AnnTip blk -> SlotNo
annTipSlotNo AnnTip blk
predTip
            ebHash :: EndorserBlockHash
ebHash = LeiosAnnouncement -> EndorserBlockHash
announcementEbHash LeiosAnnouncement
announcement
        LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> ElectionId -> EndorserBlockHash -> m ()
forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> ElectionId -> EndorserBlockHash -> m ()
noteCertificationClaim
          LeiosFetchKernel m peer blk
kernel
          LeiosFetchPeer m blk
peerVars
          (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId SlotNo
slot (LeiosAnnouncement -> KeyHash BlockIssuer
announcementElectee LeiosAnnouncement
announcement))
          EndorserBlockHash
ebHash
        LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> LeiosPoint -> PeerOffer -> m ()
forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> LeiosPoint -> PeerOffer -> m ()
recordLeiosOffer LeiosFetchKernel m peer blk
kernel LeiosFetchPeer m blk
peerVars (SlotNo -> EndorserBlockHash -> LeiosPoint
MkLeiosPoint SlotNo
slot EndorserBlockHash
ebHash) (PeerOffer -> m ()) -> PeerOffer -> m ()
forall a b. (a -> b) -> a -> b
$
          MkPeerOffer
            { poEbBounds :: StrictMaybe (LeiosEbByteSizes 'SizeLimit)
poEbBounds = LeiosEbByteSizes 'SizeLimit
-> StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. a -> StrictMaybe a
SJust (LeiosLedgerView -> LeiosEbByteSizes 'SizeLimit
leiosEbByteSizeBounds LeiosLedgerView
llv)
            , poOffered :: OfferedHalves
poOffered = BytesSize -> OfferedHalves
OfferedBodyAndClosure (LeiosAnnouncement -> BytesSize
announcementEbSize LeiosAnnouncement
announcement)
            }
      (WithOrigin (AnnTip blk), Maybe LeiosAnnouncement,
 StrictMaybe LeiosLedgerView)
_ -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
 where
  p :: Proxy (BlockProtocol blk)
p = forall t. Proxy t
forall {k} (t :: k). Proxy t
Proxy @(BlockProtocol blk)
  predHeaderState :: HeaderState blk
predHeaderState = HeaderStateWithTime blk -> HeaderState blk
forall blk. HeaderStateWithTime blk -> HeaderState blk
hswtHeaderState HeaderStateWithTime blk
predState

-- | Count the peer's claim that an endorser block is certified for an
-- election, disconnecting it if it contradicts an earlier claim of the peer's.
--
-- An honest peer rolls forward only what it selects, and one chain certifies at
-- most one endorser block per election. Two chains certifying different ones
-- take two valid certificates for one election, which only a committee that
-- equivocated can produce.
--
-- Without this, a pool could equivocate its won slots into arbitrarily many
-- announcing blocks, follow each with a header claiming a certificate --- the
-- certificate is in the block body, which the node need never fetch --- and roll
-- them all forward, growing the peer's offers without bound.
--
-- A claim for an election older than what has been pruned is not counted.
noteCertificationClaim ::
  IOLike m =>
  LeiosFetchKernel m peer blk -> LeiosFetchPeer m blk -> ElectionId -> EndorserBlockHash -> m ()
noteCertificationClaim :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk -> ElectionId -> EndorserBlockHash -> m ()
noteCertificationClaim LeiosFetchKernel m peer blk
kernel MkLeiosFetchPeer{StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims :: forall (m :: * -> *) blk.
LeiosFetchPeer m blk
-> StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims :: StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims} ElectionId
elId EndorserBlockHash
ebHash = do
  conflict <- STM m (Maybe EndorserBlockHash) -> m (Maybe EndorserBlockHash)
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m (Maybe EndorserBlockHash) -> m (Maybe EndorserBlockHash))
-> STM m (Maybe EndorserBlockHash) -> m (Maybe EndorserBlockHash)
forall a b. (a -> b) -> a -> b
$ do
    prunedSlot <- StrictTVar m SlotNo -> STM m SlotNo
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar (LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
lfkPrunedSlot LeiosFetchKernel m peer blk
kernel)
    claims <- readTVar lfpCertificationClaims
    if electionSlot elId < prunedSlot
      then pure Nothing
      else case Map.lookup elId claims of
        Maybe EndorserBlockHash
Nothing -> Maybe EndorserBlockHash
forall a. Maybe a
Nothing Maybe EndorserBlockHash
-> STM m () -> STM m (Maybe EndorserBlockHash)
forall a b. a -> STM m b -> STM m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ StrictTVar m (Map ElectionId EndorserBlockHash)
-> Map ElectionId EndorserBlockHash -> STM m ()
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
StrictTVar m a -> a -> STM m ()
writeTVar StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims (ElectionId
-> EndorserBlockHash
-> Map ElectionId EndorserBlockHash
-> Map ElectionId EndorserBlockHash
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert ElectionId
elId EndorserBlockHash
ebHash Map ElectionId EndorserBlockHash
claims)
        Just EndorserBlockHash
claimed -> Maybe EndorserBlockHash -> STM m (Maybe EndorserBlockHash)
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe EndorserBlockHash -> STM m (Maybe EndorserBlockHash))
-> Maybe EndorserBlockHash -> STM m (Maybe EndorserBlockHash)
forall a b. (a -> b) -> a -> b
$ if EndorserBlockHash
claimed EndorserBlockHash -> EndorserBlockHash -> Bool
forall a. Eq a => a -> a -> Bool
== EndorserBlockHash
ebHash then Maybe EndorserBlockHash
forall a. Maybe a
Nothing else EndorserBlockHash -> Maybe EndorserBlockHash
forall a. a -> Maybe a
Just EndorserBlockHash
claimed
  forM_ conflict $ \EndorserBlockHash
claimed -> ExnLeiosTwoCertificationClaims -> m (ZonkAny 0)
forall e a. Exception e => e -> m a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwIO (ExnLeiosTwoCertificationClaims -> m (ZonkAny 0))
-> ExnLeiosTwoCertificationClaims -> m (ZonkAny 0)
forall a b. (a -> b) -> a -> b
$ ElectionId
-> EndorserBlockHash
-> EndorserBlockHash
-> ExnLeiosTwoCertificationClaims
ExnLeiosTwoCertificationClaims ElectionId
elId EndorserBlockHash
claimed EndorserBlockHash
ebHash

-- | Thrown when a peer's ChainSync roll-forwards claim that two different
-- endorser blocks are certified for one election; see 'noteCertificationClaim'.
data ExnLeiosTwoCertificationClaims
  = ExnLeiosTwoCertificationClaims !ElectionId !EndorserBlockHash !EndorserBlockHash
  deriving Int -> ExnLeiosTwoCertificationClaims -> ShowS
[ExnLeiosTwoCertificationClaims] -> ShowS
ExnLeiosTwoCertificationClaims -> String
(Int -> ExnLeiosTwoCertificationClaims -> ShowS)
-> (ExnLeiosTwoCertificationClaims -> String)
-> ([ExnLeiosTwoCertificationClaims] -> ShowS)
-> Show ExnLeiosTwoCertificationClaims
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ExnLeiosTwoCertificationClaims -> ShowS
showsPrec :: Int -> ExnLeiosTwoCertificationClaims -> ShowS
$cshow :: ExnLeiosTwoCertificationClaims -> String
show :: ExnLeiosTwoCertificationClaims -> String
$cshowList :: [ExnLeiosTwoCertificationClaims] -> ShowS
showList :: [ExnLeiosTwoCertificationClaims] -> ShowS
Show

instance Exception ExnLeiosTwoCertificationClaims

-- | 'recordLeiosCertOffer' for each header of a ChainSync jump the peer
-- accepted that its earlier jumps did not already cover.
--
-- Successive jumps along one chain overlap in all but their newest headers. If
-- this jump's fragment holds the newest header of the previous jump, it holds
-- the same headers before that one too, so those are skipped.
recordLeiosJumpOffers ::
  (IOLike m, LedgerSupportsProtocol blk) =>
  TopLevelConfig blk ->
  LeiosFetchKernel m peer blk ->
  LeiosFetchPeer m blk ->
  JumpInfo blk ->
  m ()
recordLeiosJumpOffers :: forall (m :: * -> *) blk peer.
(IOLike m, LedgerSupportsProtocol blk) =>
TopLevelConfig blk
-> LeiosFetchKernel m peer blk
-> LeiosFetchPeer m blk
-> JumpInfo blk
-> m ()
recordLeiosJumpOffers TopLevelConfig blk
cfg LeiosFetchKernel m peer blk
kernel LeiosFetchPeer m blk
peerVars JumpInfo blk
jumpInfo = do
  jumpedThrough <- StrictTVar m (Point blk) -> m (Point blk)
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> m a
readTVarIO (LeiosFetchPeer m blk -> StrictTVar m (Point blk)
forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Point blk)
lfpJumpedThrough LeiosFetchPeer m blk
peerVars)
  forM_ (headersWithPredecessorStates jumpedThrough jumpInfo) $
    uncurry (recordLeiosCertOffer cfg kernel peerVars)
  atomically $
    writeTVar (lfpJumpedThrough peerVars) (castPoint (AF.headPoint (jTheirFragment jumpInfo)))

-- | The headers of the jump's fragment after the given point, each with the
-- state as of its predecessor.
--
-- The history holds the state after each header of the fragment and after its
-- anchor, so splitting both after the same point leaves the history's anchor
-- holding the state before the first remaining header. If neither holds that
-- point, all of the fragment is walked.
headersWithPredecessorStates ::
  forall blk.
  LedgerSupportsProtocol blk =>
  Point blk ->
  JumpInfo blk ->
  [(Header blk, HeaderStateWithTime blk)]
headersWithPredecessorStates :: forall blk.
LedgerSupportsProtocol blk =>
Point blk
-> JumpInfo blk -> [(Header blk, HeaderStateWithTime blk)]
headersWithPredecessorStates Point blk
jumpedThrough JumpInfo blk
jumpInfo =
  [Header blk]
-> [HeaderStateWithTime blk]
-> [(Header blk, HeaderStateWithTime blk)]
forall a b. [a] -> [b] -> [(a, b)]
zip
    (HeaderWithTime blk -> Header blk
forall blk. HeaderWithTime blk -> Header blk
hwtHeader (HeaderWithTime blk -> Header blk)
-> [HeaderWithTime blk] -> [Header blk]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> AnchoredSeq
  (WithOrigin SlotNo)
  (Anchor (HeaderWithTime blk))
  (HeaderWithTime blk)
-> [HeaderWithTime blk]
forall v a b. AnchoredSeq v a b -> [b]
AF.toOldestFirst AnchoredSeq
  (WithOrigin SlotNo)
  (Anchor (HeaderWithTime blk))
  (HeaderWithTime blk)
fragment)
    (AnchoredSeq
  (WithOrigin SlotNo)
  (HeaderStateWithTime blk)
  (HeaderStateWithTime blk)
-> HeaderStateWithTime blk
forall v a b. AnchoredSeq v a b -> a
AS.anchor AnchoredSeq
  (WithOrigin SlotNo)
  (HeaderStateWithTime blk)
  (HeaderStateWithTime blk)
history HeaderStateWithTime blk
-> [HeaderStateWithTime blk] -> [HeaderStateWithTime blk]
forall a. a -> [a] -> [a]
: AnchoredSeq
  (WithOrigin SlotNo)
  (HeaderStateWithTime blk)
  (HeaderStateWithTime blk)
-> [HeaderStateWithTime blk]
forall v a b. AnchoredSeq v a b -> [b]
AS.toOldestFirst AnchoredSeq
  (WithOrigin SlotNo)
  (HeaderStateWithTime blk)
  (HeaderStateWithTime blk)
history)
 where
  past ::
    AS.Anchorable (WithOrigin SlotNo) a b =>
    (Either a b -> Point blk) ->
    AS.AnchoredSeq (WithOrigin SlotNo) a b ->
    AS.AnchoredSeq (WithOrigin SlotNo) a b
  past :: forall a b.
Anchorable (WithOrigin SlotNo) a b =>
(Either a b -> Point blk)
-> AnchoredSeq (WithOrigin SlotNo) a b
-> AnchoredSeq (WithOrigin SlotNo) a b
past Either a b -> Point blk
pointOf AnchoredSeq (WithOrigin SlotNo) a b
s =
    AnchoredSeq (WithOrigin SlotNo) a b
-> ((AnchoredSeq (WithOrigin SlotNo) a b,
     AnchoredSeq (WithOrigin SlotNo) a b)
    -> AnchoredSeq (WithOrigin SlotNo) a b)
-> Maybe
     (AnchoredSeq (WithOrigin SlotNo) a b,
      AnchoredSeq (WithOrigin SlotNo) a b)
-> AnchoredSeq (WithOrigin SlotNo) a b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe AnchoredSeq (WithOrigin SlotNo) a b
s (AnchoredSeq (WithOrigin SlotNo) a b,
 AnchoredSeq (WithOrigin SlotNo) a b)
-> AnchoredSeq (WithOrigin SlotNo) a b
forall a b. (a, b) -> b
snd (Maybe
   (AnchoredSeq (WithOrigin SlotNo) a b,
    AnchoredSeq (WithOrigin SlotNo) a b)
 -> AnchoredSeq (WithOrigin SlotNo) a b)
-> Maybe
     (AnchoredSeq (WithOrigin SlotNo) a b,
      AnchoredSeq (WithOrigin SlotNo) a b)
-> AnchoredSeq (WithOrigin SlotNo) a b
forall a b. (a -> b) -> a -> b
$
      WithOrigin SlotNo
-> (Either a b -> Bool)
-> AnchoredSeq (WithOrigin SlotNo) a b
-> Maybe
     (AnchoredSeq (WithOrigin SlotNo) a b,
      AnchoredSeq (WithOrigin SlotNo) a b)
forall v a b.
Anchorable v a b =>
v
-> (Either a b -> Bool)
-> AnchoredSeq v a b
-> Maybe (AnchoredSeq v a b, AnchoredSeq v a b)
AS.splitAfterMeasure (Point blk -> WithOrigin SlotNo
forall {k} (block :: k). Point block -> WithOrigin SlotNo
pointSlot Point blk
jumpedThrough) ((Point blk -> Point blk -> Bool
forall a. Eq a => a -> a -> Bool
== Point blk
jumpedThrough) (Point blk -> Bool)
-> (Either a b -> Point blk) -> Either a b -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either a b -> Point blk
pointOf) AnchoredSeq (WithOrigin SlotNo) a b
s

  fragment :: AnchoredSeq
  (WithOrigin SlotNo)
  (Anchor (HeaderWithTime blk))
  (HeaderWithTime blk)
fragment =
    (Either (Anchor (HeaderWithTime blk)) (HeaderWithTime blk)
 -> Point blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (Anchor (HeaderWithTime blk))
     (HeaderWithTime blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (Anchor (HeaderWithTime blk))
     (HeaderWithTime blk)
forall a b.
Anchorable (WithOrigin SlotNo) a b =>
(Either a b -> Point blk)
-> AnchoredSeq (WithOrigin SlotNo) a b
-> AnchoredSeq (WithOrigin SlotNo) a b
past ((Anchor (HeaderWithTime blk) -> Point blk)
-> (HeaderWithTime blk -> Point blk)
-> Either (Anchor (HeaderWithTime blk)) (HeaderWithTime blk)
-> Point blk
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Point (HeaderWithTime blk) -> Point blk
forall {k1} {k2} (b :: k1) (b' :: k2).
Coercible (HeaderHash b) (HeaderHash b') =>
Point b -> Point b'
castPoint (Point (HeaderWithTime blk) -> Point blk)
-> (Anchor (HeaderWithTime blk) -> Point (HeaderWithTime blk))
-> Anchor (HeaderWithTime blk)
-> Point blk
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Anchor (HeaderWithTime blk) -> Point (HeaderWithTime blk)
forall block. Anchor block -> Point block
AF.anchorToPoint) (Point (HeaderWithTime blk) -> Point blk
forall {k1} {k2} (b :: k1) (b' :: k2).
Coercible (HeaderHash b) (HeaderHash b') =>
Point b -> Point b'
castPoint (Point (HeaderWithTime blk) -> Point blk)
-> (HeaderWithTime blk -> Point (HeaderWithTime blk))
-> HeaderWithTime blk
-> Point blk
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HeaderWithTime blk -> Point (HeaderWithTime blk)
forall block. HasHeader block => block -> Point block
blockPoint)) (AnchoredSeq
   (WithOrigin SlotNo)
   (Anchor (HeaderWithTime blk))
   (HeaderWithTime blk)
 -> AnchoredSeq
      (WithOrigin SlotNo)
      (Anchor (HeaderWithTime blk))
      (HeaderWithTime blk))
-> AnchoredSeq
     (WithOrigin SlotNo)
     (Anchor (HeaderWithTime blk))
     (HeaderWithTime blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (Anchor (HeaderWithTime blk))
     (HeaderWithTime blk)
forall a b. (a -> b) -> a -> b
$
      JumpInfo blk
-> AnchoredSeq
     (WithOrigin SlotNo)
     (Anchor (HeaderWithTime blk))
     (HeaderWithTime blk)
forall blk. JumpInfo blk -> AnchoredFragment (HeaderWithTime blk)
jTheirFragment JumpInfo blk
jumpInfo
  history :: AnchoredSeq
  (WithOrigin SlotNo)
  (HeaderStateWithTime blk)
  (HeaderStateWithTime blk)
history =
    (Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
 -> Point blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
forall a b.
Anchorable (WithOrigin SlotNo) a b =>
(Either a b -> Point blk)
-> AnchoredSeq (WithOrigin SlotNo) a b
-> AnchoredSeq (WithOrigin SlotNo) a b
past (HeaderState blk -> Point blk
forall blk. HasAnnTip blk => HeaderState blk -> Point blk
headerStatePoint (HeaderState blk -> Point blk)
-> (Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
    -> HeaderState blk)
-> Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
-> Point blk
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HeaderStateWithTime blk -> HeaderState blk
forall blk. HeaderStateWithTime blk -> HeaderState blk
hswtHeaderState (HeaderStateWithTime blk -> HeaderState blk)
-> (Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
    -> HeaderStateWithTime blk)
-> Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
-> HeaderState blk
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (HeaderStateWithTime blk -> HeaderStateWithTime blk)
-> (HeaderStateWithTime blk -> HeaderStateWithTime blk)
-> Either (HeaderStateWithTime blk) (HeaderStateWithTime blk)
-> HeaderStateWithTime blk
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either HeaderStateWithTime blk -> HeaderStateWithTime blk
forall a. a -> a
id HeaderStateWithTime blk -> HeaderStateWithTime blk
forall a. a -> a
id) (AnchoredSeq
   (WithOrigin SlotNo)
   (HeaderStateWithTime blk)
   (HeaderStateWithTime blk)
 -> AnchoredSeq
      (WithOrigin SlotNo)
      (HeaderStateWithTime blk)
      (HeaderStateWithTime blk))
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
forall a b. (a -> b) -> a -> b
$
      HeaderStateHistory blk
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
forall blk.
HeaderStateHistory blk
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
unHeaderStateHistory (HeaderStateHistory blk
 -> AnchoredSeq
      (WithOrigin SlotNo)
      (HeaderStateWithTime blk)
      (HeaderStateWithTime blk))
-> HeaderStateHistory blk
-> AnchoredSeq
     (WithOrigin SlotNo)
     (HeaderStateWithTime blk)
     (HeaderStateWithTime blk)
forall a b. (a -> b) -> a -> b
$
        JumpInfo blk -> HeaderStateHistory blk
forall blk. JumpInfo blk -> HeaderStateHistory blk
jTheirHeaderStateHistory JumpInfo blk
jumpInfo

-- | Commit, within the transaction in which
-- 'Ouroboros.Consensus.Leios.AnnounceState.onValidAnnouncement' accepts this
-- announcement as new and as proving no equivocation, to
-- 'leiosFetchAnnouncementFocuser' acting on it.
enqueueLeiosAnnouncement ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  ValidAnnouncement blk ->
  STM m ()
enqueueLeiosAnnouncement :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk -> ValidAnnouncement blk -> STM m ()
enqueueLeiosAnnouncement LeiosFetchKernel m peer blk
kernel = TQueue m (ValidAnnouncement blk)
-> ValidAnnouncement blk -> STM m ()
forall a. TQueue m a -> a -> STM m ()
forall (m :: * -> *) a. MonadSTM m => TQueue m a -> a -> STM m ()
writeTQueue (LeiosFetchKernel m peer blk -> TQueue m (ValidAnnouncement blk)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> TQueue m (ValidAnnouncement blk)
lfkAnnouncements LeiosFetchKernel m peer blk
kernel)

-- | Act on each announcement 'enqueueLeiosAnnouncement' commits to, in turn.
--
-- This thread must be carefully arranged to die if and only if the node is
-- shutting down. Then the transaction that accepts an announcement need only
-- include an enqueue, which this thread will definitely eventually handle.
--
-- The queue doesn't need an explicit bound, because it's only written to
-- after dedup and age checks, and only for an election's first announcement,
-- so it can't have more entries than there are volatile elections (at most
-- ~10000).
leiosFetchAnnouncementFocuser ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  m Void
leiosFetchAnnouncementFocuser :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk -> m Void
leiosFetchAnnouncementFocuser LeiosFetchKernel m peer blk
kernel =
  m () -> m Void
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (m () -> m Void) -> m () -> m Void
forall a b. (a -> b) -> a -> b
$ STM m (ValidAnnouncement blk) -> m (ValidAnnouncement blk)
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (TQueue m (ValidAnnouncement blk) -> STM m (ValidAnnouncement blk)
forall a. TQueue m a -> STM m a
forall (m :: * -> *) a. MonadSTM m => TQueue m a -> STM m a
readTQueue (LeiosFetchKernel m peer blk -> TQueue m (ValidAnnouncement blk)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> TQueue m (ValidAnnouncement blk)
lfkAnnouncements LeiosFetchKernel m peer blk
kernel)) m (ValidAnnouncement blk)
-> (ValidAnnouncement blk -> m ()) -> m ()
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= LeiosFetchKernel m peer blk -> ValidAnnouncement blk -> m ()
forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk -> ValidAnnouncement blk -> m ()
onNewLeiosAnnouncement LeiosFetchKernel m peer blk
kernel

-- | List the endorser block a new announcement names as one to fetch, if it
-- takes its election's focus.
--
-- One entry per election: the announcement that takes the election's focus. A
-- second announcement for an already-focused election is an equivocation, and
-- tracking its endorser block too would let a pool double what its won slots
-- cost us. If that one turns out to be the certified one, a verified
-- certificate gives it an entry then.
onNewLeiosAnnouncement ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  ValidAnnouncement blk ->
  m ()
onNewLeiosAnnouncement :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk -> ValidAnnouncement blk -> m ()
onNewLeiosAnnouncement LeiosFetchKernel m peer blk
kernel ValidAnnouncement blk
valid = do
  changed <- StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool))
-> m Bool
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
modifyMVar StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding ((LeiosOutstanding (LeiosPeerLifetimeId peer)
  -> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool))
 -> m Bool)
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool))
-> m Bool
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding ->
    let tooOld :: Bool
tooOld = SlotNo
slot SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< LeiosOutstanding (LeiosPeerLifetimeId peer) -> SlotNo
forall peer. LeiosOutstanding peer -> SlotNo
outstandingPrunedSlot LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding
        introducesFocus :: Bool
introducesFocus = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ ElectionId -> Map ElectionId EndorserBlockHash -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member ElectionId
elId (LeiosOutstanding (LeiosPeerLifetimeId peer)
-> Map ElectionId EndorserBlockHash
forall peer.
LeiosOutstanding peer -> Map ElectionId EndorserBlockHash
elFocus LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding)
        outstanding' :: LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding' =
          ElectionId
-> EndorserBlockHash
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused ElectionId
elId EndorserBlockHash
ebHash (LeiosOutstanding (LeiosPeerLifetimeId peer)
 -> LeiosOutstanding (LeiosPeerLifetimeId peer))
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall a b. (a -> b) -> a -> b
$
            LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime
forall a. a -> StrictMaybe a
SJust RelativeTime
announcementOnset) LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding
     in (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((LeiosOutstanding (LeiosPeerLifetimeId peer), Bool)
 -> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool))
-> (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer), Bool)
forall a b. (a -> b) -> a -> b
$
          if Bool
tooOld Bool -> Bool -> Bool
|| Bool -> Bool
not Bool
introducesFocus
            then (LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding, Bool
False)
            else (LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding', Bool
True)
  when changed $
    void $
      tryPutMVar lfcReady ()
 where
  MkLeiosFetchClientContext{StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding, StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady} = LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext LeiosFetchKernel m peer blk
kernel
  MkValidAnnouncement{announcingHeader :: forall blk. ValidAnnouncement blk -> AnnouncingHeader blk
announcingHeader = AnnouncingHeader blk
anc, RelativeTime
announcementOnset :: RelativeTime
announcementOnset :: forall blk. ValidAnnouncement blk -> RelativeTime
announcementOnset} = ValidAnnouncement blk
valid
  announcement :: LeiosAnnouncement
announcement = AnnouncingHeader blk -> LeiosAnnouncement
forall blk. AnnouncingHeader blk -> LeiosAnnouncement
ancAnnouncement AnnouncingHeader blk
anc
  elId :: ElectionId
elId = AnnouncingHeader blk -> ElectionId
forall blk. AnnouncingHeader blk -> ElectionId
ancElectionId AnnouncingHeader blk
anc
  slot :: SlotNo
slot = ElectionId -> SlotNo
electionSlot ElectionId
elId
  ebHash :: EndorserBlockHash
ebHash = LeiosAnnouncement -> EndorserBlockHash
announcementEbHash LeiosAnnouncement
announcement
  point :: LeiosPoint
point = SlotNo -> EndorserBlockHash -> LeiosPoint
MkLeiosPoint SlotNo
slot EndorserBlockHash
ebHash

-- | The forge's counterpart to receiving an announcement and its endorser block
-- from a peer: take in the endorser block the node's own forge produced, with
-- the header announcing it, with no peer ('acquireForgedEb').
--
-- The header must announce this endorser block.
onForgedLeiosEb ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  AnnouncingHeader blk ->
  ForgedEndorserBlock ->
  m ()
onForgedLeiosEb :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk
-> AnnouncingHeader blk -> ForgedEndorserBlock -> m ()
onForgedLeiosEb LeiosFetchKernel m peer blk
kernel AnnouncingHeader blk
anc = LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
-> ElectionId -> ForgedEndorserBlock -> m ()
forall (m :: * -> *) peer.
IOLike m =>
LeiosFetchClientContext m peer
-> ElectionId -> ForgedEndorserBlock -> m ()
acquireForgedEb (LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext LeiosFetchKernel m peer blk
kernel) (AnnouncingHeader blk -> ElectionId
forall blk. AnnouncingHeader blk -> ElectionId
ancElectionId AnnouncingHeader blk
anc)

-- | Each time something might give a peer something new to do, decide what to
-- request from every peer, at most twice a second.
leiosFetchDecisionLoop ::
  forall m peer blk.
  (IOLike m, Ord peer, LedgerSupportsProtocol blk, HasHardForkHistory blk) =>
  TopLevelConfig blk ->
  ChainDB m blk ->
  BlockchainTime m ->
  LeiosFetchKernel m peer blk ->
  m Void
leiosFetchDecisionLoop :: forall (m :: * -> *) peer blk.
(IOLike m, Ord peer, LedgerSupportsProtocol blk,
 HasHardForkHistory blk) =>
TopLevelConfig blk
-> ChainDB m blk
-> BlockchainTime m
-> LeiosFetchKernel m peer blk
-> m Void
leiosFetchDecisionLoop TopLevelConfig blk
cfg ChainDB m blk
chainDB BlockchainTime m
btime LeiosFetchKernel m peer blk
kernel = m () -> m Void
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (m () -> m Void) -> m () -> m Void
forall a b. (a -> b) -> a -> b
$ do
  () <- StrictMVar m () -> m ()
forall (m :: * -> *) a. MonadMVar m => StrictMVar m a -> m a
takeMVar StrictMVar m ()
lfcReady
  iterationStart <- getMonotonicTime
  (requests, offerDrops, peersVars) <- modifyMVar lfcOutstanding $ \LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding -> do
    -- Read the live peers while holding the outstanding state, so that this
    -- assigns nothing to a peer whose unregistering already cancelled its
    -- requests: their replies would never arrive, and the requests would stay
    -- outstanding forever.
    (peersVars, offerings, currentSlot, immLedger) <- STM
  m
  (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
   Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
   CurrentSlot, ExtLedgerState blk EmptyMK)
-> m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
      Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
      CurrentSlot, ExtLedgerState blk EmptyMK)
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM
   m
   (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
    Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
    CurrentSlot, ExtLedgerState blk EmptyMK)
 -> m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
       Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
       CurrentSlot, ExtLedgerState blk EmptyMK))
-> STM
     m
     (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
      Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
      CurrentSlot, ExtLedgerState blk EmptyMK)
-> m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk),
      Map (LeiosPeerLifetimeId peer) (Map LeiosPoint PeerOffer),
      CurrentSlot, ExtLedgerState blk EmptyMK)
forall a b. (a -> b) -> a -> b
$ do
      peersVars <- StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
-> STM m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers
      offerings <- traverse (readTVar . lfpOfferings) peersVars
      (,,,) peersVars offerings <$> getCurrentSlot btime <*> ChainDB.getImmutableLedger chainDB
    let
      -- One forecast anchor for the whole pass: the immutable tip, which is
      -- also what the announcement validation a LeiosNotify offer rides on
      -- forecast from, so it reaches every slot such an offer names.
      --
      -- 'forecastFor' requires a slot no older than its anchor. A point the
      -- pruner has yet to drop can be older, and gets the anchor's view.
      forecastLeiosView SlotNo
slot =
        Proxy (BlockProtocol blk)
-> LedgerView (BlockProtocol blk) -> Maybe LeiosLedgerView
forall p (proxy :: * -> *).
LeiosProtocol p =>
proxy p -> LedgerView p -> Maybe LeiosLedgerView
forall (proxy :: * -> *).
proxy (BlockProtocol blk)
-> LedgerView (BlockProtocol blk) -> Maybe LeiosLedgerView
getLeiosLedgerView (forall t. Proxy t
forall {k} (t :: k). Proxy t
Proxy @(BlockProtocol blk))
          (LedgerView (BlockProtocol blk) -> Maybe LeiosLedgerView)
-> Either OutsideForecastRange (LedgerView (BlockProtocol blk))
-> Either OutsideForecastRange (Maybe LeiosLedgerView)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Except OutsideForecastRange (LedgerView (BlockProtocol blk))
-> Either OutsideForecastRange (LedgerView (BlockProtocol blk))
forall e a. Except e a -> Either e a
runExcept
            ( Forecast (LedgerView (BlockProtocol blk))
-> SlotNo
-> Except OutsideForecastRange (LedgerView (BlockProtocol blk))
forall a. Forecast a -> SlotNo -> Except OutsideForecastRange a
forecastFor
                (LedgerCfg LedgerState blk
-> LedgerState blk EmptyMK
-> Forecast (LedgerView (BlockProtocol blk))
forall blk (mk :: MapKind).
(LedgerSupportsProtocol blk, HasCallStack) =>
LedgerConfig blk
-> LedgerState blk mk -> Forecast (LedgerView (BlockProtocol blk))
forall (mk :: MapKind).
HasCallStack =>
LedgerCfg LedgerState blk
-> LedgerState blk mk -> Forecast (LedgerView (BlockProtocol blk))
ledgerViewForecastAt (TopLevelConfig blk -> LedgerCfg LedgerState blk
forall blk. TopLevelConfig blk -> LedgerConfig blk
configLedger TopLevelConfig blk
cfg) (ExtLedgerState blk EmptyMK -> LedgerState blk EmptyMK
forall blk (mk :: MapKind).
ExtLedgerState blk mk -> LedgerState blk mk
ledgerState ExtLedgerState blk EmptyMK
immLedger))
                (SlotNo -> SlotNo -> SlotNo
forall a. Ord a => a -> a -> a
max SlotNo
anchorSlot SlotNo
slot)
            )
      anchorSlot = SlotNo -> (SlotNo -> SlotNo) -> WithOrigin SlotNo -> SlotNo
forall b t. b -> (t -> b) -> WithOrigin t -> b
withOrigin (Word64 -> SlotNo
SlotNo Word64
0) SlotNo -> SlotNo
forall a. a -> a
id (LedgerState blk EmptyMK -> WithOrigin SlotNo
forall (l :: LedgerStateKind) (mk :: MapKind).
GetTip l =>
l mk -> WithOrigin SlotNo
getTipSlot (ExtLedgerState blk EmptyMK -> LedgerState blk EmptyMK
forall blk (mk :: MapKind).
ExtLedgerState blk mk -> LedgerState blk mk
ledgerState ExtLedgerState blk EmptyMK
immLedger))
      forecastEbBounds SlotNo
slot = LeiosEbByteSizes 'SizeLimit
-> (LeiosLedgerView -> LeiosEbByteSizes 'SizeLimit)
-> Maybe LeiosLedgerView
-> LeiosEbByteSizes 'SizeLimit
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (BytesSize -> Word64 -> LeiosEbByteSizes 'SizeLimit
forall (r :: SizeRole). BytesSize -> Word64 -> LeiosEbByteSizes r
MkLeiosEbByteSizes BytesSize
0 Word64
0) LeiosLedgerView -> LeiosEbByteSizes 'SizeLimit
leiosEbByteSizeBounds (Maybe LeiosLedgerView -> LeiosEbByteSizes 'SizeLimit)
-> Either OutsideForecastRange (Maybe LeiosLedgerView)
-> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> SlotNo -> Either OutsideForecastRange (Maybe LeiosLedgerView)
forecastLeiosView SlotNo
slot
      -- The current slot, and how many slots before it a point is still worth
      -- voting on, by the Leios periods of the ledger there, if the ledger
      -- reaches that far.
      mbHorizon = case CurrentSlot
currentSlot of
        CurrentSlot
CurrentSlotUnknown -> Maybe (SlotNo, Word64)
forall a. Maybe a
Nothing
        CurrentSlot SlotNo
slot RelativeTime
_onset -> do
          llv <- (OutsideForecastRange -> Maybe LeiosLedgerView)
-> (Maybe LeiosLedgerView -> Maybe LeiosLedgerView)
-> Either OutsideForecastRange (Maybe LeiosLedgerView)
-> Maybe LeiosLedgerView
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe LeiosLedgerView
-> OutsideForecastRange -> Maybe LeiosLedgerView
forall a b. a -> b -> a
const Maybe LeiosLedgerView
forall a. Maybe a
Nothing) Maybe LeiosLedgerView -> Maybe LeiosLedgerView
forall a. a -> a
id (SlotNo -> Either OutsideForecastRange (Maybe LeiosLedgerView)
forecastLeiosView SlotNo
slot)
          (_onset, slotLength) <-
            either (const Nothing) Just $
              HardFork.runQuery
                (HardFork.slotToWallclock slot)
                (hardForkSummary (configLedger cfg) (ledgerState immLedger))
          let MkLeiosLedgerView{llvAnnouncementPeriod, llvVotePeriod, llvDiffusionPeriod} = llv
              SlotNo window =
                minCertificationSlot slotLength llvAnnouncementPeriod llvVotePeriod llvDiffusionPeriod 0
          pure (slot, window)
      (!outstanding', requests, offerDrops) =
        leiosFetchLogicIteration
          (lfcStaticEnv lfkContext)
          forecastEbBounds
          mbHorizon
          offerings
          (Map.map lfpIsBigLedgerPeer peersVars)
          outstanding
    pure (outstanding', (requests, offerDrops, peersVars))
  atomically $ do
    -- Prune what of the offers the decision found can no longer help.
    forM_ (Map.toList offerDrops) $ \(LeiosPeerLifetimeId peer
peer, NEMap LeiosPoint OfferPrune
pruned) ->
      Maybe (LeiosFetchPeer m blk)
-> (LeiosFetchPeer m blk -> STM m ()) -> STM m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (LeiosPeerLifetimeId peer
-> Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
-> Maybe (LeiosFetchPeer m blk)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPeerLifetimeId peer
peer Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
peersVars) ((LeiosFetchPeer m blk -> STM m ()) -> STM m ())
-> (LeiosFetchPeer m blk -> STM m ()) -> STM m ()
forall a b. (a -> b) -> a -> b
$ \LeiosFetchPeer m blk
vars ->
        StrictTVar m (Map LeiosPoint PeerOffer)
-> (Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer)
-> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar (LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings LeiosFetchPeer m blk
vars) (Map LeiosPoint OfferPrune
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
pruneOffers (NEMap LeiosPoint OfferPrune -> Map LeiosPoint OfferPrune
forall k a. NEMap k a -> Map k a
NEMap.toMap NEMap LeiosPoint OfferPrune
pruned))
    -- Published after the lock is released, so a peer that unregistered
    -- meanwhile still gets these, although unregistering cancelled their
    -- accounting. That is harmless: a peer unregisters only when one of its
    -- mini-protocols ends, which the diffusion layer answers by demoting or
    -- closing its connection, and its LeiosFetch client takes nothing more from
    -- its queue once told to terminate.
    forM_ (Map.toList requests) $ \(LeiosPeerLifetimeId peer
peer, NESeq LeiosFetchRequest
reqs) ->
      Maybe (LeiosFetchPeer m blk)
-> (LeiosFetchPeer m blk -> STM m ()) -> STM m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (LeiosPeerLifetimeId peer
-> Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
-> Maybe (LeiosFetchPeer m blk)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPeerLifetimeId peer
peer Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk)
peersVars) ((LeiosFetchPeer m blk -> STM m ()) -> STM m ())
-> (LeiosFetchPeer m blk -> STM m ()) -> STM m ()
forall a b. (a -> b) -> a -> b
$ \LeiosFetchPeer m blk
vars ->
        StrictTVar m (Seq LeiosFetchRequest)
-> (Seq LeiosFetchRequest -> Seq LeiosFetchRequest) -> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar (LeiosFetchPeer m blk -> StrictTVar m (Seq LeiosFetchRequest)
forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Seq LeiosFetchRequest)
lfpRequestsToSend LeiosFetchPeer m blk
vars) (Seq LeiosFetchRequest
-> Seq LeiosFetchRequest -> Seq LeiosFetchRequest
forall a. Semigroup a => a -> a -> a
<> NESeq LeiosFetchRequest -> Seq LeiosFetchRequest
forall a. NESeq a -> Seq a
NESeq.toSeq NESeq LeiosFetchRequest
reqs)
  iterationEnd <- getMonotonicTime
  threadDelay $ loopInterval - (iterationEnd `diffTime` iterationStart)
 where
  MkLeiosFetchKernel{LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext, StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> StrictTVar
     m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers} = LeiosFetchKernel m peer blk
kernel
  MkLeiosFetchClientContext{StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding, StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady} = LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext

  loopInterval :: DiffTime
  loopInterval :: DiffTime
loopInterval = DiffTime
0.5

-- | Move each election's focus onto the endorser block a verified certificate
-- certifies, as ChainSel verifies such certificates.
--
-- This is how a node that only saw some other announcement for the election,
-- or none, because the announcing block has been on its selection since before
-- it started, comes to fetch the certified one. Each iteration focuses the
-- elections certified since the one before, so a certificate verified after
-- the offer arrived still moves the focus.
leiosFetchCertificateFocuser ::
  IOLike m =>
  -- | The claims of the new Leios certifications validated since this last
  -- returned, each with the announcement it certifies, blocking until there is
  -- one
  m (NonEmpty (LeiosClaim, LeiosAnnouncement)) ->
  LeiosFetchKernel m peer blk ->
  m Void
leiosFetchCertificateFocuser :: forall (m :: * -> *) peer blk.
IOLike m =>
m (NonEmpty (LeiosClaim, LeiosAnnouncement))
-> LeiosFetchKernel m peer blk -> m Void
leiosFetchCertificateFocuser m (NonEmpty (LeiosClaim, LeiosAnnouncement))
consumeValidClaims LeiosFetchKernel m peer blk
kernel = m () -> m Void
forall (f :: * -> *) a b. Applicative f => f a -> f b
forever (m () -> m Void) -> m () -> m Void
forall a b. (a -> b) -> a -> b
$ do
  validClaims <- m (NonEmpty (LeiosClaim, LeiosAnnouncement))
consumeValidClaims
  modifyMVar_ lfcOutstanding $ \LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding ->
    LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding (LeiosPeerLifetimeId peer)
 -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall a b. (a -> b) -> a -> b
$ (LeiosOutstanding (LeiosPeerLifetimeId peer)
 -> (LeiosClaim, LeiosAnnouncement)
 -> LeiosOutstanding (LeiosPeerLifetimeId peer))
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> NonEmpty (LeiosClaim, LeiosAnnouncement)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall b a. (b -> a -> b) -> b -> NonEmpty a -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
F.foldl' LeiosOutstanding (LeiosPeerLifetimeId peer)
-> (LeiosClaim, LeiosAnnouncement)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall {peer}.
LeiosOutstanding peer
-> (LeiosClaim, LeiosAnnouncement) -> LeiosOutstanding peer
focus LeiosOutstanding (LeiosPeerLifetimeId peer)
outstanding NonEmpty (LeiosClaim, LeiosAnnouncement)
validClaims
  void $ tryPutMVar lfcReady ()
 where
  MkLeiosFetchClientContext{StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding, StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady} = LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext LeiosFetchKernel m peer blk
kernel

  focus :: LeiosOutstanding peer
-> (LeiosClaim, LeiosAnnouncement) -> LeiosOutstanding peer
focus LeiosOutstanding peer
outstanding (LeiosClaim
claim, LeiosAnnouncement
ann) =
    ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
ElectionId
-> EndorserBlockHash
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusCertifiedEb
      (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (LeiosClaim -> SlotNo
leiosClaimSlot LeiosClaim
claim) (LeiosAnnouncement -> KeyHash BlockIssuer
announcementElectee LeiosAnnouncement
ann))
      (LeiosAnnouncement -> EndorserBlockHash
announcementEbHash LeiosAnnouncement
ann)
      LeiosOutstanding peer
outstanding

-- | Prune the node's LeiosFetch state, the peers' offers and claims, and the
-- LeiosTxCache to the immutable tip's slot.
--
-- The ChainDB prunes the LeiosDB only to the slot of the blocks it has copied
-- to the ImmutableDB, after a delay, so pruning the LeiosTxCache as soon as the
-- immutable tip advances usually comes first; see
-- 'Ouroboros.Consensus.Leios.TxCache.API.evictOlderThanFoldl''.
pruneLeiosFetchToImmTip ::
  IOLike m =>
  LeiosFetchKernel m peer blk ->
  SlotNo ->
  m ()
pruneLeiosFetchToImmTip :: forall (m :: * -> *) peer blk.
IOLike m =>
LeiosFetchKernel m peer blk -> SlotNo -> m ()
pruneLeiosFetchToImmTip LeiosFetchKernel m peer blk
kernel SlotNo
immTipSlot = do
  LeiosTxCache m () Version PackedEndorserBlock -> SlotNo -> m ()
forall (m :: * -> *) a v b.
Functor m =>
LeiosTxCache m a v b -> SlotNo -> m ()
evictOlderThan LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache SlotNo
immTipSlot
  StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> m ()
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m a) -> m ()
modifyMVar_ StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding ((LeiosOutstanding (LeiosPeerLifetimeId peer)
  -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
 -> m ())
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> m ()
forall a b. (a -> b) -> a -> b
$ LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding (LeiosPeerLifetimeId peer)
 -> m (LeiosOutstanding (LeiosPeerLifetimeId peer)))
-> (LeiosOutstanding (LeiosPeerLifetimeId peer)
    -> LeiosOutstanding (LeiosPeerLifetimeId peer))
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> m (LeiosOutstanding (LeiosPeerLifetimeId peer))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SlotNo
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
-> LeiosOutstanding (LeiosPeerLifetimeId peer)
forall peer.
SlotNo -> LeiosOutstanding peer -> LeiosOutstanding peer
pruneOutstandingToImmTip SlotNo
immTipSlot
  -- Offers are keyed by point and claims by election, which both order by
  -- slot first.
  STM m () -> m ()
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m () -> m ()) -> STM m () -> m ()
forall a b. (a -> b) -> a -> b
$ do
    StrictTVar m SlotNo -> SlotNo -> STM m ()
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
StrictTVar m a -> a -> STM m ()
writeTVar StrictTVar m SlotNo
lfkPrunedSlot SlotNo
immTipSlot
    peersVars <- StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
-> STM m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers
    forM_ peersVars $ \LeiosFetchPeer m blk
vars -> do
      StrictTVar m (Map LeiosPoint PeerOffer)
-> (Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer)
-> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar (LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
forall (m :: * -> *) blk.
LeiosFetchPeer m blk -> StrictTVar m (Map LeiosPoint PeerOffer)
lfpOfferings LeiosFetchPeer m blk
vars) ((LeiosPoint -> Bool)
-> Map LeiosPoint PeerOffer -> Map LeiosPoint PeerOffer
forall k a. (k -> Bool) -> Map k a -> Map k a
Map.dropWhileAntitone ((SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< SlotNo
immTipSlot) (SlotNo -> Bool) -> (LeiosPoint -> SlotNo) -> LeiosPoint -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint -> SlotNo
pointSlotNo))
      StrictTVar m (Map ElectionId EndorserBlockHash)
-> (Map ElectionId EndorserBlockHash
    -> Map ElectionId EndorserBlockHash)
-> STM m ()
forall (m :: * -> *) a.
MonadSTM m =>
StrictTVar m a -> (a -> a) -> STM m ()
modifyTVar
        (LeiosFetchPeer m blk
-> StrictTVar m (Map ElectionId EndorserBlockHash)
forall (m :: * -> *) blk.
LeiosFetchPeer m blk
-> StrictTVar m (Map ElectionId EndorserBlockHash)
lfpCertificationClaims LeiosFetchPeer m blk
vars)
        ((ElectionId -> Bool)
-> Map ElectionId EndorserBlockHash
-> Map ElectionId EndorserBlockHash
forall k a. (k -> Bool) -> Map k a -> Map k a
Map.dropWhileAntitone ((SlotNo -> SlotNo -> Bool
forall a. Ord a => a -> a -> Bool
< SlotNo
immTipSlot) (SlotNo -> Bool) -> (ElectionId -> SlotNo) -> ElectionId -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId -> SlotNo
electionSlot))
 where
  MkLeiosFetchKernel{LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext :: LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext, StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk
-> StrictTVar
     m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers :: StrictTVar
  m (Map (LeiosPeerLifetimeId peer) (LeiosFetchPeer m blk))
lfkPeers, StrictTVar m SlotNo
lfkPrunedSlot :: forall (m :: * -> *) peer blk.
LeiosFetchKernel m peer blk -> StrictTVar m SlotNo
lfkPrunedSlot :: StrictTVar m SlotNo
lfkPrunedSlot} = LeiosFetchKernel m peer blk
kernel
  MkLeiosFetchClientContext{StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding (LeiosPeerLifetimeId peer))
lfcOutstanding, LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache} = LeiosFetchClientContext m (LeiosPeerLifetimeId peer)
lfkContext