{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

-- | What the node's LeiosFetch clients do: send the requests the decision
-- logic assigned to their peer, and take in the replies.
--
-- Taking in a reply is where the node acquires an endorser block or its
-- transactions, so it is also where it emits each acquisition, once the write
-- is durable: 'AcquiredEb' when the body is, and 'AcquiredEbTxs' when no job of
-- its closure remains. An endorser block the node forged is acquired here too,
-- as one that arrived with no peer ('acquireForgedEb').
module Ouroboros.Consensus.MiniProtocol.LeiosFetch.Client.Replies
  ( LeiosFetchClientContext (..)
  , ExnLeiosFetchInvalidReply (..)
  , JobMismatch (..)
  , awaitTerminate
  , nextLeiosFetchJob
  , processLeiosBlock
  , processLeiosBlockTxs
  , acquireForgedEb
  ) where

import Cardano.Ledger.Binary (DecoderError)
import Cardano.Ledger.Binary.Version (Version)
import Cardano.Ledger.Dijkstra (DijkstraEra)
import Control.Monad (void, when)
import Control.Tracer (Tracer, traceWith)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Foldable (fold, for_, toList)
import qualified Data.IntMap.NonEmpty as NEIntMap
import qualified Data.IntMap.Strict as IntMap
import qualified Data.IntSet as IntSet
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (..))
import Data.Monoid (Sum (..))
import Data.Proxy (Proxy (..))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Time.Clock (NominalDiffTime)
import qualified Data.Vector.Strict as V
import Data.Word (Word64)
import Ouroboros.Consensus.BlockchainTime.WallClock.Types
  ( RelativeTime
  , SystemTime (..)
  , diffRelTime
  )
import Ouroboros.Consensus.Leios.Acquisitions (LeiosAcquisition (..))
import Ouroboros.Consensus.Leios.TxCache.API
  ( LandedTx (..)
  , LeiosTxCache (..)
  , PackedEndorserBlock
  , TxState (..)
  , insertBody
  , packEndorserBlock
  )
