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

{- |
Module      : Singular.State.Assemble
Description : What the state builders share: the payer, the chain reads and the assembly
License     : Apache-2.0

A state transaction is built from facts read before it is built: the payer's
funding output, the outputs it spends or reads, and the slot the chain has
reached. This module reads the payer, answers an output query without losing
the difference between an absent output and a failed read, picks a validity
interval that starts at the tip, and hands a transaction program to the
transaction builder with the session's own script evaluator, so a script the
validator refuses stops the build.
-}
module Singular.State.Assemble
    ( -- * Programs
      NoQuery
    , Program

      -- * The payer
    , Payer (..)
    , PayerFault (..)
    , findPayer
    , resolvePayer
    , resolvePayerReserving

      -- * Reading the chain
    , readOutputs
    , inlineDatumOf
    , holdsOnly
    , tipSlot
    , validityFromTip
    , windowFromTip
    , usualSpan
    , noUsableWindow

      -- * Assembly
    , assemble
    , assembleTransaction
    ) where

import Control.Exception (Exception, throwIO, try)
import Data.Bifunctor (first)
import Data.ByteString.Lazy qualified as LBS
import Data.Either (lefts)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Data.Void (Void)
import Lens.Micro ((^.))
import PlutusCore.Data qualified as PLC
import PlutusCore.Evaluation.Machine.ExBudget
    ( ExRestrictingBudget (..)
    )
import PlutusCore.Evaluation.Machine.Exception qualified as Machine
import PlutusLedgerApi.Common qualified as Plutus
import UntypedPlutusCore.Evaluation.Machine.Cek qualified as Cek

import Cardano.Ledger.Address (Addr (..))
import Cardano.Ledger.Alonzo.Plutus.Evaluate
    ( TransactionScriptFailure (..)
    )
import Cardano.Ledger.Alonzo.Scripts (AsIx)
import Cardano.Ledger.Alonzo.TxWits (Redeemers (..))
import Cardano.Ledger.Api.PParams (ppMaxTxExUnitsL, ppMaxTxSizeL)
import Cardano.Ledger.Api.Scripts.Data
    ( Data (..)
    , Datum (..)
    , binaryDataToData
    )
import Cardano.Ledger.Api.Tx (bodyTxL, witsTxL)
import Cardano.Ledger.Api.Tx.Body
    ( collateralInputsTxBodyL
    , inputsTxBodyL
    )
import Cardano.Ledger.Api.Tx.Out (datumTxOutL, valueTxOutL)
import Cardano.Ledger.Api.Tx.Wits (rdmrsTxWitsL)
import Cardano.Ledger.BaseTypes (Network)
import Cardano.Ledger.Binary (serialize)
import Cardano.Ledger.Conway.Scripts (ConwayPlutusPurpose)
import Cardano.Ledger.Core (eraProtVerHigh)
import Cardano.Ledger.Credential (Credential (..))
import Cardano.Ledger.Keys (KeyHash (..), KeyRole (Guard))
import Cardano.Ledger.Mary.Value
    ( AssetName
    , MaryValue (..)
    , MultiAsset (..)
    , PolicyID
    )
import Cardano.Ledger.Plutus.ExUnits (ExUnits (..))
import Cardano.Ledger.Tools (addDummyWitsTx)
import Cardano.Ledger.TxIn (TxIn)
import Cardano.Slotting.Slot (SlotNo (..))
import Cardano.Tx.Build qualified as Tx
import Cardano.Tx.Ledger (ConwayTx)
import Cardano.Tx.Witnesses (estimatedKeyWitnessCount)

import Singular.Registry.Evidence (Evidenced (..), NoWitness)
import Singular.Registry.Ledger (ConwayEra, PParams, TxOut)
import Singular.Registry.LedgerProvider
    ( OutputQuery
    , Outputs
    , ReadFailure
    , Session (..)
    , TipObservation (..)
    )
import Singular.Registry.NetworkTime (NetworkTimeFailure (..))
import Singular.Registry.SessionIO
    ( outputsAt
    , parameters
    , validityUpper
    )
import Singular.Registry.SessionIO qualified as Services
import Singular.Registry.TxBuilder.Publication (selectFunding)
import Singular.State.Refusal
    ( CapacityLimit (..)
    , Refusal (..)
    , capacityMessage
    )

{- | No queries. A state transaction reads the chain before it is built,
never while it is.
-}
data NoQuery a

-- | A transaction program as the state builders write it.
type Program = Tx.TxBuild NoQuery Void

