{-# LANGUAGE LambdaCase #-}

{- |
Module      : Singular.State.Fold
Description : Discover foldable requests and build a registry batch from public data
License     : Apache-2.0

Anyone may fold the acceptable pending requests of a registry. The folder reads
its public state and trie history, skips individually unfoldable requests and
keeps the first foldable request per key in take order. A registration proves
its key absent and mints its token into the committed holding; a termination
proves its key active and burns its token. The batch consumes the requests and
their approvals, continues the state and writes the new root. The booker
contributes only the public request: no file, key or local record.

What a pending request is, how it is spent and how its approval is burned
belong to the application. The application hands the builder those three
things; the builder owns everything the state validator decides.
-}
module Singular.State.Fold
    ( Registration (..)
    , Request (..)
    , requestKey
    , Folded (..)
    , Application (..)
    , PendingRequest (..)
    , SkippedHolder (..)
    , SkipReason (..)
    , discoverPending
    , FoldResult (..)
    , FoldFailure (..)
    , pendingTake
    , buildFold
    , attemptFold
    , buildRegistrationFold
    , foldedRequests
    ) where

import Control.Exception (throwIO)
import Control.Monad (forM, forM_, unless, when)
import Control.Monad.Except
    ( ExceptT (..)
    , runExceptT
    , throwError
    , withExceptT
    )
import Control.Monad.IO.Class (liftIO)
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Either (partitionEithers)
import Data.List.NonEmpty qualified as NE
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe)
import Data.Set qualified as Set
import Data.Word (Word32)
import Lens.Micro ((&), (.~), (^.))
import PlutusCore.Data qualified as PLC
import PlutusLedgerApi.V3 qualified as PV3
import PlutusTx.Builtins.Internal (BuiltinData (..))

import Cardano.Ledger.Address (Addr (..))
import Cardano.Ledger.Alonzo.TxWits (Redeemers (..))
import Cardano.Ledger.Api.Scripts.Data (getPlutusData)
import Cardano.Ledger.Api.Tx (witsTxL)
import Cardano.Ledger.Api.Tx.Out
    ( addrTxOutL
    , coinTxOutL
    , datumTxOutL
    , getMinCoinTxOut
    , mkBasicTxOut
    , valueTxOutL
    )
import Cardano.Ledger.Api.Tx.Wits (rdmrsTxWitsL)
import Cardano.Ledger.Coin (Coin (..))
import Cardano.Ledger.Credential (Credential (..))
import Cardano.Ledger.Mary.Value
    ( AssetName
    , MaryValue (..)
    , MultiAsset (..)
    , PolicyID (..)
    )
import Cardano.Ledger.Plutus.TxInfo (transAddr)
import Cardano.Ledger.TxIn (TxIn)
import Cardano.Slotting.Slot (SlotNo)
import Cardano.Tx.Build qualified as Tx
import Cardano.Tx.Ledger (ConwayTx)

import Singular.Registry.Evidence (NoWitness)
import Singular.Registry.Ledger (ConwayEra, PParams, Root (..), TxOut)
import Singular.Registry.LedgerProvider
    ( OutputQuery (..)
    , ReadFailure (..)
    , Session (..)
    )
import Singular.Registry.SessionIO (floorSlot, parameters, slotStart)
import Singular.Registry.TrieState
    ( Leaf (..)
    , RegistryIdentity (..)
    , SpeculativeWalk (..)
    , StatePoint (..)
    , TrieSelection (..)
    , TrieSnapshot
    , leafAt
    , speculateEdges
    )
import Singular.Registry.TrieState.Core (snapshotObserved)
import Singular.Registry.TrieState.Types (CompleteFromCreate (..))
import Singular.Registry.TxBuilder.Internal (mkInlineDatum)
import Singular.Registry.Types (edgeInsertActive, edgeUpdateTerminal)
import Singular.State.Assemble
    ( Payer (..)
    , Program
    , assembleTransaction
    , holdsOnly
    , inlineDatumOf
    , readOutputs
    , resolvePayer
    , tipSlot
    , usualSpan
    , validityFromTip
    )
import Singular.State.Batch
    ( BatchSelection (..)
    , largestFittingPrefix
    , orderByTake
    )
import Singular.State.Lineage
    ( Replayed (..)
    , registryAsset
    , replayRegistry
    )
import Singular.State.Preimage
    ( activeTokenName
    , approvalName
    , initialDatumHash
    , registrationPreimage
    , terminationPreimage
    )
import Singular.State.Records
    ( Change (..)
    , decodeFoldRedeemer
    , decodeStateDatum
    , foldRedeemer
    , foldedRedeemer
    , stateDatum
    )
import Singular.State.Refusal (CapacityLimit, Refusal (..))
import Singular.State.Script
    ( StateScript (..)
    , referenceOutputs
    , stateAddress
    , statePolicy
    , stateScriptHash
    , useScript
    )

{- | What the fold needs to know of a pending registration, as the
application publishes it in the registration's datum.
-}
data Registration = Registration
    { Registration -> RegistryIdentity
regRegistry :: RegistryIdentity
    -- ^ The registry it asks to join
    , Registration -> ByteString
regKey :: ByteString
    , Registration -> Addr
regHolding :: Addr
    -- ^ Where the key's token goes
    , Registration -> Data
regDatum :: PLC.Data
    -- ^ The datum the holding starts with
    , Registration -> Coin
regDeposit :: Coin
    -- ^ What the holding keeps
    , Registration -> Edge
regDeadline :: Integer
    -- ^ The time, in milliseconds, after which only the application's other phases spend it
    }
    deriving stock (Registration -> Registration -> Bool
(Registration -> Registration -> Bool)
-> (Registration -> Registration -> Bool) -> Eq Registration
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Registration -> Registration -> Bool
== :: Registration -> Registration -> Bool
$c/= :: Registration -> Registration -> Bool
/= :: Registration -> Registration -> Bool
Eq, Int -> Registration -> ShowS
[Registration] -> ShowS
Registration -> String
(Int -> Registration -> ShowS)
-> (Registration -> String)
-> ([Registration] -> ShowS)
-> Show Registration
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Registration -> ShowS
showsPrec :: Int -> Registration -> ShowS
$cshow :: Registration -> String
show :: Registration -> String
$cshowList :: [Registration] -> ShowS
showList :: [Registration] -> ShowS
Show)

-- | An application request, decoded from public data.
data Request
    = RegistrationRequest Registration
    | TerminationRequest RegistryIdentity ByteString
    deriving stock (Request -> Request -> Bool
(Request -> Request -> Bool)
-> (Request -> Request -> Bool) -> Eq Request
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Request -> Request -> Bool
== :: Request -> Request -> Bool
$c/= :: Request -> Request -> Bool
/= :: Request -> Request -> Bool
Eq, Int -> Request -> ShowS
[Request] -> ShowS
Request -> String
(Int -> Request -> ShowS)
-> (Request -> String) -> ([Request] -> ShowS) -> Show Request
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Request -> ShowS
showsPrec :: Int -> Request -> ShowS
$cshow :: Request -> String
show :: Request -> String
$cshowList :: [Request] -> ShowS
showList :: [Request] -> ShowS
Show)

requestKey :: Request -> ByteString
requestKey :: Request -> ByteString
requestKey (RegistrationRequest Registration
r) = Registration -> ByteString
regKey Registration
r
requestKey (TerminationRequest RegistryIdentity
_ ByteString
key) = ByteString
key

requestRegistry :: Request -> RegistryIdentity
requestRegistry :: Request -> RegistryIdentity
requestRegistry (RegistrationRequest Registration
r) = Registration -> RegistryIdentity
regRegistry Registration
r
requestRegistry (TerminationRequest RegistryIdentity
registry ByteString
_) = RegistryIdentity
registry

-- | A request being folded, with a holding output only for registration.
data Folded = Folded
    { Folded -> TxIn
foldedRequest :: TxIn
    , Folded -> AssetName
foldedApproval :: AssetName
    , Folded -> RegistryIdentity
foldedRegistry :: RegistryIdentity
    , Folded -> ByteString
foldedKey :: ByteString
    , Folded -> Maybe Word32
foldedHolding :: Maybe Word32
    }
    deriving stock (Folded -> Folded -> Bool
(Folded -> Folded -> Bool)
-> (Folded -> Folded -> Bool) -> Eq Folded
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Folded -> Folded -> Bool
== :: Folded -> Folded -> Bool
$c/= :: Folded -> Folded -> Bool
/= :: Folded -> Folded -> Bool
Eq, Int -> Folded -> ShowS
[Folded] -> ShowS
Folded -> String
(Int -> Folded -> ShowS)
-> (Folded -> String) -> ([Folded] -> ShowS) -> Show Folded
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Folded -> ShowS
showsPrec :: Int -> Folded -> ShowS
$cshow :: Folded -> String
show :: Folded -> String
$cshowList :: [Folded] -> ShowS
showList :: [Folded] -> ShowS
Show)