import Ouroboros.Consensus.Leios.Types
  ( BytesSize
  , ElectionId (..)
  , EndorserBlock
  , EndorserBlockHash
  , ForgedEndorserBlock (..)
  , LeiosEbByteSizes (..)
  , LeiosPoint (..)
  , LeiosTx (..)
  , Serialised (..)
  , TxHash
  , TxLocation
  , TxOffset
  , deserialiseEndorserBlock
  , encodeEndorserBlockSize
  , endorserBlockHash
  , endorserBlockReferences
  , hashLeiosTx
  , hashSerialisedEndorserBlock
  , leiosEbByteSizes
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Client (SomeLeiosFetchJob (..))
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision
  ( EbFetchState (..)
  , EbState (..)
  , LeiosBlockRequest (..)
  , LeiosBlockTxsRequest (..)
  , LeiosFetchRequest (..)
  , LeiosFetchStaticEnv (..)
  , LeiosOutstanding (..)
  , acquireEbBody
  , completeTxRequest
  , ebStateOnset
  , holdForgedEb
  , newLeiosJobPool
  , refundEbRequest
  , refundTxRequest
  )
import qualified Ouroboros.Consensus.MiniProtocol.LeiosFetch.Jobs as Jobs
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Trace
  ( FetchArrivalBytes
  , TraceLeiosFetchClientEvent (..)
  , fetchArrivalEvicted
  , fetchArrivalExtra
  , fetchArrivalGood
  , fetchArrivalInvalid
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Type (Message (..), offsetsToBitmap)
import Ouroboros.Consensus.Storage.LeiosDB.API
  ( LeiosDbWriter (..)
  , LocalFills
  , Promise (..)
  , awaitAll
  )
import Ouroboros.Consensus.Util.IOLike
  ( Exception
  , IOLike
  , STM
  , StrictMVar
  , StrictTVar
  , atomically
  , evaluate
  , modifyMVar
  , readTVar
  , retry
  , throwIO
  , tryPutMVar
  , writeTVar
  )
import Ouroboros.Network.ControlMessage (ControlMessage (..), ControlMessageSTM)

-- | What every LeiosFetch client of the node shares.
data LeiosFetchClientContext m peer = MkLeiosFetchClientContext
  { forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosFetchStaticEnv
lfcStaticEnv :: !LeiosFetchStaticEnv
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: !(StrictMVar m (LeiosOutstanding peer))
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: !(StrictMVar m ())
  -- ^ Filled by anything that might unblock a new fetch decision.
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: !(LeiosTxCache m () Version PackedEndorserBlock)
  -- ^ Records each validated tx with the major protocol version it was
  -- validated under. The Mempool and LeiosVoting validate a tx only under the
  -- current major version, so a recorded validation still holds exactly when
  -- its version matches the current one.
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosDbWriter m
lfcWriter :: !(LeiosDbWriter m)
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosAcquisition -> STM m ()
lfcNotify :: !(LeiosAcquisition -> STM m ())
  -- ^ Emit an acquisition to the rest of the node.
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> SystemTime m
lfcSystemTime :: !(SystemTime m)
  -- ^ For reporting how long after its point's slot began an endorser block,
  -- or its transactions, were acquired.
  , forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: !(Tracer m (TraceLeiosFetchClientEvent peer))
  }

-- | A reply an honest peer would not send; the ensuing thread death
-- disconnects it.
data ExnLeiosFetchInvalidReply
  = -- | The endorser block does not have the requested hash.
    ExnLeiosBlockWrongHash
      !LeiosPoint
      -- | the hash of what arrived
      !EndorserBlockHash
  | -- | The endorser block has the requested hash, but not the size the peer
    -- offered it at.
    ExnLeiosBlockWrongSize
      !LeiosPoint
      -- | the offered size
      !BytesSize
      -- | its actual size
      !BytesSize
  | -- | The endorser block has the requested hash, but does not decode, so no
    -- honest peer holds it.
    ExnLeiosBlockUndecodable !LeiosPoint !DecoderError
  | -- | The endorser block is larger than the ledger allows.
    ExnLeiosBlockTooBig
      !LeiosPoint
      -- | its size
      !BytesSize
      -- | the most the ledger allows
      !BytesSize
  | -- | The endorser block references more transaction bytes than the ledger
    -- allows.
    ExnLeiosClosureTooBig
      !LeiosPoint
      -- | the bytes it references
      !Word64
      -- | the most the ledger allows
      !Word64
  | -- | Not as many transactions arrived as were requested.
    ExnLeiosBlockTxsWrongCount
      !LeiosPoint
      -- | how many were requested
      !Int
      -- | how many arrived
      !Int
  | -- | The transactions that arrived for a job are not the ones its
    -- endorser block lists.
    ExnLeiosBlockTxsJobMismatch !LeiosPoint !Jobs.LeiosJobId !JobMismatch
  deriving Int -> ExnLeiosFetchInvalidReply -> ShowS
[ExnLeiosFetchInvalidReply] -> ShowS
ExnLeiosFetchInvalidReply -> String
(Int -> ExnLeiosFetchInvalidReply -> ShowS)
-> (ExnLeiosFetchInvalidReply -> String)
-> ([ExnLeiosFetchInvalidReply] -> ShowS)
-> Show ExnLeiosFetchInvalidReply
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ExnLeiosFetchInvalidReply -> ShowS
showsPrec :: Int -> ExnLeiosFetchInvalidReply -> ShowS
$cshow :: ExnLeiosFetchInvalidReply -> String
show :: ExnLeiosFetchInvalidReply -> String
$cshowList :: [ExnLeiosFetchInvalidReply] -> ShowS
showList :: [ExnLeiosFetchInvalidReply] -> ShowS
Show

instance Exception ExnLeiosFetchInvalidReply

-- | How a job's transactions differ from what it covers.
data JobMismatch = JobBytesSizeMismatch | JobCommitmentMismatch
  deriving Int -> JobMismatch -> ShowS
[JobMismatch] -> ShowS
JobMismatch -> String
(Int -> JobMismatch -> ShowS)
-> (JobMismatch -> String)
-> ([JobMismatch] -> ShowS)
-> Show JobMismatch
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> JobMismatch -> ShowS
showsPrec :: Int -> JobMismatch -> ShowS
$cshow :: JobMismatch -> String
show :: JobMismatch -> String
$cshowList :: [JobMismatch] -> ShowS
showList :: [JobMismatch] -> ShowS
Show

-----

-- | Blocks until this peer's client should stop.
awaitTerminate :: IOLike m => ControlMessageSTM m -> STM m ()
awaitTerminate :: forall (m :: * -> *). IOLike m => ControlMessageSTM m -> STM m ()
awaitTerminate ControlMessageSTM m
controlMessageSTM =
  ControlMessageSTM m
controlMessageSTM ControlMessageSTM m -> (ControlMessage -> STM m ()) -> STM m ()
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
    ControlMessage
Terminate -> () -> STM m ()
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    -- Only warm mini-protocols receive this, and LeiosFetch is hot.
    ControlMessage
Quiesce -> STM m ()
forall a. STM m a
forall (m :: * -> *) a. MonadSTM m => STM m a
retry
    ControlMessage
Continue -> STM m ()
forall a. STM m a
forall (m :: * -> *) a. MonadSTM m => STM m a
retry

-- | The next request the decision logic assigned to this peer, with what to do
-- with its reply. Blocks until there is one.
nextLeiosFetchJob ::
  forall peer m.
  (Ord peer, IOLike m) =>
  LeiosFetchClientContext m peer ->
  peer ->
  -- | the requests the decision logic assigned to this peer and the client has
  -- not sent yet
  StrictTVar m (Seq LeiosFetchRequest) ->
  STM m (SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m)
nextLeiosFetchJob :: forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer
-> StrictTVar m (Seq LeiosFetchRequest)
-> STM
     m
     (SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m)
nextLeiosFetchJob LeiosFetchClientContext m peer
ctx peer
peer StrictTVar m (Seq LeiosFetchRequest)
reqsVar =
  StrictTVar m (Seq LeiosFetchRequest)
-> STM m (Seq LeiosFetchRequest)
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar m (Seq LeiosFetchRequest)
reqsVar STM m (Seq LeiosFetchRequest)
-> (Seq LeiosFetchRequest
    -> STM
         m
         (SomeLeiosFetchJob
            LeiosPoint (Serialised EndorserBlock) LeiosTx m))
-> STM
     m
     (SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m)
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
    Seq LeiosFetchRequest
Seq.Empty -> STM
  m
  (SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m)
forall a. STM m a
forall (m :: * -> *) a. MonadSTM m => STM m a
retry
    LeiosFetchRequest
req Seq.:<| Seq LeiosFetchRequest
reqs -> LeiosFetchRequest
-> SomeLeiosFetchJob
     LeiosPoint (Serialised EndorserBlock) LeiosTx m
toJob LeiosFetchRequest
req SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m
-> STM m ()
-> STM
     m
     (SomeLeiosFetchJob LeiosPoint (Serialised EndorserBlock) LeiosTx m)
forall a b. a -> STM m b -> STM m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ StrictTVar m (Seq LeiosFetchRequest)
-> Seq LeiosFetchRequest -> STM m ()
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
StrictTVar m a -> a -> STM m ()
writeTVar StrictTVar m (Seq LeiosFetchRequest)
reqsVar Seq LeiosFetchRequest
reqs
 where
  -- Replies are processed right on the pipelined peer's collector thread:
  -- everything they touch is thread-safe.
  toJob :: LeiosFetchRequest
-> SomeLeiosFetchJob
     LeiosPoint (Serialised EndorserBlock) LeiosTx m
toJob = \case
    LeiosBlockRequest LeiosBlockRequest
req ->
      Message
  (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
  'StIdle
  ('StBusy 'StBlock)
-> (Message
      (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
      ('StBusy 'StBlock)
      'StIdle
    -> m ())
-> SomeLeiosFetchJob
     LeiosPoint (Serialised EndorserBlock) LeiosTx m
forall point eb tx (m :: * -> *)
       (st' :: LeiosFetchBusy point eb tx).
StateTokenI ('StBusy st') =>
Message (LeiosFetch point eb tx) 'StIdle ('StBusy st')
-> (Message (LeiosFetch point eb tx) ('StBusy st') 'StIdle -> m ())
-> SomeLeiosFetchJob point eb tx m
MkSomeLeiosFetchJob
        (LeiosPoint
-> Message
     (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
     'StIdle
     ('StBusy 'StBlock)
forall point eb tx.
point
-> Message (LeiosFetch point eb tx) 'StIdle ('StBusy 'StBlock)
MsgLeiosBlockRequest (LeiosBlockRequest -> LeiosPoint
lbrPoint LeiosBlockRequest
req))
        (\(MsgLeiosBlock Serialised EndorserBlock
bytes) -> LeiosFetchClientContext m peer
-> peer -> LeiosBlockRequest -> Serialised EndorserBlock -> m ()
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockRequest -> Serialised EndorserBlock -> m ()
processLeiosBlock LeiosFetchClientContext m peer
ctx peer
peer LeiosBlockRequest
req Serialised EndorserBlock
bytes)
    LeiosBlockTxsRequest req :: LeiosBlockTxsRequest
req@(MkLeiosBlockTxsRequest LeiosPoint
p NEIntMap LeiosJob
jobs) ->
      -- The wire request is just the point and bitmap: the union of the
      -- covered jobs' offsets.
      let bitmaps :: TxBitmaps
bitmaps = IntSet -> TxBitmaps
offsetsToBitmap ((LeiosJob -> IntSet) -> NEIntMap LeiosJob -> IntSet
forall m a. Monoid m => (a -> m) -> NEIntMap a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Jobs.MkLeiosJob IntSet
offs Word32
_ JobCommitment
_) -> IntSet
offs) NEIntMap LeiosJob
jobs)
       in Message
  (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
  'StIdle
  ('StBusy 'StBlockTxs)
-> (Message
      (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
      ('StBusy 'StBlockTxs)
      'StIdle
    -> m ())
-> SomeLeiosFetchJob
     LeiosPoint (Serialised EndorserBlock) LeiosTx m
forall point eb tx (m :: * -> *)
       (st' :: LeiosFetchBusy point eb tx).
StateTokenI ('StBusy st') =>
Message (LeiosFetch point eb tx) 'StIdle ('StBusy st')
-> (Message (LeiosFetch point eb tx) ('StBusy st') 'StIdle -> m ())
-> SomeLeiosFetchJob point eb tx m
MkSomeLeiosFetchJob
            (LeiosPoint
-> TxBitmaps
-> Message
     (LeiosFetch LeiosPoint (Serialised EndorserBlock) LeiosTx)
     'StIdle
     ('StBusy 'StBlockTxs)
forall point eb tx.
point
-> TxBitmaps
-> Message (LeiosFetch point eb tx) 'StIdle ('StBusy 'StBlockTxs)
MsgLeiosBlockTxsRequest LeiosPoint
p TxBitmaps
bitmaps)
            (\(MsgLeiosBlockTxs Vector LeiosTx
txs) -> LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext m peer
ctx peer
peer LeiosBlockTxsRequest
req Vector LeiosTx
txs)

-- | Take in an endorser block that arrived in reply to this request.
--
-- The hash is the whole of it: these bytes either are the endorser block we
-- asked for or they are not, and no announcement gets a say. Bytes that are
-- the right block but not the size the peer offered still cost the peer its
-- connection. Bytes larger than the ledger allows, referencing more
-- transaction bytes than it allows, or that do not decode, are never written,
-- so the node never offers them onward.
--
-- The hash is checked before the bytes are decoded. They decode at Dijkstra's
-- ledger version, the only era with endorser blocks.
processLeiosBlock ::
  forall peer m.
  (Ord peer, IOLike m) =>
  LeiosFetchClientContext m peer ->
  peer ->
  LeiosBlockRequest ->
  Serialised EndorserBlock ->
  m ()
processLeiosBlock :: forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockRequest -> Serialised EndorserBlock -> m ()
processLeiosBlock LeiosFetchClientContext m peer
ctx peer
peer LeiosBlockRequest
req Serialised EndorserBlock
bytes = do
  Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Serialised EndorserBlock -> Hash HASH EraIndependentEbReferences
hashSerialisedEndorserBlock Serialised EndorserBlock
bytes Hash HASH EraIndependentEbReferences
-> Hash HASH EraIndependentEbReferences -> Bool
forall a. Eq a => a -> a -> Bool
/= Hash HASH EraIndependentEbReferences
requestedEbHash) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ do
    Tracer m (TraceLeiosFetchClientEvent peer)
-> TraceLeiosFetchClientEvent peer -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer (TraceLeiosFetchClientEvent peer -> m ())
-> TraceLeiosFetchClientEvent peer -> m ()
forall a b. (a -> b) -> a -> b
$
      peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
forall peer.
peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockArrived peer
peer LeiosPoint
point (Word32 -> FetchArrivalBytes
fetchArrivalInvalid Word32
ebBytesSize)
    ExnLeiosFetchInvalidReply -> m ()
forall e a. Exception e => e -> m a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwIO (ExnLeiosFetchInvalidReply -> m ())
-> ExnLeiosFetchInvalidReply -> m ()
forall a b. (a -> b) -> a -> b
$ LeiosPoint
-> Hash HASH EraIndependentEbReferences
-> ExnLeiosFetchInvalidReply
ExnLeiosBlockWrongHash LeiosPoint
point (Serialised EndorserBlock -> Hash HASH EraIndependentEbReferences
hashSerialisedEndorserBlock Serialised EndorserBlock
bytes)
  -- Decoded before taking the lock, which the replies of every peer share.
  verdict <- Either ExnLeiosFetchInvalidReply EndorserBlock
-> m (Either ExnLeiosFetchInvalidReply EndorserBlock)
forall a. a -> m a
forall (m :: * -> *) a. MonadEvaluate m => a -> m a
evaluate Either ExnLeiosFetchInvalidReply EndorserBlock
checkedEb
  -- Under the lock, decide what to do with this body. The point lacks the body
  -- until a reply's write settles, so another reply meanwhile is written
  -- too.
  disposition <- modifyMVar lfcOutstanding $ \LeiosOutstanding peer
outstanding -> do
    -- Answered, so this request is no longer in flight.
    let cleaned :: LeiosOutstanding peer
cleaned = peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
Ord peer =>
peer
-> LeiosPoint
-> Word32
-> LeiosOutstanding peer
-> LeiosOutstanding peer
refundEbRequest peer
peer LeiosPoint
point (LeiosBlockRequest -> Word32
lbrOfferedSize LeiosBlockRequest
req) LeiosOutstanding peer
outstanding
    case Either ExnLeiosFetchInvalidReply EndorserBlock
verdict of
      Left ExnLeiosFetchInvalidReply
exn ->
        -- Held with nothing to fetch, so that neither its closure nor a
        -- re-send of the same bytes costs us anything more at this point.
        -- It is not written, so it is never emitted as acquired.
        (LeiosOutstanding peer, BodyDisposition)
-> m (LeiosOutstanding peer, BodyDisposition)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
point LeiosJobPool
Jobs.emptyJobPool LeiosOutstanding peer
cleaned, ExnLeiosFetchInvalidReply -> BodyDisposition
BodyTooBig ExnLeiosFetchInvalidReply
exn)
      Right EndorserBlock
eb -> case LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding) of
        -- Pruned meanwhile.
        Maybe EbState
Nothing -> (LeiosOutstanding peer, BodyDisposition)
-> m (LeiosOutstanding peer, BodyDisposition)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
cleaned, FetchArrivalBytes -> BodyDisposition
BodyDiscarded (Word32 -> FetchArrivalBytes
fetchArrivalEvicted Word32
ebBytesSize))
        -- Another reply's write settled first.
        Just (MkEbState StrictMaybe RelativeTime
_onset BodyAcquired{}) ->
          (LeiosOutstanding peer, BodyDisposition)
-> m (LeiosOutstanding peer, BodyDisposition)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
cleaned, FetchArrivalBytes -> BodyDisposition
BodyDiscarded (Word32 -> FetchArrivalBytes
fetchArrivalExtra Word32
ebBytesSize))
        Just (MkEbState StrictMaybe RelativeTime
_onset EbFetchState
NoBody) -> do
          -- Register the body's transactions in the tx cache, and read where
          -- some recent point holds any of them, so that the body
          -- write copies those rather than us fetching them again.
          (_summary, fills) <-
            LeiosTxCache m () Version PackedEndorserBlock
-> forall w.
   LeiosPoint
   -> PackedEndorserBlock
   -> w
   -> (w -> Int -> TxHash -> Word32 -> Maybe TxLocation -> w)
   -> m (Maybe LeiosTxCacheInsertBodySummary, w)
forall (m :: * -> *) a v b.
LeiosTxCache m a v b
-> forall w.
   LeiosPoint
   -> b
   -> w
   -> (w -> Int -> TxHash -> Word32 -> Maybe TxLocation -> w)
   -> m (Maybe LeiosTxCacheInsertBodySummary, w)
insertBodyAndFoldl' LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache LeiosPoint
point (EndorserBlock -> PackedEndorserBlock
packEndorserBlock EndorserBlock
eb) Map Int TxLocation
forall k a. Map k a
Map.empty Map Int TxLocation
-> Int
-> TxHash
-> Word32
-> Maybe TxLocation
-> Map Int TxLocation
snocLocated
          pure (cleaned, BodyToWrite eb fills)
  void $ tryPutMVar lfcReady ()
  case disposition of
    BodyTooBig ExnLeiosFetchInvalidReply
exn -> do
      Tracer m (TraceLeiosFetchClientEvent peer)
-> TraceLeiosFetchClientEvent peer -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer (TraceLeiosFetchClientEvent peer -> m ())
-> TraceLeiosFetchClientEvent peer -> m ()
forall a b. (a -> b) -> a -> b
$
        peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
forall peer.
peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockArrived peer
peer LeiosPoint
point (Word32 -> FetchArrivalBytes
fetchArrivalInvalid Word32
ebBytesSize)
      ExnLeiosFetchInvalidReply -> m ()
forall e a. Exception e => e -> m a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwIO ExnLeiosFetchInvalidReply
exn
    BodyDiscarded FetchArrivalBytes
arrival -> Tracer m (TraceLeiosFetchClientEvent peer)
-> TraceLeiosFetchClientEvent peer -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer (TraceLeiosFetchClientEvent peer -> m ())
-> TraceLeiosFetchClientEvent peer -> m ()
forall a b. (a -> b) -> a -> b
$ peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
forall peer.
peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockArrived peer
peer LeiosPoint
point FetchArrivalBytes
arrival
    BodyToWrite EndorserBlock
eb Map Int TxLocation
localFills -> do
      -- Settled only once the write lands, since the settle needs the offsets
      -- the point then holds. The client takes no other reply from this peer
      -- meanwhile.
      heldOffs <- Promise m (Set Int) -> m (Set Int)
forall (m :: * -> *) a. Promise m a -> m a
await (Promise m (Set Int) -> m (Set Int))
-> m (Promise m (Set Int)) -> m (Set Int)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< LeiosDbWriter m
-> HasCallStack =>
   LeiosPoint
   -> EndorserBlock -> Map Int TxLocation -> m (Promise m (Set Int))
forall (m :: * -> *).
LeiosDbWriter m
-> HasCallStack =>
   LeiosPoint
   -> EndorserBlock -> Map Int TxLocation -> m (Promise m (Set Int))
writeEbBody LeiosDbWriter m
lfcWriter LeiosPoint
point EndorserBlock
eb Map Int TxLocation
localFills
      settleBody ctx peer point eb heldOffs
  -- Checked last, so that the body is still taken: throwing it away would let
  -- a peer deny us an endorser block just by lowballing its own offer.
  when (ebBytesSize /= lbrOfferedSize req) $
    throwIO $
      ExnLeiosBlockWrongSize point (lbrOfferedSize req) ebBytesSize
 where
  MkLeiosFetchClientContext
    { StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding peer)
lfcOutstanding
    , StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady
    , LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache
    , LeiosDbWriter m
lfcWriter :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosDbWriter m
lfcWriter :: LeiosDbWriter m
lfcWriter
    , Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer
    } = LeiosFetchClientContext m peer
ctx

  point :: LeiosPoint
point = LeiosBlockRequest -> LeiosPoint
lbrPoint LeiosBlockRequest
req
  requestedEbHash :: Hash HASH EraIndependentEbReferences
requestedEbHash = LeiosPoint -> Hash HASH EraIndependentEbReferences
pointEbHash LeiosPoint
point
  ebBytesSize :: Word32
ebBytesSize = Int64 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int64
BSL.length (Serialised EndorserBlock -> ByteString
forall {k} (a :: k). Serialised a -> ByteString
unSerialised Serialised EndorserBlock
bytes))
  limits :: LeiosEbByteSizes 'SizeLimit
limits = LeiosBlockRequest -> LeiosEbByteSizes 'SizeLimit
lbrEbBounds LeiosBlockRequest
req
  checkedEb :: Either ExnLeiosFetchInvalidReply EndorserBlock
checkedEb
    | Word32
ebBytesSize Word32 -> Word32 -> Bool
forall a. Ord a => a -> a -> Bool
> LeiosEbByteSizes 'SizeLimit -> Word32
forall (r :: SizeRole). LeiosEbByteSizes r -> Word32
lebBodySize LeiosEbByteSizes 'SizeLimit
limits =
        ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. a -> Either a b
Left (ExnLeiosFetchInvalidReply
 -> Either ExnLeiosFetchInvalidReply EndorserBlock)
-> ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> Word32 -> Word32 -> ExnLeiosFetchInvalidReply
ExnLeiosBlockTooBig LeiosPoint
point Word32
ebBytesSize (LeiosEbByteSizes 'SizeLimit -> Word32
forall (r :: SizeRole). LeiosEbByteSizes r -> Word32
lebBodySize LeiosEbByteSizes 'SizeLimit
limits)
    | Bool
otherwise = case Proxy DijkstraEra
-> Serialised EndorserBlock -> Either DecoderError EndorserBlock
forall era (proxy :: * -> *).
Era era =>
proxy era
-> Serialised EndorserBlock -> Either DecoderError EndorserBlock
deserialiseEndorserBlock (forall t. Proxy t
forall {k} (t :: k). Proxy t
Proxy @DijkstraEra) Serialised EndorserBlock
bytes of
        Left DecoderError
err -> ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. a -> Either a b
Left (ExnLeiosFetchInvalidReply
 -> Either ExnLeiosFetchInvalidReply EndorserBlock)
-> ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> DecoderError -> ExnLeiosFetchInvalidReply
ExnLeiosBlockUndecodable LeiosPoint
point DecoderError
err
        Right EndorserBlock
eb
          | LeiosEbByteSizes 'SizeActual -> Word64
forall (r :: SizeRole). LeiosEbByteSizes r -> Word64
lebTxsSize LeiosEbByteSizes 'SizeActual
sizes Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
> LeiosEbByteSizes 'SizeLimit -> Word64
forall (r :: SizeRole). LeiosEbByteSizes r -> Word64
lebTxsSize LeiosEbByteSizes 'SizeLimit
limits ->
              ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. a -> Either a b
Left (ExnLeiosFetchInvalidReply
 -> Either ExnLeiosFetchInvalidReply EndorserBlock)
-> ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> Word64 -> Word64 -> ExnLeiosFetchInvalidReply
ExnLeiosClosureTooBig LeiosPoint
point (LeiosEbByteSizes 'SizeActual -> Word64
forall (r :: SizeRole). LeiosEbByteSizes r -> Word64
lebTxsSize LeiosEbByteSizes 'SizeActual
sizes) (LeiosEbByteSizes 'SizeLimit -> Word64
forall (r :: SizeRole). LeiosEbByteSizes r -> Word64
lebTxsSize LeiosEbByteSizes 'SizeLimit
limits)
          | Bool
otherwise -> EndorserBlock -> Either ExnLeiosFetchInvalidReply EndorserBlock
forall a b. b -> Either a b
Right EndorserBlock
eb
         where
          sizes :: LeiosEbByteSizes 'SizeActual
sizes = EndorserBlock -> LeiosEbByteSizes 'SizeActual
leiosEbByteSizes EndorserBlock
eb

-- | What 'processLeiosBlock' does with a body, decided under the lock.
data BodyDisposition
  = -- | Beyond its point's bounds, or undecodable, so never written.
    BodyTooBig !ExnLeiosFetchInvalidReply
  | -- | No longer wanted, its bytes classified so.
    BodyDiscarded !FetchArrivalBytes
  | -- | Wanted, so written, with these fills, and traced once that settles.
    BodyToWrite !EndorserBlock !LocalFills

-- | Record the body as acquired at its point, now that its write has settled
-- and holds the txs at these offsets,
-- with jobs for the txs the point does not hold yet, and emit what is acquired.
-- Nothing if the point was pruned meanwhile, or another reply with it settled
-- first. Either way, trace the reply's arrival: its bytes were needed only if
-- it settled first.
--
-- The LeiosDB drops the writes of a point older than its promoted slot, which
-- reaches a block's slot once that block is copied to the ImmutableDB. The
-- fetch state normally prunes such a point first, but only timing ensures
-- that. Had the LeiosDB dropped a write first, a settle would emit an
-- acquisition of a point whose writes were dropped, as 'LeiosAcquisition'
-- allows.
settleBody ::
  IOLike m =>
  LeiosFetchClientContext m peer ->
  -- | the peer that sent it
  peer ->
  LeiosPoint ->
  EndorserBlock ->
  Set TxOffset ->
  m ()
settleBody :: forall (m :: * -> *) peer.
IOLike m =>
LeiosFetchClientContext m peer
-> peer -> LeiosPoint -> EndorserBlock -> Set Int -> m ()
settleBody LeiosFetchClientContext m peer
ctx peer
peer LeiosPoint
point EndorserBlock
eb Set Int
heldOffs = do
  traces <- StrictMVar m (LeiosOutstanding peer)
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer,
          RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> m (RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
modifyMVar StrictMVar m (LeiosOutstanding peer)
lfcOutstanding ((LeiosOutstanding peer
  -> m (LeiosOutstanding peer,
        RelativeTime -> [TraceLeiosFetchClientEvent peer]))
 -> m (RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer,
          RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> m (RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding peer
outstanding ->
    case LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding) of
      Maybe EbState
Nothing -> (LeiosOutstanding peer,
 RelativeTime -> [TraceLeiosFetchClientEvent peer])
-> m (LeiosOutstanding peer,
      RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
outstanding, \RelativeTime
_now -> [(Word32 -> FetchArrivalBytes) -> TraceLeiosFetchClientEvent peer
arrived Word32 -> FetchArrivalBytes
fetchArrivalEvicted])
      Just (MkEbState StrictMaybe RelativeTime
_onset BodyAcquired{}) -> (LeiosOutstanding peer,
 RelativeTime -> [TraceLeiosFetchClientEvent peer])
-> m (LeiosOutstanding peer,
      RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
outstanding, \RelativeTime
_now -> [(Word32 -> FetchArrivalBytes) -> TraceLeiosFetchClientEvent peer
arrived Word32 -> FetchArrivalBytes
fetchArrivalExtra])
      Just (MkEbState StrictMaybe RelativeTime
onset EbFetchState
NoBody) -> do
        let
          jobPool :: LeiosJobPool
jobPool =
            LeiosFetchStaticEnv -> IntMap (TxHash, Word32) -> LeiosJobPool
newLeiosJobPool LeiosFetchStaticEnv
lfcStaticEnv (IntMap (TxHash, Word32)
refs IntMap (TxHash, Word32) -> IntSet -> IntMap (TxHash, Word32)
forall a. IntMap a -> IntSet -> IntMap a
`IntMap.withoutKeys` Set Int -> IntSet
toIntSet Set Int
heldOffs)
        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
$ LeiosAcquisition -> STM m ()
lfcNotify (LeiosAcquisition -> STM m ()) -> LeiosAcquisition -> STM m ()
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> Word32 -> LeiosAcquisition
AcquiredEb LeiosPoint
point (EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb)
        Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
jobPool) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
          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
$
            LeiosAcquisition -> STM m ()
lfcNotify (LeiosAcquisition -> STM m ()) -> LeiosAcquisition -> STM m ()
forall a b. (a -> b) -> a -> b
$
              LeiosPoint -> LeiosAcquisition
AcquiredEbTxs LeiosPoint
point
        (LeiosOutstanding peer,
 RelativeTime -> [TraceLeiosFetchClientEvent peer])
-> m (LeiosOutstanding peer,
      RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
          ( LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
forall peer.
LeiosPoint
-> LeiosJobPool -> LeiosOutstanding peer -> LeiosOutstanding peer
acquireEbBody LeiosPoint
point LeiosJobPool
jobPool LeiosOutstanding peer
outstanding
          , \RelativeTime
now ->
              (Word32 -> FetchArrivalBytes) -> TraceLeiosFetchClientEvent peer
arrived Word32 -> FetchArrivalBytes
fetchArrivalGood
                TraceLeiosFetchClientEvent peer
-> [TraceLeiosFetchClientEvent peer]
-> [TraceLeiosFetchClientEvent peer]
forall a. a -> [a] -> [a]
: LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
forall peer.
LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockAcquired LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now StrictMaybe RelativeTime
onset)
                TraceLeiosFetchClientEvent peer
-> [TraceLeiosFetchClientEvent peer]
-> [TraceLeiosFetchClientEvent peer]
forall a. a -> [a] -> [a]
: [ LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
forall peer.
LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockTxsAcquired LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now StrictMaybe RelativeTime
onset)
                  | LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
jobPool
                  ]
          )
  -- The write of these txs has landed at this point: record them, as fill
  -- sources for later endorser blocks referencing the same txs.
  _ <-
    insertLandedTxs
      lfcTxCache
      point
      [ MkLandedTx off txHash size (TxInserted ())
      | off <- Set.toList heldOffs
      , let (txHash, size) = refs IntMap.! off
      ]
  void $ tryPutMVar lfcReady ()
  -- Read after emitting, so that the acquisitions' ages run until then.
  now <- systemTimeCurrent lfcSystemTime
  mapM_ (traceWith lfcTracer) (traces now)
 where
  MkLeiosFetchClientContext
    { LeiosFetchStaticEnv
lfcStaticEnv :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosFetchStaticEnv
lfcStaticEnv :: LeiosFetchStaticEnv
lfcStaticEnv
    , StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding peer)
lfcOutstanding
    , StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady
    , LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache
    , LeiosAcquisition -> STM m ()
lfcNotify :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosAcquisition -> STM m ()
lfcNotify :: LeiosAcquisition -> STM m ()
lfcNotify
    , SystemTime m
lfcSystemTime :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> SystemTime m
lfcSystemTime :: SystemTime m
lfcSystemTime
    , Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer
    } = LeiosFetchClientContext m peer
ctx
  refs :: IntMap (TxHash, Word32)
refs = [(Int, (TxHash, Word32))] -> IntMap (TxHash, Word32)
forall a. [(Int, a)] -> IntMap a
IntMap.fromList ([Int] -> [(TxHash, Word32)] -> [(Int, (TxHash, Word32))]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 ..] (EndorserBlock -> [(TxHash, Word32)]
endorserBlockReferences EndorserBlock
eb))
  arrived :: (Word32 -> FetchArrivalBytes) -> TraceLeiosFetchClientEvent peer
arrived Word32 -> FetchArrivalBytes
bucket =
    peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
forall peer.
peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockArrived peer
peer LeiosPoint
point (Word32 -> FetchArrivalBytes
bucket (EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb))

-- | Acquire an endorser block the node's own forge produced in this election,
-- as one that arrived with no peer: take its body into the LeiosTxCache, write
-- it and all its txs, and once both writes land, record those txs in the
-- LeiosTxCache as validated, hold it with no job left ('holdForgedEb') and
-- emit the acquisitions not yet emitted at its point.
--
-- Its bytes are not checked: the forge built the body from these very txs. No
-- tx is filled from another point, since all of them are written.
--
-- So 'AcquiredEb', and with it the node's offer of the body, waits for the txs
-- write as well as the body's.
acquireForgedEb ::
  IOLike m =>
  LeiosFetchClientContext m peer ->
  ElectionId ->
  ForgedEndorserBlock ->
  m ()
acquireForgedEb :: forall (m :: * -> *) peer.
IOLike m =>
LeiosFetchClientContext m peer
-> ElectionId -> ForgedEndorserBlock -> m ()
acquireForgedEb LeiosFetchClientContext m peer
ctx ElectionId
elId ForgedEndorserBlock
forged = do
  _ <- LeiosTxCache m () Version PackedEndorserBlock
-> LeiosPoint
-> PackedEndorserBlock
-> m (Maybe LeiosTxCacheInsertBodySummary)
forall (m :: * -> *) a v b.
Functor m =>
LeiosTxCache m a v b
-> LeiosPoint -> b -> m (Maybe LeiosTxCacheInsertBodySummary)
insertBody LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache LeiosPoint
point (EndorserBlock -> PackedEndorserBlock
packEndorserBlock EndorserBlock
eb)
  bodyWritten <- writeEbBody lfcWriter point eb mempty
  txsWritten <- writeTxs lfcWriter point (Map.fromList (zip [0 ..] (toList (forgedEbTxs forged))))
  awaitAll [void bodyWritten, txsWritten]
  -- The write of these txs has landed at this point: record them, as fill
  -- sources for later endorser blocks referencing the same txs. The point
  -- holds them all: the forge built the body from these very txs, so none is
  -- of another size than it declares.
  _ <-
    insertLandedTxs
      lfcTxCache
      point
      [ MkLandedTx off txHash size (TxValidated (forgedEbTxsProtVer forged))
      | (off, (txHash, size)) <- zip [0 ..] refs
      ]
  (onset, acquired) <- modifyMVar lfcOutstanding $ \LeiosOutstanding peer
outstanding -> do
    let (LeiosOutstanding peer
outstanding', [LeiosAcquisition]
acquired) = ElectionId
-> Hash HASH EraIndependentEbReferences
-> Word32
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, [LeiosAcquisition])
forall peer.
ElectionId
-> Hash HASH EraIndependentEbReferences
-> Word32
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, [LeiosAcquisition])
holdForgedEb ElectionId
elId Hash HASH EraIndependentEbReferences
ebHash (EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb) LeiosOutstanding peer
outstanding
    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
