{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}

{- |
Module      : Singular.State.Lineage
Description : A registry's trie rebuilt from the public history of its state token
License     : Apache-2.0

The chain commits a registry's trie by its root only. This module rebuilds the
trie itself from the transactions that moved the registry's state token since
its genesis, so a folder needs nothing from the person who booked.

The lineage is read in the order the history gives it, creator before spender.
The genesis mints the token under the state policy with the seed in its
redeemer, spends that seed and writes the empty root; each fold spends the
current state output with the redeemer of a fold and writes the root of the
trie with its keys. A transaction whose bytes say it failed its scripts spent
only its collateral and is never in the lineage. After every fold the rebuilt
root must equal the root in the new state output, wherever in the transaction
that output sits.
-}
module Singular.State.Lineage
    ( Replayed (..)
    , replayRegistry
    , registryTrieState
    , registryAsset
    ) where

import Control.Monad (unless, when)
import Control.Monad.State.Strict (execState)
import Data.ByteString (ByteString)
import Data.Foldable (toList)
import Data.List (elemIndex)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Lens.Micro ((^.))
import MPF.Backend.Pure (MPFInMemoryDB, emptyMPFInMemoryDB)
import PlutusCore.Data qualified as PLC

import Cardano.Crypto.Hash (hashFromBytes)
import Cardano.Ledger.Address (Addr (..))
import Cardano.Ledger.Alonzo.Scripts (AsIx (..))
import Cardano.Ledger.Alonzo.Tx (IsValid (..))
import Cardano.Ledger.Alonzo.TxWits (Redeemers (..))
import Cardano.Ledger.Api.Scripts.Data
    ( Datum (..)
    , binaryDataToData
    , getPlutusData
    )
import Cardano.Ledger.Api.Tx (bodyTxL, isValidTxL, txIdTx, witsTxL)
import Cardano.Ledger.Api.Tx.Body
    ( inputsTxBodyL
    , mintTxBodyL
    , outputsTxBodyL
    )
import Cardano.Ledger.Api.Tx.Out
    ( addrTxOutL
    , datumTxOutL
    , valueTxOutL
    )
import Cardano.Ledger.Api.Tx.Wits (rdmrsTxWitsL)
import Cardano.Ledger.BaseTypes (TxIx (..))
import Cardano.Ledger.Conway.Scripts (ConwayPlutusPurpose (..))
import Cardano.Ledger.Credential (Credential (..))
import Cardano.Ledger.Hashes (ScriptHash (..))
import Cardano.Ledger.Mary.Value
    ( AssetName
    , MaryValue (..)
    , MultiAsset (..)
    , PolicyID (..)
    )
import Cardano.Ledger.TxIn (TxId, TxIn (..))
import Cardano.Tx.Ledger (ConwayTx)

import Singular.Registry.Ledger (ConwayEra, Root (..), TxOut)
import Singular.Registry.LedgerProvider (Session (..))
import Singular.Registry.Trie.Pure (rootFromDb, stateTrie)
import Singular.Registry.TrieState
    ( Incomplete (..)
    , Mismatch (..)
    , Parting (..)
    , PublicLineage (..)
    , RegistryIdentity (..)
    , Staleness (..)
    , StatePoint (..)
    , StatePolicyId (..)
    , TrieFailure (..)
    , TrieSelection (..)
    , TrieState (..)
    , Undecodable (..)
    )
import Singular.Registry.TrieState.Core (snapshotObserved)
import Singular.Registry.TrieState.Lineage (publicHistory)
import Singular.Registry.TrieState.Types (CompleteFromCreate (..))
import Singular.Registry.TxBuilder.Internal (emptyRoot, walkEdge)
import Singular.Registry.Types (edgeInsertActive, edgeUpdateTerminal)
import Singular.State.Preimage (stateTokenName)
import Singular.State.Records
    ( Change (..)
    , decodeFoldRedeemer
    , decodeGenesisRedeemer
    , decodeStateDatum
    )

-- | A replay that reached the selected state output from the genesis.
data Replayed = Replayed
    { Replayed -> TxIn
replayedSeed :: TxIn
    -- ^ The seed the genesis spent
    , Replayed -> TxId
replayedGenesis :: TxId
    , Replayed -> [TxId]
replayedFolds :: [TxId]
    -- ^ Every fold from the genesis to the selected output, in chain order
    , Replayed -> [ByteString]
replayedKeys :: [ByteString]
    -- ^ The distinct keys the folds registered, ascending
    }
    deriving stock (Replayed -> Replayed -> Bool
(Replayed -> Replayed -> Bool)
-> (Replayed -> Replayed -> Bool) -> Eq Replayed
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Replayed -> Replayed -> Bool
== :: Replayed -> Replayed -> Bool
$c/= :: Replayed -> Replayed -> Bool
/= :: Replayed -> Replayed -> Bool
Eq, Int -> Replayed -> ShowS
[Replayed] -> ShowS
Replayed -> String
(Int -> Replayed -> ShowS)
-> (Replayed -> String) -> ([Replayed] -> ShowS) -> Show Replayed
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Replayed -> ShowS
showsPrec :: Int -> Replayed -> ShowS
$cshow :: Replayed -> String
show :: Replayed -> String
$cshowList :: [Replayed] -> ShowS
showList :: [Replayed] -> ShowS
Show)

