{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Tests of how the node's LeiosFetch client takes in replies, against an
-- in-memory LeiosDB.
module Test.Consensus.Leios.LeiosFetch.Replies (tests) where

import Cardano.Crypto.Hash (Hash (UnsafeHash))
import Cardano.Ledger.Keys (KeyHash (..), KeyRole (BlockIssuer))
import Cardano.Slotting.Slot (SlotNo (..))
import Control.Concurrent.Class.MonadSTM.Strict
  ( StrictTVar
  , atomically
  , check
  , modifyTVar
  , newEmptyTMVarIO
  , newTVarIO
  , putTMVar
  , readTMVar
  , readTVar
  , readTVarIO
  )
import Control.Exception (try)
import Control.Monad.Class.MonadAsync (wait, withAsync)
import Control.Tracer (mkTracer, nullTracer)
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy.Char8 as BSL8
import qualified Data.ByteString.Short as SBS
import Data.Foldable (toList)
import qualified Data.IntMap.NonEmpty as NEIntMap
import Data.List (sortOn)
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.Map.Strict as Map
import Data.Maybe.Strict (StrictMaybe (..))
import qualified Data.Vector.Strict as V
import Ouroboros.Consensus.BlockchainTime.WallClock.Types
  ( RelativeTime (..)
  , SystemTime (..)
  )
import Ouroboros.Consensus.Leios.Acquisitions (LeiosAcquisition (..))
import Ouroboros.Consensus.Leios.TxCache
  ( defaultLeiosTxCacheShift
  , evictOlderThan
  , newPureLeiosTxCache
  )
import Ouroboros.Consensus.Leios.Types
  ( ElectionId (..)
  , EndorserBlock
  , ForgedEndorserBlock
  , LeiosEbByteSizes (..)
  , LeiosPoint (..)
  , LeiosTx (..)
  , Serialised (..)
  , encodeEndorserBlockSize
  , endorserBlockFromTxBytes
  , endorserBlockHash
  , forgeLeiosEb
  , hashLeiosTx
  , hashSerialisedEndorserBlock
  , idLeiosEbByteSizesLimit
  , mkEndorserBlock
  , serialiseEndorserBlock
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Client.Replies
  ( ExnLeiosFetchInvalidReply (..)
  , JobMismatch (..)
  , LeiosFetchClientContext (..)
  , acquireForgedEb
  , processLeiosBlock
  , processLeiosBlockTxs
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Decision
  ( EbFetchState (..)
  , EbState (..)
  , LeiosBlockRequest (..)
  , LeiosBlockTxsRequest (..)
  , LeiosFetchRequest (..)
  , LeiosOutstanding (..)
  , OfferedHalves (..)
  , PeerOffer (..)
  , defaultLeiosFetchStaticEnv
  , emptyLeiosOutstanding
  , focusElectionIfUnfocused
  , leiosFetchLogicIteration
  , pruneOutstandingToImmTip
  , recordReferencedPoint
  )
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Jobs (nullJobPool)
import Ouroboros.Consensus.MiniProtocol.LeiosFetch.Trace
  ( FetchArrivalBytes
  , TraceLeiosFetchClientEvent (..)
  , fetchArrivalEvicted
  , fetchArrivalExtra
  , fetchArrivalGood
  )
import Ouroboros.Consensus.Storage.LeiosDB
  ( LeiosDbHandle (..)
  , newLeiosDBInMemory
  )
import Ouroboros.Consensus.Storage.LeiosDB.API
  ( LeiosDbWriter (..)
  , Promise (..)
  )
import Ouroboros.Consensus.Util.IOLike (modifyMVar, modifyMVar_, readMVar, takeMVar)
import Ouroboros.Consensus.Util.NormalForm.StrictMVar (uncheckedNewEmptyMVar, uncheckedNewMVar)
import System.Random (mkStdGen)
import qualified System.Timeout as Timeout
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))

tests :: TestTree
tests :: TestTree
tests =
  String -> [TestTree] -> TestTree
testGroup
    String
"replies"
    [ String -> Assertion -> TestTree
testCase String
"the client emits a body's acquisition, then its closure's, once each is durable" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
        Assertion
test_acquisitions
    , String -> Assertion -> TestTree
testCase String
"the client disconnects a peer whose body has another hash" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
        Assertion
test_wrongHash
    , String -> Assertion -> TestTree
testCase
        String
"the client acquires a body only at its own point, even if the endorser block was announced at a newer point while it was being written"
        Assertion
test_announcedAgainWhileWriting
    , String -> Assertion -> TestTree
testCase
        String
"the client acquires nothing for a body whose point was pruned while it was being written, and fetches the endorser block again at a newer point"
        Assertion
test_prunedWhileWriting
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose transactions are not the sizes the endorser block declares, even if they add up to their job's size, without writing them"
        Assertion
test_wrongSizedTxs
    , String -> Assertion -> TestTree
testCase
        String
"the client takes a body of the right hash but not the offered size, emits its acquisition, and then disconnects the peer"
        Assertion
test_wrongOfferedSize
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose body is bigger than its point allows, without writing it, even if the peer also misreported its size"
        Assertion
test_bodyTooBig
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose body references more transaction bytes than its point allows, without writing it"
        Assertion
test_closureTooBig
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose body has the requested hash but does not decode, without writing it"
        Assertion
test_undecodable
    , String -> Assertion -> TestTree
testCase String
"the client disconnects a peer that sends fewer transactions than requested" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
        Assertion
test_wrongTxCount
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose transactions for a job do not add up to that job's size"
        Assertion
test_jobBytesSizeMismatch
    , String -> Assertion -> TestTree
testCase
        String
"the client disconnects a peer whose transactions for a job do not hash to that job's commitment"
        Assertion
test_jobCommitmentMismatch
    , String -> Assertion -> TestTree
testCase
        String
"of two replies with a body whose writes overlap, the client counts the bytes as needed only for the one that settles first"
        Assertion
test_overlappingReplies
    , String -> Assertion -> TestTree
testCase String
"the client counts a body that arrives once its point holds it as redundant" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
        Assertion
test_replyAfterSettle
    , String -> Assertion -> TestTree
testCase
        String
"of two replies with a closure's transactions whose writes overlap, the client counts the bytes as needed only for the one that settles first"
        Assertion
test_overlappingTxsReplies
    , String -> Assertion -> TestTree
testCase String
"the client counts transactions for a point pruned meanwhile as evicted" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
        Assertion
test_txsForPrunedPoint
    , String -> Assertion -> TestTree
testCase
        String
"the client copies into a body's write the transactions another point holds, and fetches only the rest"
        Assertion
test_fillsFromAnotherPoint
    , String -> Assertion -> TestTree
testCase
        String
"the client fetches all of a body's transactions once the point holding some of them leaves the LeiosTxCache"
        Assertion
test_noFillsFromPrunedPoint
    , String -> Assertion -> TestTree
testCase
        String
"the client acquires the closure of an endorser block the node forged at a point whose body it already held, without acquiring the body again"
        Assertion
test_forgedAfterBody
    , String -> Assertion -> TestTree
testCase
        String
"the client emits nothing more for an endorser block the node forged again at a point whose closure it already acquired"
        Assertion
test_forgedAgain
    , String -> Assertion -> TestTree
testCase
        String
"the client counts transactions a peer sends after the node's own forge acquired them as redundant, and acquires nothing more"
        Assertion
test_txsAfterForged
    ]

-- | What a notification says, comparably.
data Acquired = AcquiredBody LeiosPoint | AcquiredClosure LeiosPoint
  deriving (Acquired -> Acquired -> Bool
(Acquired -> Acquired -> Bool)
-> (Acquired -> Acquired -> Bool) -> Eq Acquired
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Acquired -> Acquired -> Bool
== :: Acquired -> Acquired -> Bool
$c/= :: Acquired -> Acquired -> Bool
/= :: Acquired -> Acquired -> Bool
Eq, Int -> Acquired -> ShowS
[Acquired] -> ShowS
Acquired -> String
(Int -> Acquired -> ShowS)
-> (Acquired -> String) -> ([Acquired] -> ShowS) -> Show Acquired
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Acquired -> ShowS
showsPrec :: Int -> Acquired -> ShowS
$cshow :: Acquired -> String
show :: Acquired -> String
$cshowList :: [Acquired] -> ShowS
showList :: [Acquired] -> ShowS
Show)

-- | An endorser block of two transactions, announced in slot 5.
fixture :: (LeiosPoint, EndorserBlock, [LeiosTx])
fixture :: (LeiosPoint, EndorserBlock, [LeiosTx])
fixture = (SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
5) (EndorserBlock -> Hash HASH EraIndependentEbReferences
endorserBlockHash EndorserBlock
eb), EndorserBlock
eb, NonEmpty LeiosTx -> [LeiosTx]
forall a. NonEmpty a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList NonEmpty LeiosTx
fixtureTxs)
 where
  eb :: EndorserBlock