$ (LeiosAcquisition -> STM m ()) -> [LeiosAcquisition] -> STM m ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ LeiosAcquisition -> STM m ()
lfcNotify [LeiosAcquisition]
acquired
    (LeiosOutstanding peer,
 (StrictMaybe RelativeTime, [LeiosAcquisition]))
-> m (LeiosOutstanding peer,
      (StrictMaybe RelativeTime, [LeiosAcquisition]))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
      (LeiosOutstanding peer
outstanding', (StrictMaybe RelativeTime
-> (EbState -> StrictMaybe RelativeTime)
-> Maybe EbState
-> StrictMaybe RelativeTime
forall b a. b -> (a -> b) -> Maybe a -> b
maybe StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing EbState -> StrictMaybe RelativeTime
ebStateOnset (LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding)), [LeiosAcquisition]
acquired))
  void $ tryPutMVar lfcReady ()
  -- Read after emitting, so that the acquisitions' ages run until then.
  now <- systemTimeCurrent lfcSystemTime
  for_ acquired $
    traceWith lfcTracer . \case
      AcquiredEb{} -> LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
forall peer.
LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockAcquired LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now StrictMaybe RelativeTime
onset)
      AcquiredEbTxs{} -> LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
forall peer.
LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockTxsAcquired LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now StrictMaybe RelativeTime
onset)
 where
  MkLeiosFetchClientContext
    { LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache
    , LeiosDbWriter m
lfcWriter :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosDbWriter m
lfcWriter :: LeiosDbWriter m
lfcWriter
    , StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding peer)