{- | Rebuild the registry's trie from the history of its state token up to the
selected state output, and check every root on the way against the root the
chain recorded.
-}
replayRegistry
    :: (Monad m)
    => Session w m
    -> TrieSelection
    -> m (Either TrieFailure (Replayed, MPFInMemoryDB))
replayRegistry :: forall (m :: * -> *) w.
Monad m =>
Session w m
-> TrieSelection
-> m (Either TrieFailure (Replayed, MPFInMemoryDB))
replayRegistry Session w m
session TrieSelection
selection
    | StatePoint -> SessionId
pointSession StatePoint
point SessionId -> SessionId -> Bool
forall a. Eq a => a -> a -> Bool
/= Session w m -> SessionId
forall w (m :: * -> *). Session w m -> SessionId
sessionId Session w m
session
        Bool -> Bool -> Bool
|| StatePoint -> SessionBinding
pointBinding StatePoint
point SessionBinding -> SessionBinding -> Bool
forall a. Eq a => a -> a -> Bool
/= Session w m -> SessionBinding
forall w (m :: * -> *). Session w m -> SessionBinding
sessionBinding Session w m
session =
        Either TrieFailure (Replayed, MPFInMemoryDB)
-> m (Either TrieFailure (Replayed, MPFInMemoryDB))
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TrieFailure -> Either TrieFailure (Replayed, MPFInMemoryDB)
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Staleness -> TrieFailure
StaleState RegistryIdentity
who Maybe TxId
forall a. Maybe a
Nothing Staleness
NoSelection))
    | Bool
otherwise = do
        history <- Session w m
-> RegistryIdentity
-> m (Either TrieFailure (Map TxIn (TxOut ConwayEra), [ConwayTx]))
forall (m :: * -> *) w.
Monad m =>
Session w m
-> RegistryIdentity
-> m (Either TrieFailure (Map TxIn (TxOut ConwayEra), [ConwayTx]))
publicHistory Session w m
session RegistryIdentity
who
        pure (history >>= walk who selection . snd)
  where
    who :: RegistryIdentity
who = TrieSelection -> RegistryIdentity
trieSelectionIdentity TrieSelection
selection
    point :: StatePoint
point = TrieSelection -> StatePoint
trieSelectionPoint TrieSelection
selection

-- | The registry's trie as a capability, for the registries of this line.
registryTrieState :: (Monad m) => Session w m -> TrieState m
registryTrieState :: forall (m :: * -> *) w. Monad m => Session w m -> TrieState m
registryTrieState Session w m
session =
    TrieState
        { withTrieState :: forall a.
TrieSelection
-> (TrieSnapshot m -> m a) -> m (Either TrieFailure a)
withTrieState = \TrieSelection
selection TrieSnapshot m -> m a
use ->
            Session w m
-> TrieSelection
-> m (Either TrieFailure (Replayed, MPFInMemoryDB))
forall (m :: * -> *) w.
Monad m =>
Session w m
-> TrieSelection
-> m (Either TrieFailure (Replayed, MPFInMemoryDB))
replayRegistry Session w m
session TrieSelection
selection m (Either TrieFailure (Replayed, MPFInMemoryDB))
-> (Either TrieFailure (Replayed, MPFInMemoryDB)
    -> m (Either TrieFailure a))
-> m (Either TrieFailure a)
forall a b. m a -> (a -> m b) -> m b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                Left TrieFailure
failure -> Either TrieFailure a -> m (Either TrieFailure a)
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TrieFailure -> Either TrieFailure a
forall a b. a -> Either a b
Left TrieFailure
failure)
                Right (Replayed
replayed, MPFInMemoryDB
nodes) ->
                    a -> Either TrieFailure a
forall a b. b -> Either a b
Right
                        (a -> Either TrieFailure a) -> m a -> m (Either TrieFailure a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TrieSnapshot m -> m a
use
                            ( (TrieObservation -> m ())
-> TrieSelection
-> MPFInMemoryDB
-> CompleteFromCreate
-> Maybe PublicLineage
-> TrieSnapshot m
forall (m :: * -> *).
Monad m =>
(TrieObservation -> m ())
-> TrieSelection
-> MPFInMemoryDB
-> CompleteFromCreate
-> Maybe PublicLineage
-> TrieSnapshot m
snapshotObserved
                                (m () -> TrieObservation -> m ()
forall a b. a -> b -> a
const (() -> m ()
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()))
                                TrieSelection
selection
                                MPFInMemoryDB
nodes
                                (Int -> CompleteFromCreate
CompleteFromCreate ([TxId] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Replayed -> [TxId]
replayedFolds Replayed
replayed)))
                                (PublicLineage -> Maybe PublicLineage
forall a. a -> Maybe a
Just (Replayed -> PublicLineage
lineageOf Replayed
replayed))
                            )
        , acceptObservedFold :: ObservedFold -> m (Either TrieFailure ())