{- | The payer of a transaction: the key that signs it, and the ADA-only output
that funds it and secures it as collateral.
-}
data Payer = Payer
    { Payer -> Network
payerNetwork :: Network
    , Payer -> KeyHash Guard
payerKey :: KeyHash Guard
    , Payer -> (TxIn, TxOut ConwayEra)
payerFunding :: (TxIn, TxOut ConwayEra)
    }

-- | Why an address cannot pay for a transaction.
data PayerFault
    = -- | It holds no ADA-only output to fund and secure a transaction.
      NoFunding
    | -- | Its payment credential is a script, which cannot sign.
      NotAKey
    deriving stock (PayerFault -> PayerFault -> Bool
(PayerFault -> PayerFault -> Bool)
-> (PayerFault -> PayerFault -> Bool) -> Eq PayerFault
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PayerFault -> PayerFault -> Bool
== :: PayerFault -> PayerFault -> Bool
$c/= :: PayerFault -> PayerFault -> Bool
/= :: PayerFault -> PayerFault -> Bool
Eq, Int -> PayerFault -> ShowS
[PayerFault] -> ShowS
PayerFault -> String
(Int -> PayerFault -> ShowS)
-> (PayerFault -> String)
-> ([PayerFault] -> ShowS)
-> Show PayerFault
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PayerFault -> ShowS
showsPrec :: Int -> PayerFault -> ShowS
$cshow :: PayerFault -> String
show :: PayerFault -> String
$cshowList :: [PayerFault] -> ShowS
showList :: [PayerFault] -> ShowS
Show)

{- | The payer at an address: refused when the address is not a key's, or when
it holds no ADA-only output to fund and secure a transaction.
-}
findPayer
    :: Session NoWitness IO -> Addr -> IO (Either PayerFault Payer)
findPayer :: Session NoWitness IO -> Addr -> IO (Either PayerFault Payer)
findPayer = [TxIn]
-> Session NoWitness IO -> Addr -> IO (Either PayerFault Payer)
findPayerReserving []

-- | Select funding without spending outputs reserved for a later transaction.
findPayerReserving
    :: [TxIn]
    -> Session NoWitness IO
    -> Addr
    -> IO (Either PayerFault Payer)
findPayerReserving :: [TxIn]
-> Session NoWitness IO -> Addr -> IO (Either PayerFault Payer)
findPayerReserving [TxIn]
reserved Session NoWitness IO
session Addr
address = case Addr
address of
    Addr Network
net (KeyHashObj (KeyHash Hash ADDRHASH (VerKeyDSIGN DSIGN)
key)) StakeReference
_ -> do
        known <- Session NoWitness IO -> Addr -> IO Outputs
forall w. Session w IO -> Addr -> IO Outputs
outputsAt Session NoWitness IO
session Addr
address
        pure $ case selectFunding
            Nothing
            [entry | entry@(ref, _) <- known, ref `notElem` reserved] of
            Left String
_ -> PayerFault -> Either PayerFault Payer
forall a b. a -> Either a b
Left PayerFault
NoFunding
            Right (TxIn, TxOut ConwayEra)
funding -> Payer -> Either PayerFault Payer
forall a b. b -> Either a b
Right (Network -> KeyHash Guard -> (TxIn, TxOut ConwayEra) -> Payer
Payer Network
net (Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash Guard
forall (r :: KeyRole).
Hash ADDRHASH (VerKeyDSIGN DSIGN) -> KeyHash r
KeyHash Hash ADDRHASH (VerKeyDSIGN DSIGN)
key) (TxIn, TxOut ConwayEra)
funding)
    Addr
_ -> Either PayerFault Payer -> IO (Either PayerFault Payer)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (PayerFault -> Either PayerFault Payer
forall a b. a -> Either a b
Left PayerFault
NotAKey)

-- | The payer at an address, with the refusal of the state builders.
resolvePayer
    :: Session NoWitness IO -> Addr -> IO (Either Refusal Payer)
resolvePayer :: Session NoWitness IO -> Addr -> IO (Either Refusal Payer)
resolvePayer = [TxIn] -> Session NoWitness IO -> Addr -> IO (Either Refusal Payer)
resolvePayerReserving []

{- | The payer of a publication that must leave the reserved outputs unspent
for a later transaction. Selection still uses the session's actual wallet
outputs and the ordinary ADA-only funding rule.
-}
resolvePayerReserving
    :: [TxIn]
    -> Session NoWitness IO
    -> Addr
    -> IO (Either Refusal Payer)
resolvePayerReserving :: [TxIn] -> Session NoWitness IO -> Addr -> IO (Either Refusal Payer)
resolvePayerReserving [TxIn]
reserved Session NoWitness IO
session Addr
address =
    (PayerFault -> Refusal)