-- | What the application contributes to a fold.
data Application = Application
    { Application -> PolicyID
appPolicy :: PolicyID
    -- ^ The policy of the approvals
    , Application
-> RegistryIdentity
-> [ByteString]
-> TxOut ConwayEra
-> Maybe Request
appDecode
        :: RegistryIdentity -> [ByteString] -> TxOut ConwayEra -> Maybe Request
    -- ^ The public decoding of a pending request at the application's script
    , Application -> TxOut ConwayEra -> Bool
appIsConfiguration :: TxOut ConwayEra -> Bool
    {- ^ Whether an output is the configuration of a registry the application
    holds, not a request. Discovery neither folds nor reports such an output.
    -}
    , Application -> [(TxIn, TxOut ConwayEra)]
appReferences :: [(TxIn, TxOut ConwayEra)]
    -- ^ The outputs that carry its code, already checked, when it is referenced
    , Application -> [Folded] -> Program ()
appFold :: [Folded] -> Program ()
    {- ^ Spend the pending registrations into their holdings, burn their
    approvals and make the application's code available to the transaction
    -}
    }

-- | A request and its exact output, authenticated from public chain data.
data PendingRequest = PendingRequest
    { PendingRequest -> TxIn
pendingRef :: TxIn
    -- ^ The output the fold must spend, once.
    , PendingRequest -> TxOut ConwayEra
pendingOutput :: TxOut ConwayEra
    -- ^ Its complete value and datum as served by the provider.
    , PendingRequest -> Request
pendingRequest :: Request
    -- ^ Its decoded registry, key, kind and registration holding requirements.
    , PendingRequest -> AssetName
pendingApproval :: AssetName
    -- ^ The authenticated approval held by that same output.
    }
    deriving stock (PendingRequest -> PendingRequest -> Bool
(PendingRequest -> PendingRequest -> Bool)
-> (PendingRequest -> PendingRequest -> Bool) -> Eq PendingRequest
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PendingRequest -> PendingRequest -> Bool
== :: PendingRequest -> PendingRequest -> Bool
$c/= :: PendingRequest -> PendingRequest -> Bool
/= :: PendingRequest -> PendingRequest -> Bool
Eq, Int -> PendingRequest -> ShowS
[PendingRequest] -> ShowS
PendingRequest -> String
(Int -> PendingRequest -> ShowS)
-> (PendingRequest -> String)
-> ([PendingRequest] -> ShowS)
-> Show PendingRequest
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> PendingRequest -> ShowS
showsPrec :: Int -> PendingRequest -> ShowS
$cshow :: PendingRequest -> String
show :: PendingRequest -> String
$cshowList :: [PendingRequest] -> ShowS
showList :: [PendingRequest] -> ShowS
Show)

-- | Why an approval holder is omitted from an automatic fold.
data SkipReason
    = HeldAtKeyAddress
    | DecodedForAnotherRegistry
    | NotAcceptedByApplication
    | UnfoldableRequest Refusal
    deriving stock (SkipReason -> SkipReason -> Bool
(SkipReason -> SkipReason -> Bool)
-> (SkipReason -> SkipReason -> Bool) -> Eq SkipReason
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SkipReason -> SkipReason -> Bool
== :: SkipReason -> SkipReason -> Bool
$c/= :: SkipReason -> SkipReason -> Bool
/= :: SkipReason -> SkipReason -> Bool
Eq, Int -> SkipReason -> ShowS
[SkipReason] -> ShowS
SkipReason -> String
(Int -> SkipReason -> ShowS)
-> (SkipReason -> String)
-> ([SkipReason] -> ShowS)
-> Show SkipReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SkipReason -> ShowS
showsPrec :: Int -> SkipReason -> ShowS
$cshow :: SkipReason -> String
show :: SkipReason -> String
$cshowList :: [SkipReason] -> ShowS
showList :: [SkipReason] -> ShowS
Show)

-- | A holder omitted from an automatic fold, with its public reference and reason.
data SkippedHolder = SkippedHolder
    { SkippedHolder -> TxIn
skippedRef :: TxIn
    -- ^ The holder that remains unspent by this discovery result.
    , SkippedHolder -> SkipReason
skippedReason :: SkipReason
    -- ^ The reason it was not selected as this registry's request.
    }
    deriving stock (SkippedHolder -> SkippedHolder -> Bool
(SkippedHolder -> SkippedHolder -> Bool)
-> (SkippedHolder -> SkippedHolder -> Bool) -> Eq SkippedHolder
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SkippedHolder -> SkippedHolder -> Bool
== :: SkippedHolder -> SkippedHolder -> Bool
$c/= :: SkippedHolder -> SkippedHolder -> Bool
/= :: SkippedHolder -> SkippedHolder -> Bool
Eq, Int -> SkippedHolder -> ShowS
[SkippedHolder] -> ShowS
SkippedHolder -> String
(Int -> SkippedHolder -> ShowS)
-> (SkippedHolder -> String)
-> ([SkippedHolder] -> ShowS)
-> Show SkippedHolder
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SkippedHolder -> ShowS
showsPrec :: Int -> SkippedHolder -> ShowS
$cshow :: SkippedHolder -> String
show :: SkippedHolder -> String
$cshowList :: [SkippedHolder] -> ShowS
showList :: [SkippedHolder] -> ShowS
Show)

{- | Find requests using one complete policy query. The caller supplies keys
from the registry's public replay; neither a wallet nor a local booking record
participates. An output the application names as its configuration is in
neither list. A failed read is thrown with its provider evidence intact.
-}
discoverPending
    :: Session NoWitness IO
    -> Application
    -> RegistryIdentity
    -> [ByteString]
    -> IO ([PendingRequest], [SkippedHolder])
discoverPending :: Session NoWitness IO
-> Application
-> RegistryIdentity
-> [ByteString]
-> IO ([PendingRequest], [SkippedHolder])
discoverPending Session NoWitness IO
session Application
application RegistryIdentity
registry [ByteString]
candidates = do
    holders <-
        Session NoWitness IO
-> OutputQuery -> IO (Either ReadFailure [(TxIn, TxOut ConwayEra)])
readOutputs Session NoWitness IO
session (PolicyID -> OutputQuery
HoldingPolicy (Application -> PolicyID
appPolicy Application
application))
            IO (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)])