eb = NonEmpty ByteString -> EndorserBlock
endorserBlockFromTxBytes ((LeiosTx -> ByteString) -> NonEmpty LeiosTx -> NonEmpty ByteString
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap LeiosTx -> ByteString
leiosTxBytes NonEmpty LeiosTx
fixtureTxs)

-- | The 'fixture''s transactions.
fixtureTxs :: NonEmpty LeiosTx
fixtureTxs :: NonEmpty LeiosTx
fixtureTxs = ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx zero") LeiosTx -> [LeiosTx] -> NonEmpty LeiosTx
forall a. a -> [a] -> NonEmpty a
:| [ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx one")]

peer :: Int
peer :: Int
peer = Int
0

otherPeer :: Int
otherPeer :: Int
otherPeer = Int
1

-- | Whom every election in these tests elects.
electee :: KeyHash BlockIssuer
electee :: KeyHash BlockIssuer
electee = Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash BlockIssuer
forall (r :: KeyRole).
Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r
KeyHash (ShortByteString -> Hash ADDRHASH (VerKeyDSIGN DSIGN)
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash ([Word8] -> ShortByteString
SBS.pack (Int -> Word8 -> [Word8]
forall a. Int -> a -> [a]
replicate Int
28 Word8
0)))

-- | A client context over an in-memory LeiosDB and fresh state that is
-- fetching the 'fixture', with its notifications collected, newest first.
newContext :: IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext :: IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext = Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextHolding (() -> Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())

-- | 'newContext', whose body writes are not done until this returns.
newContextHolding :: IO () -> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextHolding :: Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextHolding = let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture in LeiosPoint
-> Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextAt LeiosPoint
point

-- | 'newContextHolding', fetching the endorser block at this point instead.
newContextAt ::
  LeiosPoint -> IO () -> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextAt :: LeiosPoint
-> Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextAt LeiosPoint
point Assertion
release = LeiosPoint
-> IO Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextGated LeiosPoint
point (Assertion -> IO Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Assertion
release)

-- | 'newContextAt', each of whose body writes is not done until what this
-- gives at that write returns.
newContextGated ::
  LeiosPoint -> IO (IO ()) -> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextGated :: LeiosPoint
-> IO Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextGated LeiosPoint
point IO Assertion
gate = do
  let MkLeiosPoint SlotNo
slot Hash HASH EraIndependentEbReferences
ebHash = LeiosPoint
point
  db <- IO (LeiosDbHandle IO)
forall (m :: * -> *). IOLike m => m (LeiosDbHandle m)
newLeiosDBInMemory
  writer <- holdingBodies <$> openWriter db
  txCache <- newPureLeiosTxCache defaultLeiosTxCacheShift
  outstanding <-
    uncheckedNewMVar $
      focusElectionIfUnfocused (ElectionId slot electee) ebHash $
        recordReferencedPoint point SNothing $
          emptyLeiosOutstanding (mkStdGen 0) (SlotNo 0)
  ready <- uncheckedNewEmptyMVar
  notes <- newTVarIO []
  let note = \case
        AcquiredEb LeiosPoint
p Word32
_bodySize -> LeiosPoint -> Acquired
AcquiredBody LeiosPoint
p
        AcquiredEbTxs LeiosPoint
p -> LeiosPoint -> Acquired
AcquiredClosure LeiosPoint
p
  pure
    ( MkLeiosFetchClientContext
        { lfcStaticEnv = defaultLeiosFetchStaticEnv maxBound
        , lfcOutstanding = outstanding
        , lfcReady = ready
        , lfcTxCache = txCache
        , lfcWriter = writer
        , lfcNotify = modifyTVar notes . (:) . note
        , lfcSystemTime = SystemTime (pure (RelativeTime 0)) (pure ())
        , lfcTracer = nullTracer
        }
    , notes
    )
 where
  holdingBodies :: LeiosDbWriter IO -> LeiosDbWriter IO
holdingBodies LeiosDbWriter IO
writer =
    LeiosDbWriter IO
writer
      { writeEbBody = \LeiosPoint
p EndorserBlock
eb LocalFills
fills -> do
          release <- IO Assertion
gate
          written <- writeEbBody writer p eb fills
          pure $ Promise $ release >> await written
      }

-- | Writes that hold until released: what to run in a held write, waiting
-- until this many writers are held, and releasing them all.
newWriteHold :: IO (IO (), Int -> IO (), IO ())
newWriteHold :: IO (Assertion, Int -> Assertion, Assertion)
newWriteHold = do
  written <- IO (StrictTMVar IO ())
forall (m :: * -> *) a. MonadSTM m => m (StrictTMVar m a)
newEmptyTMVarIO
  held <- newTVarIO (0 :: Int)
  pure
    ( atomically (modifyTVar held (+ 1)) >> atomically (readTMVar written)
    , \Int
n -> STM IO () -> Assertion
forall a. HasCallStack => STM IO a -> IO a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM IO () -> Assertion) -> STM IO () -> Assertion
forall a b. (a -> b) -> a -> b
$ StrictTVar IO Int -> STM IO Int
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar IO Int
held STM IO Int -> (Int -> STM IO ()) -> STM IO ()
forall a b. STM IO a -> (a -> STM IO b) -> STM IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Bool -> STM ()
Bool -> STM IO ()
forall (m :: * -> *). MonadSTM m => Bool -> STM m ()
check (Bool -> STM ()) -> (Int -> Bool) -> Int -> STM ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n)
    , atomically $ putTMVar written ()
    )

-- | Wait until this many notifications have arrived, and return them, oldest
-- first.
awaitNotes :: StrictTVar IO [Acquired] -> Int -> IO [Acquired]
awaitNotes :: StrictTVar IO [Acquired] -> Int -> IO [Acquired]
awaitNotes StrictTVar IO [Acquired]
notes Int
n =
  Int -> IO [Acquired] -> IO (Maybe [Acquired])
forall a. Int -> IO a -> IO (Maybe a)
Timeout.timeout
    Int
5000000
    (STM IO [Acquired] -> IO [Acquired]
forall a. HasCallStack => STM IO a -> IO a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM IO [Acquired] -> IO [Acquired])
-> STM IO [Acquired] -> IO [Acquired]
forall a b. (a -> b) -> a -> b
$ StrictTVar IO [Acquired] -> STM IO [Acquired]
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar IO [Acquired]
notes STM IO [Acquired]
-> ([Acquired] -> STM IO [Acquired]) -> STM IO [Acquired]
forall a b. STM IO a -> (a -> STM IO b) -> STM IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \[Acquired]
ns -> [Acquired] -> [Acquired]
forall a. [a] -> [a]
reverse [Acquired]
ns [Acquired] -> STM () -> STM [Acquired]
forall a b. a -> STM b -> STM a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Bool -> STM IO ()
forall (m :: * -> *). MonadSTM m => Bool -> STM m ()
check ([Acquired] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Acquired]
ns Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n))
    IO (Maybe [Acquired])