-> Either PayerFault Payer -> Either Refusal Payer
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first PayerFault -> Refusal
refusal (Either PayerFault Payer -> Either Refusal Payer)
-> IO (Either PayerFault Payer) -> IO (Either Refusal Payer)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [TxIn]
-> Session NoWitness IO -> Addr -> IO (Either PayerFault Payer)
findPayerReserving [TxIn]
reserved Session NoWitness IO
session Addr
address
  where
    refusal :: PayerFault -> Refusal
refusal = \case
        PayerFault
NoFunding -> Refusal
PayerHasNoFunding
        PayerFault
NotAKey -> Refusal
PayerIsNotAKey

{- | The outputs the session answers a query with. An absent exact reference
comes back as a 'ReadFailure' for the caller to name; any other failure is for
the caller to throw.
-}
readOutputs
    :: Session NoWitness IO -> OutputQuery -> IO (Either ReadFailure Outputs)
readOutputs :: Session NoWitness IO
-> OutputQuery -> IO (Either ReadFailure Outputs)
readOutputs Session NoWitness IO
session OutputQuery
query = (Evidenced NoWitness [(TxIn, BabbageTxOut ConwayEra)]
 -> [(TxIn, BabbageTxOut ConwayEra)])
-> Either
     ReadFailure (Evidenced NoWitness [(TxIn, BabbageTxOut ConwayEra)])
-> Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
forall a b.
(a -> b) -> Either ReadFailure a -> Either ReadFailure b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Evidenced NoWitness [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall w a. Evidenced w a -> a
value (Either
   ReadFailure (Evidenced NoWitness [(TxIn, BabbageTxOut ConwayEra)])
 -> Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)])
-> IO
     (Either
        ReadFailure (Evidenced NoWitness [(TxIn, BabbageTxOut ConwayEra)]))
-> IO (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Session NoWitness IO
-> OutputQuery
-> IO (Either ReadFailure (Evidenced NoWitness Outputs))
forall w (m :: * -> *).
Session w m
-> OutputQuery -> m (Either ReadFailure (Evidenced w Outputs))
outputs Session NoWitness IO
session OutputQuery
query

-- | The inline datum of an output.
inlineDatumOf :: TxOut ConwayEra -> Maybe PLC.Data
inlineDatumOf :: TxOut ConwayEra -> Maybe Data
inlineDatumOf TxOut ConwayEra
output = case TxOut ConwayEra
BabbageTxOut ConwayEra
output BabbageTxOut ConwayEra
-> Getting
     (Datum ConwayEra) (BabbageTxOut ConwayEra) (Datum ConwayEra)
-> Datum ConwayEra
forall s a. s -> Getting a s a -> a
^. (Datum ConwayEra -> Const (Datum ConwayEra) (Datum ConwayEra))
-> TxOut ConwayEra -> Const (Datum ConwayEra) (TxOut ConwayEra)
Getting
  (Datum ConwayEra) (BabbageTxOut ConwayEra) (Datum ConwayEra)
forall era. BabbageEraTxOut era => Lens' (TxOut era) (Datum era)
Lens' (TxOut ConwayEra) (Datum ConwayEra)
datumTxOutL of
    Datum BinaryData ConwayEra
binary -> let Data Data
d = BinaryData ConwayEra -> Data ConwayEra
forall era. Era era => BinaryData era -> Data era
binaryDataToData BinaryData ConwayEra
binary in Data -> Maybe Data
forall a. a -> Maybe a
Just Data
d
    Datum ConwayEra
_ -> Maybe Data
forall a. Maybe a
Nothing

-- | The output holds this token once and nothing but ADA besides.
holdsOnly :: PolicyID -> AssetName -> TxOut ConwayEra -> Bool
holdsOnly :: PolicyID -> AssetName -> TxOut ConwayEra -> Bool
holdsOnly PolicyID
policy AssetName
name TxOut ConwayEra
output =
    let MaryValue Coin
_ (MultiAsset Map PolicyID (Map AssetName Integer)
assets) = TxOut ConwayEra
BabbageTxOut ConwayEra
output BabbageTxOut ConwayEra
-> Getting MaryValue (BabbageTxOut ConwayEra) MaryValue
-> MaryValue
forall s a. s -> Getting a s a -> a
^. Getting MaryValue (BabbageTxOut ConwayEra) MaryValue
(Value ConwayEra -> Const MaryValue (Value ConwayEra))
-> TxOut ConwayEra -> Const MaryValue (TxOut ConwayEra)
forall era. EraTxOut era => Lens' (TxOut era) (Value era)
Lens' (TxOut ConwayEra) (Value ConwayEra)
valueTxOutL
    in  Map PolicyID (Map AssetName Integer)
assets Map PolicyID (Map AssetName Integer)
-> Map PolicyID (Map AssetName Integer) -> Bool
forall a. Eq a => a -> a -> Bool
== PolicyID
-> Map AssetName Integer -> Map PolicyID (Map AssetName Integer)
forall k a. k -> a -> Map k a
Map.singleton PolicyID
policy (AssetName -> Integer -> Map AssetName Integer
forall k a. k -> a -> Map k a
Map.singleton AssetName
name Integer
1)

-- | The slot the chain has reached.
tipSlot :: Session NoWitness IO -> IO SlotNo
tipSlot :: Session NoWitness IO -> IO SlotNo
tipSlot Session NoWitness IO
session = TipObservation -> SlotNo
observedSlot (TipObservation -> SlotNo) -> IO TipObservation -> IO SlotNo
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Session NoWitness IO -> IO TipObservation
forall w. Session w IO -> IO TipObservation
Services.tip Session NoWitness IO
session

{- | The last slot a transaction that starts at the tip can end before, when
it must end no later than @wanted@: nothing when the interval from the tip is
too short to be usable, and the nearer slot when the ledger's horizon is
nearer. The bound is exclusive, as a validity interval's end is.
-}
validityFromTip
    :: Session NoWitness IO -> SlotNo -> SlotNo -> IO (Maybe SlotNo)
validityFromTip :: Session NoWitness IO -> SlotNo -> SlotNo -> IO (Maybe SlotNo)
validityFromTip Session NoWitness IO
session SlotNo
now SlotNo
wanted
    | Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (SlotNo -> Word64
unSlotNo SlotNo
wanted) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (SlotNo -> Word64
unSlotNo SlotNo
now) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
2 =
        Maybe SlotNo -> IO (Maybe SlotNo)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe SlotNo
forall a. Maybe a
Nothing
    | Bool
otherwise = do
        selected <- IO SlotNo -> IO (Either NetworkTimeFailure SlotNo)
forall e a. Exception e => IO a -> IO (Either e a)
try (Session NoWitness IO
-> SlotNo -> Maybe SlotNo -> SlotNo -> IO SlotNo
forall w.
Session w IO -> SlotNo -> Maybe SlotNo -> SlotNo -> IO SlotNo
validityUpper Session NoWitness IO
session SlotNo
now (SlotNo -> Maybe SlotNo
forall a. a -> Maybe a
Just SlotNo
now) SlotNo
wanted)
        case selected of
            Right SlotNo
upper -> Maybe SlotNo -> IO (Maybe SlotNo)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SlotNo -> Maybe SlotNo
forall a. a -> Maybe a
Just SlotNo
upper)
            Left WindowTooShort{} -> Maybe SlotNo -> IO (Maybe SlotNo)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe SlotNo