-> (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
    -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ReadFailure -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> ([(TxIn, BabbageTxOut ConwayEra)]
    -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ReadFailure -> IO [(TxIn, BabbageTxOut ConwayEra)]
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO [(TxIn, BabbageTxOut ConwayEra)]
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
    let (skipped, pending) = partitionEithers (mapMaybe classify holders)
    pure (pending, skipped)
  where
    classify :: (TxIn, TxOut ConwayEra)
-> Maybe (Either SkippedHolder PendingRequest)
classify (TxIn
ref, TxOut ConwayEra
output)
        | Addr Network
_ KeyHashObj{} StakeReference
_ <- TxOut ConwayEra
output TxOut ConwayEra -> Getting Addr (TxOut ConwayEra) Addr -> Addr
forall s a. s -> Getting a s a -> a
^. Getting Addr (TxOut ConwayEra) Addr
forall era. EraTxOut era => Lens' (TxOut era) Addr
Lens' (TxOut ConwayEra) Addr
addrTxOutL =
            Either SkippedHolder PendingRequest
-> Maybe (Either SkippedHolder PendingRequest)
forall a. a -> Maybe a
Just (SkippedHolder -> Either SkippedHolder PendingRequest
forall a b. a -> Either a b
Left (TxIn -> SkipReason -> SkippedHolder
SkippedHolder TxIn
ref SkipReason
HeldAtKeyAddress))
        | Application -> TxOut ConwayEra -> Bool
appIsConfiguration Application
application TxOut ConwayEra
output = Maybe (Either SkippedHolder PendingRequest)
forall a. Maybe a
Nothing
        | Bool
otherwise =
            Either SkippedHolder PendingRequest
-> Maybe (Either SkippedHolder PendingRequest)
forall a. a -> Maybe a
Just (Either SkippedHolder PendingRequest
 -> Maybe (Either SkippedHolder PendingRequest))
-> Either SkippedHolder PendingRequest
-> Maybe (Either SkippedHolder PendingRequest)
forall a b. (a -> b) -> a -> b
$ case Application
-> RegistryIdentity
-> [ByteString]
-> TxIn
-> TxOut ConwayEra
-> Either Refusal PendingRequest
pendingFromOutput Application
application RegistryIdentity
registry [ByteString]
candidates TxIn
ref TxOut ConwayEra
output of
                Right PendingRequest
pending -> PendingRequest -> Either SkippedHolder PendingRequest
forall a b. b -> Either a b
Right PendingRequest
pending
                Left PendingOfAnotherRegistry{} -> SkippedHolder -> Either SkippedHolder PendingRequest
forall a b. a -> Either a b
Left (TxIn -> SkipReason -> SkippedHolder
SkippedHolder TxIn
ref SkipReason
DecodedForAnotherRegistry)
                Left Refusal
_ -> SkippedHolder -> Either SkippedHolder PendingRequest
forall a b. a -> Either a b
Left (TxIn -> SkipReason -> SkippedHolder
SkippedHolder TxIn
ref SkipReason
NotAcceptedByApplication)

{- | Fold named requests, or discover them from approvals when none is named.
The payer funds the transaction and keeps what each registration holds above
its deposit and what each termination holds in full.
-}
buildRegistrationFold
    :: Session NoWitness IO
    -> StateScript
    -> Application
    -> RegistryIdentity
    -> [TxIn]
    -> Addr
    -> IO (Either Refusal ConwayTx)
buildRegistrationFold :: Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> [TxIn]
-> Addr
-> IO (Either Refusal ConwayTx)
buildRegistrationFold Session NoWitness IO
session StateScript
script Application
application RegistryIdentity
registry [TxIn]
requests Addr
payerAddress =
    (FoldResult -> ConwayTx)
-> Either Refusal FoldResult -> Either Refusal ConwayTx
forall a b. (a -> b) -> Either Refusal a -> Either Refusal b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap FoldResult -> ConwayTx
foldTransaction
        (Either Refusal FoldResult -> Either Refusal ConwayTx)
-> IO (Either Refusal FoldResult) -> IO (Either Refusal ConwayTx)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> [TxIn]
-> Addr
-> Maybe Word32
-> IO (Either Refusal FoldResult)
buildFold
            Session NoWitness IO
session
            StateScript
script
            Application
application
            RegistryIdentity
registry
            [TxIn]
requests
            Addr
payerAddress
            Maybe Word32
forall a. Maybe a
Nothing

-- | The actual built batch and the complete discovery accounting.
data FoldResult = FoldResult
    { FoldResult -> ConwayTx
foldTransaction :: ConwayTx
    -- ^ The successful probe's transaction.
    , FoldResult -> [PendingRequest]
foldSelected :: [PendingRequest]
    -- ^ The folded requests, in their transaction order.
    , FoldResult -> [SkippedHolder]
foldSkipped :: [SkippedHolder]
    -- ^ All unaccepted or individually unfoldable holders, named with reasons.
    , FoldResult -> Int
foldLeft :: Int
    -- ^ Every foldable request beyond the chosen prefix, including the cap.
    , FoldResult -> Maybe CapacityLimit
foldBoundary :: Maybe CapacityLimit
    -- ^ The next prefix's actual capacity refusal, when a boundary was probed.
    }
    deriving stock (FoldResult -> FoldResult -> Bool
(FoldResult -> FoldResult -> Bool)
-> (FoldResult -> FoldResult -> Bool) -> Eq FoldResult
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FoldResult -> FoldResult -> Bool
== :: FoldResult -> FoldResult -> Bool
$c/= :: FoldResult -> FoldResult -> Bool
/= :: FoldResult -> FoldResult -> Bool
Eq, Int -> FoldResult -> ShowS
[FoldResult] -> ShowS
FoldResult -> String
(Int -> FoldResult -> ShowS)
-> (FoldResult -> String)
-> ([FoldResult] -> ShowS)
-> Show FoldResult
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FoldResult -> ShowS
showsPrec :: Int -> FoldResult -> ShowS
$cshow :: FoldResult -> String
show :: FoldResult -> String
$cshowList :: [FoldResult] -> ShowS
showList :: [FoldResult] -> ShowS
Show)

-- | The folder's take from the observed request, matching natural subtraction.
pendingTake :: PendingRequest -> Coin
pendingTake :: PendingRequest -> Coin
pendingTake PendingRequest
pending = case PendingRequest -> Request
pendingRequest PendingRequest
pending of
    RegistrationRequest Registration
registration ->
        let Coin Edge
deposit = Registration -> Coin
regDeposit Registration
registration
        in  Edge -> Coin
Coin (Edge -> Edge -> Edge
forall a. Ord a => a -> a -> a
max Edge
0 (Edge
held Edge -> Edge -> Edge
forall a. Num a => a -> a -> a
- Edge
deposit))
    TerminationRequest{} -> Edge -> Coin
Coin Edge
held
  where
    Coin Edge
held = PendingRequest -> TxOut ConwayEra
pendingOutput PendingRequest
pending BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL

{- | Discover and build the greatest fitting prefix, optionally capped. A
nonempty named batch is built as named, without a cap or trimming. Automatic
selection first skips individually unfoldable requests, then later foldable
requests for an already selected key. Capacity alone permits a shorter prefix;
other construction and public-read failures retain their own identity.
-}
buildFold
    :: Session NoWitness IO
    -> StateScript
    -> Application
    -> RegistryIdentity
    -> [TxIn]
    -> Addr
    -> Maybe Word32
    -> IO (Either Refusal FoldResult)
buildFold :: Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> [TxIn]
-> Addr
-> Maybe Word32
-> IO (Either Refusal FoldResult)
buildFold Session NoWitness IO
session StateScript
script Application
application RegistryIdentity
registry [TxIn]
requests Addr
payerAddress Maybe Word32
cap =
    (FoldFailure -> Refusal)
-> Either FoldFailure FoldResult -> Either Refusal FoldResult
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 FoldFailure -> Refusal
foldFailureReason
        (Either FoldFailure FoldResult -> Either Refusal FoldResult)
-> IO (Either FoldFailure FoldResult)
-> IO (Either Refusal FoldResult)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> [TxIn]
-> Addr
-> Maybe Word32
-> IO (Either FoldFailure FoldResult)
attemptFold
            Session NoWitness IO
session
            StateScript
script
            Application
application
            RegistryIdentity
registry
            [TxIn]
requests
            Addr
payerAddress
            Maybe Word32
cap

-- | A refusal, retaining complete discovery accounting when it was observed.
data FoldFailure = FoldFailure
    { FoldFailure -> Refusal
foldFailureReason :: Refusal
    , FoldFailure -> Maybe ([SkippedHolder], Int)
foldFailureObserved :: Maybe ([SkippedHolder], Int)
    {- ^ All skipped holders and the unconsumed candidate count after automatic
    filtering. Nothing means classification was incomplete, so no empty set may
    be claimed.
    -}
    }
    deriving stock (FoldFailure -> FoldFailure -> Bool
(FoldFailure -> FoldFailure -> Bool)
-> (FoldFailure -> FoldFailure -> Bool) -> Eq FoldFailure
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FoldFailure -> FoldFailure -> Bool
== :: FoldFailure -> FoldFailure -> Bool
$c/= :: FoldFailure -> FoldFailure -> Bool
/= :: FoldFailure -> FoldFailure -> Bool
Eq, Int -> FoldFailure -> ShowS
[FoldFailure] -> ShowS
FoldFailure -> String
(Int -> FoldFailure -> ShowS)
-> (FoldFailure -> String)
-> ([FoldFailure] -> ShowS)
-> Show FoldFailure
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FoldFailure -> ShowS
showsPrec :: Int -> FoldFailure -> ShowS
$cshow :: FoldFailure -> String
show :: FoldFailure -> String
$cshowList :: [FoldFailure] -> ShowS
showList :: [FoldFailure] -> ShowS
Show)

{- | Build with the same rules as 'buildFold', retaining observed holders even
when nothing is eligible or a later build refuses. Failed reads still throw.
-}
attemptFold
    :: Session NoWitness IO
    -> StateScript
    -> Application
    -> RegistryIdentity
    -> [TxIn]
    -> Addr
    -> Maybe Word32
    -> IO (Either FoldFailure FoldResult)
attemptFold :: Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> [TxIn]
-> Addr
-> Maybe Word32
-> IO (Either FoldFailure FoldResult)
attemptFold Session NoWitness IO
session StateScript
script Application
application RegistryIdentity
registry [TxIn]
requests Addr
payerAddress Maybe Word32
cap = ExceptT FoldFailure IO FoldResult
-> IO (Either FoldFailure FoldResult)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT FoldFailure IO FoldResult
 -> IO (Either FoldFailure FoldResult))
-> ExceptT FoldFailure IO FoldResult
-> IO (Either FoldFailure FoldResult)
forall a b. (a -> b) -> a -> b
$ do
    (payer, observed, pendings, skipped) <- (Refusal -> FoldFailure)
-> ExceptT
     Refusal
     IO
     (Payer, PublicRegistry, [PendingRequest], [SkippedHolder])
-> ExceptT
     FoldFailure
     IO
     (Payer, PublicRegistry, [PendingRequest], [SkippedHolder])
forall (m :: * -> *) e e' a.
Functor m =>
(e -> e') -> ExceptT e m a -> ExceptT e' m a
withExceptT (Refusal -> Maybe ([SkippedHolder], Int) -> FoldFailure
`FoldFailure` Maybe ([SkippedHolder], Int)
forall a. Maybe a
Nothing) (ExceptT
   Refusal
   IO
   (Payer, PublicRegistry, [PendingRequest], [SkippedHolder])
 -> ExceptT
      FoldFailure
      IO
      (Payer, PublicRegistry, [PendingRequest], [SkippedHolder]))
-> ExceptT
     Refusal
     IO
     (Payer, PublicRegistry, [PendingRequest], [SkippedHolder])
-> ExceptT
     FoldFailure
     IO
     (Payer, PublicRegistry, [PendingRequest], [SkippedHolder])
forall a b. (a -> b) -> a -> b
$ do
        [TxIn]
-> (TxIn -> ExceptT Refusal IO (ZonkAny 1))
-> ExceptT Refusal IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ ([TxIn] -> [TxIn]
forall a. Eq a => [a] -> [a]
duplicates [TxIn]
requests) (Refusal -> ExceptT Refusal IO (ZonkAny 1)
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Refusal -> ExceptT Refusal IO (ZonkAny 1))
-> (TxIn -> Refusal) -> TxIn -> ExceptT Refusal IO (ZonkAny 1)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TxIn -> Refusal
DuplicateRequest)
        payer <- IO (Either Refusal Payer) -> ExceptT Refusal IO Payer
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Session NoWitness IO -> Addr -> IO (Either Refusal Payer)
resolvePayer Session NoWitness IO
session Addr
payerAddress)
        observed@(PublicRegistry _ _ replayed _) <-
            readPublicRegistry session script registry
        (pendings, skipped) <-
            if null requests
                then
                    liftIO
                        (discoverPending session application registry (replayedKeys replayed))
                else do
                    named <-
                        forM
                            requests
                            ( ExceptT
                                . readPending session application registry (replayedKeys replayed)
                            )
                    pure (named, [])
        pure (payer, observed, pendings, skipped)
    (foldable, omitted, observation) <-
        if null requests
            then withExceptT (`FoldFailure` Nothing) $ do
                protocol <- liftIO (parameters session)
                now <- liftIO (tipSlot session)
                let current = PParams ConwayEra -> SlotNo -> FoldObservation