-> (Maybe [Acquired] -> IO [Acquired]) -> IO [Acquired]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO [Acquired]
-> ([Acquired] -> IO [Acquired])
-> Maybe [Acquired]
-> IO [Acquired]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> IO [Acquired]
forall a. HasCallStack => String -> IO a
assertFailure String
"timed out waiting for notifications") [Acquired] -> IO [Acquired]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

test_acquisitions :: Assertion
test_acquisitions :: Assertion
test_acquisitions = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  closureRequest ctx point >>= \LeiosBlockTxsRequest
req -> LeiosFetchClientContext IO Int
-> Int -> LeiosBlockTxsRequest -> Vector LeiosTx -> Assertion
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext IO Int
ctx Int
peer LeiosBlockTxsRequest
req ([LeiosTx] -> Vector LeiosTx
forall a. [a] -> Vector a
V.fromList [LeiosTx]
txs)
  awaitNotes notes 2 >>= (@?= [AcquiredBody point, AcquiredClosure point])

-- | The one request the decision logic makes of a peer that offers the closure
-- of the endorser block at this point, whose body the client holds.
closureRequest :: LeiosFetchClientContext IO Int -> LeiosPoint -> IO LeiosBlockTxsRequest
closureRequest :: LeiosFetchClientContext IO Int
-> LeiosPoint -> IO LeiosBlockTxsRequest
closureRequest LeiosFetchClientContext IO Int
ctx LeiosPoint
point = do
  reqs <-
    StrictMVar IO (LeiosOutstanding Int)
-> (LeiosOutstanding Int
    -> IO (LeiosOutstanding Int, [LeiosBlockTxsRequest]))
-> IO [LeiosBlockTxsRequest]
forall (m :: * -> *) a b.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m (a, b)) -> m b
modifyMVar (LeiosFetchClientContext IO Int
-> StrictMVar IO (LeiosOutstanding Int)
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding LeiosFetchClientContext IO Int
ctx) ((LeiosOutstanding Int
  -> IO (LeiosOutstanding Int, [LeiosBlockTxsRequest]))
 -> IO [LeiosBlockTxsRequest])
-> (LeiosOutstanding Int
    -> IO (LeiosOutstanding Int, [LeiosBlockTxsRequest]))
-> IO [LeiosBlockTxsRequest]
forall a b. (a -> b) -> a -> b
$ \LeiosOutstanding Int
outstanding -> do
      let (LeiosOutstanding Int
outstanding', Map Int (NESeq LeiosFetchRequest)
decisions, Map Int (NEMap LeiosPoint OfferPrune)
_drops) =
            LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map Int (Map LeiosPoint PeerOffer)
-> Map Int IsBigLedgerPeer
-> LeiosOutstanding Int
-> (LeiosOutstanding Int, Map Int (NESeq LeiosFetchRequest),
    Map Int (NEMap LeiosPoint OfferPrune))
forall peer.
Ord peer =>
LeiosFetchStaticEnv
-> (SlotNo
    -> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit))
-> Maybe (SlotNo, Word64)
-> Map peer (Map LeiosPoint PeerOffer)
-> Map peer IsBigLedgerPeer
-> LeiosOutstanding peer
-> (LeiosOutstanding peer, Map peer (NESeq LeiosFetchRequest),
    Map peer (NEMap LeiosPoint OfferPrune))
leiosFetchLogicIteration
              (LeiosFetchClientContext IO Int -> LeiosFetchStaticEnv
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> LeiosFetchStaticEnv
lfcStaticEnv LeiosFetchClientContext IO Int
ctx)
              (\SlotNo
_slot -> LeiosEbByteSizes 'SizeLimit
-> Either OutsideForecastRange (LeiosEbByteSizes 'SizeLimit)
forall a b. b -> Either a b
Right LeiosEbByteSizes 'SizeLimit
forall a. Bounded a => a
maxBound)
              ((SlotNo, Word64) -> Maybe (SlotNo, Word64)
forall a. a -> Maybe a
Just (Word64 -> SlotNo
SlotNo Word64
6, Word64
10))
              (Int
-> Map LeiosPoint PeerOffer -> Map Int (Map LeiosPoint PeerOffer)
forall k a. k -> a -> Map k a
Map.singleton Int
peer (LeiosPoint -> PeerOffer -> Map LeiosPoint PeerOffer
forall k a. k -> a -> Map k a
Map.singleton LeiosPoint
point (StrictMaybe (LeiosEbByteSizes 'SizeLimit)
-> OfferedHalves -> PeerOffer
MkPeerOffer StrictMaybe (LeiosEbByteSizes 'SizeLimit)
forall a. StrictMaybe a
SNothing OfferedHalves
OfferedClosure)))
              Map Int IsBigLedgerPeer
forall k a. Map k a
Map.empty
              LeiosOutstanding Int
outstanding
      (LeiosOutstanding Int, [LeiosBlockTxsRequest])
-> IO (LeiosOutstanding Int, [LeiosBlockTxsRequest])
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding Int
outstanding', [LeiosBlockTxsRequest
r | LeiosBlockTxsRequest LeiosBlockTxsRequest
r <- (NESeq LeiosFetchRequest -> [LeiosFetchRequest])
-> Map Int (NESeq LeiosFetchRequest) -> [LeiosFetchRequest]
forall m a. Monoid m => (a -> m) -> Map Int a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap NESeq LeiosFetchRequest -> [LeiosFetchRequest]
forall a. NESeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Map Int (NESeq LeiosFetchRequest)
decisions])
  case reqs of
    [LeiosBlockTxsRequest
req] -> LeiosBlockTxsRequest -> IO LeiosBlockTxsRequest
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure LeiosBlockTxsRequest
req
    [LeiosBlockTxsRequest]
_ -> String -> IO LeiosBlockTxsRequest
forall a. HasCallStack => String -> IO a
assertFailure (String -> IO LeiosBlockTxsRequest)
-> String -> IO LeiosBlockTxsRequest
forall a b. (a -> b) -> a -> b
$ String
"expected one request, got " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> Int -> String
forall a. Show a => a -> String
show ([LeiosBlockTxsRequest] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [LeiosBlockTxsRequest]
reqs)

-- | An endorser block that misstates the sizes of its first two transactions,
-- by amounts that cancel out, so that their job's count and total size check
-- out. Its third transaction is too big to share their job.
test_wrongSizedTxs :: Assertion
test_wrongSizedTxs :: Assertion
test_wrongSizedTxs = do
  let tx0 :: LeiosTx
tx0 = ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx zero")
      tx1 :: LeiosTx
tx1 = ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx one")
      tx2 :: LeiosTx
tx2 = ByteString -> LeiosTx
MkLeiosTx (Int -> Char -> ByteString
BS8.replicate (Int
64 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1024) Char
'x')
      eb :: EndorserBlock
eb = [(TxHash, Word32)] -> EndorserBlock
mkEndorserBlock [(LeiosTx -> TxHash
hashLeiosTx LeiosTx
tx0, Word32
6), (LeiosTx -> TxHash
hashLeiosTx LeiosTx
tx1, Word32
7), (LeiosTx -> TxHash
hashLeiosTx LeiosTx
tx2, Word32
64 Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
* Word32
1024)]
      point :: LeiosPoint
point = SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
5) (EndorserBlock -> Hash HASH EraIndependentEbReferences
endorserBlockHash EndorserBlock
eb)
  (ctx, notes) <- LeiosPoint
-> Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextAt LeiosPoint
point (() -> Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  MkLeiosBlockTxsRequest _point jobs <- closureRequest ctx point
  NEIntMap.size jobs @?= 2
  result <-
    try $
      processLeiosBlockTxs
        ctx
        peer
        (MkLeiosBlockTxsRequest point (uncurry NEIntMap.singleton (NEIntMap.findMin jobs)))
        (V.fromList [tx0, tx1])
  case result of
    Left (ExnLeiosBlockTxsJobMismatch LeiosPoint
p LeiosJobId
_job JobMismatch
JobCommitmentMismatch) -> LeiosPoint
p LeiosPoint -> LeiosPoint -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= LeiosPoint
point
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client took transactions of other sizes than the endorser block declares"
  readTVarIO notes >>= (@?= [AcquiredBody point])

test_wrongHash :: Assertion
test_wrongHash :: Assertion
test_wrongHash = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      other :: EndorserBlock
other = NonEmpty ByteString -> EndorserBlock
endorserBlockFromTxBytes (String -> ByteString
BS8.pack String
"another tx" ByteString -> [ByteString] -> NonEmpty ByteString
forall a. a -> [a] -> NonEmpty a
:| [])
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  result <-
    try $
      processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (encodeEndorserBlockSize other) maxBound)
        (serialiseEndorserBlock other)
  case result of
    Left (ExnLeiosBlockWrongHash LeiosPoint
p Hash HASH EraIndependentEbReferences
h) -> (LeiosPoint
p, Hash HASH EraIndependentEbReferences
h) (LeiosPoint, Hash HASH EraIndependentEbReferences)
-> (LeiosPoint, Hash HASH EraIndependentEbReferences) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (LeiosPoint
point, EndorserBlock -> Hash HASH EraIndependentEbReferences
endorserBlockHash EndorserBlock
other)
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client accepted a body with another hash"
  atomically (readTVar notes) >>= (@?= [])

-- | An election focuses the 'fixture' at a newer point while its body is being
-- written.
test_announcedAgainWhileWriting :: Assertion
test_announcedAgainWhileWriting :: Assertion
test_announcedAgainWhileWriting = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      ebHash :: Hash HASH EraIndependentEbReferences
ebHash = LeiosPoint -> Hash HASH EraIndependentEbReferences
pointEbHash LeiosPoint
point
      newer :: LeiosPoint
newer = SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
7) Hash HASH EraIndependentEbReferences
ebHash
  (hold, awaitHeld, release) <- IO (Assertion, Int -> Assertion, Assertion)
newWriteHold
  (ctx, notes) <- newContextHolding hold
  withAsync
    ( processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
        (serialiseEndorserBlock eb)
    )
    $ \Async IO ()
client -> do
      Int -> Assertion
awaitHeld Int
1
      StrictMVar IO (LeiosOutstanding Int)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m a) -> m ()
modifyMVar_ (LeiosFetchClientContext IO Int
-> StrictMVar IO (LeiosOutstanding Int)
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding LeiosFetchClientContext IO Int
ctx) ((LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall a b. (a -> b) -> a -> b
$
        LeiosOutstanding Int -> IO (LeiosOutstanding Int)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
          (LeiosOutstanding Int -> IO (LeiosOutstanding Int))
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> IO (LeiosOutstanding Int)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ElectionId
-> Hash HASH EraIndependentEbReferences
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
ElectionId
-> Hash HASH EraIndependentEbReferences
-> LeiosOutstanding peer
-> LeiosOutstanding peer
focusElectionIfUnfocused (SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
newer) KeyHash BlockIssuer
electee) Hash HASH EraIndependentEbReferences
ebHash
          (LeiosOutstanding Int -> LeiosOutstanding Int)
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
newer StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing
      Assertion
release
      Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
client
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  outstanding <- readMVar (lfcOutstanding ctx)
  assertNoBody newer outstanding

-- | While the 'fixture''s body is being written, pruning passes its point, and
-- an election focuses it anew at a newer point.
test_prunedWhileWriting :: Assertion
test_prunedWhileWriting :: Assertion
test_prunedWhileWriting = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      ebHash :: Hash HASH EraIndependentEbReferences
ebHash = LeiosPoint -> Hash HASH EraIndependentEbReferences
pointEbHash LeiosPoint
point
      newer :: LeiosPoint
newer = SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
8) Hash HASH EraIndependentEbReferences
ebHash
  (hold, awaitHeld, release) <- IO (Assertion, Int -> Assertion, Assertion)
newWriteHold
  (ctx, notes) <- newContextHolding hold
  withAsync
    ( processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
        (serialiseEndorserBlock eb)
    )
    $ \Async IO ()
client -> do
      Int -> Assertion
awaitHeld Int
1
      -- What 'processLeiosBlock' itself signals, so that what is left to await
      -- is the body's settlement.
      StrictMVar IO () -> Assertion
forall (m :: * -> *) a. MonadMVar m => StrictMVar m a -> m a
takeMVar (LeiosFetchClientContext IO Int -> StrictMVar IO ()
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer -> StrictMVar m ()
lfcReady LeiosFetchClientContext IO Int
ctx)
      StrictMVar IO (LeiosOutstanding Int)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m a) -> m ()
modifyMVar_ (LeiosFetchClientContext IO Int
-> StrictMVar IO (LeiosOutstanding Int)
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding LeiosFetchClientContext IO Int
ctx) ((LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall a b. (a -> b) -> a -> b
$ LeiosOutstanding Int -> IO (LeiosOutstanding Int)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding Int -> IO (LeiosOutstanding Int))
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> IO (LeiosOutstanding Int)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SlotNo -> LeiosOutstanding Int -> LeiosOutstanding Int
forall peer.
SlotNo -> LeiosOutstanding peer -> LeiosOutstanding peer
pruneOutstandingToImmTip (Word64 -> SlotNo
SlotNo Word64
6)
      StrictMVar IO (LeiosOutstanding Int)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall (m :: * -> *) a.
(HasCallStack, MonadMVar m) =>
StrictMVar m a -> (a -> m a) -> m ()
modifyMVar_ (LeiosFetchClientContext IO Int
-> StrictMVar IO (LeiosOutstanding Int)
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> StrictMVar m (LeiosOutstanding peer)
lfcOutstanding LeiosFetchClientContext IO Int
ctx) ((LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion)
-> (LeiosOutstanding Int -> IO (LeiosOutstanding Int)) -> Assertion
forall a b. (a -> b) -> a -> b
$
        LeiosOutstanding Int -> IO (LeiosOutstanding Int)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (LeiosOutstanding Int -> IO (LeiosOutstanding Int))
-> (LeiosOutstanding Int -> LeiosOutstanding Int)
-> LeiosOutstanding Int
-> IO (LeiosOutstanding Int)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding Int
-> LeiosOutstanding Int
forall peer.
LeiosPoint
-> StrictMaybe RelativeTime
-> LeiosOutstanding peer
-> LeiosOutstanding peer
recordReferencedPoint LeiosPoint
newer StrictMaybe RelativeTime
forall a. StrictMaybe a
SNothing
      Assertion
release
      Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
client
  Timeout.timeout 5000000 (takeMVar (lfcReady ctx))
    >>= maybe (assertFailure "timed out waiting for the body to settle") pure
  readTVarIO notes >>= (@?= [])
  outstanding <- readMVar (lfcOutstanding ctx)
  assertNoBody newer outstanding

-- | A peer replies with the 'fixture''s body, and then the node's own forge
-- produces the same endorser block at the same point, while the closure is
-- still to fetch.
test_forgedAfterBody :: Assertion
test_forgedAfterBody :: Assertion
test_forgedAfterBody = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  acquireForgedEb ctx (fixtureElection point) fixtureForged
  reverse <$> readTVarIO notes >>= (@?= [AcquiredBody point, AcquiredClosure point])

-- | The node's own forge produces the 'fixture''s endorser block, and once its
-- writes have settled, another of the node's forges produces the same endorser
-- block at the same point.
test_forgedAgain :: Assertion
test_forgedAgain :: Assertion
test_forgedAgain = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  acquireForgedEb ctx (fixtureElection point) fixtureForged
  reverse <$> readTVarIO notes >>= (@?= [AcquiredBody point, AcquiredClosure point])
  acquireForgedEb ctx (fixtureElection point) fixtureForged
  reverse <$> readTVarIO notes >>= (@?= [AcquiredBody point, AcquiredClosure point])
  readMVar (lfcOutstanding ctx) >>= assertNoJobLeft point

assertNoBody :: LeiosPoint -> LeiosOutstanding peer -> Assertion
assertNoBody :: forall peer. LeiosPoint -> LeiosOutstanding peer -> Assertion
assertNoBody LeiosPoint
point 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
  Just (MkEbState StrictMaybe RelativeTime
_onset EbFetchState
NoBody) -> () -> Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  Just (MkEbState StrictMaybe RelativeTime
_onset BodyAcquired{}) -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the point holds a body"
  Maybe EbState
Nothing -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the point has no entry"

assertNoJobLeft :: LeiosPoint -> LeiosOutstanding peer -> Assertion
assertNoJobLeft :: forall peer. LeiosPoint -> LeiosOutstanding peer -> Assertion
assertNoJobLeft LeiosPoint
point 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
  Just (MkEbState StrictMaybe RelativeTime
_onset (BodyAcquired LeiosJobPool
jobPool)) ->
    HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"the point has jobs left" (LeiosJobPool -> Bool
nullJobPool LeiosJobPool
jobPool)
  Just (MkEbState StrictMaybe RelativeTime
_onset EbFetchState
NoBody) -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the point holds no body"
  Maybe EbState
Nothing -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the point has no entry"

test_wrongOfferedSize :: Assertion
test_wrongOfferedSize :: Assertion
test_wrongOfferedSize = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      size :: Word32
size = EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  result <-
    try $
      processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (size + 1) maxBound)
        (serialiseEndorserBlock eb)
  case result of
    Left (ExnLeiosBlockWrongSize LeiosPoint
p Word32
offered Word32
actual) -> (LeiosPoint
p, Word32
offered, Word32
actual) (LeiosPoint, Word32, Word32)
-> (LeiosPoint, Word32, Word32) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (LeiosPoint
point, Word32
size Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
+ Word32
1, Word32
size)
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client kept a peer that misreported the body's size"
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])