lfcOutstanding
    , StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady
    , LeiosAcquisition -> STM m ()
lfcNotify :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosAcquisition -> STM m ()
lfcNotify :: LeiosAcquisition -> STM m ()
lfcNotify
    , SystemTime m
lfcSystemTime :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> SystemTime m
lfcSystemTime :: SystemTime m
lfcSystemTime
    , Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer
    } = LeiosFetchClientContext m peer
ctx
  eb :: EndorserBlock
eb = ForgedEndorserBlock -> EndorserBlock
forgedEbBody ForgedEndorserBlock
forged
  ebHash :: Hash HASH EraIndependentEbReferences
ebHash = EndorserBlock -> Hash HASH EraIndependentEbReferences
endorserBlockHash EndorserBlock
eb
  point :: LeiosPoint
point = SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (ElectionId -> SlotNo
electionSlot ElectionId
elId) Hash HASH EraIndependentEbReferences
ebHash
  refs :: [(TxHash, Word32)]
refs = EndorserBlock -> [(TxHash, Word32)]
endorserBlockReferences EndorserBlock
eb

-- | Add a tx's location, if it has one, as a fill of its offset.
snocLocated ::
  LocalFills ->
  TxOffset ->
  TxHash ->
  BytesSize ->
  Maybe TxLocation ->
  LocalFills