acceptObservedFold = \ObservedFold
_ -> Either TrieFailure () -> m (Either TrieFailure ())
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either TrieFailure ()
forall a b. b -> Either a b
Right ())
        }

lineageOf :: Replayed -> PublicLineage
lineageOf :: Replayed -> PublicLineage
lineageOf Replayed
replayed =
    TxId -> [TxId] -> [ByteString] -> PublicLineage
PublicLineage
        (Replayed -> TxId
replayedGenesis Replayed
replayed)
        (Replayed -> [TxId]
replayedFolds Replayed
replayed)
        (Replayed -> [ByteString]
replayedKeys Replayed
replayed)

-- | Where the walk stands: the current state output, its root, the trie and what was folded.
data Standing = Standing
    { Standing -> TxIn
standingOutput :: TxIn
    , Standing -> Root
standingRoot :: Root
    , Standing -> MPFInMemoryDB
standingNodes :: MPFInMemoryDB
    , Standing -> [TxId]
standingFolds :: [TxId]
    -- ^ Newest first
    , Standing -> Set ByteString
standingKeys :: Set.Set ByteString
    }

walk
    :: RegistryIdentity
    -> TrieSelection
    -> [ConwayTx]
    -> Either TrieFailure (Replayed, MPFInMemoryDB)
walk :: RegistryIdentity
-> TrieSelection
-> [ConwayTx]
-> Either TrieFailure (Replayed, MPFInMemoryDB)
walk RegistryIdentity
who TrieSelection
selection [ConwayTx]
transactions = do
    (genesis, later) <- case (ConwayTx -> Bool) -> [ConwayTx] -> ([ConwayTx], [ConwayTx])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (RegistryIdentity -> ConwayTx -> Bool
mintsToken RegistryIdentity
who) [ConwayTx]
valid of
        ([ConwayTx]
_, ConwayTx
created : [ConwayTx]
after) -> (ConwayTx, [ConwayTx]) -> Either TrieFailure (ConwayTx, [ConwayTx])
forall a b. b -> Either a b
Right (ConwayTx
created, [ConwayTx]
after)
        ([ConwayTx]
_, []) -> TrieFailure -> Either TrieFailure (ConwayTx, [ConwayTx])
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Incomplete -> TrieFailure
HistoryIncomplete RegistryIdentity
who Maybe TxId
forall a. Maybe a
Nothing Incomplete
MissingTransaction)
    (seed, start) <- checkGenesis who genesis
    reached <- go seed start later
    let current = Standing -> TxIn
