convex-testing-interface
Safe HaskellSafe-Inferred
LanguageHaskell2010

Convex.ThreatModel.Cardano.Api

Synopsis

Types

TxOut accessors

datumOfTxOut :: TxOut ctx Era -> TxOutDatum ctx Era Source #

Get the datum from a transaction output.

Redeemer and script data

updateRedeemer :: Word32 -> (Data (ShelleyLedgerEra Era), ExUnits) -> TxBodyScriptData Era -> TxBodyScriptData Era Source #

Update only the redeemer for a spending input (does not modify TxDats) Use this when the original UTxO has an inline datum to avoid adding orphaned datums

addMintingRedeemer :: Word32 -> (Data (ShelleyLedgerEra Era), ExUnits) -> TxBodyScriptData Era -> TxBodyScriptData Era Source #

Add a minting redeemer to the script data (no datum needed for minting)

recomputeScriptDataForMint :: Maybe Word32 -> (Word32 -> Word32) -> TxBodyScriptData Era -> TxBodyScriptData Era Source #

Like recomputeScriptData but only updates minting redeemer indices

toMaryAssetName :: AssetName -> AssetName Source #

Convert cardano-api AssetName to ledger Mary.AssetName

Address utilities

scriptAddressAny :: ScriptHash -> AddressAny Source #

Construct a script address.

keyAddressAny :: Hash PaymentKey -> AddressAny Source #

Construct a public key address.

isKeyAddressAny :: AddressAny -> Bool Source #

Check if an address is a public key address.

Datum/Redeemer conversion

txOutDatum :: ScriptData -> TxOutDatum CtxTx Era Source #

Convert ScriptData to a Datum.

toScriptData :: ToData a => a -> ScriptData Source #

Convert a Haskell value to ScriptData for use as a Redeemer or convert to a Datum with txOutDatum.

Transaction utilities

dummyTxId :: TxId Source #

Used for new inputs.

detectSigningWallet :: Tx Era -> Either String Wallet Source #

Detect which mock wallet signed a transaction by examining its witnesses. Returns an error message if no known mock wallet is found among the signers.

txRequiredSigners :: Tx Era -> [Hash PaymentKey] Source #

Get the required signers from the transaction body (not witnesses).

Value utilities

leqValue :: Value -> Value -> Bool Source #

Check if a value is less or equal than another value.

projectAda :: Value -> Value Source #

Keep only the Ada part of a value.

Validation

validateTx :: LedgerProtocolParameters Era -> Tx Era -> UTxO Era -> ValidityReport Source #

Validate a transaction using Phase 2 (script execution) validation only.

This uses evaluateTransactionExecutionUnits to check if Plutus scripts would accept or reject the transaction. It does NOT validate Phase 1 ledger rules (fees, signatures, value preservation, etc.) because threat model modifications alter the transaction body, invalidating signatures and fee calculations.

The purpose of threat models is to test script logic, not transaction construction.

validateTxM :: MonadMockchain Era m => NodeParams Era -> Tx Era -> UTxO Era -> m (ValidityReport, CoverageData) Source #

Validate a transaction with full Phase 1 + Phase 2 validation inside MockchainT.

This uses applyTransaction which performs complete ledger validation including: - Fee adequacy - Signature verification - UTxO existence - Value preservation - Validity intervals - Collateral requirements - Script execution (Phase 2)

buildMockState :: NodeParams Era -> SlotNo -> UTxO Era -> MockChainState Era Source #

Build a MockChainState from NodeParams, slot, and UTxO for validation

Rebalancing

rebalanceAndSignM :: (MonadMockchain Era m, MonadFail m) => Wallet -> Tx Era -> UTxO Era -> m (Tx Era) Source #

Re-balance fees, recalculate execution units, and re-sign a modified transaction.

After applying TxModifier operations, the transaction body changes which: 1. Invalidates the original signatures (body hash changed) 2. May require different fees (outputs changed) 3. May have invalid execution units (for added scripts)

This function: 1. Recalculates execution units for all scripts 2. Calculates the new required fee 3. Adjusts the change output (last output to wallet address) to compensate 4. Re-signs the transaction with the wallet's key

rebalanceAndSign :: MonadMockchain Era m => Wallet -> Tx Era -> UTxO Era -> m (Either String (Tx Era)) Source #

Like rebalanceAndSign but returns Either instead of using MonadFail.