forall a. Maybe a
Nothing
            Left NetworkTimeFailure
failure -> NetworkTimeFailure -> IO (Maybe SlotNo)
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (NetworkTimeFailure
failure :: NetworkTimeFailure)

{- | The window of a transaction built now: from the tip to the end of a span
of the given milliseconds, cut where the ledger's horizon is nearer. Nothing
when the interval from the tip is too short to use. The one place a builder
turns a span of time into slots, so that no builder reads time another way.
-}
windowFromTip
    :: Session NoWitness IO -> Integer -> IO (Maybe (SlotNo, SlotNo))
windowFromTip :: Session NoWitness IO -> Integer -> IO (Maybe (SlotNo, SlotNo))
windowFromTip Session NoWitness IO
session Integer
width = do
    now <- Session NoWitness IO -> IO SlotNo
tipSlot Session NoWitness IO
session
    nowMs <- Services.slotStart session now
    wanted <- Services.floorSlot session (nowMs + width)
    fmap (now,) <$> validityFromTip session now wanted

{- | How long a transaction stays valid when its protocol gives it no window of
its own, in milliseconds: an hour from the tip.
-}
usualSpan :: Integer
usualSpan :: Integer
usualSpan = Integer
3_600_000

-- | Why a build stops when the interval from the tip is too short to use.
noUsableWindow :: Text
noUsableWindow :: Text
noUsableWindow = Text
"no validity interval at the tip is usable"

{- | Build a transaction from a program. The session's own evaluator runs every
script, so a script the validator refuses stops the build with its message.
-}
assemble
    :: Session NoWitness IO
    -> [(TxIn, TxOut ConwayEra)]
    -- ^ The outputs the transaction spends
    -> [(TxIn, TxOut ConwayEra)]
    -- ^ The outputs it reads by reference
    -> Addr
    -- ^ Where the change goes
    -> Program ()
    -> IO (Either Text ConwayTx)
