{-# LANGUAGE GADTs #-}

-- | Genuine Byron blocks, a fixed slot timestamp and the @AnyChainBlock@ built
-- from them before field masks, shared by the block handler tests.
module Test.Cardano.Rpc.FixtureBlock where

import Cardano.Api
import Cardano.Rpc.Proto.Api.UtxoRpc.Sync qualified as U5c
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.Byron (byronBlockTxs)
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.ChainPoint (utcTimeToMs)
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.Tx (anyEraTxConstraints, txToUtxoRpcTx)

import Cardano.Chain.Block qualified as Byron (ABlockOrBoundary, decCBORABlockOrBoundary)
import Cardano.Chain.Epoch.File (mainnetEpochSlots)
import Cardano.Ledger.Binary (byronProtVer, decodeFullDecoder, slice)
import Ouroboros.Consensus.Byron.Ledger (mkByronBlock)

import RIO

import Codec.Compression.GZip qualified as GZip
import Data.ByteString.Lazy qualified as LBS
import Data.ProtoLens (defMessage)
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Network.GRPC.Spec (Proto)

import Hedgehog as H
import Hedgehog.Extras qualified as H

-- | The @AnyChainBlock@ that FetchBlock and FollowTip built before field masks, the
-- oracle for their responses under an absent mask, independent of the code under test: raw CBOR bytes, the cardano
-- header, the parsed transactions and the given slot timestamp.
oldAnyChainBlock
  :: ByteString
  -- ^ Raw CBOR bytes of the block, exactly as stored on chain
  -> BlockInMode
  -- ^ The same block, parsed and placed in its era context
  -> UTCTime
  -- ^ Slot wall-clock time; encoded as milliseconds since the Unix epoch
  -> Proto U5c.AnyChainBlock
oldAnyChainBlock :: ByteString -> BlockInMode -> UTCTime -> Proto AnyChainBlock
oldAnyChainBlock ByteString
rawBytes (BlockInMode CardanoEra era
_ Block era
block) UTCTime
timestamp = do
  let BlockHeader SlotNo
slot Hash BlockHeader
headerHash (BlockNo Word64
height) = Block era -> BlockHeader
forall era. Block era -> BlockHeader
getBlockHeader Block era
block
      txs :: [Proto Tx]
txs = case Block era
block of
        ByronBlock ByronBlock
consensusBlock -> ABlockOrBoundary ByteString -> [Proto Tx]
byronBlockTxs (ABlockOrBoundary ByteString -> [Proto Tx])
-> ABlockOrBoundary ByteString -> [Proto Tx]
forall a b. (a -> b) -> a -> b
$ ByronBlock -> ABlockOrBoundary ByteString
byronBlockRaw ByronBlock
consensusBlock
        ShelleyBlock ShelleyBasedEra era
blockEra ShelleyBlock (ConsensusProtocol era) (ShelleyLedgerEra era)
_ ->
          ShelleyBasedEra era
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
    [Proto Tx])
-> [Proto Tx]
forall era a.
ShelleyBasedEra era
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) => a)
-> a
anyEraTxConstraints ShelleyBasedEra era
blockEra (((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
  [Proto Tx])
 -> [Proto Tx])
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
    [Proto Tx])
-> [Proto Tx]
forall a b. (a -> b) -> a -> b
$
            Block era -> [Tx era]
forall era. Block era -> [Tx era]
getBlockTxs Block era
block [Tx era] -> (Tx era -> Proto Tx) -> [Proto Tx]
forall (f :: * -> *) a b. Functor f => f a -> (a -> b) -> f b
<&> \(ShelleyTx ShelleyBasedEra era
_ Tx TopTx (ShelleyLedgerEra era)
ledgerTx) -> Tx TopTx (ShelleyLedgerEra era) -> Proto Tx
forall era.
IsShelleyBasedEra era =>
Tx TopTx (ShelleyLedgerEra era) -> Proto Tx
txToUtxoRpcTx Tx TopTx (ShelleyLedgerEra era)
ledgerTx
      blockHeader :: Proto BlockHeader