test_bodyTooBig :: Assertion
test_bodyTooBig :: Assertion
test_bodyTooBig = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      size :: Word32
size = EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb
      bounds :: LeiosEbByteSizes 'SizeLimit
bounds = LeiosEbByteSizes 'SizeLimit -> LeiosEbByteSizes 'SizeLimit
idLeiosEbByteSizesLimit MkLeiosEbByteSizes{lebBodySize :: Word32
lebBodySize = Word32
size Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
1, lebTxsSize :: Word64
lebTxsSize = Word64
forall a. Bounded a => a
maxBound}
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  result <-
    try $
      processLeiosBlock ctx peer (MkLeiosBlockRequest point (size + 1) bounds) (serialiseEndorserBlock eb)
  case result of
    Left (ExnLeiosBlockTooBig LeiosPoint
p Word32
actual Word32
most) -> (LeiosPoint
p, Word32
actual, Word32
most) (LeiosPoint, Word32, Word32)
-> (LeiosPoint, Word32, Word32) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (LeiosPoint
point, Word32
size, Word32
size Word32 -> Word32 -> Word32
forall a. Num a => a -> a -> a
- Word32
1)
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client kept a peer that sent a body too big"
  readTVarIO notes >>= (@?= [])
  readMVar (lfcOutstanding ctx) >>= assertNoJobLeft point

test_closureTooBig :: Assertion
test_closureTooBig :: Assertion
test_closureTooBig = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      closure :: Word64
closure = [Word64] -> Word64
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS8.length (LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx)) | LeiosTx
tx <- [LeiosTx]
txs]
      bounds :: LeiosEbByteSizes 'SizeLimit
bounds = LeiosEbByteSizes 'SizeLimit -> LeiosEbByteSizes 'SizeLimit
idLeiosEbByteSizesLimit MkLeiosEbByteSizes{lebBodySize :: Word32
lebBodySize = Word32
forall a. Bounded a => a
maxBound, lebTxsSize :: Word64
lebTxsSize = Word64
closure Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1}
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  result <-
    try $
      processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) bounds)
        (serialiseEndorserBlock eb)
  case result of
    Left (ExnLeiosClosureTooBig LeiosPoint
p Word64
actual Word64
most) ->
      (LeiosPoint
p, Word64
actual, Word64
most) (LeiosPoint, Word64, Word64)
-> (LeiosPoint, Word64, Word64) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (LeiosPoint
point, Word64
closure, Word64
closure Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1)
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client kept a peer that sent a body referencing too many bytes"
  readTVarIO notes >>= (@?= [])
  readMVar (lfcOutstanding ctx) >>= assertNoJobLeft point

test_undecodable :: Assertion
test_undecodable :: Assertion
test_undecodable = do
  let bytes :: Serialised a
bytes = ByteString -> Serialised a
forall {k} (a :: k). ByteString -> Serialised a
Serialised (String -> ByteString
BSL8.pack String
"not an endorser block")
      point :: LeiosPoint
point = SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
5) (Serialised EndorserBlock -> Hash HASH EraIndependentEbReferences
hashSerialisedEndorserBlock Serialised EndorserBlock
forall {a}. Serialised a
bytes)
  (ctx, notes) <- LeiosPoint