snocLocated :: Map Int TxLocation
-> Int
-> TxHash
-> Word32
-> Maybe TxLocation
-> Map Int TxLocation
snocLocated Map Int TxLocation
acc Int
off TxHash
_txh Word32
_sz = \case
  Just TxLocation
loc -> Int -> TxLocation -> Map Int TxLocation -> Map Int TxLocation
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Int
off TxLocation
loc Map Int TxLocation
acc
  Maybe TxLocation
Nothing -> Map Int TxLocation
acc

-- | Take in transactions that arrived in reply to this request.
processLeiosBlockTxs ::
  forall peer m.
  (Ord peer, IOLike m) =>
  LeiosFetchClientContext m peer ->
  peer ->
  LeiosBlockTxsRequest ->
  V.Vector LeiosTx ->
  m ()
processLeiosBlockTxs :: forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext m peer
ctx peer
peer req :: LeiosBlockTxsRequest
req@(MkLeiosBlockTxsRequest LeiosPoint
point NEIntMap LeiosJob
jobs) Vector LeiosTx
txs = do
  -- Cheap checks, without hashing, of the whole reply and of every covered
  -- job, so that an over-send is caught and punished even for a job we have
  -- since completed.
  Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Vector LeiosTx -> Int
forall a. Vector a -> Int
V.length Vector LeiosTx
txs Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= IntSet -> Int
IntSet.size IntSet
offsetsSet) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
    ExnLeiosFetchInvalidReply -> m ()