assemble :: Session NoWitness IO
-> Outputs
-> Outputs
-> Addr
-> Program ()
-> IO (Either Text ConwayTx)
assemble Session NoWitness IO
session Outputs
spent Outputs
referenced Addr
change Program ()
program =
    (Refusal -> Text)
-> Either Refusal ConwayTx -> Either Text ConwayTx
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first Refusal -> Text
message
        (Either Refusal ConwayTx -> Either Text ConwayTx)
-> IO (Either Refusal ConwayTx) -> IO (Either Text ConwayTx)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Session NoWitness IO
-> Outputs
-> Outputs
-> Addr
-> Program ()
-> IO (Either Refusal ConwayTx)
assembleTransaction Session NoWitness IO
session Outputs
spent Outputs
referenced Addr
change Program ()
program
  where
    message :: Refusal -> Text
message (BuildFailed Text
reason) = Text
reason
    message (CapacityExceeded CapacityLimit
limit) = CapacityLimit -> Text
capacityMessage CapacityLimit
limit
    message Refusal
other = String -> Text
Text.pack (Refusal -> String
forall a. Show a => a -> String
show Refusal
other)

-- The builder's evaluator callback carries strings. A private, narrowly caught
-- exception preserves typed capacity until the builder returns to our boundary.
newtype ProbeCapacity = ProbeCapacity CapacityLimit
    deriving stock (Int -> ProbeCapacity -> ShowS
[ProbeCapacity] -> ShowS
ProbeCapacity -> String
(Int -> ProbeCapacity -> ShowS)
-> (ProbeCapacity -> String)
-> ([ProbeCapacity] -> ShowS)
-> Show ProbeCapacity
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ProbeCapacity -> ShowS
showsPrec :: Int -> ProbeCapacity -> ShowS
$cshow :: ProbeCapacity -> String
show :: ProbeCapacity -> String
$cshowList :: [ProbeCapacity] -> ShowS
showList :: [ProbeCapacity] -> ShowS
Show)

instance Exception ProbeCapacity

evaluate
    :: PParams ConwayEra
    -> Session NoWitness IO
    -> ConwayTx
    -> IO
        (Map.Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits))
evaluate :: PParams ConwayEra
-> Session NoWitness IO
-> ConwayTx
-> IO
     (Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits))
evaluate PParams ConwayEra
protocol Session NoWitness IO
session ConwayTx
tx = do
    results <- Session NoWitness IO -> ConwayTx -> IO (EvaluateTxResult ConwayEra)
forall w.
Session w IO -> ConwayTx -> IO (EvaluateTxResult ConwayEra)
Services.evaluateTx Session NoWitness IO
session ConwayTx
tx
    let failures = [Either (TransactionScriptFailure ConwayEra) ExUnits]
-> [TransactionScriptFailure ConwayEra]
forall a b. [Either a b] -> [a]
lefts (Map
  (ConwayPlutusPurpose AsIx ConwayEra)
  (Either (TransactionScriptFailure ConwayEra) ExUnits)
-> [Either (TransactionScriptFailure ConwayEra) ExUnits]
forall k a. Map k a -> [a]
Map.elems Map
  (ConwayPlutusPurpose AsIx ConwayEra)
  (Either (TransactionScriptFailure ConwayEra) ExUnits)
results)
    case traverse (evaluationCapacity protocol) failures of
        Just (CapacityLimit
limit : [CapacityLimit]
_) -> ProbeCapacity
-> IO
     (Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits))
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CapacityLimit -> ProbeCapacity
ProbeCapacity CapacityLimit
limit)
        Maybe [CapacityLimit]
_ -> Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits)
-> IO
     (Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((Either (TransactionScriptFailure ConwayEra) ExUnits
 -> Either String ExUnits)
-> Map
     (ConwayPlutusPurpose AsIx ConwayEra)
     (Either (TransactionScriptFailure ConwayEra) ExUnits)
-> Map (ConwayPlutusPurpose AsIx ConwayEra) (Either String ExUnits)
forall a b k. (a -> b) -> Map k a -> Map k b
Map.map ((TransactionScriptFailure ConwayEra -> Either String ExUnits)
-> (ExUnits -> Either String ExUnits)
-> Either (TransactionScriptFailure ConwayEra) ExUnits
-> Either String ExUnits
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Either String ExUnits
forall a b. a -> Either a b
Left (String -> Either String ExUnits)
-> (TransactionScriptFailure ConwayEra -> String)
-> TransactionScriptFailure ConwayEra
-> Either String ExUnits
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TransactionScriptFailure ConwayEra -> String
forall a. Show a => a -> String
show) ExUnits -> Either String ExUnits
forall a b. b -> Either a b
Right) Map
  (ConwayPlutusPurpose AsIx ConwayEra)
  (Either (TransactionScriptFailure ConwayEra) ExUnits)
results)