-> Assertion
-> IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContextAt LeiosPoint
point (() -> Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
  result <-
    try $
      processLeiosBlock
        ctx
        peer
        (MkLeiosBlockRequest point (fromIntegral (BSL8.length (unSerialised bytes))) maxBound)
        bytes
  case result of
    Left (ExnLeiosBlockUndecodable LeiosPoint
p DecoderError
_err) -> LeiosPoint
p LeiosPoint -> LeiosPoint -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= LeiosPoint
point
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client kept a peer that sent a body that does not decode"
  readTVarIO notes >>= (@?= [])
  readMVar (lfcOutstanding ctx) >>= assertNoJobLeft point

test_wrongTxCount :: Assertion
test_wrongTxCount :: Assertion
test_wrongTxCount = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  [LeiosTx] -> IO (Either ExnLeiosFetchInvalidReply ())
replyToClosure (Int -> [LeiosTx] -> [LeiosTx]
forall a. Int -> [a] -> [a]
take Int
1 [LeiosTx]
txs) IO (Either ExnLeiosFetchInvalidReply ())
-> (Either ExnLeiosFetchInvalidReply () -> Assertion) -> Assertion
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Left (ExnLeiosBlockTxsWrongCount LeiosPoint
p Int
requested Int
arrived) -> (LeiosPoint
p, Int
requested, Int
arrived) (LeiosPoint, Int, Int) -> (LeiosPoint, Int, Int) -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= (LeiosPoint
point, Int
2, Int
1)
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client took too few transactions"

test_jobBytesSizeMismatch :: Assertion
test_jobBytesSizeMismatch :: Assertion
test_jobBytesSizeMismatch = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  [LeiosTx] -> IO (Either ExnLeiosFetchInvalidReply ())
replyToClosure (Int -> [LeiosTx] -> [LeiosTx]
forall a. Int -> [a] -> [a]
take Int
1 [LeiosTx]
txs [LeiosTx] -> [LeiosTx] -> [LeiosTx]
forall a. Semigroup a => a -> a -> a
<> [ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx one!")]) IO (Either ExnLeiosFetchInvalidReply ())
-> (Either ExnLeiosFetchInvalidReply () -> Assertion) -> Assertion
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Left (ExnLeiosBlockTxsJobMismatch LeiosPoint
p LeiosJobId
_job JobMismatch
JobBytesSizeMismatch) -> LeiosPoint
p LeiosPoint -> LeiosPoint -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= LeiosPoint
point
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client took transactions of the wrong size"

test_jobCommitmentMismatch :: Assertion
test_jobCommitmentMismatch :: Assertion
test_jobCommitmentMismatch = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  [LeiosTx] -> IO (Either ExnLeiosFetchInvalidReply ())
replyToClosure (Int -> [LeiosTx] -> [LeiosTx]
forall a. Int -> [a] -> [a]
take Int
1 [LeiosTx]
txs [LeiosTx] -> [LeiosTx] -> [LeiosTx]
forall a. Semigroup a => a -> a -> a
<> [ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx onf")]) IO (Either ExnLeiosFetchInvalidReply ())
-> (Either ExnLeiosFetchInvalidReply () -> Assertion) -> Assertion
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Left (ExnLeiosBlockTxsJobMismatch LeiosPoint
p LeiosJobId
_job JobMismatch
JobCommitmentMismatch) -> LeiosPoint
p LeiosPoint -> LeiosPoint -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= LeiosPoint
point
    Left ExnLeiosFetchInvalidReply
exn -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure (String -> Assertion) -> String -> Assertion
forall a b. (a -> b) -> a -> b
$ String
"unexpected exception: " String -> ShowS
forall a. Semigroup a => a -> a -> a
<> ExnLeiosFetchInvalidReply -> String
forall a. Show a => a -> String
show ExnLeiosFetchInvalidReply
exn
    Right () -> String -> Assertion
forall a. HasCallStack => String -> IO a
assertFailure String
"the client took transactions other than the endorser block's"

-- | What the client makes of these transactions as the reply to its request
-- for the 'fixture''s closure.
replyToClosure :: [LeiosTx] -> IO (Either ExnLeiosFetchInvalidReply ())
replyToClosure :: [LeiosTx] -> IO (Either ExnLeiosFetchInvalidReply ())
replyToClosure [LeiosTx]
txs = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  req <- closureRequest ctx point
  try $ processLeiosBlockTxs ctx peer req (V.fromList txs)

-- | Two peers reply with the 'fixture''s body before either write settles.
test_overlappingReplies :: Assertion
test_overlappingReplies :: Assertion
test_overlappingReplies = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      size :: Word32
size = EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb
      req :: LeiosBlockRequest
req = LeiosPoint
-> Word32 -> LeiosEbByteSizes 'SizeLimit -> LeiosBlockRequest
MkLeiosBlockRequest LeiosPoint
point Word32
size LeiosEbByteSizes 'SizeLimit
forall a. Bounded a => a
maxBound
  (hold, awaitHeld, release) <- IO (Assertion, Int -> Assertion, Assertion)
newWriteHold
  (ctx, notes, traces) <- withTraces $ newContextHolding hold
  withAsync (processLeiosBlock ctx peer req (serialiseEndorserBlock eb)) $ \Async IO ()
client ->
    Assertion -> (Async IO () -> Assertion) -> Assertion
forall a b. IO a -> (Async IO a -> IO b) -> IO b
forall (m :: * -> *) a b.
MonadAsync m =>
m a -> (Async m a -> m b) -> m b
withAsync (LeiosFetchClientContext IO Int
-> Int
-> LeiosBlockRequest
-> Serialised EndorserBlock
-> Assertion
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockRequest -> Serialised EndorserBlock -> m ()
processLeiosBlock LeiosFetchClientContext IO Int
ctx Int
otherPeer LeiosBlockRequest
req (EndorserBlock -> Serialised EndorserBlock
serialiseEndorserBlock EndorserBlock
eb)) ((Async IO () -> Assertion) -> Assertion)
-> (Async IO () -> Assertion) -> Assertion
forall a b. (a -> b) -> a -> b
$ \Async IO ()
otherClient -> do
      Int -> Assertion
awaitHeld Int
2
      Assertion
release
      Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
client Assertion -> Assertion -> Assertion
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
otherClient
  arrivals <- awaitArrivals blockArrivals traces 2
  [p | (p, _point, _bytes) <- arrivals] @?= [peer, otherPeer]
  let byPeer = [FetchArrivalBytes
bytes | (Int
_peer, LeiosPoint
_point, FetchArrivalBytes
bytes) <- [(Int, LeiosPoint, FetchArrivalBytes)]
arrivals]
      needed = Word32 -> FetchArrivalBytes
fetchArrivalGood Word32
size
      redundant = Word32 -> FetchArrivalBytes
fetchArrivalExtra Word32
size
  assertBool
    ("the bytes were not needed once and redundant once: " <> show byPeer)
    (byPeer == [needed, redundant] || byPeer == [redundant, needed])
  readTVarIO notes >>= (@?= [AcquiredBody point])

test_replyAfterSettle :: Assertion
test_replyAfterSettle :: Assertion
test_replyAfterSettle = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      size :: Word32
size = EndorserBlock -> Word32
encodeEndorserBlockSize EndorserBlock
eb
      req :: LeiosBlockRequest
req = LeiosPoint
-> Word32 -> LeiosEbByteSizes 'SizeLimit -> LeiosBlockRequest
MkLeiosBlockRequest LeiosPoint
point Word32
size LeiosEbByteSizes 'SizeLimit
forall a. Bounded a => a
maxBound
  (ctx, notes, traces) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
-> IO
     (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired],
      StrictTVar IO [TraceLeiosFetchClientEvent Int])
withTraces IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock ctx peer req (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  processLeiosBlock ctx otherPeer req (serialiseEndorserBlock eb)
  awaitArrivals blockArrivals traces 2
    >>= (@?= [(peer, point, fetchArrivalGood size), (otherPeer, point, fetchArrivalExtra size)])

-- | Two peers reply with the 'fixture''s transactions before either write
-- settles.
test_overlappingTxsReplies :: Assertion
test_overlappingTxsReplies :: Assertion
test_overlappingTxsReplies = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      closure :: Word32
closure = [Word32] -> Word32
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS8.length (LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx)) | LeiosTx
tx <- [LeiosTx]
txs]
  (hold, awaitHeld, release) <- IO (Assertion, Int -> Assertion, Assertion)
newWriteHold
  (ctx0, notes, traces) <- withTraces newContext
  let ctx = LeiosFetchClientContext IO Int
ctx0{lfcWriter = holdingTxs hold (lfcWriter ctx0)}
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  req <- closureRequest ctx point
  withAsync (processLeiosBlockTxs ctx peer req (V.fromList txs)) $ \Async IO ()
client ->
    Assertion -> (Async IO () -> Assertion) -> Assertion
forall a b. IO a -> (Async IO a -> IO b) -> IO b
forall (m :: * -> *) a b.
MonadAsync m =>
m a -> (Async m a -> m b) -> m b
withAsync (LeiosFetchClientContext IO Int
-> Int -> LeiosBlockTxsRequest -> Vector LeiosTx -> Assertion
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext IO Int
ctx Int
otherPeer LeiosBlockTxsRequest
req ([LeiosTx] -> Vector LeiosTx
forall a. [a] -> Vector a
V.fromList [LeiosTx]
txs)) ((Async IO () -> Assertion) -> Assertion)
-> (Async IO () -> Assertion) -> Assertion
forall a b. (a -> b) -> a -> b
$ \Async IO ()
otherClient -> do
      Int -> Assertion
awaitHeld Int
2
      Assertion
release
      Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
client Assertion -> Assertion -> Assertion
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Async IO () -> Assertion
forall a. Async IO a -> IO a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async IO ()
otherClient
  arrivals <- awaitArrivals txsArrivals traces 2
  [p | (p, _point, _bytes) <- arrivals] @?= [peer, otherPeer]
  let byPeer = [FetchArrivalBytes
bytes | (Int
_peer, LeiosPoint
_point, FetchArrivalBytes
bytes) <- [(Int, LeiosPoint, FetchArrivalBytes)]
arrivals]
      needed = Word32 -> FetchArrivalBytes
fetchArrivalGood Word32
closure
      redundant = Word32 -> FetchArrivalBytes
fetchArrivalExtra Word32
closure
  assertBool
    ("the bytes were not needed once and redundant once: " <> show byPeer)
    (byPeer == [needed, redundant] || byPeer == [redundant, needed])
  readTVarIO notes >>= (@?= [AcquiredClosure point, AcquiredBody point])

-- | This writer, whose transaction writes are not done until this returns.
holdingTxs :: IO () -> LeiosDbWriter IO -> LeiosDbWriter IO
holdingTxs :: Assertion -> LeiosDbWriter IO -> LeiosDbWriter IO
holdingTxs Assertion
release LeiosDbWriter IO
writer =
  LeiosDbWriter IO
writer
    { writeTxs = \LeiosPoint
p Map Int ByteString
txs -> do
        written <- LeiosDbWriter IO
-> HasCallStack =>
   LeiosPoint -> Map Int ByteString -> IO (Promise IO ())
forall (m :: * -> *).
LeiosDbWriter m
-> HasCallStack =>
   LeiosPoint -> Map Int ByteString -> m (Promise m ())
writeTxs LeiosDbWriter IO
writer LeiosPoint
p Map Int ByteString
txs
        pure $ Promise $ release >> await written
    }

test_txsForPrunedPoint :: Assertion
test_txsForPrunedPoint :: Assertion
test_txsForPrunedPoint = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      closure :: Word32
closure = [Word32] -> Word32
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS8.length (LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx)) | LeiosTx
tx <- [LeiosTx]
txs]
  (ctx, notes, traces) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
-> IO
     (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired],
      StrictTVar IO [TraceLeiosFetchClientEvent Int])