forall a. ExnLeiosFetchInvalidReply -> m a
invalidReply (ExnLeiosFetchInvalidReply -> m ())
-> ExnLeiosFetchInvalidReply -> m ()
forall a b. (a -> b) -> a -> b
$
      LeiosPoint -> Int -> Int -> ExnLeiosFetchInvalidReply
ExnLeiosBlockTxsWrongCount LeiosPoint
point (IntSet -> Int
IntSet.size IntSet
offsetsSet) (Vector LeiosTx -> Int
forall a. Vector a -> Int
V.length Vector LeiosTx
txs)
  (ExnLeiosFetchInvalidReply -> m ())
-> (NEIntMap () -> m ())
-> Either ExnLeiosFetchInvalidReply (NEIntMap ())
-> m ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ExnLeiosFetchInvalidReply -> m ()
forall a. ExnLeiosFetchInvalidReply -> m a
invalidReply (\NEIntMap ()
_ -> () -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) (Either ExnLeiosFetchInvalidReply (NEIntMap ()) -> m ())
-> Either ExnLeiosFetchInvalidReply (NEIntMap ()) -> m ()
forall a b. (a -> b) -> a -> b
$
    (Int -> LeiosJob -> Either ExnLeiosFetchInvalidReply ())
-> NEIntMap LeiosJob
-> Either ExnLeiosFetchInvalidReply (NEIntMap ())
forall (t :: * -> *) a b.
Applicative t =>
(Int -> a -> t b) -> NEIntMap a -> t (NEIntMap b)
NEIntMap.traverseWithKey
      (\Int
i LeiosJob
job -> LeiosPoint
-> IntMap LeiosTx
-> LeiosJobId
-> LeiosJob
-> Either ExnLeiosFetchInvalidReply ()
checkJobSize LeiosPoint
point IntMap LeiosTx
aligned (Int -> LeiosJobId
Jobs.MkLeiosJobId Int
i) LeiosJob
job)
      NEIntMap LeiosJob
jobs
  -- Only jobs still pending are hashed and ingested; a redundant reply for a
  -- completed job, or a reply for an endorser block pruned meanwhile, is
  -- discarded. The lock is not held through the hashing and the write, so the
  -- state may be stale by then, harmlessly: a completed job never becomes
  -- pending again, and writing a transaction again rewrites the same bytes.
  --
  -- The same critical section refunds the request, as 'processLeiosBlock' does:
  -- its credit bounds the bytes the peer may send before the client reads
  -- them, and the client has read this reply. The jobs stay this peer's until
  -- the write lands.
  outstanding0 <-
    StrictMVar m (LeiosOutstanding peer)
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer, LeiosOutstanding peer))
-> m (LeiosOutstanding peer)
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
modifyMVar StrictMVar m (LeiosOutstanding peer)
lfcOutstanding ((LeiosOutstanding peer
  -> m (LeiosOutstanding peer, LeiosOutstanding peer))
 -> m (LeiosOutstanding peer))
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer, LeiosOutstanding peer))
-> m (LeiosOutstanding peer)
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding peer
outstanding ->
      let refunded :: LeiosOutstanding peer
refunded = peer -> Word32 -> LeiosOutstanding peer -> LeiosOutstanding peer
forall peer.
Ord peer =>
peer -> Word32 -> LeiosOutstanding peer -> LeiosOutstanding peer
refundTxRequest peer
peer (Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
batchBytes) LeiosOutstanding peer
outstanding
       in (LeiosOutstanding peer, LeiosOutstanding peer)
-> m (LeiosOutstanding peer, LeiosOutstanding peer)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
refunded, LeiosOutstanding peer
refunded)
  void $ tryPutMVar lfcReady ()
  let (pendingJobs, discardedAs) = case Map.lookup point (ebState outstanding0) of
        Just (MkEbState StrictMaybe RelativeTime
_onset (BodyAcquired LeiosJobPool
jobPool)) ->
          (IntMap LeiosJob -> LeiosJobPool -> IntMap LeiosJob
forall a. IntMap a -> LeiosJobPool -> IntMap a
Jobs.restrictToPending (NEIntMap LeiosJob -> IntMap LeiosJob
forall a. NEIntMap a -> IntMap a
NEIntMap.toMap NEIntMap LeiosJob
jobs) LeiosJobPool
jobPool, Word32 -> FetchArrivalBytes
fetchArrivalExtra)
        -- Pruned meanwhile, and perhaps referenced again since: txs are
        -- requested only once the body is held.
        Just (MkEbState StrictMaybe RelativeTime
_onset EbFetchState
NoBody) -> (IntMap LeiosJob
forall a. IntMap a
IntMap.empty, Word32 -> FetchArrivalBytes
fetchArrivalEvicted)
        Maybe EbState
Nothing -> (IntMap LeiosJob
forall a. IntMap a
IntMap.empty, Word32 -> FetchArrivalBytes
fetchArrivalEvicted)
      discarded = Word32 -> FetchArrivalBytes