FoldObservation PParams ConwayEra
protocol SlotNo
now
                (accepted, refused) <-
                    selectFoldable
                        session
                        registry
                        observed
                        current
                        (orderByTake pendingTake pendingRef pendings)
                pure (accepted, skipped <> refused, Just current)
            else pure (pendings, skipped, Nothing)
    let build =
            Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> PublicRegistry
-> Maybe FoldObservation
-> Payer
-> Addr
-> [PendingRequest]
-> ExceptT Refusal IO ConwayTx
buildPendingFold
                Session NoWitness IO
session
                StateScript
script
                Application
application
                RegistryIdentity
registry
                PublicRegistry
observed
                Maybe FoldObservation
observation
                Payer
payer
                Addr
payerAddress
    selected <-
        withExceptT
            (\Refusal
reason -> Refusal -> Maybe ([SkippedHolder], Int) -> FoldFailure
FoldFailure Refusal
reason (([SkippedHolder], Int) -> Maybe ([SkippedHolder], Int)
forall a. a -> Maybe a
Just ([SkippedHolder]
omitted, [PendingRequest] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [PendingRequest]
foldable)))
            $ if null requests
                then
                    ExceptT
                        ( largestFittingPrefix
                            (runExceptT . build)
                            cap
                            foldable
                        )
                else do
                    tx <- build foldable
                    pure (BatchSelection foldable 0 tx Nothing)
    pure
        FoldResult
            { foldTransaction = selectedBuild selected
            , foldSelected = selectedRequests selected
            , foldSkipped = omitted
            , foldLeft = requestsLeft selected
            , foldBoundary = nextCapacity selected
            }

-- | Captured public state and replay, shared by all probes of one fold.
data PublicRegistry
    = PublicRegistry TxIn (TxOut ConwayEra) Replayed (TrieSnapshot IO)

-- | One protocol and clock observation shared by eligibility and capacity probes.
data FoldObservation = FoldObservation (PParams ConwayEra) SlotNo

selectFoldable
    :: Session NoWitness IO
    -> RegistryIdentity
    -> PublicRegistry
    -> FoldObservation
    -> [PendingRequest]
    -> ExceptT Refusal IO ([PendingRequest], [SkippedHolder])
selectFoldable :: Session NoWitness IO
-> RegistryIdentity
-> PublicRegistry
-> FoldObservation
-> [PendingRequest]
-> ExceptT Refusal IO ([PendingRequest], [SkippedHolder])
selectFoldable Session NoWitness IO
session RegistryIdentity
registry (PublicRegistry TxIn
_ TxOut ConwayEra
_ Replayed
_ TrieSnapshot IO
snapshot) (FoldObservation PParams ConwayEra
protocol SlotNo
now) =
    Set ByteString
-> [PendingRequest]
-> [SkippedHolder]
-> [PendingRequest]
-> ExceptT Refusal IO ([PendingRequest], [SkippedHolder])
forall {f :: * -> *}.
(MonadIO f, MonadError Refusal f) =>
Set ByteString
-> [PendingRequest]
-> [SkippedHolder]
-> [PendingRequest]
-> f ([PendingRequest], [SkippedHolder])
go Set ByteString
forall a. Set a
Set.empty [] []
  where
    go :: Set ByteString
-> [PendingRequest]
-> [SkippedHolder]
-> [PendingRequest]
-> f ([PendingRequest], [SkippedHolder])
go Set ByteString
_ [PendingRequest]
accepted [SkippedHolder]
omitted [] = ([PendingRequest], [SkippedHolder])
-> f ([PendingRequest], [SkippedHolder])
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([PendingRequest] -> [PendingRequest]
forall a. [a] -> [a]
reverse [PendingRequest]
accepted, [SkippedHolder] -> [SkippedHolder]
forall a. [a] -> [a]
reverse [SkippedHolder]
omitted)
    go Set ByteString
keys [PendingRequest]
accepted [SkippedHolder]
omitted (PendingRequest
pending : [PendingRequest]
rest) = do
        eligible <- IO (Either Refusal ()) -> f (Either Refusal ())
forall a. IO a -> f a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either Refusal ()) -> f (Either Refusal ()))
-> (ExceptT Refusal IO () -> IO (Either Refusal ()))
-> ExceptT Refusal IO ()
-> f (Either Refusal ())
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ExceptT Refusal IO () -> IO (Either Refusal ())
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Refusal IO () -> f (Either Refusal ()))
-> ExceptT Refusal IO () -> f (Either Refusal ())
forall a b. (a -> b) -> a -> b
$ do
            PParams ConwayEra
-> RegistryIdentity -> PendingRequest -> ExceptT Refusal IO ()
checkDeposit PParams ConwayEra
protocol RegistryIdentity
registry PendingRequest
pending
            TrieSnapshot IO -> PendingRequest -> ExceptT Refusal IO ()
checkLeaf TrieSnapshot IO
snapshot PendingRequest
pending
            case PendingRequest -> Request
pendingRequest PendingRequest
pending of
                RegistrationRequest Registration
registration -> do
                    _ <- Session NoWitness IO
-> SlotNo -> [Registration] -> ExceptT Refusal IO SlotNo
processingWindow Session NoWitness IO
session SlotNo
now [Registration
registration]
                    pure ()
                TerminationRequest{} -> () -> ExceptT Refusal IO ()
forall a. a -> ExceptT Refusal IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        let key = Request -> ByteString
requestKey (PendingRequest -> Request
pendingRequest PendingRequest
pending)
            skip Refusal
reason =
                Set ByteString
-> [PendingRequest]
-> [SkippedHolder]
-> [PendingRequest]
-> f ([PendingRequest], [SkippedHolder])
go
                    Set ByteString
keys
                    [PendingRequest]
