{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeApplications #-}

-- | Properties of how the node kernel runs its components.
module Test.Consensus.NodeKernel (tests) where

import Cardano.Crypto.Hash (Hash (UnsafeHash))
import Control.Monad.Class.MonadAsync (wait, withAsync)
import Control.Monad.Class.MonadTest (MonadTest (..))
import Control.Monad.Class.MonadTime.SI (Time (..), getMonotonicTime)
import Control.Monad.Class.MonadTimer.SI (threadDelay)
import Control.Monad.IOSim (IOSim, exploreSimTrace, traceResult)
import Control.Tracer (nullTracer)
import qualified Data.ByteString.Short as SBS
import Data.Functor ((<&>))
import Ouroboros.Consensus.Block (SlotNo (..))
import Ouroboros.Consensus.BlockchainTime.WallClock.Types (RelativeTime (..), SystemTime (..))
import Ouroboros.Consensus.Leios.AnnounceState (newAnnounceState)
import Ouroboros.Consensus.Leios.NotifyLog
  ( newNotifyLog
  , nextNotifyLog
  , notifyLogStart
  )
import Ouroboros.Consensus.Leios.Types (RankingBlockHash (..))
import Ouroboros.Consensus.Leios.VoteState (ValidatedVote (..), newVoteState, recordVote)
import Ouroboros.Consensus.MiniProtocol.LeiosNotify.Client.Announcements.Validation
  ( defaultLeiosAnnouncementAgeLimits
  , maxAnnouncementAgeRecv
  , maxAnnouncementAgeSend
  )
import Ouroboros.Consensus.MiniProtocol.LeiosNotify.Client.State (voteLateGrace)
import Ouroboros.Consensus.NodeKernel (leiosDeadlinePruner, leiosDeadlinePrunerInterval)
import Ouroboros.Consensus.Util.IOLike (atomically, orElse)
import Ouroboros.Consensus.Util.Time (nominalDelay)
import Test.Consensus.Leios.LeiosNotify.Codec (signedVote)
import Test.Consensus.Leios.TestBlock (LeiosTestBlock)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (Property, conjoin, counterexample, once, testProperty)
import Test.Util.Orphans.IOLike ()

tests :: TestTree
tests :: TestTree
tests =
  TestName -> [TestTree] -> TestTree
testGroup
    TestName
"NodeKernel"
    [ TestName -> Property -> TestTree
forall a. Testable a => TestName -> a -> TestTree
testProperty
        TestName
"the deadline pruner runs far more often than a downstream peer's grace period"
        Property
prop_leiosDeadlinePrunerInterval
    , TestName -> Property -> TestTree
forall a. Testable a => TestName -> a -> TestTree
testProperty
        TestName
"the node relays every vote it keeps, however the vote races the deadline pruner"
        Property
prop_leiosDeadlinePrunerRace
    ]

-- | The node relays a notification at most 'leiosDeadlinePrunerInterval' after it
-- is no longer worth relaying, which must leave most of a downstream peer's
-- grace period for transmission and queueing: 'voteLateGrace' for a vote, and
-- the margin between 'maxAnnouncementAgeSend' and 'maxAnnouncementAgeRecv' of
-- 'defaultLeiosAnnouncementAgeLimits' for an announcement.
prop_leiosDeadlinePrunerInterval :: Property
prop_leiosDeadlinePrunerInterval :: Property
prop_leiosDeadlinePrunerInterval =
  Property -> Property
forall prop. Testable prop => prop -> Property
once (Property -> Property)
-> ([Property] -> Property) -> [Property] -> Property
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Property] -> Property
forall prop. Testable prop => [prop] -> Property
conjoin ([Property] -> Property) -> [Property] -> Property
forall a b. (a -> b) -> a -> b
$
    [ TestName -> Bool -> Property
forall prop. Testable prop => TestName -> prop -> Property
counterexample TestName
"the vote grace period" (Bool -> Property) -> Bool -> Property
forall a b. (a -> b) -> a -> b
$
        NominalDiffTime
leiosDeadlinePrunerInterval NominalDiffTime -> NominalDiffTime -> Bool
forall {a}. (Ord a, Num a) => a -> a -> Bool
`farBelow` NominalDiffTime
voteLateGrace
    , TestName -> Bool -> Property
forall prop. Testable prop => TestName -> prop -> Property
counterexample TestName
"the announcement grace period" (Bool -> Property) -> Bool -> Property
forall a b. (a -> b) -> a -> b
$
        NominalDiffTime
leiosDeadlinePrunerInterval
          NominalDiffTime -> NominalDiffTime -> Bool
forall {a}. (Ord a, Num a) => a -> a -> Bool
`farBelow` ( LeiosAnnouncementAgeLimits -> NominalDiffTime
maxAnnouncementAgeRecv LeiosAnnouncementAgeLimits
defaultLeiosAnnouncementAgeLimits
                         NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Num a => a -> a -> a
- LeiosAnnouncementAgeLimits -> NominalDiffTime
maxAnnouncementAgeSend LeiosAnnouncementAgeLimits
defaultLeiosAnnouncementAgeLimits
                     )
    ]
 where
  -- Leaving at least 90% of the grace period to transmission and queueing.
  farBelow :: a -> a -> Bool