discardedAs (Word32 -> FetchArrivalBytes) -> Word32 -> FetchArrivalBytes
forall a b. (a -> b) -> a -> b
$ IntMap LeiosJob -> Word32
jobsBytesSize (IntMap LeiosJob -> IntMap LeiosJob -> IntMap LeiosJob
forall a b. IntMap a -> IntMap b -> IntMap a
IntMap.difference (NEIntMap LeiosJob -> IntMap LeiosJob
forall a. NEIntMap a -> IntMap a
NEIntMap.toMap NEIntMap LeiosJob
jobs) IntMap LeiosJob
pendingJobs)
  toIngest <-
    either invalidReply (pure . fold) $
      IntMap.traverseWithKey
        (\Int
i LeiosJob
job -> LeiosPoint
-> IntMap LeiosTx
-> LeiosJobId
-> LeiosJob
-> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)]
checkJobCommitment LeiosPoint
point IntMap LeiosTx
aligned (Int -> LeiosJobId
Jobs.MkLeiosJobId Int
i) LeiosJob
job)
        pendingJobs
  -- Settled only once the write lands, since what follows records these txs as
  -- held. The client takes no other reply from this peer meanwhile, and the
  -- jobs stay picked by this peer, which others may already be asked for too,
  -- and which its disconnection releases.
  await
    =<< writeTxs lfcWriter point (Map.fromList [(off, bytes) | (off, _txHash, bytes) <- toIngest])
  -- After the write, so that the LeiosTxCache holds a tx only once the LeiosDB
  -- holds it, and can offer it as a fill source for later endorser blocks
  -- referencing the same txs.
  arrival <-
    insertLandedTxs
      lfcTxCache
      point
      [ MkLandedTx off txHash (fromIntegral (BS.length bytes)) (TxInserted ())
      | (off, txHash, bytes) <- toIngest
      ]
  settleTxs ctx peer req (arrival <> discarded)
 where
  MkLeiosFetchClientContext
    { StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding peer)
lfcOutstanding
    , StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady
    , LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache :: LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache
    , LeiosDbWriter m
lfcWriter :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosDbWriter m
lfcWriter :: LeiosDbWriter m
lfcWriter
    , Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer
    } = LeiosFetchClientContext m peer
ctx

  txBytess :: Vector ByteString
txBytess = (LeiosTx -> ByteString) -> Vector LeiosTx -> Vector ByteString
forall a b. (a -> b) -> Vector a -> Vector b
V.map LeiosTx -> ByteString
leiosTxBytes Vector LeiosTx
txs
  batchBytes :: Int
batchBytes = Vector Int -> Int
forall a. Num a => Vector a -> a
V.sum ((ByteString -> Int) -> Vector ByteString -> Vector Int
forall a b. (a -> b) -> Vector a -> Vector b
V.map ByteString -> Int
BS.length Vector ByteString
txBytess)
  -- The union of the covered jobs' offsets, ascending: the order the peer
  -- decoded our bitmap into, so it aligns position-wise with the arriving txs.
  offsetsSet :: IntSet
offsetsSet = (LeiosJob -> IntSet) -> NEIntMap LeiosJob -> IntSet
forall m a. Monoid m => (a -> m) -> NEIntMap a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Jobs.MkLeiosJob IntSet
offs Word32
_ JobCommitment
_) -> IntSet
offs) NEIntMap LeiosJob
jobs
  aligned :: IntMap LeiosTx
aligned = [(Int, LeiosTx)] -> IntMap LeiosTx
forall a. [(Int, a)] -> IntMap a
IntMap.fromList ([(Int, LeiosTx)] -> IntMap LeiosTx)
-> [(Int, LeiosTx)] -> IntMap LeiosTx
forall a b. (a -> b) -> a -> b
$ [Int] -> [LeiosTx] -> [(Int, LeiosTx)]
forall a b. [a] -> [b] -> [(a, b)]
zip (IntSet -> [Int]
IntSet.toAscList IntSet
offsetsSet) (Vector LeiosTx -> [LeiosTx]
forall a. Vector a -> [a]
V.toList Vector LeiosTx
txs)

  invalidReply :: ExnLeiosFetchInvalidReply -> m a
  invalidReply :: forall a. ExnLeiosFetchInvalidReply -> m a
invalidReply ExnLeiosFetchInvalidReply
exn = do
    Tracer m (TraceLeiosFetchClientEvent peer)
-> TraceLeiosFetchClientEvent peer -> m ()
forall (m :: * -> *) a. Monad m => Tracer m a -> a -> m ()
traceWith Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer (TraceLeiosFetchClientEvent peer -> m ())
-> TraceLeiosFetchClientEvent peer -> m ()
forall a b. (a -> b) -> a -> b
$
      peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
forall peer.
peer
-> LeiosPoint
-> FetchArrivalBytes
-> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientTxsArrived peer
peer LeiosPoint
point (Word32 -> FetchArrivalBytes
fetchArrivalInvalid (Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
batchBytes))
    ExnLeiosFetchInvalidReply -> m a
forall e a. Exception e => e -> m a
forall (m :: * -> *) e a. (MonadThrow m, Exception e) => e -> m a
throwIO ExnLeiosFetchInvalidReply
exn

-- | Retire the jobs of the request, now that the write of their txs is durable,
-- emit 'AcquiredEbTxs' if no job of the point remains, and trace the reply's
-- arrival, as classified when it arrived.
--
-- See 'settleBody' on the LeiosDB's GC overtaking the fetch state's pruning.
settleTxs ::
  (Ord peer, IOLike m) =>
  LeiosFetchClientContext m peer ->
  peer ->
  LeiosBlockTxsRequest ->
  -- | the reply's bytes, classified when it arrived
  FetchArrivalBytes ->
  m ()