blockHeader =
        Proto BlockHeader
forall msg. Message msg => msg
defMessage
          Proto BlockHeader
-> (Proto BlockHeader -> Proto BlockHeader) -> Proto BlockHeader
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto BlockHeader) Word64
forall (f :: * -> *) s a.
(Functor f, HasField s "slot" a) =>
LensLike' f s a
U5c.slot LensLike' Identity (Proto BlockHeader) Word64
-> Word64 -> Proto BlockHeader -> Proto BlockHeader
forall s t a b. ASetter s t a b -> b -> s -> t
.~ SlotNo -> Word64
unSlotNo SlotNo
slot
          Proto BlockHeader
-> (Proto BlockHeader -> Proto BlockHeader) -> Proto BlockHeader
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto BlockHeader) ByteString
forall (f :: * -> *) s a.
(Functor f, HasField s "hash" a) =>
LensLike' f s a
U5c.hash LensLike' Identity (Proto BlockHeader) ByteString
-> ByteString -> Proto BlockHeader -> Proto BlockHeader
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Hash BlockHeader -> ByteString
forall a. SerialiseAsRawBytes a => a -> ByteString
serialiseToRawBytes Hash BlockHeader
headerHash
          Proto BlockHeader
-> (Proto BlockHeader -> Proto BlockHeader) -> Proto BlockHeader
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto BlockHeader) Word64
forall (f :: * -> *) s a.
(Functor f, HasField s "height" a) =>
LensLike' f s a
U5c.height LensLike' Identity (Proto BlockHeader) Word64
-> Word64 -> Proto BlockHeader -> Proto BlockHeader
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Word64
height
  Proto AnyChainBlock
forall msg. Message msg => msg
defMessage
    Proto AnyChainBlock
-> (Proto AnyChainBlock -> Proto AnyChainBlock)
-> Proto AnyChainBlock
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto AnyChainBlock) ByteString
forall (f :: * -> *) s a.
(Functor f, HasField s "nativeBytes" a) =>
LensLike' f s a
U5c.nativeBytes LensLike' Identity (Proto AnyChainBlock) ByteString
-> ByteString -> Proto AnyChainBlock -> Proto AnyChainBlock
forall s t a b. ASetter s t a b -> b -> s -> t
.~ ByteString
rawBytes
    Proto AnyChainBlock
-> (Proto AnyChainBlock -> Proto AnyChainBlock)
-> Proto AnyChainBlock
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto AnyChainBlock) (Proto Block)
forall (f :: * -> *) s a.
(Functor f, HasField s "cardano" a) =>
LensLike' f s a
U5c.cardano LensLike' Identity (Proto AnyChainBlock) (Proto Block)
-> ((Proto BlockHeader -> Identity (Proto BlockHeader))
    -> Proto Block -> Identity (Proto Block))
-> (Proto BlockHeader -> Identity (Proto BlockHeader))
-> Proto AnyChainBlock
-> Identity (Proto AnyChainBlock)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Proto BlockHeader -> Identity (Proto BlockHeader))
-> Proto Block -> Identity (Proto Block)
forall (f :: * -> *) s a.
(Functor f, HasField s "header" a) =>
LensLike' f s a
U5c.header ((Proto BlockHeader -> Identity (Proto BlockHeader))
 -> Proto AnyChainBlock -> Identity (Proto AnyChainBlock))
-> Proto BlockHeader -> Proto AnyChainBlock -> Proto AnyChainBlock
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Proto BlockHeader
blockHeader
    Proto AnyChainBlock
-> (Proto AnyChainBlock -> Proto AnyChainBlock)
-> Proto AnyChainBlock
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto AnyChainBlock) (Proto Block)
forall (f :: * -> *) s a.
(Functor f, HasField s "cardano" a) =>
LensLike' f s a
U5c.cardano LensLike' Identity (Proto AnyChainBlock) (Proto Block)
-> (([Proto Tx] -> Identity [Proto Tx])
    -> Proto Block -> Identity (Proto Block))