accepted
                    ( TxIn -> SkipReason -> SkippedHolder
SkippedHolder (PendingRequest -> TxIn
pendingRef PendingRequest
pending) (Refusal -> SkipReason
UnfoldableRequest Refusal
reason)
                        SkippedHolder -> [SkippedHolder] -> [SkippedHolder]
forall a. a -> [a] -> [a]
: [SkippedHolder]
omitted
                    )
                    [PendingRequest]
rest
        case eligible of
            Left Refusal
reason | Refusal -> Bool
individualRefusal Refusal
reason -> Refusal -> f ([PendingRequest], [SkippedHolder])
skip Refusal
reason
            Left Refusal
failure -> Refusal -> f ([PendingRequest], [SkippedHolder])
forall a. Refusal -> f a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError Refusal
failure
            Right ()
                | ByteString -> Set ByteString -> Bool
forall a. Ord a => a -> Set a -> Bool
Set.member ByteString
key Set ByteString
keys -> Refusal -> f ([PendingRequest], [SkippedHolder])
skip (ByteString -> Refusal
DuplicateKey ByteString
key)
                | Bool
otherwise ->
                    Set ByteString
-> [PendingRequest]
-> [SkippedHolder]
-> [PendingRequest]
-> f ([PendingRequest], [SkippedHolder])
go (ByteString -> Set ByteString -> Set ByteString
forall a. Ord a => a -> Set a -> Set a
Set.insert ByteString
key Set ByteString
keys) (PendingRequest
pending PendingRequest -> [PendingRequest] -> [PendingRequest]
forall a. a -> [a] -> [a]
: [PendingRequest]
accepted) [SkippedHolder]
omitted [PendingRequest]
rest
    individualRefusal :: Refusal -> Bool
individualRefusal = \case
        DepositBelowHolding{} -> Bool
True
        KeyAlreadyRegistered{} -> Bool
True
        KeyNotActive{} -> Bool
True
        Refusal
ProcessingWindowClosed -> Bool
True
        Refusal
_ -> Bool
False

checkDeposit
    :: PParams ConwayEra
    -> RegistryIdentity
    -> PendingRequest
    -> ExceptT Refusal IO ()
checkDeposit :: PParams ConwayEra
-> RegistryIdentity -> PendingRequest -> ExceptT Refusal IO ()
checkDeposit PParams ConwayEra
protocol RegistryIdentity
registry PendingRequest
pending = case PendingRequest -> Request
pendingRequest PendingRequest
pending of
    RegistrationRequest Registration
registration -> do
        let smallest :: Coin
smallest = PParams ConwayEra -> TxOut ConwayEra -> Coin
forall era. EraTxOut era => PParams era -> TxOut era -> Coin
getMinCoinTxOut PParams ConwayEra
protocol (RegistryIdentity -> Registration -> TxOut ConwayEra
holdingFor RegistryIdentity
registry Registration
registration)
            deposit :: Coin
deposit = Registration -> Coin
regDeposit Registration
registration
        Bool -> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Coin
deposit Coin -> Coin -> Bool
forall a. Ord a => a -> a -> Bool
< Coin
smallest) (ExceptT Refusal IO () -> ExceptT Refusal IO ())
-> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall a b. (a -> b) -> a -> b
$
            Refusal -> ExceptT Refusal IO ()
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (TxIn -> Coin -> Coin -> Refusal
DepositBelowHolding (PendingRequest -> TxIn
pendingRef PendingRequest
pending) Coin
deposit Coin
smallest)
    TerminationRequest{} -> () -> ExceptT Refusal IO ()
forall a. a -> ExceptT Refusal IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

checkLeaf
    :: TrieSnapshot IO -> PendingRequest -> ExceptT Refusal IO ()
checkLeaf :: TrieSnapshot IO -> PendingRequest -> ExceptT Refusal IO ()
checkLeaf TrieSnapshot IO
snapshot PendingRequest
pending = do
    let request :: Request
request = PendingRequest -> Request
pendingRequest PendingRequest
pending
        key :: ByteString
key = Request -> ByteString
requestKey Request
request
    leaf <-
        IO (Either Refusal Leaf) -> ExceptT Refusal IO Leaf
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT ((TrieFailure -> Either Refusal Leaf)
-> (Leaf -> Either Refusal Leaf)
-> Either TrieFailure Leaf
-> Either Refusal Leaf
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Refusal -> Either Refusal Leaf
forall a b. a -> Either a b
Left (Refusal -> Either Refusal Leaf)
-> (TrieFailure -> Refusal) -> TrieFailure -> Either Refusal Leaf
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TrieFailure -> Refusal
TrieRefused) Leaf -> Either Refusal Leaf
forall a b. b -> Either a b
Right (Either TrieFailure Leaf -> Either Refusal Leaf)
-> IO (Either TrieFailure Leaf) -> IO (Either Refusal Leaf)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TrieSnapshot IO -> ByteString -> IO (Either TrieFailure Leaf)
forall (m :: * -> *).
TrieSnapshot m -> ByteString -> m (Either TrieFailure Leaf)
leafAt TrieSnapshot IO
snapshot ByteString
key)
    case request of
        RegistrationRequest{} -> Bool -> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Leaf
leaf Leaf -> Leaf -> Bool
forall a. Eq a => a -> a -> Bool
== Leaf
Unknown) (Refusal -> ExceptT Refusal IO ()
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ByteString -> Refusal
KeyAlreadyRegistered ByteString
key))
        TerminationRequest{} -> Bool -> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Leaf
leaf Leaf -> Leaf -> Bool
forall a. Eq a => a -> a -> Bool
== Leaf
Active) (Refusal -> ExceptT Refusal IO ()
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ByteString -> Refusal
KeyNotActive ByteString
key))

processingWindow
    :: Session NoWitness IO
    -> SlotNo
    -> [Registration]
    -> ExceptT Refusal IO SlotNo
processingWindow :: Session NoWitness IO
-> SlotNo -> [Registration] -> ExceptT Refusal IO SlotNo
processingWindow Session NoWitness IO
session SlotNo
now [Registration]
registrations = do
    fallback <- (Edge -> Edge -> Edge
forall a. Num a => a -> a -> a
+ Edge
usualSpan) (Edge -> Edge)
-> ExceptT Refusal IO Edge -> ExceptT Refusal IO Edge
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Edge -> ExceptT Refusal IO Edge
forall a. IO a -> ExceptT Refusal IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Session NoWitness IO -> SlotNo -> IO Edge
forall w. Session w IO -> SlotNo -> IO Edge
slotStart Session NoWitness IO
session SlotNo
now)
    deadline <-
        liftIO
            (floorSlot session (minimum (fallback : map regDeadline registrations)))
    liftIO (validityFromTip session now deadline)
        >>= maybe (throwError ProcessingWindowClosed) pure

readPublicRegistry
    :: Session NoWitness IO
    -> StateScript
    -> RegistryIdentity
    -> ExceptT Refusal IO PublicRegistry
readPublicRegistry :: Session NoWitness IO
-> StateScript
-> RegistryIdentity
-> ExceptT Refusal IO PublicRegistry
readPublicRegistry Session NoWitness IO
session StateScript
script RegistryIdentity
registry = do
    (stateIn, stateOut, root) <-
        IO (Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString))
-> ExceptT Refusal IO (TxIn, BabbageTxOut ConwayEra, ByteString)
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Session NoWitness IO
-> StateScript
-> RegistryIdentity
-> IO (Either Refusal (TxIn, TxOut ConwayEra, ByteString))
findState Session NoWitness IO
session StateScript
script RegistryIdentity
registry)
    let selection =
            TrieSelection
                { trieSelectionIdentity :: RegistryIdentity
trieSelectionIdentity = RegistryIdentity
registry
                , trieSelectionPoint :: StatePoint
trieSelectionPoint =
                    SessionId -> SessionBinding -> TxIn -> StatePoint
StatePoint (Session NoWitness IO -> SessionId
forall w (m :: * -> *). Session w m -> SessionId
sessionId Session NoWitness IO
session) (Session NoWitness IO -> SessionBinding
forall w (m :: * -> *). Session w m -> SessionBinding
sessionBinding Session NoWitness IO
session) TxIn
stateIn
                , trieSelectionRoot :: Root
trieSelectionRoot = ByteString -> Root
Root ByteString
root
                }
    (replayed, nodes) <-
        ExceptT
            (either (Left . TrieRefused) Right <$> replayRegistry session selection)
    let snapshot =
            (TrieObservation -> IO ())