This is useful for threat model execution where we want to handle rebalancing failures (e.g., "No change output found") as skipped tests rather than errors.

updateExecutionUnits :: LedgerProtocolParameters Era -> SystemStart -> EraHistory -> UTxO Era -> Tx Era -> Tx Era Source #

Update execution units in a transaction by evaluating all scripts.

This computes the actual execution units required for each script and updates the redeemers in the transaction with those values. This is necessary because TxModifier operations like addPlutusScriptMint use ExecutionUnits 0 0 as placeholders.

updateTxRedeemersWithExUnits :: Map ScriptWitnessIndex ExecutionUnits -> Tx Era -> Tx Era Source #

Update the execution units in a transaction's redeemers.

This function takes a map from ScriptWitnessIndex to ExecutionUnits and updates the corresponding redeemers in the transaction.

updateScriptDataExUnits :: Map ScriptWitnessIndex ExecutionUnits -> TxBodyScriptData Era -> TxBodyScriptData Era Source #

Update execution units in TxBodyScriptData based on ScriptWitnessIndex map.

recalculateScriptIntegrityHash :: LedgerProtocolParameters Era -> Tx Era -> Tx Era Source #

Recalculate and update the script integrity hash in a transaction.

The script integrity hash commits to: - The redeemers in the transaction - The datums in the witness set - The cost models for languages used (from protocol parameters)

After modifying a transaction (addingremoving inputs, changing redeemersdatums), this hash becomes stale and must be recalculated.

recalculateTotalCollateral :: LedgerProtocolParameters Era -> UTxO Era -> Tx Era -> Either String (Tx Era) Source #

Recalculate the total collateral and collateral return based on the new fee.

Total collateral = ceiling(fee * collateralPercentage / 100) Collateral return = collateral input value - total collateral

This is needed because cardano-ledger is strict about collateral matching the fee. When the fee increases (e.g., due to bloated datum), we need to: 1. Increase the total collateral field 2. Decrease the collateral return (to provide more collateral)

Returns Left if the collateral inputs don't have enough value to cover the required collateral. This can happen when a TxModifier significantly increases the transaction size (and thus the fee) - the original collateral may no longer be sufficient.

getScriptLanguage :: AlonzoScript LedgerEra -> Maybe Language Source #

Extract the Plutus language from a ledger script, if it's a Plutus script

getTxFeeCoin :: Tx Era -> Coin Source #

Get the fee from a transaction

setTxFeeCoin :: Coin -> Tx Era -> Tx Era Source #

Set the fee in a transaction

setTxOutputsList :: [TxOut CtxTx Era] -> Tx Era -> Tx Era Source #

Set transaction outputs (helper that works at the Tx level)

adjustChangeOutputM Source #

Arguments

:: MonadFail m 
=> AddressInEra Era

Wallet address to find change output

-> Coin

Fee difference (positive = fee increased)

-> [TxOut CtxTx Era]

Transaction outputs

-> m [TxOut CtxTx Era] 

Adjust the last output going to wallet address by fee difference.

If fee increased, we subtract from the change output. If fee decreased, we add to the change output.

adjustChangeOutput Source #

Arguments

:: AddressInEra Era

Wallet address to find change output

-> Coin

Fee difference (positive = fee increased)

-> [TxOut CtxTx Era]

Transaction outputs

-> Either String [TxOut CtxTx Era] 

Like adjustChangeOutput but returns Either instead of using MonadFail.

replaceAt :: Int -> a -> [a] -> [a] Source #

Replace element at index in a list

Validity interval

UTxO utilities

restrictUTxO :: Tx Era -> UTxO Era -> UTxO Era Source #

Keep only UTxOs mentioned in the given transaction.

Coverage

extractCoverageFromValidationError :: String -> CoverageData Source #

Extract coverage data from a ValidationError string containing CovLoc annotations. Handles the format found in Phase2 script evaluation errors where coverage annotations appear as "CoverLocation (CovLoc {...})" or "CoverBool (CovLoc {...}) Bool"

unescapeHaskellString :: String -> String Source #

Unescape common Haskell string escapes (backslash-quote to quote, backslash-backslash to backslash)

extractCoverageAnnotations :: String -> [String] Source #

Extract all "CoverLocation (...)" and "CoverBool (...)" substrings from text. Uses bracket counting to properly match nested parentheses.