-> ([Proto Tx] -> Identity [Proto Tx])
-> Proto AnyChainBlock
-> Identity (Proto AnyChainBlock)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LensLike' Identity (Proto Block) (Proto BlockBody)
forall (f :: * -> *) s a.
(Functor f, HasField s "body" a) =>
LensLike' f s a
U5c.body LensLike' Identity (Proto Block) (Proto BlockBody)
-> (([Proto Tx] -> Identity [Proto Tx])
    -> Proto BlockBody -> Identity (Proto BlockBody))
-> ([Proto Tx] -> Identity [Proto Tx])
-> Proto Block
-> Identity (Proto Block)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Proto Tx] -> Identity [Proto Tx])
-> Proto BlockBody -> Identity (Proto BlockBody)
forall (f :: * -> *) s a.
(Functor f, HasField s "tx" a) =>
LensLike' f s a
U5c.tx (([Proto Tx] -> Identity [Proto Tx])
 -> Proto AnyChainBlock -> Identity (Proto AnyChainBlock))
-> [Proto Tx] -> Proto AnyChainBlock -> Proto AnyChainBlock
forall s t a b. ASetter s t a b -> b -> s -> t
.~ [Proto Tx]
txs
    Proto AnyChainBlock
-> (Proto AnyChainBlock -> Proto AnyChainBlock)
-> Proto AnyChainBlock
forall a b. a -> (a -> b) -> b
& LensLike' Identity (Proto AnyChainBlock) (Proto Block)
forall (f :: * -> *) s a.
(Functor f, HasField s "cardano" a) =>
LensLike' f s a
U5c.cardano LensLike' Identity (Proto AnyChainBlock) (Proto Block)
-> ((Word64 -> Identity Word64)
    -> Proto Block -> Identity (Proto Block))
-> (Word64 -> Identity Word64)
-> Proto AnyChainBlock
-> Identity (Proto AnyChainBlock)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Word64 -> Identity Word64)
-> Proto Block -> Identity (Proto Block)
forall (f :: * -> *) s a.
(Functor f, HasField s "timestamp" a) =>
LensLike' f s a
U5c.timestamp ((Word64 -> Identity Word64)
 -> Proto AnyChainBlock -> Identity (Proto AnyChainBlock))
-> Word64 -> Proto AnyChainBlock -> Proto AnyChainBlock
forall s t a b. ASetter s t a b -> b -> s -> t
.~ UTCTime -> Word64
utcTimeToMs UTCTime
timestamp

-- | A genuine Byron 'BlockInMode' decoded from the mainnet main-block golden
-- fixture also used by 'Test.Cardano.Rpc.ByronTx'. The block handlers read
-- scripted blocks through their real block reads, so the blocks must be real,
-- valid blocks rather than placeholders; decoding an existing fixture through the
-- same 'mkByronBlock' smart constructor the node's ChainDB uses is the cheapest
-- way to get one, and reuses a fixture already checked in for this purpose.
mainBlockInMode :: HasCallStack => MonadTest m => MonadIO m => m (ByteString, BlockInMode)
mainBlockInMode :: forall (m :: * -> *).
(HasCallStack, MonadTest m, MonadIO m) =>
m (ByteString, BlockInMode)
mainBlockInMode = do
  rawBytes <-
    LazyByteString -> ByteString
LBS.toStrict (LazyByteString -> ByteString) -> m LazyByteString -> m ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> m LazyByteString
forall (m :: * -> *).
(MonadTest m, MonadIO m, HasCallStack) =>
FilePath -> m LazyByteString
H.lbsReadFile FilePath
"test/cardano-rpc-test/files/golden/byron-main-block.cbor"
  blockOrBoundary <- decodeBlockOrBoundaryFixture (LBS.fromStrict rawBytes)
  pure (rawBytes, BlockInMode ByronEra (ByronBlock (mkByronBlock mainnetEpochSlots blockOrBoundary)))