standingOutput Standing
reached
        TxIn selectedId (TxIx selectedIx) = selected
        isState =
            [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or
                [ RegistryIdentity -> TxOut ConwayEra -> Bool
holdsToken RegistryIdentity
who TxOut ConwayEra
BabbageTxOut ConwayEra
out
                | ConwayTx
tx <- [ConwayTx]
valid
                , ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx TxId -> TxId -> Bool
forall a. Eq a => a -> a -> Bool
== TxId
selectedId
                , BabbageTxOut ConwayEra
out <- Int -> [BabbageTxOut ConwayEra] -> [BabbageTxOut ConwayEra]
forall a. Int -> [a] -> [a]
take Int
1 (Int -> [BabbageTxOut ConwayEra] -> [BabbageTxOut ConwayEra]
forall a. Int -> [a] -> [a]
drop (Word16 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word16
selectedIx) (ConwayTx -> [TxOut ConwayEra]
outputsOf ConwayTx
tx))
                ]
    unless (current == selected) $
        Left
            ( if isState
                then StaleState who Nothing (StaleOutput selected current)
                else WrongRegistry who (Just selectedId) SelectionNotState
            )
    unless (standingRoot reached == trieSelectionRoot selection) $
        Left
            ( StaleState
                who
                Nothing
                (StaleRoot (trieSelectionRoot selection) (standingRoot reached))
            )
    pure
        ( Replayed
            { replayedSeed = seed
            , replayedGenesis = txIdTx genesis
            , replayedFolds = reverse (standingFolds reached)
            , replayedKeys = Set.toAscList (standingKeys reached)
            }
        , standingNodes reached
        )
  where
    selected :: TxIn
selected = StatePoint -> TxIn
pointOutput (TrieSelection -> StatePoint
trieSelectionPoint TrieSelection
selection)
    valid :: [ConwayTx]
valid = (ConwayTx -> Bool) -> [ConwayTx] -> [ConwayTx]
forall a. (a -> Bool) -> [a] -> [a]
filter (\ConwayTx
tx -> ConwayTx
tx ConwayTx -> Getting IsValid ConwayTx IsValid -> IsValid
forall s a. s -> Getting a s a -> a
^. Getting IsValid ConwayTx IsValid
forall era. AlonzoEraTx era => Lens' (Tx TopTx era) IsValid
Lens' ConwayTx IsValid
isValidTxL IsValid -> IsValid -> Bool
forall a. Eq a => a -> a -> Bool
== Bool -> IsValid
IsValid Bool
True) [ConwayTx]
transactions
    go :: TxIn -> Standing -> [ConwayTx] -> Either TrieFailure Standing
go TxIn
seed Standing
standing [ConwayTx]
remaining
        | Standing -> TxIn
standingOutput Standing
standing TxIn -> TxIn -> Bool
forall a. Eq a => a -> a -> Bool
== TxIn
selected = Standing -> Either TrieFailure Standing
forall a b. b -> Either a b
Right Standing
standing
        | Bool
otherwise = case [ConwayTx]
remaining of
            [] -> Standing -> Either TrieFailure Standing
forall a b. b -> Either a b
Right Standing
standing
            ConwayTx
tx : [ConwayTx]
more
                | Standing -> TxIn
standingOutput Standing
standing TxIn -> [TxIn] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ConwayTx -> [TxIn]
spendingInputs ConwayTx
tx ->
                    RegistryIdentity
-> TxIn -> Standing -> ConwayTx -> Either TrieFailure Standing
foldStep RegistryIdentity
who TxIn
seed Standing
standing ConwayTx
tx Either TrieFailure Standing
-> (Standing -> Either TrieFailure Standing)
-> Either TrieFailure Standing
forall a b.
Either TrieFailure a
-> (a -> Either TrieFailure b) -> Either TrieFailure b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Standing
next -> TxIn -> Standing -> [ConwayTx] -> Either TrieFailure Standing
go TxIn
seed Standing
next [ConwayTx]
more
                | RegistryIdentity -> ConwayTx -> Bool
touchesToken RegistryIdentity
who ConwayTx
tx ->
                    TrieFailure -> Either TrieFailure Standing
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Incomplete -> TrieFailure
HistoryIncomplete RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just (ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx)) Incomplete
OutsideLineage)
                | Bool
otherwise -> TxIn -> Standing -> [ConwayTx] -> Either TrieFailure Standing
go TxIn
seed Standing
standing [ConwayTx]
more

-- | The genesis: the seed it names and the state it leaves.
checkGenesis
    :: RegistryIdentity -> ConwayTx -> Either TrieFailure (TxIn, Standing)
checkGenesis :: RegistryIdentity -> ConwayTx -> Either TrieFailure (TxIn, Standing)
checkGenesis who :: RegistryIdentity
who@(RegistryIdentity StatePolicyId
_ AssetName
name) ConwayTx
tx = do
    policy <-
        Either TrieFailure PolicyID
-> (PolicyID -> Either TrieFailure PolicyID)
-> Maybe PolicyID
-> Either TrieFailure PolicyID
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
            (TrieFailure -> Either TrieFailure PolicyID
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Mismatch -> TrieFailure
WrongRegistry RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just TxId
tid) Mismatch
UnknownRegistry))
            PolicyID -> Either TrieFailure PolicyID
forall a b. b -> Either a b
Right
            (RegistryIdentity -> Maybe PolicyID
policyOf RegistryIdentity
who)
    let MultiAsset minted = tx ^. bodyTxL . mintTxBodyL
        quantity =
            Integer -> AssetName -> Map AssetName Integer -> Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault
                Integer
0
                AssetName
name
                (Map AssetName Integer
-> PolicyID
-> Map PolicyID (Map AssetName Integer)
-> Map AssetName Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map AssetName Integer
forall k a. Map k a
Map.empty PolicyID
policy Map PolicyID (Map AssetName Integer)
minted)
    unless (quantity == 1) $
        Left (WrongRegistry who (Just tid) CreateMint)
    policyIx <-
        maybe
            (Left (WrongRegistry who (Just tid) CreateMint))
            Right
            (elemIndex policy (Map.keys minted))
    datum <-
        maybe
            (Left (UndecodableRequest who (Just tid) MissingRedeemer))
            Right
            (redeemerAt (ConwayMinting (AsIx (fromIntegral policyIx))) tx)
    seed <-
        maybe
            ( Left
                ( UndecodableRequest
                    who
                    (Just tid)
                    (UnreadableRecord "the mint redeemer is not a genesis")
                )
            )
            Right
            (decodeGenesisRedeemer datum)
    unless (seed `elem` spendingInputs tx) $
        Left (WrongRegistry who (Just tid) SeedNotSpent)
    unless (stateTokenName seed == name) $
        Left (WrongRegistry who (Just tid) SeedName)
    (output, root, address) <- stateOutput who tx
    unless (isStateAddress policy address) $
        Left (WrongRegistry who (Just tid) CreateOutput)
    unless (root == emptyRoot) $
        Left
            ( RootDoesNotChain
                who
                (Just tid)
                (RootsPart (Root emptyRoot) (Root root))
            )
    pure
        ( seed
        , Standing output (Root root) emptyMPFInMemoryDB [] Set.empty
        )
  where
    tid :: TxId