-- Only actual CEK exhaustion qualifies. A negative remaining budget records
-- work already attempted, not an estimate of the cost of finishing the script.
evaluationCapacity
    :: PParams ConwayEra
    -> TransactionScriptFailure ConwayEra
    -> Maybe CapacityLimit
evaluationCapacity :: PParams ConwayEra
-> TransactionScriptFailure ConwayEra -> Maybe CapacityLimit
evaluationCapacity PParams ConwayEra
protocol = \case
    ValidationFailure
        ExUnits
_
        ( Plutus.CekError
                ( Machine.ErrorWithCause
                        ( Machine.OperationalError
                                ( Cek.CekOutOfExError
                                        ( ExRestrictingBudget
                                                (Plutus.ExBudget (Plutus.ExCPU CostingInteger
cpu) (Plutus.ExMemory CostingInteger
mem))
                                            )
                                    )
                            )
                        Maybe (Term NamedDeBruijn DefaultUni DefaultFun ())
_
                    )
            )
        [Text]
_
        PlutusWithContext
_
            | CostingInteger
mem CostingInteger -> CostingInteger -> Bool
forall a. Ord a => a -> a -> Bool
< CostingInteger
0 ->
                CapacityLimit -> Maybe CapacityLimit
forall a. a -> Maybe a
Just
                    (Integer -> Integer -> CapacityLimit
ExecutionMemory (Integer
memoryLimit Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- CostingInteger -> Integer
forall a. Num a => CostingInteger -> a
Plutus.fromSatInt CostingInteger
mem) Integer
memoryLimit)
            | CostingInteger
cpu CostingInteger -> CostingInteger -> Bool
forall a. Ord a => a -> a -> Bool
< CostingInteger
0 ->
                CapacityLimit -> Maybe CapacityLimit
forall a. a -> Maybe a
Just (Integer -> Integer -> CapacityLimit
ExecutionSteps (Integer
stepLimit Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- CostingInteger -> Integer
forall a. Num a => CostingInteger -> a
Plutus.fromSatInt CostingInteger
cpu) Integer
stepLimit)
    TransactionScriptFailure ConwayEra
_ -> Maybe CapacityLimit
forall a. Maybe a
Nothing
  where
    ExUnits Nat
memory Nat
steps = PParams ConwayEra
protocol PParams ConwayEra
-> Getting ExUnits (PParams ConwayEra) ExUnits -> ExUnits
forall s a. s -> Getting a s a -> a
^. Getting ExUnits (PParams ConwayEra) ExUnits
forall era. AlonzoEraPParams era => Lens' (PParams era) ExUnits
Lens' (PParams ConwayEra) ExUnits
ppMaxTxExUnitsL
    memoryLimit :: Integer
memoryLimit = Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
memory
    stepLimit :: Integer
stepLimit = Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
steps

-- | The transaction of a program, with the refusal of the state builders.
assembleTransaction
    :: Session NoWitness IO
    -> [(TxIn, TxOut ConwayEra)]
    -> [(TxIn, TxOut ConwayEra)]
    -> Addr
    -> Program ()
    -> IO (Either Refusal ConwayTx)
assembleTransaction :: Session NoWitness IO
-> Outputs
-> Outputs
-> Addr
-> Program ()
-> IO (Either Refusal ConwayTx)
assembleTransaction Session NoWitness IO
session Outputs
spent Outputs
referenced Addr
change Program ()
program = do
    protocol <- Session NoWitness IO -> IO (PParams ConwayEra)
forall w. Session w IO -> IO (PParams ConwayEra)
parameters Session NoWitness IO
session
    built <-
        try $
            Tx.build
                (Tx.mkPParamsBound protocol)
                (Tx.InterpretIO noQuery)
                (evaluate protocol session)
                spent
                referenced
                change
                program
    pure $ case built of
        Left (ProbeCapacity CapacityLimit
limit) -> Refusal -> Either Refusal ConwayTx
forall a b. a -> Either a b
Left (CapacityLimit -> Refusal
CapacityExceeded CapacityLimit
limit)
        Right (Left BuildError Void
failure) -> Refusal -> Either Refusal ConwayTx
forall a b. a -> Either a b
Left (Text -> Refusal
BuildFailed (String -> Text
Text.pack (BuildError Void -> String
forall a. Show a => a -> String
show BuildError Void
failure)))
        Right (Right ConwayTx
tx) ->
            Either Refusal ConwayTx
