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

-- | Conversion of a mempool transaction to the UTxO RPC @TxInMempool@
-- message.
module Cardano.Rpc.Server.Internal.UtxoRpc.Type.Mempool
  ( txInModeToTxInMempool
  , txInModeToTxInMempoolFields
  , TxInMempoolFields (..)
  , watchMempoolFill
  )
where

import Cardano.Api
import Cardano.Rpc.Proto.Api.UtxoRpc.Query qualified as Query
import Cardano.Rpc.Proto.Api.UtxoRpc.Submit qualified as U5c
import Cardano.Rpc.Proto.Api.UtxoRpc.Submit qualified as UtxoRpc
import Cardano.Rpc.Server.Internal.FieldMask
  ( FieldFill
  , FieldMaskTree (..)
  , fill
  , fillFrom
  , fillSub
  , runFillPure
  )
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.Byron (byronTxToUtxoRpcTx)
import Cardano.Rpc.Server.Internal.UtxoRpc.Type.Tx (anyEraTxConstraints, txToUtxoRpcTx)

import Cardano.Crypto qualified as Byron (hashToBytes)
import Cardano.Ledger.Binary qualified as CBOR
import Cardano.Ledger.Core qualified as L

import RIO

import Network.GRPC.Spec

-- | Per-transaction inputs of 'watchMempoolFill'. The fields are lazy:
-- a field the mask does not select is never computed.
--
-- A record rather than a 'UtxoRpc.TxInMempool' built from @defMessage@, because the
-- message's scalar fields (@ref@, @native_bytes@) are strict and would be computed
-- whenever the message is evaluated. The request predicate and the response also
-- share the one @cardano@ conversion through 'txInMempoolFieldsCardano'.
data TxInMempoolFields = TxInMempoolFields
  { TxInMempoolFields -> ByteString
txInMempoolFieldsRef :: ByteString
  , TxInMempoolFields -> ByteString
txInMempoolFieldsNativeBytes :: ByteString
  -- ^ Lazy: computed only when the mask or the predicate needs it.
  , TxInMempoolFields -> Tx
txInMempoolFieldsCardano :: Query.Tx
  -- ^ Lazy: computed only when the mask or the predicate needs it.
  }

-- | Convert a transaction read from the mempool to the lazy per-field inputs
-- of the UTxO RPC 'UtxoRpc.TxInMempool' message.
--
-- @native_bytes@ fidelity differs by era: the Shelley-onwards ledger @Tx@ is
-- not 'SafeToHash'-backed, so its @native_bytes@ is a canonical
-- re-encoding, not the submitter's original bytes (same caveat as
-- 'Cardano.Rpc.Server.Internal.UtxoRpc.Type.TxOutput.txOutToUtxoRpcTxOutput').
-- The Byron arm has no such caveat: its @ATxAux@ carries a real byte
-- annotation, so 'CBOR.recoverBytes' recovers the true original bytes.
--
-- 'Nothing' for the three Byron special payloads (delegation certificates,
-- update proposals, update votes): they have no proto @Tx@ representation,
-- and cannot occur on any network still running today, since Byron
-- transitioned to Shelley years before any currently live Cardano network
-- started.
txInModeToTxInMempoolFields
  :: TxInMode
  -- ^ The transaction read from the mempool
  -> Maybe TxInMempoolFields
txInModeToTxInMempoolFields :: TxInMode -> Maybe TxInMempoolFields
txInModeToTxInMempoolFields = \case
  TxInMode ShelleyBasedEra era
sbe tx :: Tx era
tx@(ShelleyTx ShelleyBasedEra era
_ Tx TopTx (ShelleyLedgerEra era)
ledgerTx) ->
    TxInMempoolFields -> Maybe TxInMempoolFields
forall a. a -> Maybe a
Just
      (TxInMempoolFields -> Maybe TxInMempoolFields)
-> TxInMempoolFields -> Maybe TxInMempoolFields
forall a b. (a -> b) -> a -> b
$ ShelleyBasedEra era
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
    TxInMempoolFields)