tid = ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx

-- | One fold: the redeemer of the state input, the keys it registers, the new state output.
foldStep
    :: RegistryIdentity
    -> TxIn
    -> Standing
    -> ConwayTx
    -> Either TrieFailure Standing
foldStep :: RegistryIdentity
-> TxIn -> Standing -> ConwayTx -> Either TrieFailure Standing
foldStep RegistryIdentity
who TxIn
seed Standing
standing ConwayTx
tx = do
    let tid :: TxId
tid = ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx
        undecodable :: Undecodable -> Either TrieFailure b
undecodable = TrieFailure -> Either TrieFailure b
forall a b. a -> Either a b
Left (TrieFailure -> Either TrieFailure b)
-> (Undecodable -> TrieFailure)
-> Undecodable
-> Either TrieFailure b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RegistryIdentity -> Maybe TxId -> Undecodable -> TrieFailure
UndecodableRequest RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just TxId
tid)
    index <-
        Either TrieFailure Int
-> (Int -> Either TrieFailure Int)
-> Maybe Int
-> Either TrieFailure Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
            (TrieFailure -> Either TrieFailure Int
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Incomplete -> TrieFailure
HistoryIncomplete RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just TxId
tid) Incomplete
NoStateInput))
            Int -> Either TrieFailure Int
forall a b. b -> Either a b
Right
            (TxIn -> [TxIn] -> Maybe Int
forall a. Eq a => a -> [a] -> Maybe Int
elemIndex (Standing -> TxIn
standingOutput Standing
standing) (ConwayTx -> [TxIn]
spendingInputs ConwayTx
tx))
    datum <-
        maybe
            (undecodable MissingRedeemer)
            Right
            (redeemerAt (ConwaySpending (AsIx (fromIntegral index))) tx)
    (named, changes) <-
        maybe
            (undecodable (UnreadableRecord "the spend redeemer is not a fold"))
            Right
            (decodeFoldRedeemer datum)
    unless (named == seed) $ Left (WrongRegistry who (Just tid) SeedName)
    let edges = (Change -> (ByteString, Integer))
-> [Change] -> [(ByteString, Integer)]
forall a b. (a -> b) -> [a] -> [b]
map Change -> (ByteString, Integer)
changed [Change]
changes
        keys = ((ByteString, Integer) -> ByteString)
-> [(ByteString, Integer)] -> [ByteString]
forall a b. (a -> b) -> [a] -> [b]
map (ByteString, Integer) -> ByteString
forall a b. (a, b) -> a
fst [(ByteString, Integer)]
edges
    (output, root, _) <- stateOutput who tx
    let nodes = (MPFInMemoryDB -> (ByteString, Integer) -> MPFInMemoryDB)
-> MPFInMemoryDB -> [(ByteString, Integer)] -> MPFInMemoryDB
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl MPFInMemoryDB -> (ByteString, Integer) -> MPFInMemoryDB
applyEdge (Standing -> MPFInMemoryDB
standingNodes Standing
standing) [(ByteString, Integer)]
edges
        rebuilt = MPFInMemoryDB -> Root
rootFromDb MPFInMemoryDB
nodes
    when (rebuilt /= Root root) $
        Left (RootDoesNotChain who (Just tid) (RootsPart rebuilt (Root root)))
    pure
        Standing
            { standingOutput = output
            , standingRoot = Root root
            , standingNodes = nodes
            , standingFolds = tid : standingFolds standing
            , standingKeys = foldr Set.insert (standingKeys standing) keys
            }
  where
    changed :: Change -> (ByteString, Integer)
changed = \case
        Register{ByteString
changeKey :: ByteString
changeKey :: Change -> ByteString
changeKey} -> (ByteString
changeKey, Integer
edgeInsertActive)
        Terminate{ByteString
changeKey :: Change -> ByteString
changeKey :: ByteString
changeKey} -> (ByteString
changeKey, Integer
edgeUpdateTerminal)
    applyEdge :: MPFInMemoryDB -> (ByteString, Integer) -> MPFInMemoryDB
applyEdge MPFInMemoryDB
nodes (ByteString
key, Integer
edge) =
        State MPFInMemoryDB [ProofStep] -> MPFInMemoryDB -> MPFInMemoryDB