-> TrieSelection
-> MPFInMemoryDB
-> CompleteFromCreate
-> Maybe PublicLineage
-> TrieSnapshot IO
forall (m :: * -> *).
Monad m =>
(TrieObservation -> m ())
-> TrieSelection
-> MPFInMemoryDB
-> CompleteFromCreate
-> Maybe PublicLineage
-> TrieSnapshot m
snapshotObserved
                (IO () -> TrieObservation -> IO ()
forall a b. a -> b -> a
const (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()))
                TrieSelection
selection
                MPFInMemoryDB
nodes
                (Int -> CompleteFromCreate
CompleteFromCreate Int
0)
                Maybe PublicLineage
forall a. Maybe a
Nothing
    pure (PublicRegistry stateIn stateOut replayed snapshot)

buildPendingFold
    :: Session NoWitness IO
    -> StateScript
    -> Application
    -> RegistryIdentity
    -> PublicRegistry
    -> Maybe FoldObservation
    -> Payer
    -> Addr
    -> [PendingRequest]
    -> ExceptT Refusal IO ConwayTx
buildPendingFold :: Session NoWitness IO
-> StateScript
-> Application
-> RegistryIdentity
-> PublicRegistry
-> Maybe FoldObservation
-> Payer
-> Addr
-> [PendingRequest]
-> ExceptT Refusal IO ConwayTx
buildPendingFold Session NoWitness IO
session StateScript
script Application
application RegistryIdentity
registry (PublicRegistry TxIn
stateIn TxOut ConwayEra
stateOut Replayed
replayed TrieSnapshot IO
snapshot) Maybe FoldObservation
observation Payer
payer Addr
payerAddress [PendingRequest]
pendings = do
    Bool -> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([PendingRequest] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PendingRequest]
pendings) (ExceptT Refusal IO () -> ExceptT Refusal IO ())
-> ExceptT Refusal IO () -> ExceptT Refusal IO ()
forall a b. (a -> b) -> a -> b
$ Refusal -> ExceptT Refusal IO ()
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError Refusal
NothingToFold
    let keys :: [ByteString]
keys = (PendingRequest -> ByteString) -> [PendingRequest] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (Request -> ByteString
requestKey (Request -> ByteString)
-> (PendingRequest -> Request) -> PendingRequest -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PendingRequest -> Request
pendingRequest) [PendingRequest]
pendings
    [ByteString]
-> (ByteString -> ExceptT Refusal IO (ZonkAny 0))
-> ExceptT Refusal IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ ([ByteString] -> [ByteString]
forall a. Eq a => [a] -> [a]
duplicates [ByteString]
keys) (Refusal -> ExceptT Refusal IO (ZonkAny 0)
forall a. Refusal -> ExceptT Refusal IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Refusal -> ExceptT Refusal IO (ZonkAny 0))
-> (ByteString -> Refusal)
-> ByteString
-> ExceptT Refusal IO (ZonkAny 0)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Refusal
DuplicateKey)
    protocol <- case Maybe FoldObservation
observation of
        Just (FoldObservation PParams ConwayEra
observedProtocol SlotNo
_) -> PParams ConwayEra -> ExceptT Refusal IO (PParams ConwayEra)
forall a. a -> ExceptT Refusal IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure PParams ConwayEra
observedProtocol
        Maybe FoldObservation
Nothing -> IO (PParams ConwayEra) -> ExceptT Refusal IO (PParams ConwayEra)
forall a. IO a -> ExceptT Refusal IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Session NoWitness IO -> IO (PParams ConwayEra)
forall w. Session w IO -> IO (PParams ConwayEra)
parameters Session NoWitness IO
session)
    forM_ pendings (checkDeposit protocol registry)
    forM_ pendings (checkLeaf snapshot)
    walked <-
        ExceptT
            ( either (Left . TrieRefused) Right
                <$> speculateEdges
                    snapshot
                    ( NE.fromList
                        [ (requestKey request, toInteger (edgeFor request))
                        | pending <- pendings
                        , let request = PendingRequest -> Request
pendingRequest PendingRequest
pending
                        ]
                    )
            )
    now <- case observation of
        Just (FoldObservation PParams ConwayEra
_ SlotNo
observedSlot) -> SlotNo -> ExceptT Refusal IO SlotNo
forall a. a -> ExceptT Refusal IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SlotNo
observedSlot
        Maybe FoldObservation
Nothing -> IO SlotNo -> ExceptT Refusal IO SlotNo
forall a. IO a -> ExceptT Refusal IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Session NoWitness IO -> IO SlotNo
tipSlot Session NoWitness IO
session)
    upper <-
        processingWindow
            session
            now
            [ registration
            | pending <- pendings
            , RegistrationRequest registration <- [pendingRequest pending]
            ]
    stateScriptOutputs <-
        ExceptT (referenceOutputs session (ssScript script) (ssSource script))
    let policy = StateScript -> PolicyID
statePolicy StateScript
script
        RegistryIdentity _ name = registry
        funding = Payer -> (TxIn, TxOut ConwayEra)
payerFunding Payer
payer
        Root newRoot = walkRoot walked
        stateValue =
            Coin -> MultiAsset -> MaryValue
MaryValue
                (TxOut ConwayEra
BabbageTxOut ConwayEra
stateOut BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL)
                (Map PolicyID (Map AssetName Edge) -> MultiAsset
MultiAsset (PolicyID -> Map AssetName Edge -> Map PolicyID (Map AssetName Edge)
forall k a. k -> a -> Map k a
Map.singleton PolicyID
policy (AssetName -> Edge -> Map AssetName Edge
forall k a. k -> a -> Map k a
Map.singleton AssetName
name Edge
1)))
        spent =
            (TxIn, BabbageTxOut ConwayEra)
funding
                (TxIn, BabbageTxOut ConwayEra)
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall a. a -> [a] -> [a]
: (TxIn
stateIn, TxOut ConwayEra
BabbageTxOut ConwayEra
stateOut)
                (TxIn, BabbageTxOut ConwayEra)
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall a. a -> [a] -> [a]
: [(PendingRequest -> TxIn
pendingRef PendingRequest
p, PendingRequest -> TxOut ConwayEra
pendingOutput PendingRequest
p) | PendingRequest
p <- [PendingRequest]
pendings]
    ExceptT $
        assembleTransaction
            session
            spent
            (stateScriptOutputs <> appReferences application)
            payerAddress
            ( do
                _ <-
                    Tx.payTo'
                        (stateAddress (payerNetwork payer) script)
                        stateValue
                        (BuiltinData (stateDatum newRoot))
                changed <- forM (zip pendings (walkProofs walked)) $ \(PendingRequest
pending, [ProofStep]
proof) -> do
                    let request :: Request
request = PendingRequest -> Request
pendingRequest PendingRequest
pending
                        folded :: Maybe Word32 -> Folded
folded =
                            TxIn
-> AssetName
-> RegistryIdentity
-> ByteString
-> Maybe Word32
-> Folded
Folded
                                (PendingRequest -> TxIn
pendingRef PendingRequest
pending)
                                (PendingRequest -> AssetName
pendingApproval PendingRequest
pending)
                                RegistryIdentity
registry
                                (Request -> ByteString
requestKey Request
request)
                    case Request
request of
                        RegistrationRequest Registration
registration -> do
                            holding <- TxOut ConwayEra -> TxBuild NoQuery Void Word32
forall (q :: * -> *) e. TxOut ConwayEra -> TxBuild q e Word32
Tx.output (RegistryIdentity -> Registration -> TxOut ConwayEra
holdingFor RegistryIdentity
registry Registration
registration)
                            let Coin deposit = regDeposit registration
                            pure
                                ( Register
                                    (pendingRef pending)
                                    (regKey registration)
                                    (toInteger holding)
                                    deposit
                                    proof
                                , folded (Just holding)
                                )
                        TerminationRequest RegistryIdentity
_ ByteString
key ->
                            (Change, Folded)
-> ProgramT (TxInstr NoQuery Void) Identity (Change, Folded)
forall a. a -> ProgramT (TxInstr NoQuery Void) Identity a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TxIn -> ByteString -> [ProofStep] -> Change
Terminate (PendingRequest -> TxIn
pendingRef PendingRequest
pending) ByteString
key [ProofStep]
proof, Maybe Word32 -> Folded
folded Maybe Word32
forall a. Maybe a
Nothing)
                let changes = ((Change, Folded) -> Change) -> [(Change, Folded)] -> [Change]