-> TxInMempoolFields
forall era a.
ShelleyBasedEra era
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) => a)
-> a
anyEraTxConstraints ShelleyBasedEra era
sbe
      (((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
  TxInMempoolFields)
 -> TxInMempoolFields)
-> ((IsShelleyBasedEra era, AnyEraTx (ShelleyLedgerEra era)) =>
    TxInMempoolFields)
-> TxInMempoolFields
forall a b. (a -> b) -> a -> b
$ TxInMempoolFields
        { txInMempoolFieldsRef :: ByteString
txInMempoolFieldsRef = TxId -> ByteString
forall a. SerialiseAsRawBytes a => a -> ByteString
serialiseToRawBytes (TxId -> TxId
fromShelleyTxId (Tx TopTx (ShelleyLedgerEra era) -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
L.txIdTx Tx TopTx (ShelleyLedgerEra era)
ledgerTx))
        , txInMempoolFieldsNativeBytes :: ByteString
txInMempoolFieldsNativeBytes = Tx era -> ByteString
forall a. SerialiseAsCBOR a => a -> ByteString
serialiseToCBOR Tx era
tx
        , txInMempoolFieldsCardano :: Tx
txInMempoolFieldsCardano = Proto Tx -> Tx
forall msg. Proto msg -> msg
getProto (Proto Tx -> Tx) -> Proto Tx -> Tx
forall a b. (a -> b) -> a -> b
$ Tx TopTx (ShelleyLedgerEra era) -> Proto Tx
forall era.
IsShelleyBasedEra era =>
Tx TopTx (ShelleyLedgerEra era) -> Proto Tx
txToUtxoRpcTx Tx TopTx (ShelleyLedgerEra era)
ledgerTx
        }
  TxInByronSpecial GenTx ByronBlock
genTx -> case GenTx ByronBlock
genTx of
    ByronTx TxId
byronTxId ATxAux ByteString
aTxAux ->
      TxInMempoolFields -> Maybe TxInMempoolFields
forall a. a -> Maybe a
Just (TxInMempoolFields -> Maybe TxInMempoolFields)
-> TxInMempoolFields -> Maybe TxInMempoolFields
forall a b. (a -> b) -> a -> b
$
        TxInMempoolFields
          { txInMempoolFieldsRef :: ByteString
txInMempoolFieldsRef = TxId -> ByteString
forall algo a. AbstractHash algo a -> ByteString
Byron.hashToBytes TxId
byronTxId
          , txInMempoolFieldsNativeBytes :: ByteString
txInMempoolFieldsNativeBytes = ATxAux ByteString -> ByteString
forall t. Decoded t => t -> ByteString
CBOR.recoverBytes ATxAux ByteString
aTxAux
          , txInMempoolFieldsCardano :: Tx
txInMempoolFieldsCardano = Proto Tx -> Tx
forall msg. Proto msg -> msg
getProto (Proto Tx -> Tx) -> Proto Tx -> Tx
forall a b. (a -> b) -> a -> b
$ ATxAux ByteString -> Proto Tx
byronTxToUtxoRpcTx ATxAux ByteString
aTxAux
          }
    ByronDlg{} -> Maybe TxInMempoolFields
forall a. Maybe a
Nothing
    ByronUpdateProposal{} -> Maybe TxInMempoolFields
forall a. Maybe a
Nothing
    ByronUpdateVote{} -> Maybe TxInMempoolFields
forall a. Maybe a
Nothing

-- | Convert a transaction read from the mempool to the full UTxO RPC
-- 'UtxoRpc.TxInMempool' message, always at 'U5c.STAGE_MEMPOOL'.
txInModeToTxInMempool
  :: TxInMode
  -- ^ The transaction read from the mempool
  -> Maybe (Proto UtxoRpc.TxInMempool)
txInModeToTxInMempool :: TxInMode -> Maybe (Proto TxInMempool)
txInModeToTxInMempool TxInMode
txInMode = do
  fields <- TxInMode -> Maybe TxInMempoolFields
txInModeToTxInMempoolFields TxInMode
txInMode
  pure . Proto . runFillPure SelectAll $ fillFrom fields txInMempoolFill

-- | Fill the fields of a @WatchMempool@ response that a mask selects, from the
-- 'TxInMempoolFields' of a transaction.
watchMempoolFill :: FieldFill ((->) TxInMempoolFields) UtxoRpc.WatchMempoolResponse
watchMempoolFill :: FieldFill ((->) TxInMempoolFields) WatchMempoolResponse
watchMempoolFill = forall (label :: Symbol) msg sub (m :: * -> *).
(HasField msg label sub, KnownSymbol label, Message msg,
 Message sub, Applicative m) =>
FieldFill m sub -> FieldFill m msg
fillSub @"tx" FieldFill ((->) TxInMempoolFields) TxInMempool
txInMempoolFill

-- | Fill the fields of the 'UtxoRpc.TxInMempool' message that a mask selects,
-- from the 'TxInMempoolFields' of a transaction.
txInMempoolFill :: FieldFill ((->) TxInMempoolFields) UtxoRpc.TxInMempool
txInMempoolFill :: FieldFill ((->) TxInMempoolFields) TxInMempool
txInMempoolFill =
  forall (label :: Symbol) msg a (m :: * -> *).
(HasField msg label a, KnownSymbol label, Message msg,
 Functor m) =>
m a -> FieldFill m msg
fill @"ref" TxInMempoolFields -> ByteString
txInMempoolFieldsRef
    FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
forall a. Semigroup a => a -> a -> a
<> forall (label :: Symbol) msg a (m :: * -> *).
(HasField msg label a, KnownSymbol label, Message msg,
 Functor m) =>
m a -> FieldFill m msg
fill @"nativeBytes" TxInMempoolFields -> ByteString
txInMempoolFieldsNativeBytes
    FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
forall a. Semigroup a => a -> a -> a
<> forall (label :: Symbol) msg a (m :: * -> *).
(HasField msg label a, KnownSymbol label, Message msg,
 Functor m) =>
m a -> FieldFill m msg
fill @"stage" (Stage -> TxInMempoolFields -> Stage
forall a. a -> TxInMempoolFields -> a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Stage
U5c.STAGE_MEMPOOL)
    FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
-> FieldFill ((->) TxInMempoolFields) TxInMempool
forall a. Semigroup a => a -> a -> a
<> forall (label :: Symbol) msg a (m :: * -> *).
(HasField msg label a, KnownSymbol label, Message msg,
 Functor m) =>
m a -> FieldFill m msg
fill @"cardano" TxInMempoolFields -> Tx
txInMempoolFieldsCardano