farBelow a
a a
b = a
10 a -> a -> a
forall a. Num a => a -> a -> a
* a
a a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<= a
b

-- | A vote past its deadline, recorded just as the deadline pruner runs, is
-- either rejected or relayed, in every interleaving. So the pruner must prune
-- the votes before the notify log.
prop_leiosDeadlinePrunerRace :: Property
prop_leiosDeadlinePrunerRace :: Property
prop_leiosDeadlinePrunerRace =
  Property -> Property
forall prop. Testable prop => prop -> Property
once (Property -> Property) -> Property -> Property
forall a b. (a -> b) -> a -> b
$ (ExplorationOptions -> ExplorationOptions)
-> (forall s. IOSim s Bool)
-> (Maybe (SimTrace Bool) -> SimTrace Bool -> Property)
-> Property
forall a test.
Testable test =>
(ExplorationOptions -> ExplorationOptions)
-> (forall s. IOSim s a)
-> (Maybe (SimTrace a) -> SimTrace a -> test)
-> Property
exploreSimTrace ExplorationOptions -> ExplorationOptions
forall a. a -> a
id (IOSim s ()
forall (m :: * -> *). MonadTest m => m ()
exploreRaces IOSim s () -> IOSim s Bool -> IOSim s Bool
forall a b. IOSim s a -> IOSim s b -> IOSim s b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> IOSim s Bool
forall s. IOSim s Bool
raceVote) ((Maybe (SimTrace Bool) -> SimTrace Bool -> Property) -> Property)
-> (Maybe (SimTrace Bool) -> SimTrace Bool -> Property) -> Property
forall a b. (a -> b) -> a -> b
$ \Maybe (SimTrace Bool)
_ SimTrace Bool
tr ->
    case Bool -> SimTrace Bool -> Either Failure Bool
forall a. Bool -> SimTrace a -> Either Failure a
traceResult Bool
False SimTrace Bool
tr of
      Right Bool
relayed -> TestName -> Bool -> Property
forall prop. Testable prop => TestName -> prop -> Property
counterexample TestName
"kept a vote it does not relay" Bool
relayed
      Left Failure
e -> TestName -> Bool -> Property
forall prop. Testable prop => TestName -> prop -> Property
counterexample (Failure -> TestName
forall a. Show a => a -> TestName
show Failure
e) Bool
False
 where
  raceVote :: IOSim s Bool
  raceVote :: forall s. IOSim s Bool
raceVote = do
    notifyLog <- forall (m :: * -> *) blk.
(IOLike m, NoThunks (Header blk)) =>
m (NotifyLog m blk)
newNotifyLog @_ @LeiosTestBlock
    announceState <- newAnnounceState defaultLeiosAnnouncementAgeLimits notifyLog
    voteState <- newVoteState nullTracer announceState notifyLog
    let systemTime =
          SystemTime
            { systemTimeCurrent :: IOSim s RelativeTime
systemTimeCurrent = IOSim s Time
forall (m :: * -> *). MonadMonotonicTime m => m Time
getMonotonicTime IOSim s Time -> (Time -> RelativeTime) -> IOSim s RelativeTime
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \(Time DiffTime
t) -> NominalDiffTime -> RelativeTime
RelativeTime (DiffTime -> NominalDiffTime
forall a b. (Real a, Fractional b) => a -> b
realToFrac DiffTime
t)
            , systemTimeWait :: IOSim s ()
systemTimeWait = () -> IOSim s ()
forall a. a -> IOSim s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
            }
    withAsync (leiosDeadlinePruner systemTime notifyLog voteState) $ \Async (IOSim s) Void
_ ->
      IOSim s Bool
-> (Async (IOSim s) Bool -> IOSim s Bool) -> IOSim s Bool
forall a b.
IOSim s a -> (Async (IOSim s) a -> IOSim s b) -> IOSim s b
forall (m :: * -> *) a b.
MonadAsync m =>
m a -> (Async m a -> m b) -> m b
withAsync (VoteState (IOSim s) LeiosTestBlock
-> NotifyLog (IOSim s) LeiosTestBlock -> IOSim s Bool
forall {m :: * -> *} {blk} {blk}.
IOLike m =>
VoteState m blk -> NotifyLog m blk -> m Bool
addAtPrunerRun VoteState (IOSim s) LeiosTestBlock
voteState NotifyLog (IOSim s) LeiosTestBlock
notifyLog) ((Async (IOSim s) Bool -> IOSim s Bool) -> IOSim s Bool)
-> (Async (IOSim s) Bool -> IOSim s Bool) -> IOSim s Bool
forall a b. (a -> b) -> a -> b
$ \Async (IOSim s) Bool
adding -> do
        -- Let the pruner run whichever way the vote raced it.
        DiffTime -> IOSim s ()