forall a b. (a -> b) -> [a] -> [b]
map (Change, Folded) -> Change
forall a b. (a, b) -> a
fst [(Change, Folded)]
changed
                _ <-
                    Tx.spendScript
                        stateIn
                        (BuiltinData (foldRedeemer (replayedSeed replayed) changes))
                Tx.mint
                    policy
                    ( Map.fromListWith
                        (+)
                        [ ( activeTokenName registry (requestKey request)
                          , case request of RegistrationRequest{} -> Edge
1; TerminationRequest{} -> -Edge
1
                          )
                        | p <- pendings
                        , let request = PendingRequest -> Request
pendingRequest PendingRequest
p
                        ]
                    )
                    (BuiltinData foldedRedeemer)
                useScript (ssScript script) (ssSource script)
                appFold application (map snd changed)
                Tx.collateral (fst funding)
                Tx.validFrom now
                Tx.validTo upper
            )

-- | The first element that appears more than once.
duplicates :: (Eq a) => [a] -> [a]
duplicates :: forall a. Eq a => [a] -> [a]
duplicates [a]
xs = Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Int
1 [a
x | (Int
i, a
x) <- [Int] -> [a] -> [(Int, a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] [a]
xs, a
x a -> [a] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Int
i [a]
xs]

{- | The output that holds the token of a pending registration's key, at the
address the registration commits to, with the datum it commits to and exactly
its deposit.
-}
holdingFor :: RegistryIdentity -> Registration -> TxOut ConwayEra
holdingFor :: RegistryIdentity -> Registration -> TxOut ConwayEra
holdingFor RegistryIdentity
registry Registration
registration =
    Addr -> Value ConwayEra -> TxOut ConwayEra
forall era.
(EraTxOut era, HasCallStack) =>
Addr -> Value era -> TxOut era
mkBasicTxOut Addr
regHolding (Coin -> MultiAsset -> MaryValue
MaryValue Coin
regDeposit MultiAsset
tokens)
        TxOut ConwayEra
-> (TxOut ConwayEra -> BabbageTxOut ConwayEra)
-> BabbageTxOut ConwayEra
forall a b. a -> (a -> b) -> b
& (Datum ConwayEra -> Identity (Datum ConwayEra))
-> TxOut ConwayEra -> Identity (TxOut ConwayEra)
(Datum ConwayEra -> Identity (Datum ConwayEra))
-> TxOut ConwayEra -> Identity (BabbageTxOut ConwayEra)
forall era. BabbageEraTxOut era => Lens' (TxOut era) (Datum era)
Lens' (TxOut ConwayEra) (Datum ConwayEra)
datumTxOutL ((Datum ConwayEra -> Identity (Datum ConwayEra))
 -> TxOut ConwayEra -> Identity (BabbageTxOut ConwayEra))
-> Datum ConwayEra -> TxOut ConwayEra -> BabbageTxOut ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Data -> Datum ConwayEra
mkInlineDatum Data
regDatum
  where
    Registration{ByteString
regKey :: Registration -> ByteString
regKey :: ByteString
regKey, Addr
regHolding :: Registration -> Addr
regHolding :: Addr
regHolding, Data
regDatum :: Registration -> Data
regDatum :: Data
regDatum, Coin
regDeposit :: Registration -> Coin
regDeposit :: Coin
regDeposit} = Registration
registration
    tokens :: MultiAsset
tokens = case RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset RegistryIdentity
registry of
        Just (PolicyID
policy, AssetName
_) ->
            Map PolicyID (Map AssetName Edge) -> MultiAsset
MultiAsset
                ( PolicyID -> Map AssetName Edge -> Map PolicyID (Map AssetName Edge)
forall k a. k -> a -> Map k a
Map.singleton
                    PolicyID
policy
                    (AssetName -> Edge -> Map AssetName Edge
forall k a. k -> a -> Map k a
Map.singleton (RegistryIdentity -> ByteString -> AssetName
activeTokenName RegistryIdentity
registry ByteString
regKey) Edge
1)
                )
        Maybe (PolicyID, AssetName)
Nothing -> MultiAsset
forall a. Monoid a => a
mempty

{- | The live state output of the registry: the one output that holds the state
token, at the address of this state script, holding it alone besides ADA, with a
root datum. Anything else that holds the token is no state of the registry.
-}
findState
    :: Session NoWitness IO
    -> StateScript
    -> RegistryIdentity
    -> IO (Either Refusal (TxIn, TxOut ConwayEra, ByteString))
findState :: Session NoWitness IO
-> StateScript
-> RegistryIdentity
-> IO (Either Refusal (TxIn, TxOut ConwayEra, ByteString))
findState Session NoWitness IO
session StateScript
script RegistryIdentity
registry = case RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset RegistryIdentity
registry of
    Maybe (PolicyID, AssetName)
Nothing -> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
-> IO (Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Refusal
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall a b. a -> Either a b
Left (RegistryIdentity -> Refusal
NoRegistryState RegistryIdentity
registry))
    Just (PolicyID
policy, AssetName
name) -> do
        found <-
            Session NoWitness IO
-> OutputQuery -> IO (Either ReadFailure [(TxIn, TxOut ConwayEra)])
readOutputs Session NoWitness IO
session ((PolicyID, AssetName) -> OutputQuery
HoldingAsset (PolicyID
policy, AssetName
name))
                IO (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)])
-> (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
    -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (ReadFailure -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> ([(TxIn, BabbageTxOut ConwayEra)]
    -> IO [(TxIn, BabbageTxOut ConwayEra)])
-> Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ReadFailure -> IO [(TxIn, BabbageTxOut ConwayEra)]
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO [(TxIn, BabbageTxOut ConwayEra)]
-> IO [(TxIn, BabbageTxOut ConwayEra)]
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
        pure $ case found of
            [] -> Refusal
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall a b. a -> Either a b
Left (RegistryIdentity -> Refusal
NoRegistryState RegistryIdentity
registry)
            [(TxIn
ref, BabbageTxOut ConwayEra
output)] ->
                Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
-> (ByteString
    -> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString))
-> Maybe ByteString
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
                    (Refusal
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall a b. a -> Either a b
Left (TxIn -> Refusal
NotARegistryState TxIn
ref))
                    ((TxIn, BabbageTxOut ConwayEra, ByteString)
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall a b. b -> Either a b
Right ((TxIn, BabbageTxOut ConwayEra, ByteString)
 -> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString))
-> (ByteString -> (TxIn, BabbageTxOut ConwayEra, ByteString))
-> ByteString
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (,,) TxIn
ref BabbageTxOut ConwayEra
output)
                    (PolicyID -> AssetName -> BabbageTxOut ConwayEra -> Maybe ByteString
recognised PolicyID
policy AssetName
name BabbageTxOut ConwayEra
output)
            [(TxIn, BabbageTxOut ConwayEra)]
several -> Refusal
-> Either Refusal (TxIn, BabbageTxOut ConwayEra, ByteString)
forall a b. a -> Either a b
Left (Int -> Refusal
AmbiguousRegistryState ([(TxIn, BabbageTxOut ConwayEra)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(TxIn, BabbageTxOut ConwayEra)]
several))
  where
    recognised :: PolicyID -> AssetName -> TxOut ConwayEra -> Maybe ByteString
recognised PolicyID
policy AssetName
name TxOut ConwayEra
output = do
        case TxOut ConwayEra
output TxOut ConwayEra -> Getting Addr (TxOut ConwayEra) Addr -> Addr
forall s a. s -> Getting a s a -> a
^. Getting Addr (TxOut ConwayEra) Addr
forall era. EraTxOut era => Lens' (TxOut era) Addr
Lens' (TxOut ConwayEra) Addr
addrTxOutL of
            Addr Network
_ (ScriptHashObj ScriptHash
h) StakeReference
_
                | ScriptHash -> PolicyID
PolicyID ScriptHash
h PolicyID -> PolicyID -> Bool
forall a. Eq a => a -> a -> Bool
== PolicyID
policy Bool -> Bool -> Bool
&& ScriptHash
h ScriptHash -> ScriptHash -> Bool
forall a. Eq a => a -> a -> Bool
== StateScript -> ScriptHash
stateScriptHash StateScript
script -> () -> Maybe ()
forall a. a -> Maybe a
Just ()
            Addr
_ -> Maybe ()
forall a. Maybe a
Nothing
        Bool -> Maybe ()
unless' (PolicyID -> AssetName -> TxOut ConwayEra -> Bool
holdsOnly PolicyID
policy AssetName
name TxOut ConwayEra
output)
        root <- TxOut ConwayEra -> Maybe Data
inlineDatumOf TxOut ConwayEra
output Maybe Data -> (Data -> Maybe ByteString) -> Maybe ByteString
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Data -> Maybe ByteString
decodeStateDatum
        unless' (BS.length root == 32)
        pure root
    unless' :: Bool -> Maybe ()
unless' Bool
ok = if Bool
ok then () -> Maybe ()
forall a. a -> Maybe a
Just () else Maybe ()
forall a. Maybe a
Nothing

