singular-registry
LicenseApache-2.0
Safe HaskellNone
LanguageGHC2021

Singular.Registry.TxBuilder.Internal

Description

Utility functions shared across the per-operation transaction builders (Boot, Request, Update, Retract, End). Covers script construction, datum/redeemer encoding, address manipulation, UTxO lookup, spending-index computation, execution-unit defaults, and POSIX-to-slot conversion.

This module is the public compatibility facade: it holds no implementations of its own and re-exports the focused owners Singular.Registry.TxBuilder.Internal.Identity (identity and conversion), ...Internal.Lookup (lookup and balance) and ...Internal.Edges (edges and binding).

Synopsis

Script construction

mkCageScript :: CageConfig -> Script ConwayEra Source #

Build the cage Script from config bytes.

mkRequestScript :: CageConfig -> TokenId -> Script ConwayEra Source #

Build the per-cage request Script from config bytes.

scriptFromBytes :: String -> ShortByteString -> Script ConwayEra Source #

scriptHashBytes :: ScriptHash -> ByteString Source #

computeScriptHash :: ShortByteString -> ScriptHash Source #

Compute the ScriptHash from raw script bytes.

Registry-mode edges (#157 seven-admitted-edges)

leafAbsent :: ByteString Source #

The three leaf states the registry admits (#157 three-state-leaf-codec). Requests carry an edge, not a value, so these are no longer something a builder chooses: they are the bytes each edge's trie move reads and writes, and walkEdge below is the one place that pairs them with their edge.

leafActive :: ByteString Source #

The three leaf states the registry admits (#157 three-state-leaf-codec). Requests carry an edge, not a value, so these are no longer something a builder chooses: they are the bytes each edge's trie move reads and writes, and walkEdge below is the one place that pairs them with their edge.

leafTerminal :: ByteString Source #

The three leaf states the registry admits (#157 three-state-leaf-codec). Requests carry an edge, not a value, so these are no longer something a builder chooses: they are the bytes each edge's trie move reads and writes, and walkEdge below is the one place that pairs them with their edge.

walkEdge :: Monad m => Trie m -> ByteString -> Edge -> m [ProofStep] Source #

Walk one request's edge through a speculative trie and return the proof steps the fold states for it (#183).

The edge names the move and its leaf bytes, from the table `types.ak` publishes. The proof is the one the cage verifies at this request's own position in the batch, so it is read BEFORE a replacement and AFTER an insert, exactly as the cage's own walk does.

A tag outside the table names no move: the cage refuses it `edge-inadmissible` before touching the trie, so the builder walks nothing either and states the proof the refusal will be judged against. All five excluded encodings leave the local trie unchanged for refusal fixtures.

One site, so the connected fold and the update builder cannot drift apart about what an edge does to the trie.

policyIdFromPin :: ShortByteString -> PolicyID Source #

The policy id a 28-byte pin names. The four pins the state datum carries are raw script hashes; this is the one place that turns one back into the ledger's own type.

addrFromBytes :: ByteString -> Maybe Addr Source #

The address a request's binary destination names (#157 request-destination-binding). The bytes are a full Cardano address, network byte and all, so nothing here supplies a network of its own.

deltaOf :: Integer -> [(Integer, Integer)] Source #

What a supported edge owes the mint, as (kind, quantity). Registration mints one active token (kind 1); retirement burns one.

policyOfKind :: CageConfig -> Integer -> ShortByteString Source #

The policy a kind names in this registry's configuration.

approvalName Source #

Arguments

:: Integer 
-> ByteString

Registry key

-> ByteString

Owner (the payment key hash the approval binds)

-> (ByteString, ByteString)

Destination: address bytes and datum hash

-> ByteString 

The approval binding (#157 approval-asset-binding): the asset name the application policy mints to certify one edge, blake2b_256(edge ‖ key ‖ owner ‖ destination address ‖ destination datum hash). One formula, recomputed by the cage from the request it rides; a builder that computes it differently makes an honest booking refuse loudly at the fold.

approvalDestination :: (ByteString, Maybe Data) -> (ByteString, ByteString) Source #

A request's destination as approvalName binds it.

destinationDatumHash :: Maybe Data -> ByteString Source #

The hash an approval binds for the datum a request carries (#419): the BLAKE2b-256 of the datum's serialisation, empty for none — the bytes the request named before it carried the datum, so an approval's name is unchanged for the same tuple.

Derived identity

cagePolicyIdFromCfg :: CageConfig -> PolicyID Source #

Compute the cage minting policy ID from config.

cageAddrFromCfg :: CageConfig -> Network -> Addr Source #

Compute the cage script address from config.

requestAddrFromCfg :: CageConfig -> TokenId -> Network -> Addr Source #

Compute the request script address for a token.

onChainTokenId :: TokenId -> OnChainTokenId Source #

Convert a ledger token id to its on-chain token id.

Datum helpers

mkRequestDatum Source #

Arguments

:: TokenId 
-> Addr 
-> ByteString 
-> Edge

The seven-admitted-edges row index the request names

-> Integer

The deposit the request rides with, over and above the tip

-> Integer 
-> Data 

Build a CageDatum for a request at one seven-admitted-edges edge (#183).

mkRequestDatumWith Source #

Arguments

:: TokenId 
-> Addr 
-> ByteString 
-> Edge

The seven-admitted-edges row index the request names

-> Integer

The deposit the request rides with, over and above the tip

-> Integer 
-> (ByteString, Maybe Data) 
-> Data 

A request datum naming where the edge it books delivers (#157 request-destination-binding) and carrying the datum the delivered output must hold (#419). The cage reads the destination for every edge that mints an active or terminal token, and the approval that certifies the edge binds the address and the hash of that datum, so the booking and the fold cannot disagree about where the token goes or what it carries.

toPlcData :: ToData a => a -> Data Source #

Convert a ToData value to Data.

toLedgerData :: ToData a => a -> Data ConwayEra Source #

Convert a ToData value to a ledger Data.

mkInlineDatum :: Data -> Datum ConwayEra Source #

Wrap Data as an inline Datum.

extractCageDatum :: TxOut ConwayEra -> Maybe CageDatum Source #

Extract a CageDatum from an inline datum in a TxOut.

Reference conversion

txInToRef :: TxIn -> OnChainTxOutRef Source #

Convert a ledger TxIn to an on-chain OnChainTxOutRef.

addrKeyHashBytes :: Addr -> ByteString Source #

Extract the payment key hash raw bytes from an Addr.

addrFromKeyHashBytes :: Network -> ByteString -> Addr Source #

Reconstruct an Addr from raw payment key hash bytes.

addrWitnessKeyHash :: ByteString -> KeyHash 'Guard Source #

Extract a KeyHash 'Witness from raw payment key hash bytes.

UTxO lookup

findUtxoByTxIn :: TxIn -> [(TxIn, TxOut ConwayEra)] -> Maybe (TxIn, TxOut ConwayEra) Source #

Find a UTxO by its TxIn.

findStateUtxo :: PolicyID -> TokenId -> [(TxIn, TxOut ConwayEra)] -> Maybe (TxIn, TxOut ConwayEra) Source #

Find the state UTxO for a token.

findRequestUtxos :: TokenId -> [(TxIn, TxOut ConwayEra)] -> [(TxIn, TxOut ConwayEra)] Source #

Find all request UTxOs for a token.

Indexing

spendingIndex :: TxIn -> Set TxIn -> Word32 Source #

Compute the spending index of a TxIn.

Script integrity

computeScriptIntegrity :: PParams ConwayEra -> Redeemers ConwayEra -> StrictMaybe ScriptIntegrityHash Source #

Compute the ScriptIntegrityHash.

Evaluate and balance

evaluateAndBalance Source #

Arguments

:: Session NoWitness IO 
-> PParams ConwayEra 
-> [(TxIn, TxOut ConwayEra)]

All input UTxOs (fee + script)

-> Addr

Change address

-> ConwayTx

Unbalanced tx with placeholder ExUnits

-> IO ConwayTx 

Evaluate script execution units and balance a transaction.

evaluateAndBalanceReferencing Source #

Arguments

:: Session NoWitness IO 
-> PParams ConwayEra 
-> [(TxIn, TxOut ConwayEra)]

All input UTxOs (fee + script)

-> [(TxIn, TxOut ConwayEra)]

The resolved reference outputs

-> Addr

Change address

-> ConwayTx

Unbalanced tx with placeholder ExUnits

-> IO ConwayTx 

evaluateAndBalance for a transaction that reads scripts from reference outputs (#300): the resolved outputs are handed to the balancer, which charges the ledger's per-byte tier for every reference-script byte the transaction references, exactly as the node will.

placeholderExUnits :: ExUnits Source #

Placeholder execution units used in the initial unbalanced transaction.

Constants

emptyRoot :: ByteString Source #

Empty MPF root (32 zero bytes).

Time and slot helpers

currentPosixMs :: IO Integer Source #

Get current POSIX time in milliseconds.

trySlots :: Session NoWitness IO -> [Integer] -> IO SlotNo Source #

Try converting successive POSIX ms values to slots, returning the first that succeeds.

tryUpperSlots :: Session NoWitness IO -> [Integer] -> IO SlotNo Source #

Try converting successive POSIX ms values to slots, rounding down, and return the first that succeeds: an upper validity bound.

trySlots rounds up, which is right for a lower bound but not for an upper one. Rounding down never puts the upper bound later than its chosen POSIX candidate. NOTE030 opens the pinned final era, preserving this rounding rule and the caller's candidate windows. Synchronous conversion failures still try the next candidate; cancellation escapes.

trySync :: IO a -> IO (Either SomeException a) Source #

Run an action, returning its synchronous failure; an asynchronous exception — a cancellation, a timeout — is rethrown, never taken for a conversion that failed and so never answered by a fallback.

Request helpers

extractOwnerBytes :: TxOut ConwayEra -> ByteString Source #

Extract the owner key hash bytes from a request TxOut.

Refund computation

computeRefund :: PParams ConwayEra -> Network -> Integer -> TxOut ConwayEra -> TxOut ConwayEra Source #

Compute a rejected row's refund output (NOTE-014 item A2, delegated routing): exactly `input lovelace − tip`, floored at min-UTxO with the top-up funded visibly. No fee share is deducted here and none is invented (fees ride funding inputs; the validator pins per-owner floors and exact lock accumulation instead of an aggregate envelope). THE shared helper for every rejected-refund emission — Reject and manual paths call it; processed rows emit no refunds at all (their bond locks).

Pinned-hook invocation (NOTE-021)

pinScriptHash :: ByteString -> ScriptHash Source #

The consumer pin as a ledger ScriptHash. Loud on bad width (the mint gate enforces 28 bytes on chain; this mirrors it builder-side so a misconfigured pin fails at build, not on ledger).

hookAccountAddress :: Network -> ByteString -> AccountAddress Source #

The withdrawal account for the pinned consumer: the exact script credential from the pin, on the cage's network.

keyAccountAddress :: Network -> ByteString -> AccountAddress Source #

A key-hash withdrawal account (exhibit controls only): lets a row point a withdrawal at an ordinary key, where no script executes and only the cage's own credential check can refuse. Loud on bad width, like the pin helper above.

data ConsumerBinding Source #

The bound exhibit consumer, unparameterized (NOTE-021): no operator key, no appointed processor — the consumer authenticates batches from transaction evidence alone. One derivation, used for boot pinning, builder witnesses, and identity checks — never separate computations that could disagree.

Constructors

ConsumerBinding 

Fields

mkConsumerScript :: CageConfig -> Script ConwayEra Source #

Build the bound consumer Script from config bytes (mirror of mkCageScript). Builders attach this as the hook withdrawal witness.

Failure attribution (NOTE-023)

failedWitnessHash :: String -> Maybe String Source #

Parse the node's named failed-witness field (The script hash is:ScriptHash HEX) and return the hash — the FIRST occurrence, which names the failing script (later occurrences repeat the same failure's context). Anchored on the opening quote (hash letters also occur in ScriptHash itself, so a hex scan from the marker misfires). Length-checked to 56 hex chars (a 28-byte script hash) so partial garbage never matches. Nothing when the reason carries no named field (non-script failures: extraneous witnesses, unregistered withdrawals, balance errors).

evalScriptHash :: String -> Maybe String Source #

Parse a builder-EVALUATION failure's named script field (pwcScriptHash = ScriptHash HEX, first occurrence) and return the hash. NOTE-018 bind: fork-occupied assertions match THIS field against the derived applied identity — never a hex substring of the full ErrorCall show (transaction data, values and parameterized script bytes can all contain the state policy). Same 56-hex rule.

isBudgetFailure :: String -> Bool Source #

True when the refusal is budget exhaustion rather than a semantic predicate failure. Kept to the OBSERVED node wording (overspending the budget); unknown budget wordings fail closed elsewhere (no named semantic match), never silently accepted.