withTraces IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  req <- closureRequest ctx point
  modifyMVar_ (lfcOutstanding ctx) $ pure . pruneOutstandingToImmTip (SlotNo 6)
  processLeiosBlockTxs ctx peer req (V.fromList txs)
  events <- readTVarIO traces
  txsArrivals events @?= [(peer, point, fetchArrivalEvicted closure)]

-- | An endorser block at a newer point than the 'fixture''s, referencing the
-- 'fixture''s second transaction and one of its own.
sharing :: (LeiosPoint, EndorserBlock, LeiosTx, LeiosTx)
sharing :: (LeiosPoint, EndorserBlock, LeiosTx, LeiosTx)
sharing = (SlotNo -> Hash HASH EraIndependentEbReferences -> LeiosPoint
MkLeiosPoint (Word64 -> SlotNo
SlotNo Word64
6) (EndorserBlock -> Hash HASH EraIndependentEbReferences
endorserBlockHash EndorserBlock
eb), EndorserBlock
eb, LeiosTx
shared, LeiosTx
own)
 where
  shared :: LeiosTx
shared = ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx one")
  own :: LeiosTx
own = ByteString -> LeiosTx
MkLeiosTx (String -> ByteString
BS8.pack String
"tx two")
  eb :: EndorserBlock
eb = NonEmpty ByteString -> EndorserBlock
endorserBlockFromTxBytes ((LeiosTx -> ByteString) -> NonEmpty LeiosTx -> NonEmpty ByteString
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap LeiosTx -> ByteString
leiosTxBytes (LeiosTx
shared LeiosTx -> [LeiosTx] -> NonEmpty LeiosTx
forall a. a -> [a] -> NonEmpty a
:| [LeiosTx
own]))

-- | The client acquires the 'fixture''s closure, then this runs, then the
-- client takes in the body of 'sharing' and fetches its closure, which a peer
-- serves with these transactions. The notifications, oldest first.
acquireSharing :: (LeiosFetchClientContext IO Int -> IO ()) -> [LeiosTx] -> IO [Acquired]
acquireSharing :: (LeiosFetchClientContext IO Int -> Assertion)
-> [LeiosTx] -> IO [Acquired]
acquireSharing LeiosFetchClientContext IO Int -> Assertion
between [LeiosTx]
sent = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      (LeiosPoint
pointB, EndorserBlock
ebB, LeiosTx
_shared, LeiosTx
_own) = (LeiosPoint, EndorserBlock, LeiosTx, LeiosTx)
sharing
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  modifyMVar_ (lfcOutstanding ctx) $
    pure
      . focusElectionIfUnfocused (fixtureElection pointB) (pointEbHash pointB)
      . recordReferencedPoint pointB SNothing
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  closureRequest ctx point >>= \LeiosBlockTxsRequest
req -> LeiosFetchClientContext IO Int
-> Int -> LeiosBlockTxsRequest -> Vector LeiosTx -> Assertion
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext IO Int
ctx Int
peer LeiosBlockTxsRequest
req ([LeiosTx] -> Vector LeiosTx
forall a. [a] -> Vector a
V.fromList [LeiosTx]
txs)
  _ <- awaitNotes notes 2
  between ctx
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest pointB (encodeEndorserBlockSize ebB) maxBound)
    (serialiseEndorserBlock ebB)
  _ <- awaitNotes notes 3
  closureRequest ctx pointB >>= \LeiosBlockTxsRequest
req -> LeiosFetchClientContext IO Int
-> Int -> LeiosBlockTxsRequest -> Vector LeiosTx -> Assertion
forall peer (m :: * -> *).
(Ord peer, IOLike m) =>
LeiosFetchClientContext m peer
-> peer -> LeiosBlockTxsRequest -> Vector LeiosTx -> m ()
processLeiosBlockTxs LeiosFetchClientContext IO Int
ctx Int
peer LeiosBlockTxsRequest
req ([LeiosTx] -> Vector LeiosTx
forall a. [a] -> Vector a
V.fromList [LeiosTx]
sent)
  awaitNotes notes 4

test_fillsFromAnotherPoint :: Assertion
test_fillsFromAnotherPoint :: Assertion
test_fillsFromAnotherPoint = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      (LeiosPoint
pointB, EndorserBlock
_ebB, LeiosTx
_shared, LeiosTx
own) = (LeiosPoint, EndorserBlock, LeiosTx, LeiosTx)
sharing
  (LeiosFetchClientContext IO Int -> Assertion)
-> [LeiosTx] -> IO [Acquired]
acquireSharing (\LeiosFetchClientContext IO Int
_ctx -> () -> Assertion
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) [LeiosTx
own]
    IO [Acquired] -> ([Acquired] -> Assertion) -> Assertion
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ([Acquired] -> [Acquired] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [LeiosPoint -> Acquired
AcquiredBody LeiosPoint
point, LeiosPoint -> Acquired
AcquiredClosure LeiosPoint
point, LeiosPoint -> Acquired
AcquiredBody LeiosPoint
pointB, LeiosPoint -> Acquired
AcquiredClosure LeiosPoint
pointB])

test_noFillsFromPrunedPoint :: Assertion
test_noFillsFromPrunedPoint :: Assertion
test_noFillsFromPrunedPoint = do
  let (LeiosPoint
point, EndorserBlock
_eb, [LeiosTx]
_txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      (LeiosPoint
pointB, EndorserBlock
_ebB, LeiosTx
shared, LeiosTx
own) = (LeiosPoint, EndorserBlock, LeiosTx, LeiosTx)
sharing
  (LeiosFetchClientContext IO Int -> Assertion)
-> [LeiosTx] -> IO [Acquired]
acquireSharing (\LeiosFetchClientContext IO Int
ctx -> LeiosTxCache IO () Version PackedEndorserBlock
-> SlotNo -> Assertion
forall (m :: * -> *) a v b.
Functor m =>
LeiosTxCache m a v b -> SlotNo -> m ()
evictOlderThan (LeiosFetchClientContext IO Int
-> LeiosTxCache IO () Version PackedEndorserBlock
forall (m :: * -> *) peer.
LeiosFetchClientContext m peer
-> LeiosTxCache m () Version PackedEndorserBlock
lfcTxCache LeiosFetchClientContext IO Int
ctx) (LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
pointB)) [LeiosTx
shared, LeiosTx
own]
    IO [Acquired] -> ([Acquired] -> Assertion) -> Assertion
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ([Acquired] -> [Acquired] -> Assertion
forall a. (Eq a, Show a, HasCallStack) => a -> a -> Assertion
@?= [LeiosPoint -> Acquired
AcquiredBody LeiosPoint
point, LeiosPoint -> Acquired
AcquiredClosure LeiosPoint
point, LeiosPoint -> Acquired
AcquiredBody LeiosPoint
pointB, LeiosPoint -> Acquired
AcquiredClosure LeiosPoint
pointB])

-- | The context, its notifications, and its traces, newest first.
withTraces ::
  IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired]) ->
  IO
    ( LeiosFetchClientContext IO Int
    , StrictTVar IO [Acquired]
    , StrictTVar IO [TraceLeiosFetchClientEvent Int]
    )