forall s a. State s a -> s -> s
execState (Trie (StateT MPFInMemoryDB Identity)
-> ByteString -> Integer -> State MPFInMemoryDB [ProofStep]
forall (m :: * -> *).
Monad m =>
Trie m -> ByteString -> Integer -> m [ProofStep]
walkEdge Trie (StateT MPFInMemoryDB Identity)
stateTrie ByteString
key Integer
edge) MPFInMemoryDB
nodes

{- | The one output of the transaction that holds the state token, with the
root its inline datum carries and the address it sits at.
-}
stateOutput
    :: RegistryIdentity
    -> ConwayTx
    -> Either TrieFailure (TxIn, ByteString, Addr)
stateOutput :: RegistryIdentity
-> ConwayTx -> Either TrieFailure (TxIn, ByteString, Addr)
stateOutput RegistryIdentity
who ConwayTx
tx = case [(Word16, BabbageTxOut ConwayEra)]
holders of
    [(Word16
ix, BabbageTxOut ConwayEra
out)] -> do
        root <-
            Either TrieFailure ByteString
-> (ByteString -> Either TrieFailure ByteString)
-> Maybe ByteString
-> Either TrieFailure ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
                (TrieFailure -> Either TrieFailure ByteString
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Undecodable -> TrieFailure
UndecodableRequest RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just TxId
tid) Undecodable
UndecodableStateOutput))
                ByteString -> Either TrieFailure ByteString
forall a b. b -> Either a b
Right
                (TxOut ConwayEra -> Maybe Data
inlineDatum TxOut ConwayEra
BabbageTxOut ConwayEra
out 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)
        pure (TxIn tid (TxIx ix), root, out ^. addrTxOutL)
    [(Word16, BabbageTxOut ConwayEra)]
_ -> TrieFailure -> Either TrieFailure (TxIn, ByteString, Addr)
forall a b. a -> Either a b
Left (RegistryIdentity -> Maybe TxId -> Undecodable -> TrieFailure
UndecodableRequest RegistryIdentity
who (TxId -> Maybe TxId
forall a. a -> Maybe a
Just TxId
tid) Undecodable
UndecodableStateOutput)
  where
    tid :: TxId
tid = ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx
    holders :: [(Word16, BabbageTxOut ConwayEra)]
holders =
        [ (Word16
ix, BabbageTxOut ConwayEra
out)
        | (Word16
ix, BabbageTxOut ConwayEra
out) <- [Word16]
-> [BabbageTxOut ConwayEra] -> [(Word16, BabbageTxOut ConwayEra)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Word16
0 ..] (ConwayTx -> [TxOut ConwayEra]
outputsOf ConwayTx
tx)
        , RegistryIdentity -> TxOut ConwayEra -> Bool
holdsToken RegistryIdentity
who TxOut ConwayEra
BabbageTxOut ConwayEra
out
        ]

-- | The inline datum of an output.
inlineDatum :: TxOut ConwayEra -> Maybe PLC.Data
inlineDatum :: TxOut ConwayEra -> Maybe Data
inlineDatum TxOut ConwayEra
out = case TxOut ConwayEra
BabbageTxOut ConwayEra
out 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 -> Data -> Maybe Data
forall a. a -> Maybe a
Just (Data ConwayEra -> Data
forall era. Data era -> Data
getPlutusData (BinaryData ConwayEra -> Data ConwayEra
forall era. Era era => BinaryData era -> Data era
binaryDataToData BinaryData ConwayEra
binary))
    Datum ConwayEra
_ -> Maybe Data
forall a. Maybe a
Nothing

-- | Whether the address is the one of the state script of this policy.
isStateAddress :: PolicyID -> Addr -> Bool
isStateAddress :: PolicyID -> Addr -> Bool
isStateAddress (PolicyID ScriptHash
hash) = \case
    Addr Network
_ (ScriptHashObj ScriptHash
h) StakeReference
_ -> ScriptHash
h ScriptHash -> ScriptHash -> Bool
forall a. Eq a => a -> a -> Bool
== ScriptHash
hash
    Addr
_ -> Bool
False

{- | The state token of a registry as a ledger asset, when its policy is a
script hash.
-}
registryAsset :: RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset :: RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset who :: RegistryIdentity
who@(RegistryIdentity StatePolicyId
_ AssetName
name) = (,AssetName
name) (PolicyID -> (PolicyID, AssetName))
-> Maybe PolicyID -> Maybe (PolicyID, AssetName)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> RegistryIdentity -> Maybe PolicyID
policyOf RegistryIdentity
who

policyOf :: RegistryIdentity -> Maybe PolicyID
policyOf :: RegistryIdentity -> Maybe PolicyID
policyOf (RegistryIdentity (StatePolicyId ByteString
bytes) AssetName
_) =
    ScriptHash -> PolicyID