{- | A pending registration of the application, read from the chain: decoded,
of this registry, and holding the approval its datum commits to.
-}
readPending
    :: Session NoWitness IO
    -> Application
    -> RegistryIdentity
    -> [ByteString]
    -> TxIn
    -> IO (Either Refusal PendingRequest)
readPending :: Session NoWitness IO
-> Application
-> RegistryIdentity
-> [ByteString]
-> TxIn
-> IO (Either Refusal PendingRequest)
readPending Session NoWitness IO
session Application
application RegistryIdentity
registry [ByteString]
candidates TxIn
ref =
    Session NoWitness IO
-> OutputQuery -> IO (Either ReadFailure [(TxIn, TxOut ConwayEra)])
readOutputs Session NoWitness IO
session (TxIn -> OutputQuery
AtTxIn TxIn
ref) IO (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)])
-> (Either ReadFailure [(TxIn, BabbageTxOut ConwayEra)]
    -> IO (Either Refusal PendingRequest))
-> IO (Either Refusal PendingRequest)
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 (MissingOutput TxIn
_) -> Either Refusal PendingRequest -> IO (Either Refusal PendingRequest)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Refusal -> Either Refusal PendingRequest
forall a b. a -> Either a b
Left (TxIn -> Refusal
PendingNotFound TxIn
ref))
        Left ReadFailure
failure -> ReadFailure -> IO (Either Refusal PendingRequest)
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO ReadFailure
failure
        Right [(TxIn
_, BabbageTxOut ConwayEra
output)] ->
            Either Refusal PendingRequest -> IO (Either Refusal PendingRequest)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Application
-> RegistryIdentity
-> [ByteString]
-> TxIn
-> TxOut ConwayEra
-> Either Refusal PendingRequest
pendingFromOutput Application
application RegistryIdentity
registry [ByteString]
candidates TxIn
ref TxOut ConwayEra
BabbageTxOut ConwayEra
output)
        Right [(TxIn, BabbageTxOut ConwayEra)]
_ -> Either Refusal PendingRequest -> IO (Either Refusal PendingRequest)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Refusal -> Either Refusal PendingRequest
forall a b. a -> Either a b
Left (TxIn -> Refusal
PendingNotFound TxIn
ref))

-- | The same request authentication for discovered and explicitly named outputs.
pendingFromOutput
    :: Application
    -> RegistryIdentity
    -> [ByteString]
    -> TxIn
    -> TxOut ConwayEra
    -> Either Refusal PendingRequest
pendingFromOutput :: Application
-> RegistryIdentity
-> [ByteString]
-> TxIn
-> TxOut ConwayEra
-> Either Refusal PendingRequest
pendingFromOutput Application
application RegistryIdentity
registry [ByteString]
candidates TxIn
ref TxOut ConwayEra
output = do
    request <-
        Either Refusal Request
-> (Request -> Either Refusal Request)
-> Maybe Request
-> Either Refusal Request
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
            Either Refusal Request
forall {b}. Either Refusal b
declined
            Request -> Either Refusal Request
forall a b. b -> Either a b
Right
            (Application
-> RegistryIdentity
-> [ByteString]
-> TxOut ConwayEra
-> Maybe Request
appDecode Application
application RegistryIdentity
registry [ByteString]
candidates TxOut ConwayEra
output)
    when (requestRegistry request /= registry) $
        Left (PendingOfAnotherRegistry ref)
    approval <- maybe declined Right (approvalOf request)
    case request of
        RegistrationRequest Registration
registration -> do
            Bool -> Either Refusal () -> Either Refusal ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (PolicyID -> AssetName -> TxOut ConwayEra -> Bool
holdsOnly (Application -> PolicyID
appPolicy Application
application) AssetName
approval TxOut ConwayEra
output) Either Refusal ()
forall {b}. Either Refusal b
declined
            Bool -> Either Refusal () -> Either Refusal ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Registration -> Coin
regDeposit Registration
registration Coin -> Coin -> Bool
forall a. Ord a => a -> a -> Bool
<= TxOut ConwayEra
BabbageTxOut ConwayEra
output BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL) Either Refusal ()
forall {b}. Either Refusal b
declined
        TerminationRequest RegistryIdentity
_ ByteString
key -> do
            (policy, _) <- Either Refusal (PolicyID, AssetName)
-> ((PolicyID, AssetName) -> Either Refusal (PolicyID, AssetName))
-> Maybe (PolicyID, AssetName)
-> Either Refusal (PolicyID, AssetName)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Either Refusal (PolicyID, AssetName)
forall {b}. Either Refusal b
declined (PolicyID, AssetName) -> Either Refusal (PolicyID, AssetName)
forall a b. b -> Either a b
Right (RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset RegistryIdentity
registry)
            let expected =
                    Map PolicyID (Map AssetName Edge) -> MultiAsset
MultiAsset
                        ( (Map AssetName Edge -> Map AssetName Edge -> Map AssetName Edge)
-> [(PolicyID, Map AssetName Edge)]
-> Map PolicyID (Map AssetName Edge)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith
                            ((Edge -> Edge -> Edge)
-> Map AssetName Edge -> Map AssetName Edge -> Map AssetName Edge
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
Map.unionWith Edge -> Edge -> Edge
forall a. Num a => a -> a -> a
(+))
                            [ (PolicyID
policy, AssetName -> Edge -> Map AssetName Edge
forall k a. k -> a -> Map k a
Map.singleton (RegistryIdentity -> ByteString -> AssetName
activeTokenName RegistryIdentity
registry ByteString
key) Edge
1)
                            , (Application -> PolicyID
appPolicy Application
application, AssetName -> Edge -> Map AssetName Edge
forall k a. k -> a -> Map k a
Map.singleton AssetName
approval Edge
1)
                            ]
                        )
                MaryValue _ actual = output ^. valueTxOutL
            unless (actual == expected) declined
    pure (PendingRequest ref output request approval)
  where
    declined :: Either Refusal b
declined = Refusal -> Either Refusal b
forall a b. a -> Either a b
Left (TxIn -> Refusal
NotAPendingRegistration TxIn
ref)

edgeFor :: Request -> Int
edgeFor :: Request -> Int
edgeFor RegistrationRequest{} = Edge -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Edge
edgeInsertActive
edgeFor TerminationRequest{} = Edge -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Edge
edgeUpdateTerminal

-- | The name of the approval a registration commits to.
approvalOf :: Request -> Maybe AssetName
approvalOf :: Request -> Maybe AssetName
approvalOf (TerminationRequest RegistryIdentity
registry ByteString
key) = AssetName -> Maybe AssetName
forall a. a -> Maybe a
Just (ByteString -> AssetName
approvalName (ByteString -> RegistryIdentity -> ByteString
terminationPreimage ByteString
key RegistryIdentity
registry))
approvalOf (RegistrationRequest Registration
registration) = do
    holding <- Addr -> Maybe Address
transAddr (Registration -> Addr
regHolding Registration
registration)
    let Coin deposit = regDeposit registration
    pure . approvalName $
        registrationPreimage
            (regKey registration)
            (regRegistry registration)
            holding
            (initialDatumHash (regDatum registration))
            (PV3.Lovelace deposit)

-- | Requests named by the fold redeemer of a built transaction.
foldedRequests :: ConwayTx -> [(TxIn, ByteString)]
foldedRequests :: ConwayTx -> [(TxIn, ByteString)]
foldedRequests ConwayTx
tx =
    [ (Change -> TxIn
changeRequest Change
change, Change -> ByteString
changeKey Change
change)
    | (TxIn
_, [Change]
changes) <- [(TxIn, [Change])]
decoded
    , Change
change <- [Change]
changes
    ]
  where
    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
    decoded :: [(TxIn, [Change])]
decoded =
        ((Data ConwayEra, ExUnits) -> Maybe (TxIn, [Change]))
-> [(Data ConwayEra, ExUnits)] -> [(TxIn, [Change])]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe
            (Data -> Maybe (TxIn, [Change])
decodeFoldRedeemer (Data -> Maybe (TxIn, [Change]))
-> ((Data ConwayEra, ExUnits) -> Data)
-> (Data ConwayEra, ExUnits)
-> Maybe (TxIn, [Change])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Data ConwayEra -> Data
forall era. Data era -> Data
getPlutusData (Data ConwayEra -> Data)
-> ((Data ConwayEra, ExUnits) -> Data ConwayEra)
-> (Data ConwayEra, ExUnits)
-> Data
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Data ConwayEra, ExUnits) -> Data ConwayEra
forall a b. (a, b) -> a
fst)
            (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)