withTraces :: IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
-> IO
     (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired],
      StrictTVar IO [TraceLeiosFetchClientEvent Int])
withTraces IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
mk = do
  (ctx, notes) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
mk
  traces <- newTVarIO []
  pure (ctx{lfcTracer = mkTracer $ atomically . modifyTVar traces . (:)}, notes, traces)

-- | Wait until this many of these arrivals are traced, and return them,
-- ordered by peer.
awaitArrivals ::
  ([TraceLeiosFetchClientEvent Int] -> [(Int, LeiosPoint, FetchArrivalBytes)]) ->
  StrictTVar IO [TraceLeiosFetchClientEvent Int] ->
  Int ->
  IO [(Int, LeiosPoint, FetchArrivalBytes)]
awaitArrivals :: ([TraceLeiosFetchClientEvent Int]
 -> [(Int, LeiosPoint, FetchArrivalBytes)])
-> StrictTVar IO [TraceLeiosFetchClientEvent Int]
-> Int
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
awaitArrivals [TraceLeiosFetchClientEvent Int]
-> [(Int, LeiosPoint, FetchArrivalBytes)]
select StrictTVar IO [TraceLeiosFetchClientEvent Int]
traces Int
n =
  Int
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
-> IO (Maybe [(Int, LeiosPoint, FetchArrivalBytes)])
forall a. Int -> IO a -> IO (Maybe a)
Timeout.timeout
    Int
5000000
    ( STM IO [(Int, LeiosPoint, FetchArrivalBytes)]
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall a. HasCallStack => STM IO a -> IO a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM IO [(Int, LeiosPoint, FetchArrivalBytes)]
 -> IO [(Int, LeiosPoint, FetchArrivalBytes)])
-> STM IO [(Int, LeiosPoint, FetchArrivalBytes)]
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall a b. (a -> b) -> a -> b
$ do
        arrivals <- [TraceLeiosFetchClientEvent Int]
-> [(Int, LeiosPoint, FetchArrivalBytes)]
select ([TraceLeiosFetchClientEvent Int]
 -> [(Int, LeiosPoint, FetchArrivalBytes)])
-> STM [TraceLeiosFetchClientEvent Int]
-> STM [(Int, LeiosPoint, FetchArrivalBytes)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StrictTVar IO [TraceLeiosFetchClientEvent Int]
-> STM IO [TraceLeiosFetchClientEvent Int]
forall (m :: * -> *) a. MonadSTM m => StrictTVar m a -> STM m a
readTVar StrictTVar IO [TraceLeiosFetchClientEvent Int]
traces
        sortOn (\(Int
p, LeiosPoint
_pt, FetchArrivalBytes
_bytes) -> Int
p) arrivals <$ check (length arrivals >= n)
    )
    IO (Maybe [(Int, LeiosPoint, FetchArrivalBytes)])
-> (Maybe [(Int, LeiosPoint, FetchArrivalBytes)]
    -> IO [(Int, LeiosPoint, FetchArrivalBytes)])
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO [(Int, LeiosPoint, FetchArrivalBytes)]
-> ([(Int, LeiosPoint, FetchArrivalBytes)]
    -> IO [(Int, LeiosPoint, FetchArrivalBytes)])
-> Maybe [(Int, LeiosPoint, FetchArrivalBytes)]
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall a. HasCallStack => String -> IO a
assertFailure String
"timed out waiting for arrivals") [(Int, LeiosPoint, FetchArrivalBytes)]
-> IO [(Int, LeiosPoint, FetchArrivalBytes)]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

blockArrivals
  , txsArrivals ::
    [TraceLeiosFetchClientEvent Int] -> [(Int, LeiosPoint, FetchArrivalBytes)]
blockArrivals :: [TraceLeiosFetchClientEvent Int]
-> [(Int, LeiosPoint, FetchArrivalBytes)]
blockArrivals [TraceLeiosFetchClientEvent Int]
events = [(Int
p, LeiosPoint
pt, FetchArrivalBytes
bytes) | TraceLeiosFetchClientBlockArrived Int
p LeiosPoint
pt FetchArrivalBytes
bytes <- [TraceLeiosFetchClientEvent Int]
events]
txsArrivals :: [TraceLeiosFetchClientEvent Int]
-> [(Int, LeiosPoint, FetchArrivalBytes)]
txsArrivals [TraceLeiosFetchClientEvent Int]
events = [(Int
p, LeiosPoint
pt, FetchArrivalBytes
bytes) | TraceLeiosFetchClientTxsArrived Int
p LeiosPoint
pt FetchArrivalBytes
bytes <- [TraceLeiosFetchClientEvent Int]
events]

-- | A peer sends the 'fixture''s body, the node asks it for the closure, and
-- the node's own forge acquires the same endorser block at that point before
-- the peer's txs arrive.
test_txsAfterForged :: Assertion
test_txsAfterForged :: Assertion
test_txsAfterForged = do
  let (LeiosPoint
point, EndorserBlock
eb, [LeiosTx]
txs) = (LeiosPoint, EndorserBlock, [LeiosTx])
fixture
      closure :: Word32
closure = [Word32] -> Word32
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ByteString -> Int
BS8.length (LeiosTx -> ByteString
leiosTxBytes LeiosTx
tx)) | LeiosTx
tx <- [LeiosTx]
txs]
  (ctx, notes, traces) <- IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
-> IO
     (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired],
      StrictTVar IO [TraceLeiosFetchClientEvent Int])
withTraces IO (LeiosFetchClientContext IO Int, StrictTVar IO [Acquired])
newContext
  processLeiosBlock
    ctx
    peer
    (MkLeiosBlockRequest point (encodeEndorserBlockSize eb) maxBound)
    (serialiseEndorserBlock eb)
  awaitNotes notes 1 >>= (@?= [AcquiredBody point])
  req <- closureRequest ctx point
  acquireForgedEb ctx (fixtureElection point) fixtureForged
  processLeiosBlockTxs ctx peer req (V.fromList txs)
  awaitArrivals txsArrivals traces 1 >>= (@?= [(peer, point, fetchArrivalExtra closure)])
  reverse <$> readTVarIO notes >>= (@?= [AcquiredBody point, AcquiredClosure point])

-- | The 'fixture''s endorser block, as the node's own forge produces it.
fixtureForged :: ForgedEndorserBlock
fixtureForged :: ForgedEndorserBlock
fixtureForged = Version -> NonEmpty ByteString -> ForgedEndorserBlock
forgeLeiosEb Version
forall a. Bounded a => a
minBound ((LeiosTx -> ByteString) -> NonEmpty LeiosTx -> NonEmpty ByteString
forall a b. (a -> b) -> NonEmpty a -> NonEmpty b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap LeiosTx -> ByteString
leiosTxBytes NonEmpty LeiosTx
fixtureTxs)

-- | The election announcing the endorser block at this point.
fixtureElection :: LeiosPoint -> ElectionId
fixtureElection :: LeiosPoint -> ElectionId
fixtureElection LeiosPoint
point = SlotNo -> KeyHash BlockIssuer -> ElectionId
ElectionId (LeiosPoint -> SlotNo
pointSlotNo LeiosPoint
point) KeyHash BlockIssuer
electee