PolicyID (ScriptHash -> PolicyID)
-> (Hash ADDRHASH EraIndependentScript -> ScriptHash)
-> Hash ADDRHASH EraIndependentScript
-> PolicyID
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Hash ADDRHASH EraIndependentScript -> ScriptHash
ScriptHash (Hash ADDRHASH EraIndependentScript -> PolicyID)
-> Maybe (Hash ADDRHASH EraIndependentScript) -> Maybe PolicyID
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> Maybe (Hash ADDRHASH EraIndependentScript)
forall h a. HashAlgorithm h => ByteString -> Maybe (Hash h a)
hashFromBytes ByteString
bytes

mintsToken :: RegistryIdentity -> ConwayTx -> Bool
mintsToken :: RegistryIdentity -> ConwayTx -> Bool
mintsToken RegistryIdentity
who ConwayTx
tx = case RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset RegistryIdentity
who of
    Maybe (PolicyID, AssetName)
Nothing -> Bool
False
    Just (PolicyID
policy, AssetName
name) ->
        let MultiAsset Map PolicyID (Map AssetName Integer)
minted = ConwayTx
tx ConwayTx -> Getting MultiAsset ConwayTx MultiAsset -> MultiAsset
forall s a. s -> Getting a s a -> a
^. (TxBody TopTx ConwayEra
 -> Const MultiAsset (TxBody TopTx ConwayEra))
-> ConwayTx -> Const MultiAsset ConwayTx
forall era (l :: TxLevel).
EraTx era =>
Lens' (Tx l era) (TxBody l era)
forall (l :: TxLevel). Lens' (Tx l ConwayEra) (TxBody l ConwayEra)
bodyTxL ((TxBody TopTx ConwayEra
  -> Const MultiAsset (TxBody TopTx ConwayEra))
 -> ConwayTx -> Const MultiAsset ConwayTx)
-> ((MultiAsset -> Const MultiAsset MultiAsset)
    -> TxBody TopTx ConwayEra
    -> Const MultiAsset (TxBody TopTx ConwayEra))