settleTxs :: forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> FetchArrivalBytes -> m ()
settleTxs LeiosFetchClientContext m peer
ctx peer
peer req :: LeiosBlockTxsRequest
req@(MkLeiosBlockTxsRequest LeiosPoint
point NEIntMap LeiosJob
_jobs) FetchArrivalBytes
arrival = do
  traces <- StrictMVar m (LeiosOutstanding peer)
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer,
          RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> m (RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
modifyMVar StrictMVar m (LeiosOutstanding peer)
lfcOutstanding ((LeiosOutstanding peer
  -> m (LeiosOutstanding peer,
        RelativeTime -> [TraceLeiosFetchClientEvent peer]))
 -> m (RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> (LeiosOutstanding peer
    -> m (LeiosOutstanding peer,
          RelativeTime -> [TraceLeiosFetchClientEvent peer]))
-> m (RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding peer
outstanding -> do
    let outstanding' :: LeiosOutstanding peer
outstanding' = peer
-> LeiosBlockTxsRequest
-> LeiosOutstanding peer
-> LeiosOutstanding peer
forall peer.
Ord peer =>
peer
-> LeiosBlockTxsRequest
-> LeiosOutstanding peer
-> LeiosOutstanding peer
completeTxRequest peer
peer LeiosBlockTxsRequest
req LeiosOutstanding peer
outstanding
    case (LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding), LeiosPoint -> Map LeiosPoint EbState -> Maybe EbState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup LeiosPoint
point (LeiosOutstanding peer -> Map LeiosPoint EbState
forall peer. LeiosOutstanding peer -> Map LeiosPoint EbState
ebState LeiosOutstanding peer
outstanding')) of
      -- This reply's write completed the closure.
      ( Just (MkEbState StrictMaybe RelativeTime
_ (BodyAcquired LeiosJobPool
before))
        , Just (MkEbState StrictMaybe RelativeTime
onset (BodyAcquired LeiosJobPool
after))
        )
          | Bool -> Bool
not (LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
before)
          , LeiosJobPool -> Bool
Jobs.nullJobPool LeiosJobPool
after -> 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
$ LeiosAcquisition -> STM m ()
lfcNotify (LeiosAcquisition -> STM m ()) -> LeiosAcquisition -> STM m ()
forall a b. (a -> b) -> a -> b
$ LeiosPoint -> LeiosAcquisition
AcquiredEbTxs LeiosPoint
point
              (LeiosOutstanding peer,
 RelativeTime -> [TraceLeiosFetchClientEvent peer])
-> m (LeiosOutstanding peer,
      RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
                ( LeiosOutstanding peer
outstanding'
                , \RelativeTime
now -> [LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
forall peer.
LeiosPoint
-> Maybe NominalDiffTime -> TraceLeiosFetchClientEvent peer
TraceLeiosFetchClientBlockTxsAcquired LeiosPoint
point (RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now StrictMaybe RelativeTime
onset)]
                )
      (Maybe EbState, Maybe EbState)
_ -> (LeiosOutstanding peer,
 RelativeTime -> [TraceLeiosFetchClientEvent peer])
-> m (LeiosOutstanding peer,
      RelativeTime -> [TraceLeiosFetchClientEvent peer])
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding peer
outstanding', [TraceLeiosFetchClientEvent peer]
-> RelativeTime -> [TraceLeiosFetchClientEvent peer]
forall a b. a -> b -> a
const [])
  void $ tryPutMVar lfcReady ()
  -- Read after emitting, so that the acquisition's age runs until then.
  now <- systemTimeCurrent lfcSystemTime
  mapM_ (traceWith lfcTracer) (TraceLeiosFetchClientTxsArrived peer point arrival : traces now)
 where
  MkLeiosFetchClientContext
    { StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding :: StrictMVar m (LeiosOutstanding peer)
lfcOutstanding
    , StrictMVar m ()
lfcReady :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady :: StrictMVar m ()
lfcReady
    , LeiosAcquisition -> STM m ()
lfcNotify :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosAcquisition -> STM m ()
lfcNotify :: LeiosAcquisition -> STM m ()
lfcNotify
    , SystemTime m
lfcSystemTime :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> SystemTime m
lfcSystemTime :: SystemTime m
lfcSystemTime
    , Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer :: Tracer m (TraceLeiosFetchClientEvent peer)
lfcTracer
    } = LeiosFetchClientContext m peer
ctx

-- | The total size of these jobs' txs.
jobsBytesSize :: IntMap.IntMap Jobs.LeiosJob -> BytesSize
jobsBytesSize :: IntMap LeiosJob -> Word32
jobsBytesSize = Sum Word32 -> Word32
forall a. Sum a -> a
getSum (Sum Word32 -> Word32)
-> (IntMap LeiosJob -> Sum Word32) -> IntMap LeiosJob -> Word32
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (LeiosJob -> Sum Word32) -> IntMap LeiosJob -> Sum Word32
forall m a. Monoid m => (a -> m) -> IntMap a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Jobs.MkLeiosJob IntSet
_ Word32
bytes JobCommitment
_) -> Word32 -> Sum Word32
forall a. a -> Sum a
Sum Word32
bytes)

-- | How long after this onset @now@ is, if there is an onset.
ageAt :: RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt :: RelativeTime -> StrictMaybe RelativeTime -> Maybe NominalDiffTime
ageAt RelativeTime
now = \case
  SJust RelativeTime
onset -> NominalDiffTime -> Maybe NominalDiffTime
forall a. a -> Maybe a
Just (RelativeTime -> RelativeTime -> NominalDiffTime
diffRelTime RelativeTime
now RelativeTime
onset)
  StrictMaybe RelativeTime
SNothing -> Maybe NominalDiffTime
forall a. Maybe a
Nothing

-- | Cheap validation of one covered job against the commitment the request
-- carries for it: its arriving txs have its total byte size.
--
-- Assumes the reply has as many txs as its request has offsets (see
-- 'ExnLeiosBlockTxsWrongCount'), so every offset of the job has a tx.
--
-- Does /no/ hashing so that redundant\/"hedge" requests don't contend for
-- CPU. A peer that over-sends to create extra work is punished even if we
-- already did the (right amount of) CPU work for a peer that replied earlier,
-- without pointlessly repeating that CPU work.
checkJobSize ::
  LeiosPoint ->
  IntMap.IntMap LeiosTx ->
  Jobs.LeiosJobId ->
  Jobs.LeiosJob ->
  Either ExnLeiosFetchInvalidReply ()
checkJobSize :: LeiosPoint
-> IntMap LeiosTx
-> LeiosJobId
-> LeiosJob
-> Either ExnLeiosFetchInvalidReply ()
checkJobSize LeiosPoint
point IntMap LeiosTx
aligned LeiosJobId
jid (Jobs.MkLeiosJob IntSet
offs Word32
expectedBytes JobCommitment
_commitment)
  | Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ByteString -> Int
BS.length (LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx) | LeiosTx
tx <- IntMap LeiosTx -> [LeiosTx]
forall a. IntMap a -> [a]
IntMap.elems IntMap LeiosTx
sub]) Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word32
expectedBytes =
      ExnLeiosFetchInvalidReply -> Either ExnLeiosFetchInvalidReply ()
forall a b. a -> Either a b
Left (ExnLeiosFetchInvalidReply -> Either ExnLeiosFetchInvalidReply ())
-> ExnLeiosFetchInvalidReply -> Either ExnLeiosFetchInvalidReply ()
forall a b. (a -> b) -> a -> b
$ LeiosPoint
-> LeiosJobId -> JobMismatch -> ExnLeiosFetchInvalidReply
ExnLeiosBlockTxsJobMismatch LeiosPoint
point LeiosJobId
jid JobMismatch
JobBytesSizeMismatch
  | Bool
otherwise = () -> Either ExnLeiosFetchInvalidReply ()
forall a b. b -> Either a b
Right ()
 where
  -- just the txs from /this/ job
  sub :: IntMap LeiosTx
sub = IntMap LeiosTx -> IntSet -> IntMap LeiosTx
forall a. IntMap a -> IntSet -> IntMap a
IntMap.restrictKeys IntMap LeiosTx
aligned IntSet
offs

-- | Content validation of one /pending/ job we intend to ingest: hash its
-- arriving txs and check their hashes and sizes against the job's commitment.
-- Gives those txs, with their hashes.
--
-- Only runs for the first reply for a job, in addition to 'checkJobSize'.
checkJobCommitment ::
  LeiosPoint ->
  IntMap.IntMap LeiosTx ->
  Jobs.LeiosJobId ->
  Jobs.LeiosJob ->
  Either ExnLeiosFetchInvalidReply [(Int, TxHash, BS.ByteString)]
checkJobCommitment :: LeiosPoint
-> IntMap LeiosTx
-> LeiosJobId
-> LeiosJob
-> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)]
checkJobCommitment LeiosPoint
point IntMap LeiosTx
aligned LeiosJobId
jid (Jobs.MkLeiosJob IntSet
offs Word32
_expectedBytes JobCommitment
commitment)
  | [(TxHash, Word32)] -> JobCommitment
Jobs.jobCommitmentOfTxs [(TxHash
h, Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS.length ByteString
bytes)) | (Int
_, TxHash
h, ByteString
bytes) <- [(Int, TxHash, ByteString)]
hashed]
      JobCommitment -> JobCommitment -> Bool
forall a. Eq a => a -> a -> Bool
/= JobCommitment
commitment =
      ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)]
forall a b. a -> Either a b
Left (ExnLeiosFetchInvalidReply
 -> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)])
-> ExnLeiosFetchInvalidReply
-> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)]
forall a b. (a -> b) -> a -> b
$ LeiosPoint
-> LeiosJobId -> JobMismatch -> ExnLeiosFetchInvalidReply
ExnLeiosBlockTxsJobMismatch LeiosPoint
point LeiosJobId
jid JobMismatch
JobCommitmentMismatch
  | Bool
otherwise = [(Int, TxHash, ByteString)]
-> Either ExnLeiosFetchInvalidReply [(Int, TxHash, ByteString)]
forall a b. b -> Either a b
Right [(Int, TxHash, ByteString)]
hashed
 where
  -- Ascending by offset: the order the commitment hashes them in, and the key
  -- the LeiosDb stores the bytes under.
  hashed :: [(Int, TxHash, ByteString)]
hashed =
    [ (Int
off, LeiosTx -> TxHash
hashLeiosTx LeiosTx
tx, LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx)
    | (Int
off, LeiosTx
tx) <- IntMap LeiosTx -> [(Int, LeiosTx)]
forall a. IntMap a -> [(Int, a)]
IntMap.toAscList (IntMap LeiosTx -> IntSet -> IntMap LeiosTx
forall a. IntMap a -> IntSet -> IntMap a
IntMap.restrictKeys IntMap LeiosTx
aligned IntSet
offs)
    ]

toIntSet :: Set TxOffset -> IntSet.IntSet
toIntSet :: Set Int -> IntSet
toIntSet = [Int] -> IntSet
IntSet.fromDistinctAscList ([Int] -> IntSet) -> (Set Int -> [Int]) -> Set Int -> IntSet
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Set Int -> [Int]
forall a. Set a -> [a]
Set.toAscList