forall (m :: * -> *). MonadDelay m => DiffTime -> m ()
threadDelay (DiffTime
2 DiffTime -> DiffTime -> DiffTime
forall a. Num a => a -> a -> a
* NominalDiffTime -> DiffTime
nominalDelay NominalDiffTime
leiosDeadlinePrunerInterval)
        Async (IOSim s) Bool -> IOSim s Bool
forall a. Async (IOSim s) a -> IOSim s a
forall (m :: * -> *) a. MonadAsync m => Async m a -> m a
wait Async (IOSim s) Bool
adding

  -- When the pruner runs the second time, record the vote, and say whether the
  -- node relays it if it keeps it.
  addAtPrunerRun :: VoteState m blk -> NotifyLog m blk -> m Bool
addAtPrunerRun VoteState m blk
voteState NotifyLog m blk
notifyLog = do
    DiffTime -> m ()
forall (m :: * -> *). MonadDelay m => DiffTime -> m ()
threadDelay (NominalDiffTime -> DiffTime
nominalDelay NominalDiffTime
leiosDeadlinePrunerInterval)
    STM m Bool -> m Bool
forall a. HasCallStack => STM m a -> m a
forall (m :: * -> *) a.
(MonadSTM m, HasCallStack) =>
STM m a -> m a
atomically (STM m Bool -> m Bool) -> STM m Bool -> m Bool
forall a b. (a -> b) -> a -> b
$
      VoteState m blk
-> ValidatedVote
-> STM
     m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
forall (m :: * -> *) blk.
IOLike m =>
VoteState m blk
-> ValidatedVote
-> STM
     m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
recordVote VoteState m blk
voteState ValidatedVote
validated STM
  m (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature)))
-> (Either AddVoteResult (Maybe (Map LeiosSeatId LeiosSignature))
    -> STM m Bool)
-> STM m Bool
forall a b. STM m a -> (a -> STM m b) -> STM m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Left AddVoteResult
_ -> Bool -> STM m Bool
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
        Right Maybe (Map LeiosSeatId LeiosSignature)
_ -> (Bool
True Bool -> STM m (Notification blk, NotifyCursor) -> STM m Bool
forall a b. a -> STM m b -> STM m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ NotifyLog m blk
-> NotifyCursor -> STM m (Notification blk, NotifyCursor)
forall (m :: * -> *) blk.
IOLike m =>
NotifyLog m blk
-> NotifyCursor -> STM m (Notification blk, NotifyCursor)
nextNotifyLog NotifyLog m blk
notifyLog NotifyCursor
notifyLogStart) STM m Bool -> STM m Bool -> STM m Bool
forall a. STM m a -> STM m a -> STM m a
forall (m :: * -> *) a. MonadSTM m => STM m a -> STM m a -> STM m a
`orElse` Bool -> STM m Bool
forall a. a -> STM m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False

  vote :: LeiosVote
vote = RankingBlockHash -> Word16 -> LeiosVote
signedVote (Hash HASH EraIndependentBlockHeader -> RankingBlockHash
MkRankingBlockHash (ShortByteString -> Hash HASH EraIndependentBlockHeader
forall h a.
(HashAlgorithm h, HasCallStack) =>
ShortByteString -> Hash h a
UnsafeHash (Int -> Word8 -> ShortByteString
SBS.replicate Int
32 Word8
0))) Word16
0

  -- Between the pruner's first run and its second.
  deadline :: RelativeTime
deadline = NominalDiffTime -> RelativeTime
RelativeTime (NominalDiffTime
leiosDeadlinePrunerInterval NominalDiffTime -> NominalDiffTime -> NominalDiffTime
forall a. Fractional a => a -> a -> a
/ NominalDiffTime
2)

  validated :: ValidatedVote
validated =
    MkValidatedVote
      { validatedVote :: LeiosVote
validatedVote = LeiosVote
vote
      , validatedElectionSlot :: SlotNo
validatedElectionSlot = Word64 -> SlotNo
SlotNo Word64
0
      , validatedSeatWeight :: Ratio Integer
validatedSeatWeight = Ratio Integer
0
      , validatedQuorum :: Ratio Integer
validatedQuorum = Ratio Integer
1
      , voteValidUntil :: RelativeTime
voteValidUntil = RelativeTime
deadline
      }