-> Getting MultiAsset ConwayTx MultiAsset
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (MultiAsset -> Const MultiAsset MultiAsset)
-> TxBody TopTx ConwayEra
-> Const MultiAsset (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
MaryEraTxBody era =>
Lens' (TxBody l era) MultiAsset
forall (l :: TxLevel). Lens' (TxBody l ConwayEra) MultiAsset
mintTxBodyL
        in  Integer -> AssetName -> Map AssetName Integer -> Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault
                Integer
0
                AssetName
name
                (Map AssetName Integer
-> PolicyID
-> Map PolicyID (Map AssetName Integer)
-> Map AssetName Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map AssetName Integer
forall k a. Map k a
Map.empty PolicyID
policy Map PolicyID (Map AssetName Integer)
minted)
                Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
/= Integer
0

holdsToken :: RegistryIdentity -> TxOut ConwayEra -> Bool
holdsToken :: RegistryIdentity -> TxOut ConwayEra -> Bool
holdsToken RegistryIdentity
who TxOut ConwayEra
out = case RegistryIdentity -> Maybe (PolicyID, AssetName)
registryAsset RegistryIdentity
who of
    Maybe (PolicyID, AssetName)
Nothing -> Bool
False
    Just (PolicyID
policy, AssetName
name) ->
        let MaryValue Coin
_ (MultiAsset Map PolicyID (Map AssetName Integer)
assets) = TxOut ConwayEra
BabbageTxOut ConwayEra
out 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  Integer -> AssetName -> Map AssetName Integer -> Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault
                Integer
0
                AssetName
name
                (Map AssetName Integer
-> PolicyID
-> Map PolicyID (Map AssetName Integer)
-> Map AssetName Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Map AssetName Integer
forall k a. Map k a
Map.empty PolicyID
policy Map PolicyID (Map AssetName Integer)
assets)
                Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
== Integer
1

touchesToken :: RegistryIdentity -> ConwayTx -> Bool
touchesToken :: RegistryIdentity -> ConwayTx -> Bool
touchesToken RegistryIdentity
who ConwayTx
tx = RegistryIdentity -> ConwayTx -> Bool
mintsToken RegistryIdentity
who ConwayTx
tx Bool -> Bool -> Bool
|| (BabbageTxOut ConwayEra -> Bool)
-> [BabbageTxOut ConwayEra] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (RegistryIdentity -> TxOut ConwayEra -> Bool
holdsToken RegistryIdentity
who) (ConwayTx -> [TxOut ConwayEra]
outputsOf ConwayTx
tx)

outputsOf :: ConwayTx -> [TxOut ConwayEra]
outputsOf :: ConwayTx -> [TxOut ConwayEra]
outputsOf ConwayTx
tx = StrictSeq (BabbageTxOut ConwayEra) -> [BabbageTxOut ConwayEra]
forall a. StrictSeq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (ConwayTx
tx ConwayTx
-> Getting
     (StrictSeq (BabbageTxOut ConwayEra))
     ConwayTx
     (StrictSeq (BabbageTxOut ConwayEra))
-> StrictSeq (BabbageTxOut ConwayEra)
forall s a. s -> Getting a s a -> a
^. (TxBody TopTx ConwayEra
 -> Const
      (StrictSeq (BabbageTxOut ConwayEra)) (TxBody TopTx ConwayEra))
-> ConwayTx -> Const (StrictSeq (BabbageTxOut ConwayEra)) ConwayTx
forall era (l :: TxLevel).
EraTx era =>
Lens' (Tx l era) (TxBody l era)
forall (l :: TxLevel). Lens' (Tx l ConwayEra) (TxBody l ConwayEra)
bodyTxL ((TxBody TopTx ConwayEra
  -> Const
       (StrictSeq (BabbageTxOut ConwayEra)) (TxBody TopTx ConwayEra))
 -> ConwayTx -> Const (StrictSeq (BabbageTxOut ConwayEra)) ConwayTx)
-> ((StrictSeq (BabbageTxOut ConwayEra)
     -> Const
          (StrictSeq (BabbageTxOut ConwayEra))
          (StrictSeq (BabbageTxOut ConwayEra)))
    -> TxBody TopTx ConwayEra
    -> Const
         (StrictSeq (BabbageTxOut ConwayEra)) (TxBody TopTx ConwayEra))
-> Getting
     (StrictSeq (BabbageTxOut ConwayEra))
     ConwayTx
     (StrictSeq (BabbageTxOut ConwayEra))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (StrictSeq (TxOut ConwayEra)
 -> Const
      (StrictSeq (BabbageTxOut ConwayEra)) (StrictSeq (TxOut ConwayEra)))
-> TxBody TopTx ConwayEra
-> Const
     (StrictSeq (BabbageTxOut ConwayEra)) (TxBody TopTx ConwayEra)
(StrictSeq (BabbageTxOut ConwayEra)
 -> Const
      (StrictSeq (BabbageTxOut ConwayEra))
      (StrictSeq (BabbageTxOut ConwayEra)))
-> TxBody TopTx ConwayEra
-> Const
     (StrictSeq (BabbageTxOut ConwayEra)) (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (StrictSeq (TxOut era))
forall (l :: TxLevel).
Lens' (TxBody l ConwayEra) (StrictSeq (TxOut ConwayEra))
outputsTxBodyL)

-- | The spending inputs in ledger order.
spendingInputs :: ConwayTx -> [TxIn]
spendingInputs :: ConwayTx -> [TxIn]
spendingInputs ConwayTx
tx = Set TxIn -> [TxIn]
forall a. Set a -> [a]
Set.toAscList (ConwayTx
tx ConwayTx -> Getting (Set TxIn) ConwayTx (Set TxIn) -> Set TxIn
forall s a. s -> Getting a s a -> a
^. (TxBody TopTx ConwayEra
 -> Const (Set TxIn) (TxBody TopTx ConwayEra))
-> ConwayTx -> Const (Set TxIn) ConwayTx
forall era (l :: TxLevel).
EraTx era =>
Lens' (Tx l era) (TxBody l era)
forall (l :: TxLevel). Lens' (Tx l ConwayEra) (TxBody l ConwayEra)
bodyTxL ((TxBody TopTx ConwayEra
  -> Const (Set TxIn) (TxBody TopTx ConwayEra))
 -> ConwayTx -> Const (Set TxIn) ConwayTx)
-> ((Set TxIn -> Const (Set TxIn) (Set TxIn))
    -> TxBody TopTx ConwayEra
    -> Const (Set TxIn) (TxBody TopTx ConwayEra))
-> Getting (Set TxIn) ConwayTx (Set TxIn)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Set TxIn -> Const (Set TxIn) (Set TxIn))
-> TxBody TopTx ConwayEra
-> Const (Set TxIn) (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (Set TxIn)
forall (l :: TxLevel). Lens' (TxBody l ConwayEra) (Set TxIn)
inputsTxBodyL)

-- | A redeemer of the transaction, as data.
redeemerAt
    :: ConwayPlutusPurpose AsIx ConwayEra -> ConwayTx -> Maybe PLC.Data
redeemerAt :: ConwayPlutusPurpose AsIx ConwayEra -> ConwayTx -> Maybe Data
redeemerAt ConwayPlutusPurpose AsIx ConwayEra
purpose ConwayTx
tx = do
    let Redeemers Map (PlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
declared = 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
    (datum, _) <- ConwayPlutusPurpose AsIx ConwayEra
-> Map
     (ConwayPlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
-> Maybe (Data ConwayEra, ExUnits)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ConwayPlutusPurpose AsIx ConwayEra
purpose Map (ConwayPlutusPurpose AsIx ConwayEra) (Data ConwayEra, ExUnits)
declared
    pure (getPlutusData datum)