-- | A genuine Byron 'BlockInMode' decoded from the mainnet epoch-boundary
-- golden fixture also used by 'Test.Cardano.Rpc.ByronTx'; see
-- 'mainBlockInMode'. Distinct from it (a boundary block instead of a main
-- block, at a different slot and hash), so a two-block script has two
-- genuinely different blocks to distinguish, for free.
boundaryBlockInMode :: HasCallStack => MonadTest m => MonadIO m => m (ByteString, BlockInMode)
boundaryBlockInMode :: forall (m :: * -> *).
(HasCallStack, MonadTest m, MonadIO m) =>
m (ByteString, BlockInMode)
boundaryBlockInMode = do
  compressedBytes <- FilePath -> m LazyByteString
forall (m :: * -> *).
(MonadTest m, MonadIO m, HasCallStack) =>
FilePath -> m LazyByteString
H.lbsReadFile FilePath
"test/cardano-rpc-test/files/golden/byron-ebb.cbor.gz"
  let rawBytes = LazyByteString -> ByteString
LBS.toStrict (LazyByteString -> ByteString) -> LazyByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ LazyByteString -> LazyByteString
GZip.decompress LazyByteString
compressedBytes
  blockOrBoundary <- decodeBlockOrBoundaryFixture (LBS.fromStrict rawBytes)
  pure (rawBytes, BlockInMode ByronEra (ByronBlock (mkByronBlock mainnetEpochSlots blockOrBoundary)))

-- | A fixed stub slot timestamp, returned regardless of the slot asked for.
stubTimestamp :: UTCTime
stubTimestamp :: UTCTime
stubTimestamp = NominalDiffTime -> UTCTime
posixSecondsToUTCTime NominalDiffTime
1700000000

-- | Decode a 'Byron.ABlockOrBoundary' fixture from the wire encoding the
-- node's ImmutableDB stores, annotating the result with the original bytes,
-- exactly as a block fetched from the node would carry them.
decodeBlockOrBoundaryFixture
  :: HasCallStack
  => MonadTest m
  => LBS.ByteString
  -> m (Byron.ABlockOrBoundary ByteString)
decodeBlockOrBoundaryFixture :: forall (m :: * -> *).
(HasCallStack, MonadTest m) =>
LazyByteString -> m (ABlockOrBoundary ByteString)
decodeBlockOrBoundaryFixture LazyByteString
blockBytes = do
  blockOrBoundary <-
    Either DecoderError (ABlockOrBoundary ByteSpan)
-> m (ABlockOrBoundary ByteSpan)
forall (m :: * -> *) e a.
(MonadTest m, Show e, HasCallStack) =>
Either e a -> m a
H.leftFail (Either DecoderError (ABlockOrBoundary ByteSpan)
 -> m (ABlockOrBoundary ByteSpan))
-> Either DecoderError (ABlockOrBoundary ByteSpan)
-> m (ABlockOrBoundary ByteSpan)
forall a b. (a -> b) -> a -> b
$
      Version
-> Text
-> (forall s. Decoder s (ABlockOrBoundary ByteSpan))
-> LazyByteString
-> Either DecoderError (ABlockOrBoundary ByteSpan)
forall a.
Version
-> Text
-> (forall s. Decoder s a)
-> LazyByteString
-> Either DecoderError a
decodeFullDecoder
        Version
byronProtVer
        Text
"ABlockOrBoundary"
        (EpochSlots -> Decoder s (ABlockOrBoundary ByteSpan)
forall s. EpochSlots -> Decoder s (ABlockOrBoundary ByteSpan)
Byron.decCBORABlockOrBoundary EpochSlots
mainnetEpochSlots)
        LazyByteString
blockBytes
  pure $ LBS.toStrict . slice blockBytes <$> blockOrBoundary