-> (CapacityLimit -> Either Refusal ConwayTx)
-> Maybe CapacityLimit
-> Either Refusal ConwayTx
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
                (ConwayTx -> Either Refusal ConwayTx
forall a b. b -> Either a b
Right ConwayTx
tx)
                (Refusal -> Either Refusal ConwayTx
forall a b. a -> Either a b
Left (Refusal -> Either Refusal ConwayTx)
-> (CapacityLimit -> Refusal)
-> CapacityLimit
-> Either Refusal ConwayTx
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CapacityLimit -> Refusal
CapacityExceeded)
                (PParams ConwayEra -> Outputs -> ConwayTx -> Maybe CapacityLimit
capacityOf PParams ConwayEra
protocol (Outputs
[(TxIn, BabbageTxOut ConwayEra)]
spent [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall a. Semigroup a => a -> a -> a
<> Outputs
[(TxIn, BabbageTxOut ConwayEra)]
referenced) ConwayTx
tx)
  where
    noQuery :: NoQuery a -> IO b
    noQuery :: forall {k} (a :: k) b. NoQuery a -> IO b
noQuery NoQuery a
query = case NoQuery a
query of {}

{- | Compare bytes including the required key witnesses, and declared execution
units, with the session's parameters. No builder message is interpreted as a
capacity refusal.
-}
capacityOf
    :: PParams ConwayEra
    -> [(TxIn, TxOut ConwayEra)]
    -> ConwayTx
    -> Maybe CapacityLimit
capacityOf :: PParams ConwayEra -> Outputs -> ConwayTx -> Maybe CapacityLimit
capacityOf PParams ConwayEra
protocol Outputs
resolved ConwayTx
tx
    | Integer
bytes Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
byteLimit = CapacityLimit -> Maybe CapacityLimit
forall a. a -> Maybe a
Just (Integer -> Integer -> CapacityLimit
TransactionSize Integer
bytes Integer
byteLimit)
    | Integer
memory Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
memoryLimit = CapacityLimit -> Maybe CapacityLimit
forall a. a -> Maybe a
Just (Integer -> Integer -> CapacityLimit
ExecutionMemory Integer
memory Integer
memoryLimit)
    | Integer
steps Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
stepLimit = CapacityLimit -> Maybe CapacityLimit
forall a. a -> Maybe a
Just (Integer -> Integer -> CapacityLimit
ExecutionSteps Integer
steps Integer
stepLimit)
    | Bool
otherwise = Maybe CapacityLimit
forall a. Maybe a
Nothing
  where
    -- The builder returns no key witnesses. Count the actual distinct keys
    -- needed by its body and spending/collateral inputs, as the balancer does.
    -- Ledger padding measures their complete encoding without altering the
    -- transaction returned to the signer, including witness-array boundaries.
    body :: TxBody TopTx ConwayEra
body = ConwayTx
tx ConwayTx
-> Getting
     (TxBody TopTx ConwayEra) ConwayTx (TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall s a. s -> Getting a s a -> a
^. Getting (TxBody TopTx ConwayEra) ConwayTx (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTx era =>
Lens' (Tx l era) (TxBody l era)
forall (l :: TxLevel). Lens' (Tx l ConwayEra) (TxBody l ConwayEra)
bodyTxL
    requiredKeys :: Int
requiredKeys =
        TxBody TopTx ConwayEra -> Set TxIn -> Outputs -> Int
forall (l :: TxLevel).
TxBody l ConwayEra -> Set TxIn -> Outputs -> Int
estimatedKeyWitnessCount
            TxBody TopTx ConwayEra
body
            (Set TxIn -> Set TxIn -> Set TxIn
forall a. Ord a => Set a -> Set a -> Set a
Set.union (TxBody TopTx ConwayEra
body TxBody TopTx ConwayEra
-> Getting (Set TxIn) (TxBody TopTx ConwayEra) (Set TxIn)
-> Set TxIn
forall s a. s -> Getting a s a -> a
^. Getting (Set TxIn) (TxBody TopTx ConwayEra) (Set TxIn)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (Set TxIn)
forall (l :: TxLevel). Lens' (TxBody l ConwayEra) (Set TxIn)
inputsTxBodyL) (TxBody TopTx ConwayEra
body TxBody TopTx ConwayEra
-> Getting (Set TxIn) (TxBody TopTx ConwayEra) (Set TxIn)
-> Set TxIn
forall s a. s -> Getting a s a -> a
^. Getting (Set TxIn) (TxBody TopTx ConwayEra) (Set TxIn)
forall era.
AlonzoEraTxBody era =>
Lens' (TxBody TopTx era) (Set TxIn)
Lens' (TxBody TopTx ConwayEra) (Set TxIn)
collateralInputsTxBodyL))
            Outputs
resolved
    submitted :: ConwayTx
submitted = PParams ConwayEra
-> ConwayTx -> Int -> [Attributes AddrAttributes] -> ConwayTx
forall era (l :: TxLevel).
EraTx era =>
PParams era
-> Tx l era -> Int -> [Attributes AddrAttributes] -> Tx l era
addDummyWitsTx PParams ConwayEra
protocol ConwayTx
tx Int
requiredKeys []
    bytes :: Integer
bytes =
        Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger
            (ByteString -> Int64
LBS.length (Version -> ConwayTx -> ByteString
forall a. EncCBOR a => Version -> a -> ByteString
serialize (forall era. Era era => Version
eraProtVerHigh @ConwayEra) ConwayTx
submitted))
    byteLimit :: Integer
byteLimit = Word32 -> Integer
forall a. Integral a => a -> Integer
toInteger (PParams ConwayEra
protocol PParams ConwayEra
-> Getting Word32 (PParams ConwayEra) Word32 -> Word32
forall s a. s -> Getting a s a -> a
^. Getting Word32 (PParams ConwayEra) Word32
forall era. EraPParams era => Lens' (PParams era) Word32
Lens' (PParams ConwayEra) Word32
ppMaxTxSizeL)
    ExUnits Nat
maxMemory Nat
maxSteps = PParams ConwayEra
protocol PParams ConwayEra
-> Getting ExUnits (PParams ConwayEra) ExUnits -> ExUnits
forall s a. s -> Getting a s a -> a
^. Getting ExUnits (PParams ConwayEra) ExUnits
forall era. AlonzoEraPParams era => Lens' (PParams era) ExUnits
Lens' (PParams ConwayEra) ExUnits
ppMaxTxExUnitsL
    memoryLimit :: Integer
memoryLimit = Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
maxMemory
    stepLimit :: Integer
stepLimit = Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
maxSteps
    Redeemers Map (PlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
redeemers = ConwayTx
tx ConwayTx
-> Getting (Redeemers ConwayEra) ConwayTx (Redeemers ConwayEra)
-> Redeemers ConwayEra
forall s a. s -> Getting a s a -> a
^. (AlonzoTxWits ConwayEra
 -> Const (Redeemers ConwayEra) (AlonzoTxWits ConwayEra))
-> ConwayTx -> Const (Redeemers ConwayEra) ConwayTx
(TxWits ConwayEra
 -> Const (Redeemers ConwayEra) (TxWits ConwayEra))
-> ConwayTx -> Const (Redeemers ConwayEra) ConwayTx
forall era (l :: TxLevel).
EraTx era =>
Lens' (Tx l era) (TxWits era)
forall (l :: TxLevel). Lens' (Tx l ConwayEra) (TxWits ConwayEra)
witsTxL ((AlonzoTxWits ConwayEra
  -> Const (Redeemers ConwayEra) (AlonzoTxWits ConwayEra))
 -> ConwayTx -> Const (Redeemers ConwayEra) ConwayTx)
-> ((Redeemers ConwayEra
     -> Const (Redeemers ConwayEra) (Redeemers ConwayEra))
    -> AlonzoTxWits ConwayEra
    -> Const (Redeemers ConwayEra) (AlonzoTxWits ConwayEra))
-> Getting (Redeemers ConwayEra) ConwayTx (Redeemers ConwayEra)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Redeemers ConwayEra
 -> Const (Redeemers ConwayEra) (Redeemers ConwayEra))
-> AlonzoTxWits ConwayEra
-> Const (Redeemers ConwayEra) (AlonzoTxWits ConwayEra)
(Redeemers ConwayEra
 -> Const (Redeemers ConwayEra) (Redeemers ConwayEra))
-> TxWits ConwayEra
-> Const (Redeemers ConwayEra) (TxWits ConwayEra)
forall era.
AlonzoEraTxWits era =>
Lens' (TxWits era) (Redeemers era)
Lens' (TxWits ConwayEra) (Redeemers ConwayEra)
rdmrsTxWitsL
    budgets :: [ExUnits]
budgets = ((Data ConwayEra, ExUnits) -> ExUnits)
-> [(Data ConwayEra, ExUnits)] -> [ExUnits]
forall a b. (a -> b) -> [a] -> [b]
map (Data ConwayEra, ExUnits) -> ExUnits
forall a b. (a, b) -> b
snd (Map (ConwayPlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
-> [(Data ConwayEra, ExUnits)]
forall k a. Map k a -> [a]
Map.elems Map (ConwayPlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
redeemers)
    memory :: Integer
memory = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
used | ExUnits Nat
used Nat
_ <- [ExUnits]
budgets]
    steps :: Integer
steps = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Nat -> Integer
forall a. Integral a => a -> Integer
toInteger Nat
used | ExUnits Nat
_ Nat
used <- [ExUnits]
budgets]