cometa (empty) → 0.2.0.0
raw patch · 450 files changed
+78079/−0 lines, 450 filesdep +aesondep +asyncdep +basebinary-added
Dependencies added: aeson, async, base, bech32, bytestring, cardano-c-clib, cborg, cometa, containers, crypton-x509, crypton-x509-store, crypton-x509-system, directory, hedgehog, http-client, http-client-tls, http-types, network, network-uri, scientific, stm, tasty, tasty-hedgehog, tasty-hunit, text, tls, transformers
This diff is very large; some files are shown as “too large to diff”. Download the raw patch for the complete diff.
Files
- .clang-format +72/−0
- .hlint.yaml +9/−0
- .readthedocs.yaml +14/−0
- AGENTS.md +81/−0
- CODING_CONVENTIONS.md +335/−0
- LICENSE +201/−0
- README.md +455/−0
- assets/cometa_hs.png binary
- benchmark/Main.hs +151/−0
- cbits/cometa_bip32.c +124/−0
- cbits/cometa_bip32.h +133/−0
- cbits/cometa_bip39.c +36/−0
- cbits/cometa_bip39.h +58/−0
- cbits/cometa_building.c +257/−0
- cbits/cometa_building.h +44/−0
- cbits/cometa_cbor.c +459/−0
- cbits/cometa_cbor.h +309/−0
- cbits/cometa_cip8.c +66/−0
- cbits/cometa_cip8.h +30/−0
- cbits/cometa_coin_selection.c +536/−0
- cbits/cometa_coin_selection.h +81/−0
- cbits/cometa_contextual_transaction.c +210/−0
- cbits/cometa_contextual_transaction.h +34/−0
- cbits/cometa_ed25519_values.c +97/−0
- cbits/cometa_ed25519_values.h +88/−0
- cbits/cometa_error_codes_test.c +193/−0
- cbits/cometa_evaluation.c +303/−0
- cbits/cometa_evaluation.h +35/−0
- cbits/cometa_inspection.c +661/−0
- cbits/cometa_inspection.h +45/−0
- cbits/cometa_key_handler.c +150/−0
- cbits/cometa_key_handler.h +55/−0
- cbits/cometa_native_evaluation.c +184/−0
- cbits/cometa_native_evaluation.h +54/−0
- cbits/cometa_parameters.c +787/−0
- cbits/cometa_parameters.h +65/−0
- cbits/cometa_password_crypto.c +53/−0
- cbits/cometa_password_crypto.h +81/−0
- cbits/cometa_provider.c +254/−0
- cbits/cometa_provider.h +187/−0
- cbits/cometa_provider_runtime.c +899/−0
- cbits/cometa_provider_runtime.h +47/−0
- cbits/cometa_reencode.c +106/−0
- cbits/cometa_reencode.h +34/−0
- cbits/cometa_runtime.c +147/−0
- cbits/cometa_runtime.h +71/−0
- cbits/cometa_script.c +80/−0
- cbits/cometa_script.h +55/−0
- cbits/cometa_signing_key.c +122/−0
- cbits/cometa_signing_key.h +121/−0
- cbits/cometa_sub_transaction_builder.c +568/−0
- cbits/cometa_sub_transaction_builder.h +45/−0
- cbits/cometa_transaction.c +297/−0
- cbits/cometa_transaction.h +80/−0
- cbits/cometa_transaction_builder.c +1102/−0
- cbits/cometa_transaction_builder.h +44/−0
- cometa.cabal +826/−0
- docs/development/BIP39_PURITY.md +118/−0
- docs/development/PBKDF2_PURITY.md +87/−0
- docs/development/PERFORMANCE.md +25/−0
- docs/development/RELEASING.md +84/−0
- docs/requirements.txt +3/−0
- docs/userguide/_static/custom.css +8/−0
- docs/userguide/api-reference.md +17/−0
- docs/userguide/blockfrost.md +87/−0
- docs/userguide/conf.py +42/−0
- docs/userguide/connected-examples.md +144/−0
- docs/userguide/connected-governance.md +66/−0
- docs/userguide/development.md +39/−0
- docs/userguide/error-handling.md +52/−0
- docs/userguide/index.md +20/−0
- docs/userguide/installation.md +68/−0
- docs/userguide/providers.md +67/−0
- docs/userguide/transaction-building.md +73/−0
- examples/Bip39.hs +50/−0
- examples/DRepPubkey.hs +143/−0
- examples/DRepScript.hs +159/−0
- examples/DeferredRedeemerBatch.hs +144/−0
- examples/DeferredRedeemerSelfIndex.hs +133/−0
- examples/DeferredWithdrawZero.hs +147/−0
- examples/DonateToTreasury.hs +89/−0
- examples/MintBurnNativeScript.hs +161/−0
- examples/MintBurnPlutusScript.hs +164/−0
- examples/PlutusV4GuardedSubTransaction.hs +174/−0
- examples/ProposeTreasuryWithdrawal.hs +143/−0
- examples/Provider.hs +75/−0
- examples/README.md +57/−0
- examples/RewardAccountPubkey.hs +121/−0
- examples/RewardAccountScript.hs +126/−0
- examples/SecureKeyHandler.hs +66/−0
- examples/SendLovelace.hs +108/−0
- examples/SignData.hs +46/−0
- examples/SpendFromNativeScript.hs +138/−0
- examples/SpendFromValidator.hs +140/−0
- examples/SubTransactionBatch.hs +176/−0
- examples/Support/Configuration.hs +70/−0
- examples/Support/Governance.hs +61/−0
- examples/Support/Inputs.hs +69/−0
- examples/Support/Scripts.hs +69/−0
- examples/Support/Terminal.hs +38/−0
- examples/Support/Transaction.hs +111/−0
- examples/Support/Wallet.hs +259/−0
- examples/VoteForProposalPubkey.hs +136/−0
- examples/VoteForProposalScript.hs +155/−0
- internal/Cometa/Internal/Bip32PrivateKey.hs +271/−0
- internal/Cometa/Internal/Bip39.hs +111/−0
- internal/Cometa/Internal/Callback.hs +231/−0
- internal/Cometa/Internal/FFI/Bip32.hs +88/−0
- internal/Cometa/Internal/FFI/Bip39.hs +44/−0
- internal/Cometa/Internal/FFI/Building.hs +28/−0
- internal/Cometa/Internal/FFI/Cbor.hs +144/−0
- internal/Cometa/Internal/FFI/Cip8.hs +34/−0
- internal/Cometa/Internal/FFI/CoinSelection.hs +35/−0
- internal/Cometa/Internal/FFI/ContextualTransaction.hs +35/−0
- internal/Cometa/Internal/FFI/Ed25519Values.hs +43/−0
- internal/Cometa/Internal/FFI/Evaluation.hs +36/−0
- internal/Cometa/Internal/FFI/Inspection.hs +33/−0
- internal/Cometa/Internal/FFI/KeyHandler.hs +85/−0
- internal/Cometa/Internal/FFI/Native.hs +87/−0
- internal/Cometa/Internal/FFI/NativeEvaluation.hs +34/−0
- internal/Cometa/Internal/FFI/ParameterUpdate.hs +34/−0
- internal/Cometa/Internal/FFI/PasswordCrypto.hs +57/−0
- internal/Cometa/Internal/FFI/Provider.hs +122/−0
- internal/Cometa/Internal/FFI/ProviderRuntime.hs +43/−0
- internal/Cometa/Internal/FFI/Reencode.hs +29/−0
- internal/Cometa/Internal/FFI/Runtime.hs +82/−0
- internal/Cometa/Internal/FFI/Script.hs +36/−0
- internal/Cometa/Internal/FFI/SigningKey.hs +86/−0
- internal/Cometa/Internal/FFI/SubTransactionBuilder.hs +33/−0
- internal/Cometa/Internal/FFI/Transaction.hs +66/−0
- internal/Cometa/Internal/FFI/TransactionBuilder.hs +34/−0
- internal/Cometa/Internal/Failure.hs +37/−0
- internal/Cometa/Internal/Hex.hs +60/−0
- internal/Cometa/Internal/KeyHandler.hs +281/−0
- internal/Cometa/Internal/Ownership.hs +102/−0
- internal/Cometa/Internal/PasswordCrypto.hs +86/−0
- internal/Cometa/Internal/Provider.hs +240/−0
- internal/Cometa/Internal/SigningKey.hs +236/−0
- internal/Cometa/Internal/Transaction.hs +131/−0
- native/NOTICE +37/−0
- native/cardano-c.ref +1/−0
- native/licenses/CC0-1.0.txt +121/−0
- native/licenses/GPL-2.0.txt +339/−0
- native/licenses/GPL-3.0.txt +674/−0
- native/licenses/LGPL-3.0.txt +165/−0
- native/licenses/libsodium-sha-BSD-2-Clause.txt +27/−0
- native/package.json +32/−0
- src/Cometa.hs +46/−0
- src/Cometa/Address.hs +84/−0
- src/Cometa/Address/Byron.hs +262/−0
- src/Cometa/Address/Reward.hs +112/−0
- src/Cometa/Address/Shelley.hs +224/−0
- src/Cometa/AssetId.hs +110/−0
- src/Cometa/AssetName.hs +103/−0
- src/Cometa/Certificate.hs +67/−0
- src/Cometa/Certificate/Collection.hs +94/−0
- src/Cometa/CoinSelection.hs +67/−0
- src/Cometa/Credential.hs +178/−0
- src/Cometa/Crypto/Bip32.hs +63/−0
- src/Cometa/Crypto/Bip32/PrivateKey.hs +178/−0
- src/Cometa/Crypto/Bip32/PublicKey.hs +135/−0
- src/Cometa/Crypto/Bip39.hs +102/−0
- src/Cometa/Crypto/Blake2b.hs +160/−0
- src/Cometa/Crypto/DerivationPath.hs +194/−0
- src/Cometa/Crypto/Ed25519/PublicKey.hs +134/−0
- src/Cometa/Crypto/Ed25519/Signature.hs +87/−0
- src/Cometa/Crypto/Ed25519/SigningKey.hs +165/−0
- src/Cometa/Crypto/Emip3.hs +65/−0
- src/Cometa/Crypto/Pbkdf2.hs +51/−0
- src/Cometa/Diagnostics.hs +84/−0
- src/Cometa/Encoding/Cbor.hs +382/−0
- src/Cometa/Encoding/Collections.hs +139/−0
- src/Cometa/Encoding/Hex.hs +49/−0
- src/Cometa/Encoding/Integer.hs +205/−0
- src/Cometa/Encoding/Reencode.hs +85/−0
- src/Cometa/Encoding/Set.hs +30/−0
- src/Cometa/Error.hs +331/−0
- src/Cometa/Error/Code.hs +385/−0
- src/Cometa/Evaluation.hs +47/−0
- src/Cometa/Evaluation/Native.hs +33/−0
- src/Cometa/Governance/Action.hs +276/−0
- src/Cometa/Governance/ActionId.hs +92/−0
- src/Cometa/Governance/Anchor.hs +71/−0
- src/Cometa/Governance/Committee.hs +109/−0
- src/Cometa/Governance/Constitution.hs +70/−0
- src/Cometa/Governance/DRep.hs +95/−0
- src/Cometa/Governance/Proposal.hs +195/−0
- src/Cometa/Governance/Voting.hs +121/−0
- src/Cometa/Inspection.hs +527/−0
- src/Cometa/Internal/AddressText.hs +76/−0
- src/Cometa/Internal/Balance.hs +143/−0
- src/Cometa/Internal/BalancingScripts.hs +213/−0
- src/Cometa/Internal/BatchValidation.hs +57/−0
- src/Cometa/Internal/Bip39Pure.hs +125/−0
- src/Cometa/Internal/Building.hs +167/−0
- src/Cometa/Internal/Certificate.hs +353/−0
- src/Cometa/Internal/CoinSelection.hs +348/−0
- src/Cometa/Internal/CoinSelection/Native.hs +55/−0
- src/Cometa/Internal/ContextualTransaction.hs +92/−0
- src/Cometa/Internal/CostModels.hs +133/−0
- src/Cometa/Internal/Ed25519SigningKey.hs +28/−0
- src/Cometa/Internal/Error.hs +33/−0
- src/Cometa/Internal/Evaluation.hs +153/−0
- src/Cometa/Internal/Evaluation/Native.hs +140/−0
- src/Cometa/Internal/EvaluationNative.hs +116/−0
- src/Cometa/Internal/Governance.hs +451/−0
- src/Cometa/Internal/Inspection.hs +46/−0
- src/Cometa/Internal/Message/Cip8.hs +120/−0
- src/Cometa/Internal/ParameterSnapshot.hs +104/−0
- src/Cometa/Internal/ParameterUpdate.hs +35/−0
- src/Cometa/Internal/Pbkdf2Pure.hs +53/−0
- src/Cometa/Internal/Pool.hs +491/−0
- src/Cometa/Internal/ProposalCbor.hs +147/−0
- src/Cometa/Internal/ProtocolValues.hs +278/−0
- src/Cometa/Internal/ProviderRuntime.hs +198/−0
- src/Cometa/Internal/Reencode.hs +30/−0
- src/Cometa/Internal/Runtime.hs +281/−0
- src/Cometa/Internal/SetEncoding.hs +51/−0
- src/Cometa/Internal/SubTransactionBuilder.hs +220/−0
- src/Cometa/Internal/SubTransactionPlan.hs +258/−0
- src/Cometa/Internal/TransactionBalancing.hs +358/−0
- src/Cometa/Internal/TransactionBuilder.hs +466/−0
- src/Cometa/Internal/TransactionCbor.hs +84/−0
- src/Cometa/Internal/TransactionFields.hs +317/−0
- src/Cometa/Internal/TransactionIndices.hs +128/−0
- src/Cometa/Internal/TransactionPlan.hs +691/−0
- src/Cometa/Internal/TransactionValue.hs +76/−0
- src/Cometa/KeyHandler/Software.hs +217/−0
- src/Cometa/Message/Cip8.hs +40/−0
- src/Cometa/Metadata.hs +426/−0
- src/Cometa/NetworkId.hs +61/−0
- src/Cometa/NetworkMagic.hs +54/−0
- src/Cometa/PlutusData.hs +256/−0
- src/Cometa/PolicyId.hs +81/−0
- src/Cometa/Pool/BlsKey.hs +49/−0
- src/Cometa/Pool/Metadata.hs +62/−0
- src/Cometa/Pool/Parameters.hs +71/−0
- src/Cometa/Pool/Relay.hs +74/−0
- src/Cometa/Protocol/CostModels.hs +102/−0
- src/Cometa/Protocol/DRepVotingThresholds.hs +44/−0
- src/Cometa/Protocol/ExUnitPrices.hs +44/−0
- src/Cometa/Protocol/ExUnits.hs +45/−0
- src/Cometa/Protocol/Parameters.hs +206/−0
- src/Cometa/Protocol/Parameters/Update.hs +588/−0
- src/Cometa/Protocol/PoolVotingThresholds.hs +44/−0
- src/Cometa/Protocol/ProposedUpdates.hs +156/−0
- src/Cometa/Protocol/Rational.hs +90/−0
- src/Cometa/Protocol/Version.hs +44/−0
- src/Cometa/Provider.hs +105/−0
- src/Cometa/Provider/Blockfrost.hs +65/−0
- src/Cometa/Provider/Blockfrost/Internal/Config.hs +153/−0
- src/Cometa/Provider/Blockfrost/Internal/Connection.hs +200/−0
- src/Cometa/Provider/Blockfrost/Internal/Http.hs +197/−0
- src/Cometa/Provider/Blockfrost/Internal/Json.hs +253/−0
- src/Cometa/Provider/Blockfrost/Internal/Protocol.hs +241/−0
- src/Cometa/Provider/Blockfrost/Internal/Provider.hs +317/−0
- src/Cometa/Provider/Hydra.hs +75/−0
- src/Cometa/Provider/Internal/Codec.hs +237/−0
- src/Cometa/Provider/Internal/Config.hs +47/−0
- src/Cometa/Provider/Internal/Hydra.hs +236/−0
- src/Cometa/Provider/Internal/Protocol.hs +204/−0
- src/Cometa/Provider/Internal/Remote.hs +411/−0
- src/Cometa/Provider/Koios.hs +74/−0
- src/Cometa/Provider/Kupmios.hs +76/−0
- src/Cometa/Script.hs +112/−0
- src/Cometa/Script/Native.hs +322/−0
- src/Cometa/Script/Plutus.hs +184/−0
- src/Cometa/Signer.hs +77/−0
- src/Cometa/SlotConfig.hs +110/−0
- src/Cometa/SubTransaction.hs +196/−0
- src/Cometa/SubTransaction/Body.hs +171/−0
- src/Cometa/SubTransaction/Builder.hs +33/−0
- src/Cometa/SubTransaction/Indices.hs +113/−0
- src/Cometa/SubTransaction/Plan.hs +102/−0
- src/Cometa/Transaction.hs +318/−0
- src/Cometa/Transaction/Authority.hs +48/−0
- src/Cometa/Transaction/AuxiliaryData.hs +219/−0
- src/Cometa/Transaction/Balancing.hs +22/−0
- src/Cometa/Transaction/Body.hs +261/−0
- src/Cometa/Transaction/Builder.hs +29/−0
- src/Cometa/Transaction/Building.hs +209/−0
- src/Cometa/Transaction/Datum.hs +58/−0
- src/Cometa/Transaction/Deferred.hs +183/−0
- src/Cometa/Transaction/Fields.hs +48/−0
- src/Cometa/Transaction/Indices.hs +113/−0
- src/Cometa/Transaction/Input.hs +67/−0
- src/Cometa/Transaction/Inspection.hs +68/−0
- src/Cometa/Transaction/Output.hs +189/−0
- src/Cometa/Transaction/Plan.hs +103/−0
- src/Cometa/Transaction/Redeemer.hs +123/−0
- src/Cometa/Transaction/Signing.hs +70/−0
- src/Cometa/Transaction/Utxo.hs +64/−0
- src/Cometa/Transaction/Witness.hs +121/−0
- src/Cometa/Transaction/Witnesses.hs +308/−0
- src/Cometa/TransactionId.hs +68/−0
- src/Cometa/UnitInterval.hs +88/−0
- src/Cometa/Value.hs +248/−0
- src/Cometa/Value/Raw.hs +101/−0
- test/AccountingReliability.hs +265/−0
- test/AdditionalProviders.hs +267/−0
- test/Address.hs +322/−0
- test/AssetId.hs +131/−0
- test/BalancingScriptLanguages.hs +281/−0
- test/Bip32.hs +401/−0
- test/Bip39.hs +179/−0
- test/BlockfrostHttp.hs +701/−0
- test/BlockfrostJson.hs +237/−0
- test/BlockfrostProtocol.hs +240/−0
- test/BlockfrostProvider.hs +333/−0
- test/Callback.hs +340/−0
- test/Cbor.hs +295/−0
- test/Certificates.hs +269/−0
- test/Cip8.hs +191/−0
- test/CoinSelection.hs +265/−0
- test/CollectionOperations.hs +330/−0
- test/Collections.hs +156/−0
- test/CompleteAddress.hs +221/−0
- test/ConnectedGovernance.hs +137/−0
- test/ContextualTransaction.hs +261/−0
- test/DeferredRedeemer.hs +368/−0
- test/DerivationPath.hs +244/−0
- test/Diagnostics.hs +104/−0
- test/DijkstraBuilder.hs +389/−0
- test/Ed25519.hs +550/−0
- test/EncodingNormalization.hs +363/−0
- test/ErrorCode.hs +176/−0
- test/Evaluation.hs +325/−0
- test/Fixtures/ACCOUNTING_RELIABILITY.md +128/−0
- test/Fixtures/ADDRESSES.md +36/−0
- test/Fixtures/ASSETS_VALUES.md +33/−0
- test/Fixtures/Address.hs +45/−0
- test/Fixtures/BIP32.md +72/−0
- test/Fixtures/BIP39-TREZOR-LICENSE.md +21/−0
- test/Fixtures/BIP39.md +51/−0
- test/Fixtures/Bip32.hs +60/−0
- test/Fixtures/Bip39.hs +54/−0
- test/Fixtures/COIN_SELECTION.md +106/−0
- test/Fixtures/DERIVATION_PATHS.md +28/−0
- test/Fixtures/ED25519.md +114/−0
- test/Fixtures/Ed25519.hs +191/−0
- test/Fixtures/ExampleParameters.hs +98/−0
- test/Fixtures/Governance.hs +46/−0
- test/Fixtures/Governance.md +21/−0
- test/Fixtures/INSPECTION.md +46/−0
- test/Fixtures/Inspection.hs +43/−0
- test/Fixtures/PARAMETER_DATA.md +16/−0
- test/Fixtures/PASSWORD_CRYPTO.md +36/−0
- test/Fixtures/PlutusData.hs +32/−0
- test/Fixtures/PlutusData.md +5/−0
- test/Fixtures/ProtocolParameters.hs +105/−0
- test/Fixtures/RELIABILITY.md +70/−0
- test/Fixtures/SOFTWARE_KEY_HANDLERS.md +27/−0
- test/Fixtures/Scripts.hs +49/−0
- test/Fixtures/Scripts.md +16/−0
- test/Fixtures/Swap.hs +123/−0
- test/Fixtures/TRANSACTIONS.md +130/−0
- test/Fixtures/TRANSACTION_ACCOUNTING.md +147/−0
- test/Fixtures/Transaction.hs +176/−0
- test/Fixtures/TransactionWorkflows.hs +321/−0
- test/Fixtures/Workflow.hs +176/−0
- test/Governance.hs +376/−0
- test/HexEncoding.hs +134/−0
- test/IdentityReliability.hs +224/−0
- test/InspectionCollections.hs +107/−0
- test/IntegerSemantics.hs +302/−0
- test/Main.hs +227/−0
- test/Metadata.hs +244/−0
- test/NativeCoinSelection.hs +376/−0
- test/NativeEvaluation.hs +239/−0
- test/NativeWorkflows.hs +348/−0
- test/NumericConversions.hs +319/−0
- test/Ownership.hs +212/−0
- test/ParameterSnapshot.hs +148/−0
- test/Parameters.hs +324/−0
- test/PasswordCrypto.hs +287/−0
- test/PlutusData.hs +221/−0
- test/Pool.hs +260/−0
- test/Proposals.hs +284/−0
- test/ProtocolValues.hs +211/−0
- test/Provider.hs +307/−0
- test/PublicTransaction.hs +351/−0
- test/Runtime.hs +223/−0
- test/RuntimeMain.hs +74/−0
- test/Scripts.hs +318/−0
- test/SelectionReliability.hs +220/−0
- test/SetEncoding.hs +158/−0
- test/SlotConfig.hs +90/−0
- test/SoftwareKeyHandler.hs +339/−0
- test/StandaloneSetEncoding.hs +172/−0
- test/SubTransactionBuilder.hs +486/−0
- test/Transaction.hs +274/−0
- test/TransactionAccountingProperties.hs +348/−0
- test/TransactionBalancing.hs +540/−0
- test/TransactionBody.hs +342/−0
- test/TransactionBuilder.hs +454/−0
- test/TransactionBuilding.hs +409/−0
- test/TransactionCollectionOperations.hs +367/−0
- test/TransactionDeferred.hs +225/−0
- test/TransactionIndices.hs +180/−0
- test/TransactionInspection.hs +898/−0
- test/TransactionMapOperations.hs too large to diff
- test/TransactionWitnesses.hs too large to diff
- test/Value.hs too large to diff
- test/cbits/address_oracle.c too large to diff
- test/cbits/asset_id_oracle.c too large to diff
- test/cbits/certificates_oracle.c too large to diff
- test/cbits/collection_operations_oracle.c too large to diff
- test/cbits/collections_oracle.c too large to diff
- test/cbits/complete_address_oracle.c too large to diff
- test/cbits/contextual_transaction_oracle.c too large to diff
- test/cbits/derivation_path_oracle.c too large to diff
- test/cbits/diagnostics_oracle.c too large to diff
- test/cbits/encoding_normalization_oracle.c too large to diff
- test/cbits/governance_oracle.c too large to diff
- test/cbits/integer_semantics_oracle.c too large to diff
- test/cbits/metadata_oracle.c too large to diff
- test/cbits/numeric_conversions_oracle.c too large to diff
- test/cbits/parameter_snapshot_oracle.c too large to diff
- test/cbits/parameters_oracle.c too large to diff
- test/cbits/plutus_data_oracle.c too large to diff
- test/cbits/pool_oracle.c too large to diff
- test/cbits/proposals_oracle.c too large to diff
- test/cbits/protocol_values_oracle.c too large to diff
- test/cbits/runtime_oracle.c too large to diff
- test/cbits/script_oracle.c too large to diff
- test/cbits/slot_config_oracle.c too large to diff
- test/cbits/transaction_body_oracle.c too large to diff
- test/cbits/transaction_collection_operations_oracle.c too large to diff
- test/cbits/transaction_indices_oracle.c too large to diff
- test/cbits/transaction_map_operations_oracle.c too large to diff
- test/cbits/transaction_oracle.c too large to diff
- test/cbits/transaction_witnesses_oracle.c too large to diff
- test/cbits/value_oracle.c too large to diff
- test/fixtures/providers/README.md too large to diff
- test/fixtures/providers/hydra-parameters.json too large to diff
- test/fixtures/providers/hydra-utxos.json too large to diff
- test/fixtures/providers/koios-utxos.json too large to diff
- test/fixtures/providers/ogmios-parameters.json too large to diff
- test/package-consumer/Main.hs too large to diff
- test/package-consumer/package-consumer.cabal too large to diff
- test/release/test_consumer.py too large to diff
- test/release/test_release.py too large to diff
- test/valgrind/ghc-9.6.7.supp too large to diff
- tools/build-api-docs.py too large to diff
- tools/build-native.py too large to diff
- tools/check-credential-roles.py too large to diff
- tools/check-key-handler-roles.py too large to diff
- tools/check-source-package.py too large to diff
- tools/package-native.py too large to diff
- tools/release.py too large to diff
@@ -0,0 +1,72 @@+Language: Cpp+BasedOnStyle: Microsoft+AlwaysBreakAfterReturnType: AllDefinitions+AlwaysBreakTemplateDeclarations: Yes+BreakBeforeBraces: Custom+BraceWrapping:+ AfterCaseLabel: true+ AfterClass: true+ AfterControlStatement: Always+ AfterEnum: true+ AfterFunction: true+ AfterNamespace: true+ AfterObjCDeclaration: true+ AfterStruct: true+ AfterUnion: true+ AfterExternBlock: false+ BeforeCatch: true+ BeforeElse: true+ BeforeLambdaBody: true+ BeforeWhile: true+ IndentBraces: false+ SplitEmptyFunction: true+ SplitEmptyRecord: true+ SplitEmptyNamespace: true+BreakStringLiterals: false+BreakConstructorInitializers: BeforeComma+BreakInheritanceList: BeforeComma+BreakBeforeBinaryOperators: None+AllowAllParametersOfDeclarationOnNextLine: false+BinPackArguments: false+BinPackParameters: false+PackConstructorInitializers: Never+PenaltyReturnTypeOnItsOwnLine: 0+PenaltyBreakBeforeFirstCallParameter: 1000+PenaltyBreakAssignment: 1000+PenaltyBreakComment: 1000+PenaltyBreakFirstLessLess: 1000+PenaltyIndentedWhitespace: 1000+ColumnLimit: 0+TabWidth: 2+IndentWidth: 2+ContinuationIndentWidth: 2+IndentCaseLabels: true+IndentExternBlock: AfterExternBlock+IndentPPDirectives: None+IndentAccessModifiers: true+AccessModifierOffset: 0+ConstructorInitializerIndentWidth: 0+EmptyLineAfterAccessModifier: Always+KeepEmptyLinesAtTheStartOfBlocks: false+SeparateDefinitionBlocks: Always+SpaceAfterTemplateKeyword: false+SpaceBeforeCpp11BracedList: true+SpaceBeforeRangeBasedForLoopColon: false+AlignEscapedNewlines: Left+AlignAfterOpenBracket: AlwaysBreak+AlignConsecutiveAssignments:+ Enabled: true+ AlignCompound: true+AlignConsecutiveBitFields:+ Enabled: true+AlignConsecutiveDeclarations:+ Enabled: true+AlignConsecutiveMacros:+ Enabled: true+PointerAlignment: Left+ReferenceAlignment: Left+QualifierAlignment: Left+AlignOperands: DontAlign+ShortNamespaceLines: 0+Cpp11BracedListStyle: false+SortIncludes: CaseInsensitive
@@ -0,0 +1,9 @@+- warn: {name: Use explicit module export list}++# Identity expressions are the behavior under test in the Value law property.+- ignore: {name: "Monoid law, left identity", within: Value.propLaws}+- ignore: {name: "Monoid law, right identity", within: Value.propLaws}++# Preserve explicit identities in the metadata composition law.+- ignore: {name: "Monoid law, left identity", within: [Metadata.propComposition]}+- ignore: {name: "Monoid law, right identity", within: [Metadata.propComposition]}
@@ -0,0 +1,14 @@+version: 2++build:+ os: ubuntu-24.04+ tools:+ python: "3.12"++sphinx:+ configuration: docs/userguide/conf.py+ fail_on_warning: true++python:+ install:+ - requirements: docs/requirements.txt
@@ -0,0 +1,81 @@+# Repository instructions++Cometa.hs is a Haskell binding to cardano-c. Read `CODING_CONVENTIONS.md`+before making changes. Inspect neighboring modules, package metadata, native dependency pins,+and test provenance. Only code and passing tests establish implemented behavior.++## Scope and workflow++- Make focused, reviewable changes. Do not generate broad FFI wrappers before+ auditing the native declarations, ownership contract, and public Haskell API.+- Keep historical plans, progress logs and generated coverage inventories out of+ the repository. Document current contracts and maintenance procedures.+- Do not advertise incomplete domains, untested platform/compiler combinations,+ unpublished packages, or unconfigured hosted documentation.+- Preserve the maintainer's configured signing identity. Use Conventional Commit+ messages when asked to commit; do not substitute an agent identity. Commit,+ publication, and live-network actions require the corresponding task authority.+- Never check in credentials, private keys, funded-wallet material, or secrets from+ conversation history. Live tests need explicit network, wallet, and flow authority.++## Haskell changes++- Before designing or extending a public API, inspect relevant established Haskell+ libraries' actual documentation, source and usage examples. Record the reviewed+ links, version or commit, caller workflow and justified differences in the+ change description. Use that evidence to inform the design; do not copy an API+ without checking its contracts and fit for Cometa.+- Start public API design with a complete caller workflow. Validate external inputs+ once, use lawful defaults and total assembly, and keep one clear error boundary.+ Apply the [workflow rules and API review checklist](CODING_CONVENTIONS.md#design-from-complete-workflows)+ before adding primitives or abstractions; common secret operations should manage+ intermediate scopes while advanced scoped composition remains available.++- Follow `CODING_CONVENTIONS.md`, explicit exports, public signatures, and the+ configured formatter/HLint policy. Do not impose C/C++ formatting on Haskell.+- Use abstract validated values, structured errors, and qualified domain modules.+ Keep expected failure total and keep native effects in `IO`, except for the+ specifically audited private BIP39 and PBKDF2 boundaries in+ `docs/development/BIP39_PURITY.md` and `docs/development/PBKDF2_PURITY.md`.+- Keep raw FFI, marshaling, resource scopes, and callbacks internal. Audit every+ acquired, borrowed, retained, and transferred native reference.+- Never hide arbitrary native calls with `unsafePerformIO`. Never derive printable+ secret representations or expose constructors that bypass invariants.+- Document ownership contracts beside the native boundary and cover them with+ tests. Reference-count plumbing stays internal.++## Verification++Run checks appropriate to the change with the repository's native configuration:++```sh+cabal build all+cabal test all --test-show-details=direct+cabal haddock all+cabal check+```++Run the configured formatter and HLint checks for Haskell edits. Build narrative+changes with:++```sh+python3 -m sphinx -n -W --keep-going -b html docs/userguide docs/_build/html+```++- Add meaningful invalid-input and boundary tests for new behavior. Test advertised+ laws with properties and lifecycle behavior with failure/cancellation cases.+- Reuse the pinned native corpus through public Haskell values; opaque CBOR+ forwarding alone does not establish correct marshaling. Record source revision,+ path, and license/notices for imported vectors, properties, and generators.+- Compile documentation examples when adding executable examples. Pure doctests+ may use deterministic inputs; effectful examples must not require live secrets+ in ordinary CI.+- Review CI results before claiming a supported matrix or completed milestone.+ Report checks that could not run and the concrete reason.++## Documentation++Write public contracts in Haddock: meaning, units, bounds, ordering, defaults,+errors, and observable effects. Put ownership/runtime mechanics in internal docs.+Keep task-oriented prose in the Sphinx MyST guide; publish release API reference+through Haddock on Hackage. Do not create dead release links or status badges.
@@ -0,0 +1,335 @@+# Haskell coding conventions++These rules apply to Cometa.hs.+Use the checked-in formatter and HLint settings as the mechanical source of truth.+Before editing, inspect nearby modules and match their organization and vocabulary.++## Modules, layout, and imports++Use Ormolu 0.8.0.2 and HLint 3.8 with the repository's HLint configuration. Prefer readable+named arguments and pattern matching over dense point-free expressions. Use+normal Haskell layout, not Allman braces. Use ordinary comment section banners+to separate imports, types, and related operations, as described below.++Every module has an explicit export list and a Haddock introduction explaining+its domain. Group public exports by construction, inspection, transformation,+serialization, and effects when those groups help navigation. Keep public modules+focused; `Cometa` is a curated convenience module, not an indiscriminate re-export+of internals. Files follow the module hierarchy.++Give every public binding a type signature. Give internal helpers signatures when+they explain constraints or prevent unintended polymorphism. Prefer explicit+import lists; qualify domain modules with names such as `Address`, `Tx`, `Plan`,+or `Blake2b`. Do not use a custom Prelude or require an effects framework for+ordinary use. Avoid orphan instances; optional interoperability uses owned wrappers.++Use the package's declared language baseline. Enable an extension in the module+that needs it, with an explanatory comment when its safety or API consequences+are not obvious. Do not add package-wide extensions casually. Use ordinary record+selectors; do not introduce `DuplicateRecordFields` or `OverloadedRecordDot`+without a repository-wide decision and compiler-matrix evidence.++## Design from complete workflows++Before designing or extending a public API, review how relevant established+Haskell libraries solve the same task. Read their actual documentation, source+and usage examples, including the complete caller workflow and error handling.+Record links and the reviewed version or commit in the change description,+explain which contracts inform Cometa, and justify material differences. This+review is required before choosing the API; familiar names or remembered+signatures are insufficient evidence. Adopt patterns that fit the domain and+Cometa's guarantees rather than copying another library mechanically.++Design a complete caller workflow before adding primitives. Write the code an+application needs to validate input, assemble values, execute the operation, and+handle the result. Review successful use, invalid input, and cleanup together.+Use these examples to justify abstractions and discover avoidable ceremony.++Validate external input once, then compose abstract validated values with total+functions. Provide lawful standard instances and useful defaults when their+semantics are clear: `Bounded Index` supplies raw zero and `2^31 - 1`, so a known+first index can use `minBound` without an impossible error branch. Do not add+`Num`, `Enum`, partial literals, or unsafe constructors merely to shorten examples.+Keep `mkIndex` for integers supplied at runtime.++Prefer pure, Haskell-owned values for validation, assembly, and inspection.+Require effects only for observable effects, scoped resources, or unaudited+native boundaries; follow the specific purity audits below. Offer a small+workflow helper when the common task otherwise requires callers to manage+intermediate secrets. For example, one-shot BIP32 public-key derivation manages+private scopes internally while lower-level scoped operations remain available+for several related operations. Convenience must preserve cancellation, cleanup,+and error behavior.++Group pure input validation in small `Either` functions before running effects.+Use ordinary `do` notation or applicative composition inside `Either`; lift a+validated group once when combining it with `ExceptT`. Use `ExceptT` for a+sequence of fallible effects, and handle the result at the caller's boundary. Avoid nested error matches and mandatory custom monads or+effects frameworks. A single fallible operation needs no transformer. Helpers+should name actual workflow steps rather than disguise errors or ownership.++Review signatures for ambiguous same-typed arguments, especially password,+entropy, and storage `ByteString` values. Use descriptive argument documentation+and examples; introduce an options record or another abstraction only when a+complete workflow demonstrates its benefit. Compare the relevant contracts of+idiomatic libraries; do not copy historical+partial conveniences or claim one universal Haskell style.++## Naming++- Modules, types, classes, and constructors use `UpperCamelCase`; functions,+ fields, variables, and constants use `lowerCamelCase`.+- Prefer domain names and qualified module vocabulary. Do not repeat `cometa` or+ mechanically expose C prefixes, getters, and setters.+- Use `fromBytes`/`toBytes`, `fromText`/`toText`, and `decodeCbor`/`encodeCbor`+ consistently. The type signature, not the name, determines effects.+- Use `mk...` for validated construction from a more general value. Return an+ explicit error; do not shorten call sites with partial smart constructors.+ Prefer plain names such as `accountPath` for total assembly from validated+ values. This repository uses the distinction to make validation boundaries+ visible; other Haskell libraries may use `mk...` more broadly.+- `with...` scopes a resource. `run...` interprets an action. `eval...` and+ `exec...` follow the familiar distinction between returning a result or state.+- Prefer observers such as `fee` or `networkId` in qualified modules.+- Suffix `_` means a result is discarded. An apostrophe marks a documented variant,+ usually strictness, not an unexplained error policy. Use `By` for supplied+ comparison behavior and `On` for projection behavior where appropriate.+- Keep `TxId`, `Utxo`, and `Cbor` consistent. Prefer complete domain names over+ unexplained abbreviations. Exported unqualified record fields receive a domain+ prefix when needed to avoid ambiguity.+- Reuse lawful standard operators. A new symbolic operator needs a demonstrated+ readability benefit, a named equivalent, and documented fixity.+- Private FFI names may retain C spelling with an internal prefix for auditing;+ this vocabulary must not determine public Haskell names.++## Values, invariants, and laws++Use algebraic data types for alternatives and validated newtypes for invariants.+Hide constructors when they protect bounds, byte lengths, original encodings,+roles, or resource ownership. An exported record update or representation+conversion must not bypass those protections.++Audit every instance. `Read`, `IsString`, `Num`, `Generic`, and `Data` can expose+construction routes that violate invariants; justify their use individually.+`Show` is diagnostic, not a stable interchange format. Never derive secret-bearing+`Show` output. Role-indexed hashes and keys need a `Coercible` audit, nominal+roles where required, and compile-fail checks for the intended boundary.++Introduce a class only for a coherent abstraction with meaningful instances and+laws. Runtime providers, evaluators, selectors, and signers initially use records+of functions. Test every advertised law, including associativity and identity for+plan composition. Do not claim a total numeric monoid when bounded arithmetic+can fail. Optional optics must preserve invariants and obey their laws; a+normalizing or validating operation is not automatically a lawful lens.++Use `Integer` for arbitrary-precision protocol integers. Keep signed quantities+signed; validate nonnegative amounts and native bounds before conversion. Never+route monetary values through floating point. Do not derive unrestricted `Num`+for validated quantities.++Choose collections by their semantics. Preserve order, duplicate keys, absence,+null, empty, and zero wherever the format distinguishes them. Do not automatically+replace arbitrary Plutus maps with `Data.Map`. Define equality and ordering for+encoded values explicitly; pointer identity is not domain equality.++## Totality, effects, and evaluation++Expected invalid input returns `Either` with a structured domain error. `Maybe`+means legitimate absence. Native/effectful operations initially return+`IO (Either ... ...)`. Preserve error codes and context without leaking secrets.+Do not make a universal Cometa monad mandatory; callers may compose with `ExceptT`.++Normal public input handling must not rely on `error`, `undefined`, `fromJust`,+unchecked indexing, or incomplete patterns. Genuinely necessary unsafe operations+belong in an explicitly separated internal/unsafe surface with preconditions and+safe alternatives. Keep validation, composition, and materialized-value inspection+pure where practical. Native calls remain in `IO` until a specific purity review;+`unsafePerformIO` is not a shortcut. The reviewed exceptions are the concrete,+private boundaries documented in [the BIP39 purity audit](docs/development/BIP39_PURITY.md)+and [the PBKDF2 purity audit](docs/development/PBKDF2_PURITY.md).+They apply only to the separately audited pinned deterministic owner-free paths+and their marshaling/cleanup/error handling. Re-audit source and native build changes; never+generalize the boundary to an arbitrary IO runner.++Use strict accumulators and snapshots where needed to bound retention or keep+exceptions inside cleanup scopes. Do not enable blanket strictness without+justification. Strict fields and strict maps force particular structures only to+WHNF; nested values and functions may remain lazy. Specify which callback result+parts must be forced before returning to C. `NFData` on a surrounding record does+not establish that a function has been fully evaluated.++Preserve ordinary asynchronous cancellation after safe foreign-boundary unwind.+Use structured, bounded concurrency. A timeout is not evidence that C stopped+using its buffers or callback state. Measure marshaling, allocations, startup,+and evaluation before adding specialization or unsafe optimization.++## FFI and resource safety++Separate raw declarations, marshaling, ownership scopes, and callbacks. Audit the+current native headers and implementation rather than assuming that all getters+borrow or all outputs transfer ownership. Document contracts beside the FFI boundary.++- Copy borrowed bytes/strings or retain an immutable owner for their entire use.+ Retaining a reference is not cloning; native reference counts are not atomic.+- Track every ownership obligation explicitly. After unref, mark the local+ obligation released even if another owner leaves the pointer non-null.+- Copy native diagnostics before releasing their owner. Release operation-scoped+ resources deterministically on all exits; finalizers are a fallback for suitable+ persistent resources.+- Access managed pointers through `withForeignPtr`. Typed pointer-to-pointer C+ unref functions cannot serve directly as unary `ForeignPtr` finalizers.+- Keep callback closures rooted with supported stable handles. Keep `StablePtr`,+ `FunPtr`, contexts, and error state alive through the last possible callback,+ including repeated balancing and cleanup.+- Distinguish provider/key-handler context adoption from borrowed deferred contexts.+ Retain operation owners while callbacks run. Prevent unsupported reentry.+- Use callback-capable `safe` imports when C can re-enter Haskell. Audit short,+ non-callback `unsafe` imports individually; account for scheduler behavior in+ long-running evaluation. Do not mark arbitrary calls `interruptible` for timeouts.+- Bracket/mask ownership transitions. Catch callback exceptions within the bridge,+ return a native failure, and rethrow or translate after safe unwind. Do not+ silently turn asynchronous cancellation into a recoverable provider error.+- Concurrent operations have independent mutable handles and error slots, or a+ documented synchronization scheme. A worker continuing after cancellation owns+ and eventually releases all state it still uses.++Hash-bearing transaction values must preserve original encoding where identity+requires it. Controlled edits invalidate affected caches and define witness+behavior. Never silently canonicalize a signed transaction. Establish exact CBOR,+body-hash, signature, and edit-independence tests before broad implementation.++Secret resources are opaque and scoped. Reject use after close, including escaped+handles; a callback-shaped acquisition alone does not prove safety. Private-key+export must be explicit and explain the loss of controlled lifetime after copying.++## Documentation and tests++Public Haddock describes observable behavior: meaning, parameter units and bounds,+return values, errors, defaults, ordering, and effects. Each public module explains+its purpose and has a small valid example. Keep raw ownership mechanics internal. Do not put implementation status, future+roadmaps, pointer ownership, copying strategies, or ABI details in public API+contracts. Document observable restrictions honestly, including unsupported inputs.++Use Haddock section headings to group related exports. Document constructor+payloads and arguments when their meaning, units, or bounds are not clear from+the type. Internal modules should document ownership, synchronization, and exception+contracts at the declarations that enforce them; ordinary comments explain local+invariants. Avoid comments that merely repeat a name or narrate a line of code.++Separate acquisition, computation, and result handling with blank lines where they+form distinct steps. Keep related bindings together. Let Ormolu determine indentation+and wrapping. Use section banners for substantial logical groups, not individual+functions. Keep banners outside Haddock comments so they do not enter API prose.+Use the Microsoft Writing Style Guide as an editorial reference and established+Haddock syntax for declarations. Narrative pages teach tasks; proposed interfaces+stay in developer plans and must be labeled as proposals.++Compile executable examples and check links. Use pure deterministic doctests when+appropriate and compiled fixtures for effectful flows. Never require credentials+for ordinary documentation builds. Keep the guide and versioned Haddock aligned+with the source/package they describe.++Prefer Hedgehog for new shrinking and state-machine properties; retain imported+QuickCheck properties when practical. Test laws, bounds, invalid encodings,+round trips, collection semantics, snapshot independence, allocation baselines,+callback rooting, exceptions, repeated callbacks, cancellation, and supported+concurrency as relevant. Use deterministic fakes for injected components. Selector+tests assert invariants rather than identical random choices. Save minimized+failures as regression cases.++Pin native/corpus revisions and record imported test source paths, commits, and+licenses. Test through public values, not only opaque CBOR forwarding. Native+agreement detects binding errors; use independent vectors or oracles where+possible. Keep authorized live-network evidence separate from fixture evidence.++## Native adapters++Keep C adapters in `cbits` limited to ABI layout, ownership, and marshaling.+Use the checked-in `.clang-format` with ClangFormat 18, matching cardano-c's+formatting. Haskell keeps its own Ormolu conventions. Document adoption, borrowing,+callback lifetime, and failure ownership at each boundary. Match the section+banners, Doxygen `\brief`/`\param`/`\return` comments, header guards, and logical+spacing in cardano-c provider headers and sources. A formatter alone does not+establish this organization. Document declarations in headers and local helpers+next to their definitions; avoid duplicating the same contract in both. Native callbacks must+never unwind a Haskell exception through C.++## Compatibility and review++Follow the Haskell Package Versioning Policy for exposed types, declarations,+instances, and dependency bounds; track native version/ABI separately. Test the+supported compiler matrix and dependency bounds. Use meaningful warnings,+including incomplete patterns and record updates. CI may promote warnings to+errors; do not ship unconditional `-Werror` to consumers.++Before bulk implementation, review complete use cases for payment, script spend,+custom evaluation, external signing, decoding failure, and cancellation. Before+first release, seek experienced Haskell/FFI maintainer review when available and+record its outcome. Passing automated checks does not prove exception safety or+API quality.++Use current primary documentation when comparing established library APIs.+Adopt contracts that fit this library rather than copying partial APIs or adding+dependencies solely for stylistic similarity.++## API review checklist++Before accepting a public API change, review concrete caller code:++- Have relevant established libraries' documentation, source and real usage been+ reviewed before design, with links, version or commit, workflow and justified+ differences recorded in the change description?+- Can the common task run from input to result with one clear error boundary?+ Are runtime inputs validated once and valid values assembled without spurious+ failure branches?+- Do names distinguish validation, assembly, inspection, and scoped effects?+ Are same-typed arguments, defaults, units, bounds, and byte encodings clear?+- Are standard instances lawful and useful without bypassing invariants? Can+ known defaults use existing total values instead of partial construction?+- Does a workflow helper manage intermediate secrets automatically while keeping+ advanced scoped composition available? Are cleanup and cancellation preserved?+- Are pure values and native effects separated according to audited contracts?+ Is each new abstraction justified by an actual caller workflow?+- Do compiled examples show real derivation, signing, or storage/reload work,+ with explicit imports, logical spacing, total matches, and one failure boundary?+ Are the guide, Haddock, tests, and native contracts consistent?++## File headers, sections, and function size++Start every Haskell source file with the Apache-2.0 copyright and license+notice used by neighboring modules, before language pragmas. Keep the module's+Haddock introduction immediately before its declaration. License notices are+ordinary comments, not API documentation.++Use consistent comment banners, similar to the C sources, for meaningful groups:++```haskell+-- IMPORTS --------------------------------------------------------------------++-- TYPES ----------------------------------------------------------------------++-- DEFINITIONS ---------------------------------------------------------------++-- FOREIGN IMPORTS ------------------------------------------------------------+```++Use these general names consistently: `IMPORTS` for module imports, `TYPES` for+data and type declarations and their instances, `DEFINITIONS` for functions and+other value bindings, and `FOREIGN IMPORTS` for FFI declarations. Do not add+domain-specific banners, empty sections, or a banner per declaration. Small+modules need only the sections they use. Export-list Haddock headings may remain+domain-oriented for navigation in generated API documentation.++Keep functions focused on one responsibility. Prefer short orchestration functions+and named helpers for distinct validation, acquisition, execution, and conversion+steps. Roughly 20–30 lines is a review prompt, not a hard limit: never split a+resource scope or cancellation protocol merely to meet a line count. Helpers must+clarify intent and retain the same exception masking, cleanup, evaluation order,+and resource lifetime. Keep closely related local helpers local when that makes+their scope clearer. Name test scenarios instead of embedding long sequences in+the test tree; preserve lifecycle-test ordering where global counters require it.++Keep C headers out of Haskell source. Write native constants explicitly and record+their source in internal comments; verify them against the pinned headers in tests.+Keep ABI-dependent representation conversions in small C adapters. Do not replace+header-derived types with guessed platform sizes or signedness.
@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.
@@ -0,0 +1,455 @@+<div align="center">++<img src="assets/cometa_hs.png" alt="Cometa.hs" width="320" />++[API documentation](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html) · [Examples](examples/README.md) · [User guide](https://cometahs.readthedocs.io/en/latest/)++</div>++# Cometa.hs++Haskell bindings to [cardano-c](https://github.com/Biglup/cardano-c) for building,+signing and inspecting Cardano transactions. Compose immutable transaction plans,+work with typed addresses, assets and credentials, and use Blockfrost, Koios, Kupmios or Hydra, or supply your own backend.++Pure validation returns `Either Error`; native operations and network requests+return `IO (Either Error a)`. Private keys stay inside explicit resource scopes.++[Build](#build) · [Send a payment](#build-sign-and-submit-a-payment) ·+[Explore the API](#explore-the-api) · [Run the examples](#run-the-examples)++## Build++Version 0.1.0.0 is available as a [Hackage candidate](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate).++The development version is 0.2.0.0 and uses cardano-c v2.0.0-rc.7 through+cardano-c-clib 0.1.1.0. Protocol parameter 55 now uses+`parameterRefInputsCostPerMultiAssetByte` and `updateRefInputsCostPerMultiAssetByte`.+Use `Builder.defaultConfig` and set `Builder.poolState` to the latest registered+pool parameters when estimating protocol-12 owner witnesses; prefer pending+parameters over active ones. Unknown pools retain conservative estimates.++It is not yet in the main package index. To build this checkout, use GHC 9.6.7+or 9.10.3, Cabal and a C toolchain. Prepare the bundled native sources from the+revision in [`native/cardano-c.ref`](native/cardano-c.ref):++```sh+python3 tools/package-native.py /path/to/pinned/cardano-c+cabal build all+cabal run cometa-bip39+```++See [installation](docs/userguide/installation.md) for platform requirements and+linking an installed native library. Applications depend on `cometa`; Blockfrost+is part of the same library.++## Build, sign and submit a payment++The [payment example](examples/SendLovelace.hs) reads a recipient and amount,+unlocks the encrypted wallet, and runs the complete transaction lifecycle.+Its local functions keep validation and wallet plumbing out of the main flow:++```haskell+main :: IO ()+main = Support.entrypoint "SendLovelace" (runExceptT . payment)++payment :: WalletContext -> ExceptT Error IO Tx.Transaction+payment wallet = do+ output <- readPaymentOutput++ submitPlan (Support.context wallet) (Plan.payTo output)++submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx+```++These are local example functions, not an additional library API. Their+[implementations are in the same file](examples/SendLovelace.hs): fetch current+parameters and wallet inputs, build with `Builder.build`, sign with the scoped+wallet, submit once, and wait for confirmation and wallet indexing. The wallet+prompts for its password; `runExceptT` hands any failure to the runner once.++## Explore the API++A `Plan` describes what a transaction should do. Compose requirements with+`(<>)`, then pass the whole plan to `Builder.build`. Output order is preserved;+conflicting requirements and protocol constraints are checked when building.++The functions below use typed inputs: addresses parsed with `Address.fromText`,+credentials derived from the wallet, and UTxOs resolved through a provider. The+transaction recipes return plans; the payment workflow above shows how to build,+sign and submit them. The final example inspects an existing transaction.+Amounts are integer lovelace: **1 ADA = 1,000,000 lovelace**.++<details>+<summary>Imports for the API examples</summary>++```haskell+{-# LANGUAGE OverloadedStrings #-}++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Inspection as Inspection+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Value as Value+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.Aeson as Aeson+import Data.ByteString (ByteString)+import Data.Word (Word64)+```++</details>++### Send ADA and native assets together++Pay two recipients, send tokens alongside ADA, and set an expiry slot. Output+construction is pure; the builder checks minimum ADA and selects wallet inputs.++```haskell+payments ::+ Address.Address ->+ Address.Address ->+ Asset.AssetId ->+ Word64 ->+ Either Error Plan.Plan+payments alice bob token expiry = do+ adaOutput <- Output.mkOutput alice (Value.lovelace 5000000) Datum.NoDatum Nothing++ let tokenValue = Value.lovelace 2000000 <> Value.singleton token 25+ tokenOutput <- Output.mkOutput bob tokenValue Datum.NoDatum Nothing++ pure $+ Plan.payTo adaOutput+ <> Plan.payTo tokenOutput+ <> Plan.validUntil expiry+```++### Mint tokens and attach metadata++Build a native policy requiring the wallet's signature, derive its policy ID,+mint 100 tokens and attach a text message under metadata label 674. Minted tokens+can go to the builder's change output or an explicit `Plan.payTo` output.++```haskell+mintTokens :: Credential.KeyHash Credential.Payment -> IO (Either Error Plan.Plan)+mintTokens paymentKey = runExceptT $ do+ let script = Script.Native (Native.signature paymentKey)+ scriptHash <- ExceptT (Script.hash script)++ name <- except (AssetName.fromText "CometaToken")+ message <- except (Metadata.mkText "Minted with Cometa.hs")+ messageKey <- except (Metadata.mkText "msg")++ let token = Asset.Native (Policy.fromScriptHash scriptHash) name+ metadata = Metadata.map [(messageKey, Metadata.list [message])]++ pure $+ Plan.attachScript script+ <> Plan.mint token 100+ <> Plan.metadata 674 metadata+```++A negative mint quantity burns tokens: `Plan.mint token (-50)`. Plutus policies+use `Plan.mintWithRedeemer token quantity redeemer`, together with an attached+script or a reference input. See the complete+[native mint/burn](examples/MintBurnNativeScript.hs) and+[Plutus mint/burn](examples/MintBurnPlutusScript.hs) examples for CIP-25 metadata+and the confirmed mint → burn sequence.++### Lock funds with an inline datum++Construct Plutus data in Haskell and attach it directly to a script output. Here,+the datum is a constructor containing an order number and an amount; its shape+must match the validator's schema.++```haskell+lockFunds :: Address.Address -> Either Error Plan.Plan+lockFunds scriptAddress = do+ let order = Data.fromData (Data.Constr 0 [Data.Integer 42, Data.Integer 100])++ output <-+ Output.mkOutput+ scriptAddress+ (Value.lovelace 10000000)+ (Datum.InlineDatum order)+ Nothing++ pure (Plan.payTo output)+```++### Spend through a reference script++Supply the resolved locked output, a UTxO carrying its validator, and the+validator's expected redeemer. The plan references the deployed script instead+of including another copy in its witnesses.++```haskell+spendLocked ::+ Utxo.Utxo ->+ Utxo.Utxo ->+ Data.EncodedPlutusData ->+ Output.Output ->+ Plan.Plan+spendLocked locked validatorReference redeemer payout =+ Plan.referenceInput validatorReference+ <> Plan.spendWith locked (Just redeemer) Nothing+ <> Plan.payTo payout+```++Plutus builds need compatible protocol parameters, an evaluator and collateral+in `Builder.Config`. The [validator example](examples/SpendFromValidator.hs)+shows the complete lock, confirm and spend workflow.++### Compute a redeemer after balancing++Input ordering can change while the builder balances a transaction. A deferred+redeemer receives the current draft and computes its argument from the final+input position rather than guessing an index in advance.++```haskell+spendWithOwnIndex :: Utxo.Utxo -> Script.Script -> Plan.Plan+spendWithOwnIndex locked validator =+ Plan.attachScript validator+ <> Plan.spendWithDeferredRedeemer locked ownIndex Nothing+ where+ ownIndex draft _ = do+ index <- case Indices.findInput (Utxo.input locked) draft of+ Nothing -> Left (InvalidBuildingRequest "Locked input is missing")+ Just position -> Right position++ pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger index)]))+```++Callbacks may run repeatedly during balancing and should remain pure. The+[self-index](examples/DeferredRedeemerSelfIndex.hs) and+[order settlement](examples/DeferredRedeemerBatch.hs) examples provide matching+validators and complete transactions. Deferred arguments also support minting,+certificates, withdrawals, votes and proposals.++### Register and delegate a stake credential++Combine registration, pool delegation and voting-power delegation in one plan.+Supply the current key deposit from protocol parameters and a fresh,+key-controlled stake credential.++```haskell+registerStake ::+ Credential.Credential Credential.Stake ->+ Credential.KeyHash Credential.StakePool ->+ Word64 ->+ Plan.Plan+registerStake stake pool deposit =+ Plan.certificate (Certificate.Registration stake deposit)+ <> Plan.certificate (Certificate.StakeDelegation stake pool)+ <> Plan.certificate (Certificate.VoteDelegation stake DRep.AlwaysAbstain)+```++Later, withdraw the available rewards and reclaim the registration deposit. Use+the reward account derived from the same stake credential, and supply the deposit+recorded for its registration.++```haskell+closeStake ::+ Reward.RewardAddress ->+ Credential.Credential Credential.Stake ->+ Word64 ->+ Word64 ->+ Plan.Plan+closeStake account stake rewards refund =+ Plan.withdraw account rewards+ <> Plan.certificate (Certificate.Unregistration stake refund)+```++See the [key](examples/RewardAccountPubkey.hs) and+[script](examples/RewardAccountScript.hs) versions for querying rewards,+supplying witnesses and confirming each stage.++### Vote, donate and propose treasury withdrawals++A registered, key-controlled DRep can vote on an existing governance action and+include a treasury donation in the same transaction.++```haskell+voteAndDonate ::+ Credential.Credential Credential.DRep ->+ ActionId.ActionId ->+ Plan.Plan+voteAndDonate representative action =+ Plan.vote+ (Voting.DRepVoter representative)+ action+ (Voting.VotingProcedure Voting.Yes Nothing)+ <> Plan.donate 2000000+```++A treasury withdrawal is a **proposal**, not an immediate transfer. Its deposit+comes from protocol parameters; the supplied anchor identifies the proposal's+metadata. This version targets a constitution without a guardrails policy.++```haskell+proposeWithdrawal ::+ Reward.RewardAddress ->+ Word64 ->+ Anchor.Anchor ->+ Either Error Plan.Plan+proposeWithdrawal returnAccount amount anchor = do+ withdrawals <- Action.withdrawalsFromList [(returnAccount, amount)]++ pure $+ Plan.propose+ returnAccount+ (Action.TreasuryWithdrawals withdrawals Nothing)+ anchor+```++The executable [proposal example](examples/ProposeTreasuryWithdrawal.hs) covers+a constitution guardrails policy using a reference script. There are also+complete [DRep registration](examples/DRepPubkey.hs) and+[script-authorized voting](examples/VoteForProposalScript.hs) flows.++### Batch independently signed subtransactions++Attach signed intents without changing their bytes or signatures. Each intent+comes with its resolved spending and reference inputs; the outer transaction+supplies the fee and any net funding deficit.++```haskell+batchIntents ::+ Credential.Credential Credential.Guard ->+ [(Sub.SubTransaction, [Utxo.Utxo])] ->+ Plan.Plan+batchIntents batcher intents =+ foldMap (uncurry Plan.attachSubTransaction) intents+ <> Plan.requireGuard batcher+```++This requires a protocol-12+ network. The+[three-wallet exchange](examples/SubTransactionBatch.hs) builds and signs the+buyer and seller intents before the batcher submits them; the+[V4 example](examples/PlutusV4GuardedSubTransaction.hs) adds a script guard.++### Decode and inspect transaction CBOR++Read an existing transaction and inspect its body, witnesses and other fields as+JSON. Inspection does not sign, submit or establish ledger validity.++```haskell+inspectTransaction :: ByteString -> IO (Either Error Aeson.Value)+inspectTransaction cbor = runExceptT $ do+ transaction <- except (Tx.decodeCbor cbor)+ ExceptT (Inspection.transaction transaction)+```++The API also exposes typed addresses, BIP39/BIP32 derivation, encrypted software+key handlers, CIP-8 message signatures, CBOR codecs, transaction balancing and+provider callbacks. Browse the [API reference](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html)+for their contracts and the runnable examples below for complete applications.++## Providers++Use the same `Cometa.Provider` workflow with Blockfrost, Koios, Kupmios (Kupo ++Ogmios), or an existing Hydra Head:++```haskell+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Koios as Koios++parameters <- Koios.withProvider (Koios.defaultConfig Koios.Preprod Nothing) $+ Provider.protocolParameters+```++[Provider configuration and contracts](docs/userguide/providers.md) cover+credentials, explicit networks, bounded HTTP requests, and Hydra's L2 snapshot+confirmation. Hydra has no remote evaluator or staking rewards; use a local+evaluator for script transactions inside a Head.++## Run the examples++Start by importing a recovery phrase into an encrypted wallet file. The terminal+hides both the recovery phrase and password as you type:++```sh+cabal run cometa-secure-key-handler -- wallet.key+export COMETA_KEY_HANDLER_FILE="$PWD/wallet.key"+export COMETA_NETWORK=preprod+export BLOCKFROST_PROJECT_ID="your-preprod-project-id"+```++Set a current `COMETA_INVALID_AFTER_SLOT`, `COMETA_RECIPIENT` and+`COMETA_LOVELACE` using the [connected examples guide](docs/userguide/connected-examples.md).+Then run:++```sh+cabal run cometa-send-lovelace -- --describe+cabal run cometa-send-lovelace+```++Each transaction example shows its plan, build, sign, submit and confirmation+steps in one file. Shared helpers handle wallet/provider setup. The examples+prompt for the encrypted wallet password and submit on chain. Multi-stage+examples confirm each transaction before continuing. `--help` prints usage without network requests.++| Example | What it demonstrates |+| --- | --- |+| [BIP39](examples/Bip39.hs) | Recover keys and derive an address from a mnemonic. |+| [Encrypted wallet](examples/SecureKeyHandler.hs) | Import a recovery phrase, encrypt, save and reopen a wallet. |+| [Provider](examples/Provider.hs) | Query protocol parameters, UTxOs and rewards. |+| [Send lovelace](examples/SendLovelace.hs) | Build, sign, submit and confirm a payment. |+| [Native mint/burn](examples/MintBurnNativeScript.hs) | Mint tokens with CIP-25 metadata, then burn tokens. |+| [Plutus mint/burn](examples/MintBurnPlutusScript.hs) | Mint and burn through a reference policy. |+| [Native script spend](examples/SpendFromNativeScript.hs) | Fund a script address, then spend its output. |+| [Validator spend](examples/SpendFromValidator.hs) | Lock funds and spend with a Plutus validator. |+| [Deferred self index](examples/DeferredRedeemerSelfIndex.hs) | Compute a redeemer after input ordering is known. |+| [Deferred batch](examples/DeferredRedeemerBatch.hs) | Fund and settle two script orders. |+| [Stake key](examples/RewardAccountPubkey.hs) / [stake script](examples/RewardAccountScript.hs) | Register, delegate, withdraw and deregister. |+| [DRep key](examples/DRepPubkey.hs) / [DRep script](examples/DRepScript.hs) | Register a representative, delegate and clean up. |+| [Key vote](examples/VoteForProposalPubkey.hs) / [script vote](examples/VoteForProposalScript.hs) | Register, vote on a proposal and deregister. |+| [Treasury donation](examples/DonateToTreasury.hs) | Donate ADA to the treasury. |+| [Treasury withdrawal](examples/ProposeTreasuryWithdrawal.hs) | Submit a treasury withdrawal proposal. |+| [Deferred withdrawal](examples/DeferredWithdrawZero.hs) | Forward input indexes through a withdrawal redeemer. |+| [Subtransaction batch](examples/SubTransactionBatch.hs) | Three encrypted wallets sign and settle a buyer/seller exchange. |+| [Guarded subtransaction](examples/PlutusV4GuardedSubTransaction.hs) | Sign a guarded V4 intent and submit its enclosing batch. |+| [Sign data](examples/SignData.hs) | Produce a CIP-8 message signature offline. |++See the [example index](examples/README.md) for Cabal commands and+[governance setup](docs/userguide/connected-governance.md) for required chain state.+The batch and V4 examples require a network supporting protocol 12 or later.+BIP39 and data-signing demos use public demonstration keys; never fund them.++## Contributing++See [development](docs/userguide/development.md) and+[coding conventions](CODING_CONVENTIONS.md). Run `cabal test all+--test-show-details=direct` and the configured formatter and linter before+submitting changes.++Licensed under [Apache-2.0](LICENSE). The bundled native dependency includes+third-party components with their own [notices](native/NOTICE).
binary file changed (absent → 39107 bytes)
@@ -0,0 +1,151 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Small offline wall-clock baselines, not a statistical benchmark suite.+-- Run an optimized build with an optional positive iteration count (default 100):+-- @cabal bench cometa-performance --benchmark-options="1000 +RTS -s -RTS"@.+-- RTS statistics include setup and all operations, and exclude native allocations.+module Main (main) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey+import Cometa.Error (Error)+import qualified Cometa.NetworkId as Network+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Inspection as Inspection+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Value+import Control.Exception (evaluate)+import Control.Monad.Trans.Except (except, runExceptT)+import qualified Data.Aeson as Aeson+import qualified Data.ByteString as Bytes+import qualified Data.ByteString.Lazy as Lazy+import Data.IORef (newIORef, readIORef)+import qualified Fixtures.ProtocolParameters as Fixture+import GHC.Clock (getMonotonicTimeNSec)+import System.Environment (getArgs)+import System.Exit (die)+import System.Mem (performGC)+import Text.Printf (printf)+import Text.Read (readMaybe)++-- DEFINITIONS ----------------------------------------------------------------++main :: IO ()+main = do+ iterations <- getArgs >>= parseIterations+ (config, plan) <- paymentFixture >>= require+ transaction <- Builder.build config plan >>= require+ encoded <- evaluate (Tx.encodeCbor transaction)+ -- Reading the fixed input through IO on every iteration prevents a shared+ -- decode/encode thunk from replacing repeated work under optimization.+ encodedInput <- newIORef encoded+ printf "Offline baseline: %d iterations per operation; one untimed warm-up each.\n" iterations+ putStrLn "Times include result consumption and loop overhead; no network is used."+ measure iterations "native payment build" $ do+ built <- Builder.build config plan >>= require+ consumeBytes (Tx.encodeCbor built)+ -- Synthetic public fixture bytes only. Acquire once, outside signing timing.+ result <- SigningKey.withNormalKey (Bytes.replicate 32 7) $ \key -> do+ measure iterations "native transaction signing" $ do+ signed <- Signing.sign key transaction >>= require+ consumeBytes (Tx.encodeCbor signed)+ pure (Right ())+ require result+ measure iterations "native inspection + JSON encode" $ do+ inspected <- Inspection.transaction transaction >>= require+ evaluate (Lazy.foldl' (\total byte -> total + fromIntegral byte) (0 :: Int) (Aeson.encode inspected))+ measure iterations "CBOR decode + exact encode" $ do+ input <- readIORef encodedInput+ decoded <- require (Tx.decodeCbor input)+ consumeBytes (Tx.encodeCbor decoded)++-- | Validate CLI input before fixture setup. A bounded Int also bounds the loop.+parseIterations :: [String] -> IO Int+parseIterations arguments = case arguments of+ [] -> pure 100+ [argument] -> case readMaybe argument of+ Just count | count > 0 -> pure count+ _ -> usage+ _ -> usage+ where+ usage = die "Usage: cometa-performance [positive-iterations] [+RTS -s -RTS]"++-- | Traverse every output byte, forcing serialization within the timed action.+consumeBytes :: Bytes.ByteString -> IO Int+consumeBytes = evaluate . Bytes.foldl' (\total byte -> total + fromIntegral byte) 0++-- | Warm once, collect before timing, and retain an observed strict checksum.+-- Fixed input measures repeated execution with warm caches. Decode preserves+-- original component bytes; this is not a canonicalizing re-encoder baseline.+measure :: Int -> String -> IO Int -> IO ()+measure iterations label action = do+ _ <- action+ performGC+ start <- getMonotonicTimeNSec+ checksum <- loop iterations 0+ end <- getMonotonicTimeNSec+ let elapsed = fromIntegral (end - start) / 1000000 :: Double+ printf "%s: %.3f ms total, %.3f us/op (checksum %d)\n" label elapsed (elapsed * 1000 / fromIntegral iterations) checksum+ where+ loop remaining checksum+ | remaining == 0 = pure checksum+ | otherwise = do+ observed <- action+ next <- evaluate (checksum + observed)+ loop (remaining - 1) next++-- | Stop on unexpected fixture/native failures instead of timing error paths.+require :: (Show failure) => Either failure value -> IO value+require = either (die . show) pure++-- | Prepare the same small payment shape as the offline building example.+-- The full-field parameter fixture is synthetic and is not a network snapshot.+paymentFixture :: IO (Either Error (Builder.Config, Plan.Plan))+paymentFixture = runExceptT $ do+ raw <- except Fixture.parameters+ key <- except (Credential.keyHashFromBytes (Bytes.replicate 28 7))+ previous <- except (TxId.fromBytes (Bytes.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ parameters =+ raw+ { Parameters.parameterMinFeeA = 44,+ Parameters.parameterMinFeeB = 155381,+ Parameters.parameterMaxTxSize = 16384,+ Parameters.parameterMaxValueSize = Just 5000,+ Parameters.parameterAdaPerUtxoByte = Just 4310,+ Parameters.parameterProtocolVersion = Version.ProtocolVersion 10 0+ }+ funding <- except (Output.mkOutput destination (Value.lovelace 10000000) Datum.NoDatum Nothing)+ payment <- except (Output.mkOutput destination (Value.lovelace 2000000) Datum.NoDatum Nothing)+ let config =+ (Builder.defaultConfig parameters Slot.preview destination)+ { Builder.availableUtxos = [Utxo.utxo (Input.input previous 0) funding]+ }+ pure (config, Plan.payTo payment <> Plan.validUntil 1000000)
@@ -0,0 +1,124 @@+/**+ * \file cometa_bip32.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_bip32.h"+#include <cardano/crypto/bip32_public_key.h>++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_bip32_from_bytes(const unsigned char* data, size_t size, cardano_bip32_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_from_bytes(data, size, key);+}++unsigned int+cometa_bip32_from_hex(const unsigned char* data, size_t size, cardano_bip32_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_from_hex((const char*)data, size, key);+}++unsigned int+cometa_bip32_from_entropy(const unsigned char* password, size_t password_size, const unsigned char* entropy, size_t entropy_size, cardano_bip32_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_from_bip39_entropy(password, password_size, entropy, entropy_size, key);+}++unsigned int+cometa_bip32_clone(const cardano_bip32_private_key_t* source, cardano_bip32_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_deep_clone(source, key);+}++unsigned int+cometa_bip32_derive(const cardano_bip32_private_key_t* source, const uint32_t* indices, size_t count, cardano_bip32_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_derive(source, indices, count, key);+}++unsigned int+cometa_bip32_to_signing_key(const cardano_bip32_private_key_t* source, cardano_ed25519_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_bip32_private_key_to_ed25519_key(source, key);+}++void+cometa_bip32_unref(cardano_bip32_private_key_t** key)+{+ cardano_bip32_private_key_unref(key);+}++const unsigned char*+cometa_bip32_data(const cardano_bip32_private_key_t* key)+{+ return cardano_bip32_private_key_get_data(key);+}++size_t+cometa_bip32_size(const cardano_bip32_private_key_t* key)+{+ return cardano_bip32_private_key_get_bytes_size(key);+}++unsigned int+cometa_bip32_public_key(const cardano_bip32_private_key_t* key, unsigned char* output)+{+ cardano_bip32_public_key_t* public_key = NULL;+ cardano_error_t result = cardano_bip32_private_key_get_public_key(key, &public_key);++ if (result == CARDANO_SUCCESS)+ {+ result = public_key == NULL ? CARDANO_ERROR_GENERIC : cardano_bip32_public_key_to_bytes(public_key, output, 64U);+ }++ cardano_bip32_public_key_unref(&public_key);++ return (unsigned int)result;+}++unsigned int+cometa_bip32_derive_public(const unsigned char* bytes, const uint32_t* indices, size_t count, unsigned char* output)+{+ cardano_bip32_public_key_t* source = NULL;+ cardano_bip32_public_key_t* derived = NULL;+ cardano_error_t result = cardano_bip32_public_key_from_bytes(bytes, 64U, &source);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_bip32_public_key_derive(source, indices, count, &derived);+ }++ if (result == CARDANO_SUCCESS)+ {+ result = derived == NULL ? CARDANO_ERROR_GENERIC : cardano_bip32_public_key_to_bytes(derived, output, 64U);+ }++ cardano_bip32_public_key_unref(&derived);+ cardano_bip32_public_key_unref(&source);++ return (unsigned int)result;+}
@@ -0,0 +1,133 @@+/**+ * \file cometa_bip32.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_BIP32_H+#define BIGLUP_LABS_INCLUDE_COMETA_BIP32_H++/* INCLUDES ******************************************************************/++#include <cardano/crypto/bip32_private_key.h>+#include <stddef.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif++/**+ * \brief Import borrowed 96-byte secret data into one owned output.+ * \param[in] data Borrowed input; valid until return.+ * \param[in] size Byte length, exactly 96.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_from_bytes(const unsigned char* data, size_t size, cardano_bip32_private_key_t** key);++/**+ * \brief Import borrowed validated 192-digit ASCII hex into one owned output.+ * \param[in] data Borrowed input; valid until return.+ * \param[in] size Digit count, exactly 192; no terminator.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_from_hex(const unsigned char* data, size_t size, cardano_bip32_private_key_t** key);++/**+ * \brief Derive one owned root; password and entropy are borrowed until return.+ * \param[in] password Borrowed input; valid until return.+ * \param[in] password_size Password byte count; zero is permitted.+ * \param[in] entropy Borrowed nonempty entropy bytes, valid until return.+ * \param[in] entropy_size Entropy byte count.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_from_entropy(const unsigned char* password, size_t password_size, const unsigned char* entropy, size_t entropy_size, cardano_bip32_private_key_t** key);++/**+ * \brief Clone a locked borrowed source into independent owned storage.+ * \param[in] source Borrowed input; valid until return.+ * \param[out] key Initialized to NULL; receives one independent owned reference.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_clone(const cardano_bip32_private_key_t* source, cardano_bip32_private_key_t** key);++/**+ * \brief Derive an owned key from locked source and borrowed nonempty path.+ * \param[in] source Borrowed input; valid until return.+ * \param[in] indices Borrowed encoded indices, valid until return.+ * \param[in] count Number of indices; must be positive.+ * \param[out] key Initialized to NULL; receives one independent owned reference.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_derive(const cardano_bip32_private_key_t* source, const uint32_t* indices, size_t count, cardano_bip32_private_key_t** key);++/**+ * \brief Copy locked source into one owned extended Ed25519 key.+ * \param[in] source Borrowed input; valid until return.+ * \param[out] key Initialized to NULL; receives one independent owned signing key.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_to_signing_key(const cardano_bip32_private_key_t* source, cardano_ed25519_private_key_t** key);++/**+ * \brief Consume one reference; callers clear their local slot even for retained aliases.+ * \param[in,out] key Owned local slot; NULL is tolerated.+ * \returns No result.+ */+void cometa_bip32_unref(cardano_bip32_private_key_t** key);++/**+ * \brief Borrow secret storage only while holding the key lock.+ * \param[in] key Live locked borrowed key.+ * \returns Borrowed bytes; never release or mutate.+ */+const unsigned char* cometa_bip32_data(const cardano_bip32_private_key_t* key);++/**+ * \brief Read fixed length while holding the key lock.+ * \param[in] key Live locked borrowed key.+ * \returns Native byte length.+ */+size_t cometa_bip32_size(const cardano_bip32_private_key_t* key);++/**+ * \brief Copy 64 public bytes to caller buffer; release temporary public owner on every path.+ * \param[in] key Borrowed input; valid until return.+ * \param[out] output Caller-owned 64-byte buffer, valid until return.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_public_key(const cardano_bip32_private_key_t* key, unsigned char* output);++/**+ * \brief Borrow 64 input bytes and nonempty path; write 64 output bytes only on success.+ * \param[in] bytes Borrowed input; valid until return.+ * \param[in] indices Borrowed soft indices, valid until return.+ * \param[in] count Number of indices; must be positive.+ * \param[out] output Caller-owned 64-byte buffer, valid until return.+ * \returns cardano-c status as unsigned int; outputs are valid only on success.+ */+unsigned int cometa_bip32_derive_public(const unsigned char* bytes, const uint32_t* indices, size_t count, unsigned char* output);++#ifdef __cplusplus+}+#endif++#endif /* BIGLUP_LABS_INCLUDE_COMETA_BIP32_H */
@@ -0,0 +1,36 @@+/**+ * \file cometa_bip39.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_bip39.h"++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_bip39_from_entropy(const unsigned char* entropy, size_t size, const char** words, size_t* count)+{+ return (unsigned int)cardano_bip39_entropy_to_mnemonic_words(entropy, size, words, count);+}++unsigned int+cometa_bip39_to_entropy(const char** words, size_t count, unsigned char* entropy, size_t capacity, size_t* size)+{+ return (unsigned int)cardano_bip39_mnemonic_words_to_entropy(words, count, entropy, capacity, size);+}
@@ -0,0 +1,58 @@+/**+ * \file cometa_bip39.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_BIP39_H+#define BIGLUP_LABS_INCLUDE_COMETA_BIP39_H++/* INCLUDES ******************************************************************/++#include <cardano/bip39.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif++/**+ * \brief Convert borrowed entropy to borrowed static English words.+ * \param[in] entropy Borrowed bytes, valid until return.+ * \param[in] size Validated byte count: 16, 20, 24, 28 or 32.+ * \param[out] words Caller-owned array of 24 slots; returned strings must not be freed.+ * \param[out] count Number of words on success.+ * \return Native status converted to unsigned int; outputs valid only on success.+ */+unsigned int cometa_bip39_from_entropy(const unsigned char* entropy, size_t size, const char** words, size_t* count);++/**+ * \brief Convert borrowed words to caller-owned entropy; no ownership transfer.+ * \param[in] words Borrowed NUL-terminated words, valid until return.+ * \param[in] count Validated word count: 12, 15, 18, 21 or 24.+ * \param[out] entropy Caller-owned scratch buffer; wipe even on checksum failure.+ * \param[in] capacity Entropy buffer byte capacity, at least 32.+ * \param[out] size Entropy byte count; output may be written before failure.+ * \return Native status converted to unsigned int; outputs valid only on success.+ */+unsigned int cometa_bip39_to_entropy(const char** words, size_t count, unsigned char* entropy, size_t capacity, size_t* size);++#ifdef __cplusplus+}+#endif++#endif /* BIGLUP_LABS_INCLUDE_COMETA_BIP39_H */
@@ -0,0 +1,257 @@+/**+ * \file cometa_building.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_building.h"+#include "cometa_parameters.h"++/* STATIC FUNCTIONS **********************************************************/++/** \brief Decode a retained UTxO list; release each local item after insertion. */+static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count < 0)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(output);+ }+ for (int64_t i = 0; result == CARDANO_SUCCESS && i < count; ++i)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_from_cbor(reader, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, item);+ }+ cardano_utxo_unref(&item);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/** \brief Materialize one owned parameter set from its encoded snapshot. */+static cardano_error_t+read_parameters(cardano_cbor_reader_t* reader, cardano_protocol_parameters_t** output)+{+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_encoded_value(reader, &bytes);+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_parameters_from_snapshot(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), output);+ }+ cardano_buffer_unref(&bytes);+ return result;+}++/** \brief Hash exact native witness fields, releasing both retained getters. */+static cardano_error_t+write_script_hash(cardano_cbor_reader_t* reader, cardano_cbor_writer_t* writer)+{+ cardano_costmdls_t* models = NULL;+ cardano_witness_set_t* witnesses = NULL;+ cardano_blake2b_hash_t* hash = NULL;+ cardano_plutus_data_set_t* datums = NULL;+ cardano_redeemer_list_t* redeemers = NULL;+ cardano_error_t result = cardano_costmdls_from_cbor(reader, &models);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_from_cbor(reader, &witnesses);+ }+ if (result == CARDANO_SUCCESS)+ {+ datums = cardano_witness_set_get_plutus_data(witnesses);+ redeemers = cardano_witness_set_get_redeemers(witnesses);+ result = cardano_compute_script_data_hash(models, redeemers, datums, &hash);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = hash == NULL ? cardano_cbor_writer_write_null(writer) : cardano_cbor_writer_write_bytestring(writer, cardano_blake2b_hash_get_data(hash), cardano_blake2b_hash_get_bytes_size(hash));+ }+ cardano_blake2b_hash_unref(&hash);+ cardano_redeemer_list_unref(&redeemers);+ cardano_plutus_data_set_unref(&datums);+ cardano_witness_set_unref(&witnesses);+ cardano_costmdls_unref(&models);+ return result;+}++/** \brief Encode signed imbalance coin and assets without unsigned ledger Value encoding. */+static cardano_error_t+write_imbalance(cardano_cbor_writer_t* writer, cardano_value_t* value)+{+ cardano_multi_asset_t* assets = cardano_value_get_multi_asset(value);+ cardano_error_t result = cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_signed_int(writer, cardano_value_get_coin(value));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_multi_asset_to_cbor(assets, writer);+ }+ cardano_multi_asset_unref(&assets);+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_building_compute(unsigned int operation, const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ *output = NULL;+ cardano_value_t* imbalance = NULL;+ cardano_sub_transaction_t* sub_tx = NULL;+ cardano_transaction_t* tx = NULL;+ cardano_protocol_parameters_t* parameters = NULL;+ cardano_utxo_list_t* references = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ int64_t count = 0;+ uint64_t amount = 0U;+ uint64_t constant = 0U;+ uint64_t coefficient = 0U;+ cardano_implicit_coin_t implicit = { 0 };+ cardano_error_t result = reader == NULL || writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && (operation > 8U || count != ((operation == 0U || operation == 4U || operation >= 6U) ? 3 : 2)))+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (result == CARDANO_SUCCESS && operation == 3U)+ {+ result = write_script_hash(reader, writer);+ }+ if (result == CARDANO_SUCCESS && operation != 1U && operation != 3U && operation != 5U && operation != 7U)+ {+ result = cardano_transaction_from_cbor(reader, &tx);+ }+ if (result == CARDANO_SUCCESS && (operation == 5U || operation == 7U))+ {+ result = cardano_sub_transaction_from_cbor(reader, &sub_tx);+ }+ if (result == CARDANO_SUCCESS && (operation < 3U || operation >= 5U))+ {+ result = read_parameters(reader, ¶meters);+ }+ if (result == CARDANO_SUCCESS && (operation < 2U || operation >= 6U))+ {+ result = read_utxos(reader, &references);+ }+ if (result == CARDANO_SUCCESS && operation == 4U)+ {+ result = cardano_cbor_reader_read_uint(reader, &constant);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &coefficient);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ switch (operation)+ {+ case 0U:+ result = cardano_compute_transaction_fee(tx, references, parameters, &amount);+ break;+ case 1U:+ result = cardano_compute_script_ref_fee_with_params(references, parameters, &amount);+ break;+ case 2U:+ result = cardano_compute_implicit_coin(tx, parameters, &implicit);+ break;+ case 5U:+ result = cardano_compute_sub_transaction_implicit_coin(sub_tx, parameters, &implicit);+ break;+ case 6U:+ result = cardano_compute_transaction_imbalance(tx, references, parameters, &imbalance);+ break;+ case 7U:+ result = cardano_compute_sub_transaction_imbalance(sub_tx, references, parameters, &imbalance);+ break;+ case 8U:+ result = cardano_compute_transaction_batch_imbalance(tx, references, parameters, &imbalance);+ break;+ case 4U:+ result = cardano_compute_min_fee_without_scripts(tx, constant, coefficient, &amount);+ break;+ default:+ break;+ }+ }+ if (result == CARDANO_SUCCESS && operation != 3U)+ {+ if (operation >= 6U)+ {+ result = write_imbalance(writer, imbalance);+ }+ else if (operation == 2U || operation == 5U)+ {+ result = cardano_cbor_writer_write_start_array(writer, 3);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, implicit.withdrawals);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, implicit.deposits);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, implicit.reclaim_deposits);+ }+ }+ else+ {+ result = cardano_cbor_writer_write_uint(writer, amount);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ size_t remaining = 0U;+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if (result == CARDANO_SUCCESS && remaining != 0U)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_value_unref(&imbalance);+ cardano_utxo_list_unref(&references);+ cardano_protocol_parameters_unref(¶meters);+ cardano_transaction_unref(&tx);+ cardano_sub_transaction_unref(&sub_tx);+ cardano_cbor_writer_unref(&writer);+ cardano_cbor_reader_unref(&reader);+ return (unsigned int)result;+}
@@ -0,0 +1,44 @@+/**+ * \file cometa_building.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_BUILDING_H+#define BIGLUP_LABS_COMETA_BUILDING_H++/* INCLUDES ******************************************************************/++#include <cardano/cardano.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Marshal standalone building utilities through fresh native values.+ * \param operation 0 minimum fee, 1 reference fee, 2 implicit coin, 3 script+ * data hash, 4 base fee, 5 subtransaction implicit coin, 6 top-level imbalance,+ * 7 local subtransaction imbalance, 8 whole-batch imbalance. Internal CBOR tuples+ * carry domain values, never pointers.+ * \param bytes Borrowed request bytes until synchronous return.+ * \param size Complete request byte count; trailing input is rejected.+ * \param output Owned CBOR result buffer on success; NULL on failure. All native+ * objects and retained getters are released on every exit. No callbacks occur.+ * \return Native status. Unknown operations return invalid argument.+ */+unsigned int cometa_building_compute(unsigned int operation, const unsigned char* bytes, size_t size, cardano_buffer_t** output);++#endif /* BIGLUP_LABS_COMETA_BUILDING_H */
@@ -0,0 +1,459 @@+/**+ * \file cometa_cbor.c+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_cbor.h"++#include <cardano/cbor/cbor_writer.h>+#include <limits.h>+#include <stdio.h>++/* STATIC FUNCTIONS **********************************************************/++/**+ * \brief Copies a bounded diagnostic without transferring native string ownership.+ */+static void+copy_error(char* error, size_t capacity, const char* message)+{+ if ((error != NULL) && (capacity > 0U))+ {+ (void)snprintf(error, capacity, "%s", message);+ }+}++/**+ * \brief Copies a reader-local failure before its owner can be released.+ */+static unsigned int+reader_status(cardano_cbor_reader_t* reader, cardano_error_t result, char* error, size_t capacity)+{+ if (result != CARDANO_SUCCESS)+ {+ const char* message = cardano_cbor_reader_get_last_error(reader);+ copy_error(error, capacity, message[0] == '\0' ? cardano_error_to_string(result) : message);+ }++ return (unsigned int)result;+}++/**+ * \brief Encodes an owned result if writing succeeded, then releases the writer on every path.+ */+static unsigned int+finish_writer(cardano_cbor_writer_t* writer, cardano_error_t result, cardano_buffer_t** output, char* error, size_t capacity)+{+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }++ if (result != CARDANO_SUCCESS)+ {+ const char* message = cardano_cbor_writer_get_last_error(writer);+ copy_error(error, capacity, message[0] == '\0' ? cardano_error_to_string(result) : message);+ }++ cardano_cbor_writer_unref(&writer);++ return (unsigned int)result;+}++/**+ * \brief Allocates a scoped writer and initializes the caller's owned-result slot.+ */+static cardano_cbor_writer_t*+new_writer(cardano_buffer_t** output, char* error, size_t capacity)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();++ if (writer == NULL)+ {+ copy_error(error, capacity, "Failed to allocate CBOR writer.");+ }++ return writer;+}++/**+ * \brief Requires the reader to have consumed the entire input after one item.+ */+static cardano_error_t+require_finished(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);++ if ((result == CARDANO_SUCCESS) && (remaining != 0U))+ {+ cardano_cbor_reader_set_last_error(reader, "Trailing bytes after one CBOR item.");+ return CARDANO_ERROR_DECODING;+ }++ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_cbor_reader_new(const unsigned char* data, size_t size, cardano_cbor_reader_t** output, char* error, size_t error_size)+{+ *output = NULL;++ if (size == 0U)+ {+ copy_error(error, error_size, "CBOR input is empty.");+ return CARDANO_ERROR_DECODING;+ }++ *output = cardano_cbor_reader_new(data, size);++ if (*output == NULL)+ {+ copy_error(error, error_size, "Failed to allocate CBOR reader.");+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ return CARDANO_SUCCESS;+}++unsigned int+cometa_cbor_validate(const unsigned char* data, size_t size, char* error, size_t error_size)+{+ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_error_t status = cardano_cbor_reader_skip_value(reader);++ if (status == CARDANO_SUCCESS)+ {+ status = require_finished(reader);+ }++ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_encode_integer(int negative, uint64_t argument, cardano_buffer_t** output, char* error, size_t error_size)+{+ cardano_cbor_writer_t* writer = new_writer(output, error, error_size);++ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = negative != 0 ? cardano_cbor_writer_write_negative_int(writer, argument) : cardano_cbor_writer_write_uint(writer, argument);++ return finish_writer(writer, result, output, error, error_size);+}++unsigned int+cometa_cbor_decode_integer(const unsigned char* data, size_t size, int* negative, uint64_t* argument, char* error, size_t error_size)+{+ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ cardano_error_t status = cardano_cbor_reader_peek_state(reader, &state);+ *negative = state == CARDANO_CBOR_READER_STATE_NEGATIVE_INTEGER ? 1 : 0;++ if (status == CARDANO_SUCCESS)+ {+ status = *negative != 0 ? cardano_cbor_reader_read_negative_int(reader, argument) : cardano_cbor_reader_read_uint(reader, argument);+ }++ if (status == CARDANO_SUCCESS)+ {+ status = require_finished(reader);+ }++ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_encode_string(int text, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size)+{+ cardano_cbor_writer_t* writer = new_writer(output, error, error_size);++ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = text != 0 ? cardano_cbor_writer_write_textstring(writer, (const char*)data, size) : cardano_cbor_writer_write_bytestring(writer, data, size);++ return finish_writer(writer, result, output, error, error_size);+}++unsigned int+cometa_cbor_decode_string(int text, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size)+{+ *output = NULL;++ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_error_t status = text != 0 ? cardano_cbor_reader_read_textstring(reader, output) : cardano_cbor_reader_read_bytestring(reader, output);+ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_encode_bool(int value, cardano_buffer_t** output, char* error, size_t error_size)+{+ cardano_cbor_writer_t* writer = new_writer(output, error, error_size);++ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = cardano_cbor_writer_write_bool(writer, value != 0);++ return finish_writer(writer, result, output, error, error_size);+}++unsigned int+cometa_cbor_decode_bool(const unsigned char* data, size_t size, int* value, char* error, size_t error_size)+{+ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ bool native = false;+ cardano_error_t status = cardano_cbor_reader_read_bool(reader, &native);+ *value = native ? 1 : 0;+ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_encode_undefined(cardano_buffer_t** output, char* error, size_t error_size)+{+ cardano_cbor_writer_t* writer = new_writer(output, error, error_size);++ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ return finish_writer(writer, cardano_cbor_writer_write_undefined(writer), output, error, error_size);+}++unsigned int+cometa_cbor_decode_double(const unsigned char* data, size_t size, double* value, char* error, size_t error_size)+{+ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_error_t status = cardano_cbor_reader_read_double(reader, value);+ if (status == CARDANO_SUCCESS)+ {+ status = require_finished(reader);+ }+ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_decode_simple(const unsigned char* data, size_t size, uint8_t* value, char* error, size_t error_size)+{+ cardano_cbor_reader_t* reader = NULL;+ unsigned int result = cometa_cbor_reader_new(data, size, &reader, error, error_size);++ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_cbor_simple_value_t native = CARDANO_CBOR_SIMPLE_VALUE_UNDEFINED;+ cardano_error_t status = cardano_cbor_reader_read_simple_value(reader, &native);+ if (status == CARDANO_SUCCESS)+ {+ status = require_finished(reader);+ *value = (uint8_t)native;+ }+ result = reader_status(reader, status, error, error_size);+ cardano_cbor_reader_unref(&reader);++ return result;+}++unsigned int+cometa_cbor_encode_collection(int map, size_t count, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size)+{+ *output = NULL;++ if (count > INT64_MAX)+ {+ copy_error(error, error_size, "CBOR collection length exceeds the native bound.");+ return CARDANO_ERROR_INTEGER_OVERFLOW;+ }++ cardano_cbor_writer_t* writer = new_writer(output, error, error_size);++ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = map != 0 ? cardano_cbor_writer_write_start_map(writer, (int64_t)count) : cardano_cbor_writer_write_start_array(writer, (int64_t)count);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_encoded(writer, data, size);+ }++ // Definite collections have no trailing break; native end writers always emit one.+ return finish_writer(writer, result, output, error, error_size);+}++unsigned int+cometa_cbor_collection_start(cardano_cbor_reader_t* reader, int map, char* error, size_t error_size)+{+ int64_t length = 0;+ cardano_error_t result = map != 0 ? cardano_cbor_reader_read_start_map(reader, &length) : cardano_cbor_reader_read_start_array(reader, &length);++ return reader_status(reader, result, error, error_size);+}++unsigned int+cometa_cbor_collection_at_end(cardano_cbor_reader_t* reader, int map, int* at_end, char* error, size_t error_size)+{+ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ cardano_error_t result = cardano_cbor_reader_peek_state(reader, &state);+ *at_end = state == (map != 0 ? CARDANO_CBOR_READER_STATE_END_MAP : CARDANO_CBOR_READER_STATE_END_ARRAY) ? 1 : 0;++ return reader_status(reader, result, error, error_size);+}++unsigned int+cometa_cbor_collection_end(cardano_cbor_reader_t* reader, int map, char* error, size_t error_size)+{+ cardano_error_t result = map != 0 ? cardano_cbor_reader_read_end_map(reader) : cardano_cbor_reader_read_end_array(reader);++ if (result == CARDANO_SUCCESS)+ {+ result = require_finished(reader);+ }++ return reader_status(reader, result, error, error_size);+}++unsigned int+cometa_cbor_read_item(cardano_cbor_reader_t* reader, cardano_buffer_t** output, char* error, size_t error_size)+{+ *output = NULL;++ return reader_status(reader, cardano_cbor_reader_read_encoded_value(reader, output), error, error_size);+}++unsigned int+cometa_cbor_reader_remaining(cardano_cbor_reader_t* reader, size_t* remaining, char* error, size_t error_size)+{+ return reader_status(reader, cardano_cbor_reader_get_bytes_remaining(reader, remaining), error, error_size);+}++unsigned int+cometa_cbor_read_text_chunk(cardano_cbor_reader_t* reader, cardano_buffer_t** output, char* error, size_t error_size)+{+ *output = NULL;++ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ cardano_error_t result = cardano_cbor_reader_peek_state(reader, &state);++ if ((result == CARDANO_SUCCESS) && (state != CARDANO_CBOR_READER_STATE_TEXTSTRING))+ {+ cardano_cbor_reader_set_last_error(reader, "An indefinite text chunk must be a definite text string.");+ result = CARDANO_ERROR_DECODING;+ }++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_encoded_value(reader, output);+ }++ return reader_status(reader, result, error, error_size);+}++void+cometa_cbor_reader_unref(cardano_cbor_reader_t** reader)+{+ cardano_cbor_reader_unref(reader);+}++void+cometa_cbor_buffer_unref(cardano_buffer_t** buffer)+{+ cardano_buffer_unref(buffer);+}++const unsigned char*+cometa_cbor_buffer_data(const cardano_buffer_t* buffer)+{+ return cardano_buffer_get_data(buffer);+}++size_t+cometa_cbor_buffer_size(const cardano_buffer_t* buffer)+{+ return cardano_buffer_get_size(buffer);+}
@@ -0,0 +1,309 @@+/**+ * \file cometa_cbor.h+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_CBOR_H+#define BIGLUP_LABS_INCLUDE_COMETA_CBOR_H++/* INCLUDES ******************************************************************/++#include <cardano/buffer.h>+#include <cardano/cbor/cbor_reader.h>+#include <stddef.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif /* __cplusplus */++/**+ * \brief Private, synchronous CBOR adapters with an explicit unsigned status ABI.+ *+ * Data, readers, diagnostic buffers and output slots must be non-NULL unless their function contract+ * states otherwise. Diagnostic pointers may be NULL to disable copying. Every status-returning function returns a cardano-c status converted to unsigned int.+ * Diagnostic capacities count bytes including the terminator; zero capacity disables diagnostic copying.+ * Output references are initialized to NULL and belong to the caller even on a partial failure.+ * The caller must keep input storage and output slots valid until the complete synchronous call returns.+ */++/**+ * \brief Validates exactly one native-reader-accepted item. Input is borrowed; diagnostics are copied before reader release.+ *+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_validate(const unsigned char* data, size_t size, char* error, size_t error_size);++/**+ * \brief Encodes a primitive integer. A negative argument represents -1 minus argument. Output owns one buffer reference.+ *+ * \param[in] negative Zero selects unsigned encoding; nonzero selects negative encoding.+ * \param[in] argument Unsigned value, or the argument in the negative value -1 - argument.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_encode_integer(int negative, uint64_t argument, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Reads an untagged primitive integer into an exact sign and unsigned magnitude argument.+ *+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] negative Receives 1 for a negative integer and 0 for an unsigned integer.+ * \param[out] argument Receives the unsigned integer or the argument in the value -1 - argument.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_decode_integer(const unsigned char* data, size_t size, int* negative, uint64_t* argument, char* error, size_t error_size);++/**+ * \brief Encodes borrowed bytes as a byte string or UTF-8 text string. Output owns one buffer reference.+ *+ * \param[in] text Zero selects a byte string; nonzero selects a text string.+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_encode_string(int text, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Reads a byte or text string into one owned buffer, flattening indefinite chunks. UTF-8 validation belongs to Haskell.+ *+ * \param[in] text Zero selects a byte string; nonzero selects a text string.+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_decode_string(int text, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Encodes a Boolean without exposing native bool layout. Output owns one buffer reference.+ *+ * \param[in] value Zero encodes false; nonzero encodes true.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_encode_bool(int value, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Reads an untagged Boolean and writes 0 or 1 without exposing native bool layout.+ *+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] value Receives the decoded Boolean as 0 or 1.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_decode_bool(const unsigned char* data, size_t size, int* value, char* error, size_t error_size);++/**+ * \brief Encodes a definite array or map around validated concatenated items. Map count counts pairs. Child bytes remain exact.+ *+ * \param[in] map Zero selects an array; nonzero selects a map.+ * \param[in] count Array element count or map pair count; must fit INT64_MAX.+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_encode_collection(int map, size_t count, const unsigned char* data, size_t size, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Creates one owned reader that copies the borrowed input. Empty input is a decoding failure.+ *+ * \param[in] data Borrowed bytes kept valid until the call returns.+ * \param[in] size Number of bytes available at data.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_reader_new(const unsigned char* data, size_t size, cardano_cbor_reader_t** output, char* error, size_t error_size);++/**+ * \brief Opens an array or map in a borrowed reader. Both definite and indefinite lengths are accepted.+ *+ * \param[in,out] reader Borrowed reader whose parsing position is advanced or inspected.+ * \param[in] map Zero selects an array; nonzero selects a map.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_collection_start(cardano_cbor_reader_t* reader, int map, char* error, size_t error_size);++/**+ * \brief Peeks whether the borrowed reader is at the matching collection end and writes 0 or 1.+ *+ * \param[in,out] reader Borrowed reader whose parsing position is advanced or inspected.+ * \param[in] map Zero selects an array; nonzero selects a map.+ * \param[out] at_end Receives 0 or 1 indicating whether the matching collection end was reached.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_collection_at_end(cardano_cbor_reader_t* reader, int map, int* at_end, char* error, size_t error_size);++/**+ * \brief Closes the collection and rejects trailing bytes. The borrowed reader remains owned by the caller.+ *+ * \param[in,out] reader Borrowed reader whose parsing position is advanced or inspected.+ * \param[in] map Zero selects an array; nonzero selects a map.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_collection_end(cardano_cbor_reader_t* reader, int map, char* error, size_t error_size);++/**+ * \brief Copies the next encoded child into one owned buffer without normalizing its original representation.+ *+ * \param[in,out] reader Borrowed reader whose parsing position is advanced or inspected.+ * \param[out] output Receives one owned reference, including any partial result on failure.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int; output values are valid on success.+ */+unsigned int cometa_cbor_read_item(cardano_cbor_reader_t* reader, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Retrieves the unread byte count of a borrowed reader.+ *+ * \param[in] reader Borrowed reader retained until this call returns.+ * \param[out] remaining Receives the number of unread bytes.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_cbor_reader_remaining(cardano_cbor_reader_t* reader, size_t* remaining, char* error, size_t error_size);++/**+ * \brief Copies one definite-length text chunk from an indefinite text string's interior.+ *+ * \param[in,out] reader Borrowed reader advanced past exactly one definite text string.+ * \param[out] output Receives one owned buffer containing the chunk's encoded bytes.+ * \param[out] error Caller-owned diagnostic buffer; NULL disables diagnostic copying.+ * \param[in] error_size Diagnostic capacity in bytes, including the null terminator.+ *+ * \returns A native status converted to unsigned int. Tags, nested indefinite strings and other+ * chunk types return CARDANO_ERROR_DECODING. Partial output references remain caller-owned.+ */+unsigned int cometa_cbor_read_text_chunk(cardano_cbor_reader_t* reader, cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Consumes one reader reference. The caller invalidates its released slot even when another owner retains it.+ *+ * \param[in,out] reader Slot containing one reader reference to release; NULL is tolerated.+ */+void cometa_cbor_reader_unref(cardano_cbor_reader_t** reader);++/**+ * \brief Consumes one buffer reference. The caller invalidates its released slot even when another owner retains it.+ *+ * \param[in,out] buffer Slot containing one buffer reference to release; NULL is tolerated.+ */+void cometa_cbor_buffer_unref(cardano_buffer_t** buffer);++/**+ * \brief Borrows buffer storage until its owner is released or mutated. Empty buffers may have no data storage.+ *+ * \param[in] buffer Borrowed buffer retained for the duration of this call.+ *+ * \returns Borrowed storage, which may be NULL for an empty buffer.+ */+const unsigned char* cometa_cbor_buffer_data(const cardano_buffer_t* buffer);++/**+ * \brief Retrieves the byte length of a borrowed buffer, including zero for an empty decoded string.+ *+ * \param[in] buffer Borrowed buffer retained for the duration of this call.+ *+ * \returns The buffer length in bytes.+ */+size_t cometa_cbor_buffer_size(const cardano_buffer_t* buffer);++/**+ * \brief Writes CBOR undefined, returning one owned buffer reference.+ * \param[out] output Owned result slot, initialized even on failure.+ * \param[out] error Optional diagnostic storage.+ * \param[in] error_size Diagnostic capacity including the terminator.+ * \returns Native status; the caller releases any output reference.+ */+unsigned int cometa_cbor_encode_undefined(cardano_buffer_t** output, char* error, size_t error_size);++/**+ * \brief Reads one IEEE floating-point item, copying its value before cleanup.+ * \param[in] data Borrowed encoded item bytes.+ * \param[in] size Input byte count.+ * \param[out] value Receives the converted double on success.+ * \param[out] error Optional diagnostic storage.+ * \param[in] error_size Diagnostic capacity including the terminator.+ * \returns Native status; reader ownership never escapes the call.+ */+unsigned int cometa_cbor_decode_double(const unsigned char* data, size_t size, double* value, char* error, size_t error_size);++/**+ * \brief Reads a simple value into a fixed-width byte, without exposing C enum layout.+ * \param[in] data Borrowed encoded item bytes.+ * \param[in] size Input byte count.+ * \param[out] value Receives the simple-value number on success.+ * \param[out] error Optional diagnostic storage.+ * \param[in] error_size Diagnostic capacity including the terminator.+ * \returns Native status; reader ownership never escapes the call.+ */+unsigned int cometa_cbor_decode_simple(const unsigned char* data, size_t size, uint8_t* value, char* error, size_t error_size);++#ifdef __cplusplus+}+#endif /* __cplusplus */++#endif // BIGLUP_LABS_INCLUDE_COMETA_CBOR_H
@@ -0,0 +1,66 @@+/**+ * \file cometa_cip8.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/+#include "cometa_cip8.h"+#include <cardano/address/address.h>+#include <cardano/crypto/blake2b_hash.h>+#include <cardano/message_signing/cip8.h>++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_cip8_sign(const cardano_ed25519_private_key_t* key, unsigned int kind, const unsigned char* binding, size_t binding_size, const unsigned char* message, size_t message_size, cardano_buffer_t** sign1, cardano_buffer_t** cose_key)+{+ if ((sign1 == NULL) || (cose_key == NULL))+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }++ *sign1 = NULL;+ *cose_key = NULL;++ cardano_address_t* address = NULL;+ cardano_blake2b_hash_t* hash = NULL;+ cardano_error_t result = CARDANO_ERROR_INVALID_ARGUMENT;++ if (kind == 0U)+ {+ result = cardano_address_from_bytes(binding, binding_size, &address);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cip8_sign(message, message_size, address, key, sign1, cose_key);+ }+ }+ else if ((kind == 1U) && (binding_size == 28U))+ {+ result = cardano_blake2b_hash_from_bytes(binding, binding_size, &hash);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cip8_sign_ex(message, message_size, hash, key, sign1, cose_key);+ }+ }++ cardano_address_unref(&address);+ cardano_blake2b_hash_unref(&hash);++ return (unsigned int)result;+}
@@ -0,0 +1,30 @@+/**+ * \file cometa_cip8.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef COMETA_CIP8_H+#define COMETA_CIP8_H+#include <cardano/buffer.h>+#include <cardano/crypto/ed25519_private_key.h>++/** Borrow inputs until return. kind 0 binds an address, 1 a key hash.+ * Both initialized output slots own their buffers; release each with buffer_unref.+ * Temporary address/hash objects are always released. No callbacks or retention.+ */+unsigned int cometa_cip8_sign(const cardano_ed25519_private_key_t* key, unsigned int kind, const unsigned char* binding, size_t binding_size, const unsigned char* message, size_t message_size, cardano_buffer_t** sign1, cardano_buffer_t** cose_key);+#endif
@@ -0,0 +1,536 @@+/**+ * \file cometa_coin_selection.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_coin_selection.h"+#include "cometa_parameters.h"+#include <cardano/transaction_builder/coin_selection/coin_selector_impl.h>+#include <cardano/transaction_builder/coin_selection/large_first_coin_selector.h>+#include <cardano/transaction_builder/coin_selection/random_improve_coin_selector.h>+#include <limits.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* STRUCTURES ****************************************************************/++/** \brief Adopted selector context; caller serializes refcount transitions. */+typedef struct selector_context_t+{+ cardano_object_t base;+ cometa_runtime_t* runtime;+ cardano_buffer_t* parameter_template;+} selector_context_t;++/** \brief Own every field referenced by a borrowed native request structure. */+typedef struct owned_request_t+{+ cardano_coin_selection_request_t value;+ cardano_buffer_t* parameter_template;+} owned_request_t;++/* STATIC FUNCTIONS **********************************************************/++/** \brief Release context roots only after native selector final destruction. */+static void+selector_context_free(void* opaque)+{+ selector_context_t* context = opaque;+ cardano_buffer_unref(&context->parameter_template);+ cometa_runtime_release(context->runtime);+ free(context);+}++/** \brief Consume exactly the local request-field ownership obligations. */+static void+request_free(owned_request_t* request)+{+ cardano_utxo_list_unref(&request->value.pre_selected_utxo);+ cardano_utxo_list_unref(&request->value.available_utxo);+ cardano_value_unref(&request->value.target);+ cardano_transaction_output_list_unref(&request->value.outputs_to_cover);+ cardano_address_unref(&request->value.change_address);+ cardano_protocol_parameters_unref(&request->value.protocol_params);+ cardano_buffer_unref(&request->parameter_template);+}++/** \brief Check complete consumption without borrowing reader storage past return. */+static cardano_error_t+reader_finished(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ return (result == CARDANO_SUCCESS && remaining != 0U) ? CARDANO_ERROR_INVALID_ARGUMENT : result;+}++/** \brief Decode an owned native UTxO list; each add retains before local release. */+static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ *output = NULL;+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result != CARDANO_SUCCESS || count < 0)+ {+ return result == CARDANO_SUCCESS ? CARDANO_ERROR_INVALID_ARGUMENT : result;+ }+ result = cardano_utxo_list_new(output);+ for (int64_t i = 0; result == CARDANO_SUCCESS && i < count; ++i)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_from_cbor(reader, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, item);+ }+ cardano_utxo_unref(&item);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/** \brief Snapshot a borrowed list using retained element getters. */+static cardano_error_t+write_utxos(cardano_cbor_writer_t* writer, cardano_utxo_list_t* list)+{+ const size_t count = list == NULL ? 0U : cardano_utxo_list_get_length(list);+ cardano_error_t result = cardano_cbor_writer_write_start_array(writer, (int64_t)count);+ for (size_t i = 0U; result == CARDANO_SUCCESS && i < count; ++i)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_list_get(list, i, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(item, writer);+ }+ cardano_utxo_unref(&item);+ }+ return result;+}++/** \brief Internal signed target codec; ledger value CBOR uses unsigned coin.+ * Native value_t and multi_asset_t support signed implicit funding quantities.+ */+static cardano_error_t+read_target(cardano_cbor_reader_t* reader, cardano_value_t** output)+{+ int64_t count = 0;+ int64_t coin = 0;+ cardano_multi_asset_t* assets = NULL;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count != 2)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_int(reader, &coin);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_multi_asset_from_cbor(reader, &assets);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_value_new(coin, assets, output);+ }+ cardano_multi_asset_unref(&assets);+ return result;+}++/** \brief Snapshot signed quantities without passing through ledger Value CBOR. */+static cardano_error_t+write_target(cardano_cbor_writer_t* writer, cardano_value_t* target)+{+ cardano_multi_asset_t* assets = cardano_value_get_multi_asset(target);+ cardano_error_t result = cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_signed_int(writer, cardano_value_get_coin(target));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_multi_asset_to_cbor(assets, writer);+ }+ cardano_multi_asset_unref(&assets);+ return result;+}++/** \brief Materialize all six request fields from an internal exact snapshot. */+static cardano_error_t+read_request(const unsigned char* bytes, size_t size, owned_request_t* output)+{+ memset(output, 0, sizeof(*output));+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_buffer_t* address = NULL;+ int64_t count = 0;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count != 6)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, &output->value.pre_selected_utxo);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, &output->value.available_utxo);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_target(reader, &output->value.target);+ }+ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_peek_state(reader, &state);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = state == CARDANO_CBOR_READER_STATE_NULL ? cardano_cbor_reader_read_null(reader) : cardano_transaction_output_list_from_cbor(reader, &output->value.outputs_to_cover);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_bytestring(reader, &address);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_address_from_bytes(cardano_buffer_get_data(address), cardano_buffer_get_size(address), &output->value.change_address);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_encoded_value(reader, &output->parameter_template);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_parameters_from_snapshot(cardano_buffer_get_data(output->parameter_template), cardano_buffer_get_size(output->parameter_template), &output->value.protocol_params);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = reader_finished(reader);+ }+ cardano_buffer_unref(&address);+ cardano_cbor_reader_unref(&reader);+ return result;+}++/** \brief Snapshot actual borrowed native request values before Haskell dispatch.+ * Parameter availability uses optional known-origin template, never echoed values.+ */+static cardano_error_t+write_request(selector_context_t* context, const cardano_coin_selection_request_t* request, cardano_buffer_t** output)+{+ *output = NULL;+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_buffer_t* parameters = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 6);+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, request->pre_selected_utxo);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, request->available_utxo);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_target(writer, request->target);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = request->outputs_to_cover == NULL ? cardano_cbor_writer_write_null(writer) : cardano_transaction_output_list_to_cbor(request->outputs_to_cover, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bytestring(writer, cardano_address_get_bytes(request->change_address), cardano_address_get_bytes_size(request->change_address));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_parameters_to_snapshot(request->protocol_params, context->parameter_template == NULL ? NULL : cardano_buffer_get_data(context->parameter_template), context->parameter_template == NULL ? 0U : cardano_buffer_get_size(context->parameter_template), ¶meters);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_encoded(writer, cardano_buffer_get_data(parameters), cardano_buffer_get_size(parameters));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_buffer_unref(¶meters);+ cardano_cbor_writer_unref(&writer);+ return result;+}++/** \brief Decode all three callback outputs with independent failure cleanup. */+static cardano_error_t+read_selection(cardano_buffer_t* buffer, cardano_utxo_list_t** selected, cardano_utxo_list_t** remaining, cardano_transaction_output_list_t** change)+{+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(cardano_buffer_get_data(buffer), cardano_buffer_get_size(buffer));+ int64_t count = 0;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count != 3)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, selected);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, remaining);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_output_list_from_cbor(reader, change);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = reader_finished(reader);+ }+ cardano_cbor_reader_unref(&reader);+ return result;+}++/** \brief Native selector callback; output slots initialized and partial owners+ * released before any failure returns through the C ABI. Runtime contains and+ * later rethrows Haskell exceptions only after native unwind and ownership cleanup.+ */+static cardano_error_t+select_callback(cardano_coin_selector_impl_t* selector, const cardano_coin_selection_request_t* request, cardano_utxo_list_t** selected, cardano_utxo_list_t** remaining, cardano_transaction_output_list_t** change)+{+ *selected = NULL;+ *remaining = NULL;+ *change = NULL;+ selector_context_t* context = (selector_context_t*)selector->context;+ cardano_buffer_t* request_bytes = NULL;+ cardano_buffer_t* response_bytes = NULL;+ cardano_error_t result = write_request(context, request, &request_bytes);+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_runtime_dispatch(context->runtime, 200U, cardano_buffer_get_data(request_bytes), cardano_buffer_get_size(request_bytes), &response_bytes, selector->error_message, sizeof(selector->error_message));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_selection(response_bytes, selected, remaining, change);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_list_unref(selected);+ *selected = NULL;+ cardano_utxo_list_unref(remaining);+ *remaining = NULL;+ cardano_transaction_output_list_unref(change);+ *change = NULL;+ }+ cardano_buffer_unref(&response_bytes);+ cardano_buffer_unref(&request_bytes);+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_coin_selector_new(cometa_runtime_t* runtime, const unsigned char* parameter_template, size_t template_size, cardano_coin_selector_t** output)+{+ *output = NULL;+ selector_context_t* context = calloc(1U, sizeof(*context));+ if (context == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ context->base.ref_count = 1U;+ context->base.deallocator = selector_context_free;+ context->runtime = runtime;+ cometa_runtime_ref(runtime);+ cardano_error_t result = CARDANO_SUCCESS;+ if (parameter_template != NULL)+ {+ context->parameter_template = cardano_buffer_new_from(parameter_template, template_size);+ result = context->parameter_template == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ cardano_coin_selector_impl_t implementation = { 0 };+ (void)snprintf(implementation.name, sizeof(implementation.name), "%s", "Cometa selector");+ implementation.context = &context->base;+ implementation.select = select_callback;+ result = cardano_coin_selector_new(implementation, output);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_object_t* owner = &context->base;+ cardano_object_unref(&owner);+ }+ return (unsigned int)result;+}++unsigned int+cometa_coin_selection_invoke(cometa_runtime_t* runtime, const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ *output = NULL;+ owned_request_t request = { 0 };+ cardano_coin_selector_t* selector = NULL;+ cardano_utxo_list_t* selected = NULL;+ cardano_utxo_list_t* remaining = NULL;+ cardano_transaction_output_list_t* change = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_error_t result = read_request(bytes, size, &request);+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_coin_selector_new(runtime, cardano_buffer_get_data(request.parameter_template), cardano_buffer_get_size(request.parameter_template), &selector);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_coin_selector_select(selector, &request.value, &selected, &remaining, &change);+ }+ if (result == CARDANO_SUCCESS)+ {+ writer = cardano_cbor_writer_new();+ result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 3);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, selected);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, remaining);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_output_list_to_cbor(change, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_cbor_writer_unref(&writer);+ cardano_transaction_output_list_unref(&change);+ cardano_utxo_list_unref(&remaining);+ cardano_utxo_list_unref(&selected);+ cardano_coin_selector_unref(&selector);+ request_free(&request);+ return (unsigned int)result;+}++unsigned int+cometa_coin_selection_native(unsigned int algorithm, uint64_t seed, unsigned int strategy, const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ *output = NULL;+ owned_request_t request = { 0 };+ cardano_coin_selector_t* selector = NULL;+ cardano_utxo_list_t* selected = NULL;+ cardano_utxo_list_t* remaining = NULL;+ cardano_transaction_output_list_t* change = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_error_t result = read_request(bytes, size, &request);+ if (result == CARDANO_SUCCESS)+ {+ if (algorithm == 0U)+ {+ result = cardano_large_first_coin_selector_new(&selector);+ }+ else if (algorithm == 1U)+ {+ result = cardano_random_improve_coin_selector_new(&selector);+ }+ else if (algorithm == 2U && strategy <= 1U)+ {+ result = cardano_random_improve_coin_selector_new_with_options(seed, (cardano_selection_strategy_t)strategy, &selector);+ }+ else+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_coin_selector_select(selector, &request.value, &selected, &remaining, &change);+ }+ if (result == CARDANO_SUCCESS)+ {+ writer = cardano_cbor_writer_new();+ result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 3);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, selected);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, remaining);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_output_list_to_cbor(change, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_cbor_writer_unref(&writer);+ cardano_transaction_output_list_unref(&change);+ cardano_utxo_list_unref(&remaining);+ cardano_utxo_list_unref(&selected);+ cardano_coin_selector_unref(&selector);+ request_free(&request);+ return (unsigned int)result;+}++unsigned int+cometa_coin_selection_minimum_ada(const unsigned char* bytes, size_t size, uint64_t coins_per_byte, uint64_t* minimum)+{+ *minimum = 0U;+ if ((size > SIZE_MAX - 168U) || (coins_per_byte > UINT64_MAX / (size + 168U)))+ {+ return CARDANO_ERROR_INTEGER_OVERFLOW;+ }+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_transaction_output_t* output = NULL;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_transaction_output_from_cbor(reader, &output);+ if (result == CARDANO_SUCCESS)+ {+ result = reader_finished(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_compute_min_ada_required(output, coins_per_byte, minimum);+ }+ cardano_transaction_output_unref(&output);+ cardano_cbor_reader_unref(&reader);+ return (unsigned int)result;+}
@@ -0,0 +1,81 @@+/**+ * \file cometa_coin_selection.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_COIN_SELECTION_H+#define BIGLUP_LABS_COMETA_COIN_SELECTION_H++/* INCLUDES ******************************************************************/++#include "cometa_runtime.h"+#include <cardano/cardano.h>+#include <stddef.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Create a native selector adopting an independently retained runtime.+ * \param runtime Borrowed live runtime, serialized by the caller's operation gate.+ * \param parameter_template Optional borrowed availability snapshot copied here.+ * \param template_size Byte count, zero when no originating snapshot is known.+ * \param output Owned selector on success; NULL on failure. Factory failure+ * releases its runtime reference and any copied template; caller retains its own.+ * \return Native status. The context retains both runtime and optional template+ * until final native selector destruction. Callback request pointers borrow only+ * until synchronous return. Success transfers three independent list references.+ */+unsigned int cometa_coin_selector_new(cometa_runtime_t* runtime, const unsigned char* parameter_template, size_t template_size, cardano_coin_selector_t** output);++/**+ * \brief Internal native-dispatch integration harness and future adapter caller.+ * \param runtime Live callback runtime; retain before invoking native callbacks.+ * \param bytes Borrowed six-field request snapshot until synchronous return.+ * \param size Request size in bytes.+ * \param output Owned three-list result snapshot on success, NULL on failure.+ * \return Native status. Decodes typed native values, calls actual selector+ * dispatch, snapshots all returned native collections, and releases every owner+ * on success, malformed reply, partial output failure and callback unwind.+ */+unsigned int cometa_coin_selection_invoke(cometa_runtime_t* runtime, const unsigned char* bytes, size_t size, cardano_buffer_t** output);++/**+ * \brief Execute an actual native algorithm with operation-local ownership.+ * \param algorithm 0 largest-first, 1 secure-seeded random-improve, 2 seeded.+ * \param seed Seed for algorithm 2, ignored otherwise; replayed on each call.+ * \param strategy 0 minimal or 1 optimal, for algorithm 2 only.+ * \param bytes Borrowed validated request snapshot, including full parameters.+ * \param size Complete request size.+ * \param output Owned result buffer on success, NULL on failure.+ * \return Native status. Constructor, request fields, and all three result+ * lists are released synchronously before return, including partial failures.+ */+unsigned int cometa_coin_selection_native(unsigned int algorithm, uint64_t seed, unsigned int strategy, const unsigned char* bytes, size_t size, cardano_buffer_t** output);++/**+ * \brief Compute minimum Ada with the pinned native fee utility.+ * \param bytes Borrowed fresh semantic output CBOR until return.+ * \param size Complete output byte count.+ * \param coins_per_byte Unsigned lovelace price per UTxO byte.+ * \param minimum Required lovelace on success. No native object escapes.+ * \return Native status; excessive multiplication bounds return integer overflow+ * rather than accepting native unsigned wraparound as a valid minimum.+ */+unsigned int cometa_coin_selection_minimum_ada(const unsigned char* bytes, size_t size, uint64_t coins_per_byte, uint64_t* minimum);++#endif /* BIGLUP_LABS_COMETA_COIN_SELECTION_H */
@@ -0,0 +1,210 @@+/**+ * \file cometa_contextual_transaction.c+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_contextual_transaction.h"+#include <cardano/cardano.h>++/* STATIC FUNCTIONS **********************************************************/++static cardano_error_t+finish_reader(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ return result == CARDANO_SUCCESS && remaining != 0U ? CARDANO_ERROR_DECODING : result;+}++static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ *output = NULL;+ int64_t size = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &size);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(output);+ }+ for (int64_t index = 0; result == CARDANO_SUCCESS; ++index)+ {+ cardano_cbor_reader_state_t state;+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result != CARDANO_SUCCESS || state == CARDANO_CBOR_READER_STATE_END_ARRAY)+ {+ break;+ }+ if (size >= 0 && index >= size)+ {+ result = CARDANO_ERROR_DECODING;+ break;+ }+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_from_cbor(reader, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, item);+ }+ cardano_utxo_unref(&item);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_contextual_certificate_index(const unsigned char* bytes, size_t size, const unsigned char* target, size_t target_size, uint64_t* index)+{+ if (index == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *index = 0U;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_cbor_reader_t* target_reader = cardano_cbor_reader_new(target, target_size);+ cardano_certificate_set_t* certificates = NULL;+ cardano_certificate_t* certificate = NULL;+ cardano_transaction_input_set_t* inputs = NULL;+ cardano_transaction_output_list_t* outputs = NULL;+ cardano_transaction_body_t* body = NULL;+ cardano_witness_set_t* witnesses = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ if (reader == NULL || target_reader == NULL)+ {+ goto cleanup;+ }+ result = cardano_certificate_set_from_cbor(reader, &certificates);+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_certificate_from_cbor(target_reader, &certificate);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(target_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_input_set_new(&inputs);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_output_list_new(&outputs);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_body_new(inputs, outputs, 0U, NULL, &body);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_body_set_certificates(body, certificates);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_new(&witnesses);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_new(body, witnesses, NULL, &transaction);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_find_certificate_index(transaction, certificate, index);+ }+cleanup:+ cardano_transaction_unref(&transaction);+ cardano_witness_set_unref(&witnesses);+ cardano_transaction_body_unref(&body);+ cardano_transaction_output_list_unref(&outputs);+ cardano_transaction_input_set_unref(&inputs);+ cardano_certificate_unref(&certificate);+ cardano_certificate_set_unref(&certificates);+ cardano_cbor_reader_unref(&target_reader);+ cardano_cbor_reader_unref(&reader);+ return (unsigned int)result;+}++unsigned int+cometa_contextual_required_keys(const unsigned char* bytes, size_t size, const unsigned char* utxos, size_t utxos_size, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_cbor_reader_t* utxo_reader = cardano_cbor_reader_new(utxos, utxos_size);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_transaction_t* transaction = NULL;+ cardano_utxo_list_t* resolved = NULL;+ cardano_blake2b_hash_set_t* hashes = NULL;+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ if (reader == NULL || utxo_reader == NULL || writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_transaction_from_cbor(reader, &transaction);+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(utxo_reader, &resolved);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(utxo_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_get_unique_signers(transaction, resolved, &hashes);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_blake2b_hash_set_to_cbor(hashes, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }+ cardano_blake2b_hash_set_unref(&hashes);+ cardano_utxo_list_unref(&resolved);+ cardano_transaction_unref(&transaction);+ cardano_cbor_writer_unref(&writer);+ cardano_cbor_reader_unref(&utxo_reader);+ cardano_cbor_reader_unref(&reader);+ return (unsigned int)result;+}
@@ -0,0 +1,34 @@+/**+ * \file cometa_contextual_transaction.h+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_CONTEXTUAL_TRANSACTION_H+#define BIGLUP_LABS_COMETA_CONTEXTUAL_TRANSACTION_H+#include <cardano/buffer.h>+#include <stdint.h>++/** Borrow all input buffers until synchronous return. The certificate index is+ * initialized even on failure. Temporary native objects never escape. */+unsigned int cometa_contextual_certificate_index(const unsigned char* certificates, size_t certificates_size, const unsigned char* target, size_t target_size, uint64_t* index);++/** Borrow input buffers, parse independent snapshots, and transfer one owned+ * serialized hash-set buffer on success. Output is NULL on every failure. */+unsigned int cometa_contextual_required_keys(const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, cardano_buffer_t** output);+#endif
@@ -0,0 +1,97 @@+/**+ * \file cometa_ed25519_values.c+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_ed25519_values.h"++#include <cardano/crypto/ed25519_public_key.h>+#include <cardano/crypto/ed25519_signature.h>++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_ed25519_verify(+ const unsigned char* public_key,+ size_t public_key_size,+ const unsigned char* signature,+ size_t signature_size,+ const unsigned char* message,+ size_t message_size,+ int* verified)+{+ if (verified == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ *verified = 0;++ if ((message == NULL) && (message_size != 0U))+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ cardano_ed25519_public_key_t* native_key = NULL;+ cardano_ed25519_signature_t* native_signature = NULL;+ cardano_error_t result = cardano_ed25519_public_key_from_bytes(public_key, public_key_size, &native_key);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_ed25519_signature_from_bytes(signature, signature_size, &native_signature);+ }++ if (result == CARDANO_SUCCESS)+ {+ *verified = cardano_ed25519_public_verify(native_key, native_signature, message, message_size) ? 1 : 0;+ }++ cardano_ed25519_signature_unref(&native_signature);+ cardano_ed25519_public_key_unref(&native_key);++ return (unsigned int)result;+}++unsigned int+cometa_ed25519_public_key_hash(+ const unsigned char* public_key,+ size_t public_key_size,+ cardano_blake2b_hash_t** hash)+{+ if (hash == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ *hash = NULL;++ cardano_ed25519_public_key_t* native_key = NULL;+ cardano_error_t result = cardano_ed25519_public_key_from_bytes(public_key, public_key_size, &native_key);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_ed25519_public_key_to_hash(native_key, hash);+ }++ cardano_ed25519_public_key_unref(&native_key);++ return (unsigned int)result;+}
@@ -0,0 +1,88 @@+/**+ * \file cometa_ed25519_values.h+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_ED25519_VALUES_H+#define BIGLUP_LABS_INCLUDE_COMETA_ED25519_VALUES_H++/* INCLUDES ******************************************************************/++#include <cardano/crypto/blake2b_hash.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif /* __cplusplus */++/**+ * \brief Verifies a detached Ed25519 signature using operation-scoped native values.+ *+ * All input spans are borrowed until return. Public key and signature objects are constructed+ * locally and released on every path, including when the second constructor fails. No native+ * object or borrowed storage survives the call. Native bool does not cross the Haskell ABI.+ *+ * \param[in] public_key Public key bytes. Must not be NULL.+ * \param[in] public_key_size Number of public key bytes; native import requires 32.+ * \param[in] signature Signature bytes. Must not be NULL.+ * \param[in] signature_size Number of signature bytes; native import requires 64.+ * \param[in] message Exact message bytes. NULL is accepted only when message_size is zero.+ * \param[in] message_size Message length in bytes, including embedded NUL bytes.+ * \param[out] verified Receives 1 when verification succeeds and 0 otherwise. Must not be NULL.+ *+ * \returns A cardano-c status converted to unsigned int. Invalid signatures produce CARDANO_SUCCESS+ * with output zero; import and allocation failures preserve their native status.+ *+ * \note The native verifier also returns false when its cryptographic backend cannot initialize.+ * Its Boolean interface provides no distinct status for that condition.+ */+unsigned int cometa_ed25519_verify(+ const unsigned char* public_key,+ size_t public_key_size,+ const unsigned char* signature,+ size_t signature_size,+ const unsigned char* message,+ size_t message_size,+ int* verified);++/**+ * \brief Computes the native BLAKE2b-224 digest of encoded public key bytes.+ *+ * The public key is borrowed, imported into one local native object, and released before return.+ * The returned hash is an owned result; its reference is not consumed with the temporary key.+ *+ * \param[in] public_key Public key bytes. Must not be NULL.+ * \param[in] public_key_size Number of public key bytes; native import requires 32.+ * \param[out] hash Receives one owned hash reference. Must not be NULL and must not overwrite an owner.+ *+ * \returns A cardano-c status converted to unsigned int. The hash slot is initialized to NULL before+ * import. The caller releases any result reference, including a partial failure result.+ */+unsigned int cometa_ed25519_public_key_hash(+ const unsigned char* public_key,+ size_t public_key_size,+ cardano_blake2b_hash_t** hash);++#ifdef __cplusplus+}+#endif /* __cplusplus */++#endif // BIGLUP_LABS_INCLUDE_COMETA_ED25519_VALUES_H
@@ -0,0 +1,193 @@+/**+ * \file cometa_error_codes_test.c+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include <cardano/error.h>++#include <limits.h>+#include <stddef.h>++/* STRUCTURES ****************************************************************/++/**+ * \brief One native-header status name and numeric value used only by the test suite.+ */+typedef struct cometa_test_error_code_t+{+ /**+ * \brief Symbol name used in assertion diagnostics.+ */+ const char* name;++ /**+ * \brief Header-defined value converted to the adapter's explicit unsigned status ABI.+ */+ unsigned int value;+} cometa_test_error_code_t;++/* STATIC VARIABLES **********************************************************/++/**+ * \brief Complete status inventory from the pinned cardano-c header, in numeric order.+ *+ * Values are read from the installed header rather than copied numeric literals. This independent+ * test oracle detects drift between native assignments and the copied Haskell status values.+ */+static const cometa_test_error_code_t error_codes[] = {+ { "CARDANO_SUCCESS", CARDANO_SUCCESS },+ { "CARDANO_ERROR_GENERIC", CARDANO_ERROR_GENERIC },+ { "CARDANO_ERROR_INSUFFICIENT_BUFFER_SIZE", CARDANO_ERROR_INSUFFICIENT_BUFFER_SIZE },+ { "CARDANO_ERROR_POINTER_IS_NULL", CARDANO_ERROR_POINTER_IS_NULL },+ { "CARDANO_ERROR_MEMORY_ALLOCATION_FAILED", CARDANO_ERROR_MEMORY_ALLOCATION_FAILED },+ { "CARDANO_ERROR_OUT_OF_BOUNDS_MEMORY_READ", CARDANO_ERROR_OUT_OF_BOUNDS_MEMORY_READ },+ { "CARDANO_ERROR_OUT_OF_BOUNDS_MEMORY_WRITE", CARDANO_ERROR_OUT_OF_BOUNDS_MEMORY_WRITE },+ { "CARDANO_ERROR_INVALID_ARGUMENT", CARDANO_ERROR_INVALID_ARGUMENT },+ { "CARDANO_ERROR_INVALID_URL", CARDANO_ERROR_INVALID_URL },+ { "CARDANO_ERROR_ELEMENT_NOT_FOUND", CARDANO_ERROR_ELEMENT_NOT_FOUND },+ { "CARDANO_ERROR_ENCODING", CARDANO_ERROR_ENCODING },+ { "CARDANO_ERROR_DECODING", CARDANO_ERROR_DECODING },+ { "CARDANO_ERROR_CHECKSUM_MISMATCH", CARDANO_ERROR_CHECKSUM_MISMATCH },+ { "CARDANO_ERROR_INVALID_JSON", CARDANO_ERROR_INVALID_JSON },+ { "CARDANO_ERROR_INTEGER_OVERFLOW", CARDANO_ERROR_INTEGER_OVERFLOW },+ { "CARDANO_ERROR_INTEGER_UNDERFLOW", CARDANO_ERROR_INTEGER_UNDERFLOW },+ { "CARDANO_ERROR_CONVERSION_FAILED", CARDANO_ERROR_CONVERSION_FAILED },+ { "CARDANO_ERROR_INDEX_OUT_OF_BOUNDS", CARDANO_ERROR_INDEX_OUT_OF_BOUNDS },+ { "CARDANO_ERROR_INVALID_CERTIFICATE_TYPE", CARDANO_ERROR_INVALID_CERTIFICATE_TYPE },+ { "CARDANO_ERROR_NOT_IMPLEMENTED", CARDANO_ERROR_NOT_IMPLEMENTED },+ { "CARDANO_ERROR_INVALID_PASSPHRASE", CARDANO_ERROR_INVALID_PASSPHRASE },+ { "CARDANO_ERROR_ILLEGAL_STATE", CARDANO_ERROR_ILLEGAL_STATE },+ { "CARDANO_ERROR_DUPLICATED_KEY", CARDANO_ERROR_DUPLICATED_KEY },+ { "CARDANO_ERROR_JSON_TYPE_MISMATCH", CARDANO_ERROR_JSON_TYPE_MISMATCH },+ { "CARDANO_ERROR_LOSS_OF_PRECISION", CARDANO_ERROR_LOSS_OF_PRECISION },+ { "CARDANO_ERROR_INVALID_MAGIC", CARDANO_ERROR_INVALID_MAGIC },+ { "CARDANO_ERROR_INVALID_CHECKSUM", CARDANO_ERROR_INVALID_CHECKSUM },+ { "CARDANO_ERROR_INVALID_BLAKE2B_HASH_SIZE", CARDANO_ERROR_INVALID_BLAKE2B_HASH_SIZE },+ { "CARDANO_ERROR_INVALID_ED25519_SIGNATURE_SIZE", CARDANO_ERROR_INVALID_ED25519_SIGNATURE_SIZE },+ { "CARDANO_ERROR_INVALID_ED25519_PUBLIC_KEY_SIZE", CARDANO_ERROR_INVALID_ED25519_PUBLIC_KEY_SIZE },+ { "CARDANO_ERROR_INVALID_ED25519_PRIVATE_KEY_SIZE", CARDANO_ERROR_INVALID_ED25519_PRIVATE_KEY_SIZE },+ { "CARDANO_ERROR_INVALID_BIP32_PUBLIC_KEY_SIZE", CARDANO_ERROR_INVALID_BIP32_PUBLIC_KEY_SIZE },+ { "CARDANO_ERROR_INVALID_BIP32_PRIVATE_KEY_SIZE", CARDANO_ERROR_INVALID_BIP32_PRIVATE_KEY_SIZE },+ { "CARDANO_ERROR_INVALID_BIP32_DERIVATION_INDEX", CARDANO_ERROR_INVALID_BIP32_DERIVATION_INDEX },+ { "CARDANO_ERROR_UNEXPECTED_CBOR_TYPE", CARDANO_ERROR_UNEXPECTED_CBOR_TYPE },+ { "CARDANO_ERROR_INVALID_CBOR_VALUE", CARDANO_ERROR_INVALID_CBOR_VALUE },+ { "CARDANO_ERROR_INVALID_CBOR_ARRAY_SIZE", CARDANO_ERROR_INVALID_CBOR_ARRAY_SIZE },+ { "CARDANO_ERROR_INVALID_CBOR_MAP_SIZE", CARDANO_ERROR_INVALID_CBOR_MAP_SIZE },+ { "CARDANO_ERROR_DUPLICATED_CBOR_MAP_KEY", CARDANO_ERROR_DUPLICATED_CBOR_MAP_KEY },+ { "CARDANO_ERROR_INVALID_CBOR_MAP_KEY", CARDANO_ERROR_INVALID_CBOR_MAP_KEY },+ { "CARDANO_ERROR_INVALID_ADDRESS_TYPE", CARDANO_ERROR_INVALID_ADDRESS_TYPE },+ { "CARDANO_ERROR_INVALID_ADDRESS_FORMAT", CARDANO_ERROR_INVALID_ADDRESS_FORMAT },+ { "CARDANO_ERROR_INVALID_CREDENTIAL_TYPE", CARDANO_ERROR_INVALID_CREDENTIAL_TYPE },+ { "CARDANO_ERROR_INVALID_PLUTUS_DATA_CONVERSION", CARDANO_ERROR_INVALID_PLUTUS_DATA_CONVERSION },+ { "CARDANO_ERROR_INVALID_DATUM_TYPE", CARDANO_ERROR_INVALID_DATUM_TYPE },+ { "CARDANO_ERROR_INVALID_SCRIPT_LANGUAGE", CARDANO_ERROR_INVALID_SCRIPT_LANGUAGE },+ { "CARDANO_ERROR_INVALID_NATIVE_SCRIPT_TYPE", CARDANO_ERROR_INVALID_NATIVE_SCRIPT_TYPE },+ { "CARDANO_ERROR_INVALID_PLUTUS_COST_MODEL", CARDANO_ERROR_INVALID_PLUTUS_COST_MODEL },+ { "CARDANO_ERROR_INVALID_PROCEDURE_PROPOSAL_TYPE", CARDANO_ERROR_INVALID_PROCEDURE_PROPOSAL_TYPE },+ { "CARDANO_ERROR_INVALID_METADATUM_CONVERSION", CARDANO_ERROR_INVALID_METADATUM_CONVERSION },+ { "CARDANO_ERROR_INVALID_METADATUM_TEXT_STRING_SIZE", CARDANO_ERROR_INVALID_METADATUM_TEXT_STRING_SIZE },+ { "CARDANO_ERROR_INVALID_METADATUM_BOUNDED_BYTES_SIZE", CARDANO_ERROR_INVALID_METADATUM_BOUNDED_BYTES_SIZE },+ { "CARDANO_ERROR_INVALID_HTTP_REQUEST", CARDANO_ERROR_INVALID_HTTP_REQUEST },+ { "CARDANO_ERROR_BALANCE_INSUFFICIENT", CARDANO_ERROR_BALANCE_INSUFFICIENT },+ { "CARDANO_ERROR_UTXO_NOT_FRAGMENTED_ENOUGH", CARDANO_ERROR_UTXO_NOT_FRAGMENTED_ENOUGH },+ { "CARDANO_ERROR_UTXO_FULLY_DEPLETED", CARDANO_ERROR_UTXO_FULLY_DEPLETED },+ { "CARDANO_ERROR_MAXIMUM_INPUT_COUNT_EXCEEDED", CARDANO_ERROR_MAXIMUM_INPUT_COUNT_EXCEEDED },+ { "CARDANO_ERROR_UNBALANCED_SUB_TRANSACTIONS", CARDANO_ERROR_UNBALANCED_SUB_TRANSACTIONS },+ { "CARDANO_ERROR_NOT_ALLOWED_SUPPLEMENTAL_DATUMS", CARDANO_ERROR_NOT_ALLOWED_SUPPLEMENTAL_DATUMS },+ { "CARDANO_ERROR_MISSING_REDEEMER", CARDANO_ERROR_MISSING_REDEEMER },+ { "CARDANO_ERROR_SCRIPT_EVALUATION_FAILURE", CARDANO_ERROR_SCRIPT_EVALUATION_FAILURE }+};++/* DEFINITIONS ***************************************************************/++/**+ * \brief Retrieves the number of native status constants covered by this pinned inventory.+ *+ * \returns The number of entries in the status oracle.+ */+size_t+cometa_test_error_code_count(void)+{+ return sizeof(error_codes) / sizeof(error_codes[0]);+}++/**+ * \brief Retrieves a status constant's native symbol name.+ *+ * \param[in] index Zero-based index into the status inventory.+ *+ * \returns A borrowed static symbol name, or an empty string if the index is out of bounds.+ */+const char*+cometa_test_error_code_name(size_t index)+{+ return index < cometa_test_error_code_count() ? error_codes[index].name : "";+}++/**+ * \brief Retrieves a status constant's value from the installed native header.+ *+ * \param[in] index Zero-based index into the status inventory.+ *+ * \returns The unsigned status value, or zero if the index is out of bounds.+ */+unsigned int+cometa_test_error_code_value(size_t index)+{+ return index < cometa_test_error_code_count() ? error_codes[index].value : 0U;+}++/**+ * \brief Retrieves the size of the C adapter's explicit unsigned status type.+ *+ * \returns The size of unsigned int in bytes. Native enum layout does not cross the adapter ABI.+ */+size_t+cometa_test_status_size(void)+{+ return sizeof(unsigned int);+}++/**+ * \brief Retrieves the largest value representable by the explicit unsigned status ABI.+ *+ * \returns UINT_MAX, allowing the Haskell test to detect width or signedness mismatches.+ */+unsigned int+cometa_test_status_max(void)+{+ return UINT_MAX;+}++/**+ * \brief Exercises status conversion through the native enum and the explicit unsigned ABI.+ *+ * \param[in] value A known native status value from the pinned header.+ *+ * \returns The value after conversion to cardano_error_t and back to unsigned int.+ */+unsigned int+cometa_test_status_roundtrip(unsigned int value)+{+ cardano_error_t native = (cardano_error_t)value;++ return (unsigned int)native;+}
@@ -0,0 +1,303 @@+/**+ * \file cometa_evaluation.c+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/+#include "cometa_evaluation.h"+#include "cometa_provider_runtime.h"+#include <cardano/cardano.h>+#include <string.h>++/* STATIC FUNCTIONS **********************************************************/++static cardano_error_t+finish_reader(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if (result == CARDANO_SUCCESS && remaining != 0)+ {+ result = CARDANO_ERROR_DECODING;+ }+ return result;+}++/* Indexed UTxO getters retain children. Null additional UTxOs serialize as []. */+static cardano_error_t+write_utxos(cardano_cbor_writer_t* writer, cardano_utxo_list_t* values)+{+ size_t count = cardano_utxo_list_get_length(values);+ cardano_error_t result = cardano_cbor_writer_write_start_array(writer, (int64_t)count);+ for (size_t index = 0; result == CARDANO_SUCCESS && index < count; ++index)+ {+ cardano_utxo_t* child = NULL;+ result = cardano_utxo_list_get(values, index, &child);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(child, writer);+ }+ cardano_utxo_unref(&child);+ }+ return result;+}++static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ *output = NULL;+ int64_t size = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &size);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(output);+ }+ for (int64_t index = 0; result == CARDANO_SUCCESS; ++index)+ {+ cardano_cbor_reader_state_t state;+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result != CARDANO_SUCCESS || state == CARDANO_CBOR_READER_STATE_END_ARRAY)+ {+ break;+ }+ if (size >= 0 && index >= size)+ {+ result = CARDANO_ERROR_DECODING;+ break;+ }+ cardano_utxo_t* child = NULL;+ result = cardano_utxo_from_cbor(reader, &child);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, child);+ }+ cardano_utxo_unref(&child);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/* Inputs borrow for the synchronous callback. Dispatch roots and joins Haskell+ * workers; reply parsing completes before transferring one owned redeemer list. */+static cardano_error_t+evaluate_callback(cardano_tx_evaluator_impl_t* impl, cardano_transaction_t* transaction, cardano_utxo_list_t* additional, cardano_redeemer_list_t** output)+{+ *output = NULL;+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* request = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ if (writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_to_cbor(transaction, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, additional);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, &request);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_runtime_dispatch((cometa_runtime_t*)impl->context, 100, cardano_buffer_get_data(request), cardano_buffer_get_size(request), &reply, impl->error_message, sizeof(impl->error_message));+ }+ if (result == CARDANO_SUCCESS && reply == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (result == CARDANO_SUCCESS)+ {+ reader = cardano_cbor_reader_new(cardano_buffer_get_data(reply), cardano_buffer_get_size(reply));+ if (reader == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_from_cbor(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(reader);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ cardano_redeemer_list_unref(output);+ *output = NULL;+ }+ cardano_cbor_reader_unref(&reader);+ cardano_buffer_unref(&reply);+ cardano_buffer_unref(&request);+ cardano_cbor_writer_unref(&writer);+ return result;+}++/* DEFINITIONS ***************************************************************/+unsigned int+cometa_evaluation_new(cometa_runtime_t* runtime, cardano_tx_evaluator_t** output)+{+ if (output != NULL)+ {+ *output = NULL;+ }+ if (runtime == NULL || output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ cardano_tx_evaluator_impl_t impl = { 0 };+ memcpy(impl.name, "Cometa evaluator", sizeof("Cometa evaluator"));+ impl.context = cometa_runtime_object(runtime);+ impl.evaluate = evaluate_callback;+ cometa_runtime_ref(runtime);+ cardano_error_t result = cardano_tx_evaluator_new(impl, output);+ if (result != CARDANO_SUCCESS)+ {+ cometa_runtime_release(runtime);+ }+ return (unsigned int)result;+}++static unsigned int+run_evaluator(unsigned int from_provider, cometa_runtime_t* runtime, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, uint32_t count, cardano_buffer_t** output)+{+ if (output != NULL)+ {+ *output = NULL;+ }+ if (runtime == NULL || transaction == NULL || utxos == NULL || output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (count == 0)+ {+ return (unsigned int)CARDANO_ERROR_INVALID_ARGUMENT;+ }+ cardano_provider_t* provider = NULL;+ cardano_tx_evaluator_t* evaluator = NULL;+ cardano_transaction_t* tx = NULL;+ cardano_utxo_list_t* additional = NULL;+ cardano_redeemer_list_t* redeemers = NULL;+ cardano_cbor_reader_t* tx_reader = cardano_cbor_reader_new(transaction, transaction_size);+ cardano_cbor_reader_t* utxo_reader = cardano_cbor_reader_new(utxos, utxos_size);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ if (tx_reader == NULL || utxo_reader == NULL || writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_transaction_from_cbor(tx_reader, &tx);+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(tx_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(utxo_reader, &additional);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(utxo_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ if (from_provider == 0)+ {+ result = (cardano_error_t)cometa_evaluation_new(runtime, &evaluator);+ }+ else+ {+ static const unsigned char name[] = "Cometa evaluator provider";+ result = (cardano_error_t)cometa_provider_runtime_new(runtime, name, sizeof(name) - 1, 0, &provider);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_tx_evaluator_from_provider(provider, &evaluator);+ }+ /* The evaluator retained its own provider owner on success. This local+ * construction obligation is released once regardless of pointer value. */+ cardano_provider_unref(&provider);+ provider = NULL;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ /* Exercise the native evaluator through a retained alias. Native unref leaves+ * its pointer nonnull while that alias keeps the object alive. */+ cardano_tx_evaluator_t* retained = evaluator;+ cardano_tx_evaluator_ref(retained);+ cardano_tx_evaluator_unref(&evaluator);+ evaluator = retained;+ for (uint32_t index = 0; result == CARDANO_SUCCESS && index < count; ++index)+ {+ cardano_redeemer_list_unref(&redeemers);+ redeemers = NULL;+ result = cardano_tx_evaluator_evaluate(evaluator, tx, additional, &redeemers);+ }+ }+ if (result == CARDANO_SUCCESS && redeemers == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_to_cbor(redeemers, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }+ cardano_redeemer_list_unref(&redeemers);+ cardano_tx_evaluator_unref(&evaluator);+ cardano_utxo_list_unref(&additional);+ cardano_transaction_unref(&tx);+ cardano_cbor_reader_unref(&utxo_reader);+ cardano_cbor_reader_unref(&tx_reader);+ cardano_cbor_writer_unref(&writer);+ return (unsigned int)result;+}++unsigned int+cometa_evaluation_run(cometa_runtime_t* runtime, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, uint32_t count, cardano_buffer_t** output)+{+ return run_evaluator(0, runtime, transaction, transaction_size, utxos, utxos_size, count, output);+}++unsigned int+cometa_evaluation_run_provider(cometa_runtime_t* runtime, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, uint32_t count, cardano_buffer_t** output)+{+ return run_evaluator(1, runtime, transaction, transaction_size, utxos, utxos_size, count, output);+}
@@ -0,0 +1,35 @@+/**+ * \file cometa_evaluation.h+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_EVALUATION_H+#define BIGLUP_LABS_COMETA_EVALUATION_H+#include "cometa_runtime.h"+#include <cardano/transaction_builder/evaluation/tx_evaluator.h>+/* New evaluator adopts one independently retained runtime context on success.+ * Failure initializes output null and leaves the caller's context owner intact. */+unsigned int cometa_evaluation_new(cometa_runtime_t* runtime, cardano_tx_evaluator_t** output);+/* Parse borrowed inputs, dispatch the actual native evaluator count times, then+ * transfer one serialized redeemer result. All partial state is always released. */+unsigned int cometa_evaluation_run(cometa_runtime_t* runtime, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, uint32_t count, cardano_buffer_t** output);+/* Same operation through cardano_tx_evaluator_from_provider. The provider's+ * construction owner is released before dispatch, proving retained lifetime. */+unsigned int cometa_evaluation_run_provider(cometa_runtime_t* runtime, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, uint32_t count, cardano_buffer_t** output);+#endif
@@ -0,0 +1,661 @@+/**+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_inspection.h"++/* STATIC FUNCTIONS **********************************************************/++/* Governance actions have concrete native types, not a generic native owner.+ * Peek with an independent reader; parse the chosen complete action with the+ * original reader, borrow it for JSON, and release before returning. */+static cardano_error_t+inspect_action(const unsigned char* input, size_t size, cardano_cbor_reader_t* reader, cardano_json_writer_t* writer)+{+ cardano_cbor_reader_t* probe = cardano_cbor_reader_new(input, size);+ if (probe == NULL)+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ int64_t count = 0;+ uint64_t tag = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(probe, &count);+ if (result == CARDANO_SUCCESS)+ result = cardano_cbor_reader_read_uint(probe, &tag);+ cardano_cbor_reader_unref(&probe);+ if (result != CARDANO_SUCCESS)+ return result;+ switch (tag)+ {+ case 0U:+ {+ cardano_parameter_change_action_t* action = NULL;+ result = cardano_parameter_change_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_parameter_change_action_to_cip116_json(action, writer);+ cardano_parameter_change_action_unref(&action);+ return result;+ }+ case 1U:+ {+ cardano_hard_fork_initiation_action_t* action = NULL;+ result = cardano_hard_fork_initiation_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_hard_fork_initiation_action_to_cip116_json(action, writer);+ cardano_hard_fork_initiation_action_unref(&action);+ return result;+ }+ case 2U:+ {+ cardano_treasury_withdrawals_action_t* action = NULL;+ result = cardano_treasury_withdrawals_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_treasury_withdrawals_action_to_cip116_json(action, writer);+ cardano_treasury_withdrawals_action_unref(&action);+ return result;+ }+ case 3U:+ {+ cardano_no_confidence_action_t* action = NULL;+ result = cardano_no_confidence_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_no_confidence_action_to_cip116_json(action, writer);+ cardano_no_confidence_action_unref(&action);+ return result;+ }+ case 4U:+ {+ cardano_update_committee_action_t* action = NULL;+ result = cardano_update_committee_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_update_committee_action_to_cip116_json(action, writer);+ cardano_update_committee_action_unref(&action);+ return result;+ }+ case 5U:+ {+ cardano_new_constitution_action_t* action = NULL;+ result = cardano_new_constitution_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_new_constitution_action_to_cip116_json(action, writer);+ cardano_new_constitution_action_unref(&action);+ return result;+ }+ case 6U:+ {+ cardano_info_action_t* action = NULL;+ result = cardano_info_action_from_cbor(reader, &action);+ if (result == CARDANO_SUCCESS)+ result = cardano_info_action_to_cip116_json(action, writer);+ cardano_info_action_unref(&action);+ return result;+ }+ default:+ return CARDANO_ERROR_INVALID_ARGUMENT;+ }+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_inspection_compute(unsigned int operation, const unsigned char* input, size_t size, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ if (operation > 58U)+ {+ return CARDANO_ERROR_INVALID_ARGUMENT;+ }+ if (input == NULL && size != 0U)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(input, size);+ cardano_json_writer_t* writer = cardano_json_writer_new(CARDANO_JSON_FORMAT_COMPACT);+ cardano_transaction_t* transaction = NULL;+ cardano_sub_transaction_t* sub = NULL;+ cardano_transaction_body_t* body = NULL;+ cardano_sub_transaction_body_t* sub_body = NULL;+ cardano_value_t* value = NULL;+ cardano_script_t* script = NULL;+ cardano_credential_t* credential = NULL;+ cardano_certificate_t* certificate = NULL;+ cardano_proposal_procedure_t* proposal = NULL;+ cardano_pool_params_t* pool = NULL;+ cardano_protocol_param_update_t* update = NULL;+ cardano_plutus_data_t* data = NULL;+ cardano_transaction_output_t* tx_output = NULL;+ cardano_witness_set_t* witnesses = NULL;+ cardano_utxo_t* utxo = NULL;+ cardano_drep_t* drep = NULL;+ cardano_governance_action_id_t* action_id = NULL;+ cardano_anchor_t* anchor = NULL;+ cardano_voting_procedures_t* votes = NULL;+ cardano_metadatum_t* metadatum = NULL;+ cardano_transaction_metadata_t* metadata = NULL;+ cardano_auxiliary_data_t* auxiliary = NULL;+ cardano_transaction_input_t* tx_input = NULL;+ cardano_datum_t* datum = NULL;+ cardano_redeemer_t* redeemer = NULL;+ cardano_ex_units_t* inspection_ex_units = NULL;+ cardano_protocol_version_t* inspection_protocol_version = NULL;+ cardano_unit_interval_t* inspection_unit_interval = NULL;+ cardano_relay_t* inspection_relay = NULL;+ cardano_pool_metadata_t* inspection_pool_metadata = NULL;+ cardano_constitution_t* inspection_constitution = NULL;+ cardano_voter_t* inspection_voter = NULL;+ cardano_voting_procedure_t* inspection_voting_procedure = NULL;+ cardano_vkey_witness_t* inspection_verification_witness = NULL;+ cardano_bootstrap_witness_t* inspection_bootstrap_witness = NULL;+ cardano_cost_model_t* inspection_cost_model = NULL;+ cardano_costmdls_t* inspection_cost_models = NULL;+ cardano_ex_unit_prices_t* inspection_ex_unit_prices = NULL;+ cardano_pool_voting_thresholds_t* inspection_pool_voting_thresholds = NULL;+ cardano_drep_voting_thresholds_t* inspection_drep_voting_thresholds = NULL;+ cardano_proposed_param_updates_t* inspection_proposed_updates = NULL;+ cardano_update_t* inspection_update_proposal = NULL;+ cardano_account_balance_interval_t* inspection_balance_interval = NULL;+ cardano_account_balance_intervals_map_t* inspection_balance_intervals = NULL;+ cardano_direct_deposit_map_t* inspection_direct_deposits = NULL;+ cardano_required_guards_map_t* inspection_required_guards = NULL;+ cardano_asset_name_t* inspection_asset_name = NULL;+ cardano_blake2b_hash_t* inspection_blake2b_hash = NULL;+ cardano_bls_key_t* inspection_bls_key = NULL;+ cardano_committee_members_map_t* inspection_committee_members_map = NULL;+ cardano_withdrawal_map_t* inspection_withdrawal_map = NULL;+ cardano_blake2b_hash_set_t* inspection_blake2b_hash_set = NULL;+ cardano_guard_set_t* inspection_guard_set = NULL;+ cardano_sub_transaction_set_t* inspection_sub_transaction_set = NULL;+ cardano_multi_asset_t* inspection_assets = NULL;+ cardano_multi_asset_t* inspection_asset_entries = NULL;+ cardano_asset_name_map_t* inspection_policy_assets = NULL;+ cardano_asset_name_map_t* inspection_policy_asset_entries = NULL;+ size_t remaining = 0U;+ cardano_error_t result = reader == NULL || writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : CARDANO_SUCCESS;++ if (result == CARDANO_SUCCESS)+ {+ switch (operation)+ {+ case 0U:+ result = cardano_transaction_from_cbor(reader, &transaction);+ break;+ case 1U:+ result = cardano_sub_transaction_from_cbor(reader, &sub);+ break;+ case 2U:+ result = cardano_transaction_body_from_cbor(reader, &body);+ break;+ case 3U:+ result = cardano_sub_transaction_body_from_cbor(reader, &sub_body);+ break;+ case 4U:+ result = cardano_value_from_cbor(reader, &value);+ break;+ case 5U:+ result = cardano_script_from_cbor(reader, &script);+ break;+ case 6U:+ result = cardano_credential_from_cbor(reader, &credential);+ break;+ case 7U:+ result = cardano_certificate_from_cbor(reader, &certificate);+ break;+ case 8U:+ result = cardano_proposal_procedure_from_cbor(reader, &proposal);+ break;+ case 9U:+ {+ int64_t count = 0;+ result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count != 9 && count != 10 && count != -1)+ result = CARDANO_ERROR_DECODING;+ if (result == CARDANO_SUCCESS)+ result = cardano_pool_params_from_cbor(reader, &pool);+ if (result == CARDANO_SUCCESS)+ result = cardano_cbor_reader_read_end_array(reader);+ break;+ }+ case 10U:+ result = cardano_protocol_param_update_from_cbor(reader, &update);+ break;+ case 11U:+ result = cardano_plutus_data_from_cbor(reader, &data);+ break;+ case 12U:+ result = cardano_transaction_output_from_cbor(reader, &tx_output);+ break;+ case 13U:+ result = cardano_witness_set_from_cbor(reader, &witnesses);+ break;+ case 14U:+ result = cardano_utxo_from_cbor(reader, &utxo);+ break;+ case 15U:+ result = cardano_drep_from_cbor(reader, &drep);+ break;+ case 16U:+ result = cardano_governance_action_id_from_cbor(reader, &action_id);+ break;+ case 17U:+ result = cardano_anchor_from_cbor(reader, &anchor);+ break;+ case 18U:+ result = cardano_voting_procedures_from_cbor(reader, &votes);+ break;+ case 19U:+ result = inspect_action(input, size, reader, writer);+ break;+ case 20U:+ result = cardano_metadatum_from_cbor(reader, &metadatum);+ break;+ case 21U:+ result = cardano_transaction_metadata_from_cbor(reader, &metadata);+ break;+ case 22U:+ result = cardano_auxiliary_data_from_cbor(reader, &auxiliary);+ break;+ case 23U:+ result = cardano_transaction_input_from_cbor(reader, &tx_input);+ break;+ case 24U:+ result = cardano_datum_from_cbor(reader, &datum);+ break;+ case 25U:+ result = cardano_redeemer_from_cbor(reader, &redeemer);+ break;+ case 26U:+ result = cardano_ex_units_from_cbor(reader, &inspection_ex_units);+ break;+ case 27U:+ result = cardano_protocol_version_from_cbor(reader, &inspection_protocol_version);+ break;+ case 28U:+ result = cardano_unit_interval_from_cbor(reader, &inspection_unit_interval);+ break;+ case 29U:+ result = cardano_relay_from_cbor(reader, &inspection_relay);+ break;+ case 30U:+ result = cardano_pool_metadata_from_cbor(reader, &inspection_pool_metadata);+ break;+ case 31U:+ result = cardano_constitution_from_cbor(reader, &inspection_constitution);+ break;+ case 32U:+ result = cardano_voter_from_cbor(reader, &inspection_voter);+ break;+ case 33U:+ result = cardano_voting_procedure_from_cbor(reader, &inspection_voting_procedure);+ break;+ case 34U:+ result = cardano_vkey_witness_from_cbor(reader, &inspection_verification_witness);+ break;+ case 35U:+ result = cardano_bootstrap_witness_from_cbor(reader, &inspection_bootstrap_witness);+ break;+ case 36U:+ {+ int64_t count = 0;+ result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count != 2 && count != -1)+ result = CARDANO_ERROR_DECODING;+ if (result == CARDANO_SUCCESS)+ result = cardano_cost_model_from_cbor(reader, &inspection_cost_model);+ if (result == CARDANO_SUCCESS)+ result = cardano_cbor_reader_read_end_array(reader);+ break;+ }+ case 37U:+ result = cardano_costmdls_from_cbor(reader, &inspection_cost_models);+ break;+ case 38U:+ result = cardano_ex_unit_prices_from_cbor(reader, &inspection_ex_unit_prices);+ break;+ case 39U:+ result = cardano_pool_voting_thresholds_from_cbor(reader, &inspection_pool_voting_thresholds);+ break;+ case 40U:+ result = cardano_drep_voting_thresholds_from_cbor(reader, &inspection_drep_voting_thresholds);+ break;+ case 41U:+ result = cardano_proposed_param_updates_from_cbor(reader, &inspection_proposed_updates);+ break;+ case 42U:+ result = cardano_update_from_cbor(reader, &inspection_update_proposal);+ break;+ case 43U:+ result = cardano_account_balance_interval_from_cbor(reader, &inspection_balance_interval);+ break;+ case 44U:+ result = cardano_account_balance_intervals_map_from_cbor(reader, &inspection_balance_intervals);+ break;+ case 45U:+ result = cardano_direct_deposit_map_from_cbor(reader, &inspection_direct_deposits);+ break;+ case 46U:+ result = cardano_required_guards_map_from_cbor(reader, &inspection_required_guards);+ break;+ case 47U:+ result = cardano_asset_name_from_cbor(reader, &inspection_asset_name);+ break;+ case 48U:+ result = cardano_blake2b_hash_from_cbor(reader, &inspection_blake2b_hash);+ break;+ case 49U:+ result = cardano_bls_key_from_cbor(reader, &inspection_bls_key);+ break;+ case 50U:+ result = cardano_committee_members_map_from_cbor(reader, &inspection_committee_members_map);+ break;+ case 51U:+ result = cardano_withdrawal_map_from_cbor(reader, &inspection_withdrawal_map);+ break;+ case 52U:+ result = cardano_blake2b_hash_set_from_cbor(reader, &inspection_blake2b_hash_set);+ break;+ case 53U:+ result = cardano_guard_set_from_cbor(reader, &inspection_guard_set);+ break;+ case 54U:+ result = cardano_sub_transaction_set_from_cbor(reader, &inspection_sub_transaction_set);+ break;+ case 55U:+ result = cardano_multi_asset_from_cbor(reader, &inspection_assets);+ break;+ case 56U:+ result = cardano_multi_asset_from_cbor(reader, &inspection_asset_entries);+ break;+ case 57U:+ result = cardano_asset_name_map_from_cbor(reader, &inspection_policy_assets);+ break;+ case 58U:+ result = cardano_asset_name_map_from_cbor(reader, &inspection_policy_asset_entries);+ break;+ default:+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ break;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if (result == CARDANO_SUCCESS && remaining != 0U)+ {+ result = CARDANO_ERROR_DECODING;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ switch (operation)+ {+ case 0U:+ result = cardano_transaction_to_cip116_json(transaction, writer);+ break;+ case 1U:+ result = cardano_sub_transaction_to_cip116_json(sub, writer);+ break;+ case 2U:+ result = cardano_transaction_body_to_cip116_json(body, writer);+ break;+ case 3U:+ result = cardano_sub_transaction_body_to_cip116_json(sub_body, writer);+ break;+ case 4U:+ result = cardano_value_to_cip116_json(value, writer);+ break;+ case 5U:+ result = cardano_script_to_cip116_json(script, writer);+ break;+ case 6U:+ result = cardano_credential_to_cip116_json(credential, writer);+ break;+ case 7U:+ result = cardano_certificate_to_cip116_json(certificate, writer);+ break;+ case 8U:+ result = cardano_proposal_procedure_to_cip116_json(proposal, writer);+ break;+ case 9U:+ result = cardano_pool_params_to_cip116_json(pool, writer);+ break;+ case 10U:+ result = cardano_protocol_param_update_to_cip116_json(update, writer);+ break;+ case 11U:+ result = cardano_plutus_data_to_cip116_json(data, writer);+ break;+ case 12U:+ result = cardano_transaction_output_to_cip116_json(tx_output, writer);+ break;+ case 13U:+ result = cardano_witness_set_to_cip116_json(witnesses, writer);+ break;+ case 14U:+ result = cardano_utxo_to_cip116_json(utxo, writer);+ break;+ case 15U:+ result = cardano_drep_to_cip116_json(drep, writer);+ break;+ case 16U:+ result = cardano_governance_action_id_to_cip116_json(action_id, writer);+ break;+ case 17U:+ result = cardano_anchor_to_cip116_json(anchor, writer);+ break;+ case 18U:+ result = cardano_voting_procedures_to_cip116_json(votes, writer);+ break;+ case 19U:+ break; /* Action inspection already wrote its concrete variant. */+ case 20U:+ result = cardano_metadatum_to_cip116_json(metadatum, writer);+ break;+ case 21U:+ result = cardano_transaction_metadata_to_cip116_json(metadata, writer);+ break;+ case 22U:+ result = cardano_auxiliary_data_to_cip116_json(auxiliary, writer);+ break;+ case 23U:+ result = cardano_transaction_input_to_cip116_json(tx_input, writer);+ break;+ case 24U:+ result = cardano_datum_to_cip116_json(datum, writer);+ break;+ case 25U:+ result = cardano_redeemer_to_cip116_json(redeemer, writer);+ break;+ case 26U:+ result = cardano_ex_units_to_cip116_json(inspection_ex_units, writer);+ break;+ case 27U:+ result = cardano_protocol_version_to_cip116_json(inspection_protocol_version, writer);+ break;+ case 28U:+ result = cardano_unit_interval_to_cip116_json(inspection_unit_interval, writer);+ break;+ case 29U:+ result = cardano_relay_to_cip116_json(inspection_relay, writer);+ break;+ case 30U:+ result = cardano_pool_metadata_to_cip116_json(inspection_pool_metadata, writer);+ break;+ case 31U:+ result = cardano_constitution_to_cip116_json(inspection_constitution, writer);+ break;+ case 32U:+ result = cardano_voter_to_cip116_json(inspection_voter, writer);+ break;+ case 33U:+ result = cardano_voting_procedure_to_cip116_json(inspection_voting_procedure, writer);+ break;+ case 34U:+ result = cardano_vkey_witness_to_cip116_json(inspection_verification_witness, writer);+ break;+ case 35U:+ result = cardano_bootstrap_witness_to_cip116_json(inspection_bootstrap_witness, writer);+ break;+ case 36U:+ result = cardano_cost_model_to_cip116_json(inspection_cost_model, writer);+ break;+ case 37U:+ result = cardano_costmdls_to_cip116_json(inspection_cost_models, writer);+ break;+ case 38U:+ result = cardano_ex_unit_prices_to_cip116_json(inspection_ex_unit_prices, writer);+ break;+ case 39U:+ result = cardano_pool_voting_thresholds_to_cip116_json(inspection_pool_voting_thresholds, writer);+ break;+ case 40U:+ result = cardano_drep_voting_thresholds_to_cip116_json(inspection_drep_voting_thresholds, writer);+ break;+ case 41U:+ result = cardano_proposed_param_updates_to_cip116_json(inspection_proposed_updates, writer);+ break;+ case 42U:+ result = cardano_update_to_cip116_json(inspection_update_proposal, writer);+ break;+ case 43U:+ result = cardano_account_balance_interval_to_cip116_json(inspection_balance_interval, writer);+ break;+ case 44U:+ result = cardano_account_balance_intervals_map_to_cip116_json(inspection_balance_intervals, writer);+ break;+ case 45U:+ result = cardano_direct_deposit_map_to_cip116_json(inspection_direct_deposits, writer);+ break;+ case 46U:+ result = cardano_required_guards_map_to_cip116_json(inspection_required_guards, writer);+ break;+ case 47U:+ result = cardano_asset_name_to_cip116_json(inspection_asset_name, writer);+ break;+ case 48U:+ result = cardano_blake2b_hash_to_cip116_json(inspection_blake2b_hash, writer);+ break;+ case 49U:+ result = cardano_bls_key_to_cip116_json(inspection_bls_key, writer);+ break;+ case 50U:+ result = cardano_committee_members_map_to_cip116_json(inspection_committee_members_map, writer);+ break;+ case 51U:+ result = cardano_withdrawal_map_to_cip116_json(inspection_withdrawal_map, writer);+ break;+ case 52U:+ result = cardano_blake2b_hash_set_to_cip116_json(inspection_blake2b_hash_set, writer);+ break;+ case 53U:+ result = cardano_guard_set_to_cip116_json(inspection_guard_set, writer);+ break;+ case 54U:+ result = cardano_sub_transaction_set_to_cip116_json(inspection_sub_transaction_set, writer);+ break;+ case 55U:+ result = cardano_multi_asset_to_cip116_json(inspection_assets, writer);+ break;+ case 56U:+ result = cardano_multi_asset_to_cip116_json_ex(inspection_asset_entries, writer);+ break;+ case 57U:+ result = cardano_asset_name_map_to_cip116_json(inspection_policy_assets, writer);+ break;+ case 58U:+ result = cardano_asset_name_map_to_cip116_json_ex(inspection_policy_asset_entries, writer);+ break;+ default:+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ break;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ /* Native JSON buffers contain their exact length, without a trailing NUL. */+ result = cardano_json_writer_encode_in_buffer(writer, output);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }+ cardano_ex_units_unref(&inspection_ex_units);+ cardano_protocol_version_unref(&inspection_protocol_version);+ cardano_unit_interval_unref(&inspection_unit_interval);+ cardano_relay_unref(&inspection_relay);+ cardano_pool_metadata_unref(&inspection_pool_metadata);+ cardano_constitution_unref(&inspection_constitution);+ cardano_voter_unref(&inspection_voter);+ cardano_voting_procedure_unref(&inspection_voting_procedure);+ cardano_vkey_witness_unref(&inspection_verification_witness);+ cardano_bootstrap_witness_unref(&inspection_bootstrap_witness);+ cardano_cost_model_unref(&inspection_cost_model);+ cardano_costmdls_unref(&inspection_cost_models);+ cardano_ex_unit_prices_unref(&inspection_ex_unit_prices);+ cardano_pool_voting_thresholds_unref(&inspection_pool_voting_thresholds);+ cardano_drep_voting_thresholds_unref(&inspection_drep_voting_thresholds);+ cardano_proposed_param_updates_unref(&inspection_proposed_updates);+ cardano_update_unref(&inspection_update_proposal);+ cardano_account_balance_interval_unref(&inspection_balance_interval);+ cardano_account_balance_intervals_map_unref(&inspection_balance_intervals);+ cardano_direct_deposit_map_unref(&inspection_direct_deposits);+ cardano_required_guards_map_unref(&inspection_required_guards);+ cardano_asset_name_unref(&inspection_asset_name);+ cardano_blake2b_hash_unref(&inspection_blake2b_hash);+ cardano_bls_key_unref(&inspection_bls_key);+ cardano_committee_members_map_unref(&inspection_committee_members_map);+ cardano_withdrawal_map_unref(&inspection_withdrawal_map);+ cardano_blake2b_hash_set_unref(&inspection_blake2b_hash_set);+ cardano_guard_set_unref(&inspection_guard_set);+ cardano_sub_transaction_set_unref(&inspection_sub_transaction_set);+ cardano_multi_asset_unref(&inspection_assets);+ cardano_multi_asset_unref(&inspection_asset_entries);+ cardano_asset_name_map_unref(&inspection_policy_assets);+ cardano_asset_name_map_unref(&inspection_policy_asset_entries);+ cardano_redeemer_unref(&redeemer);+ cardano_datum_unref(&datum);+ cardano_transaction_input_unref(&tx_input);+ cardano_auxiliary_data_unref(&auxiliary);+ cardano_transaction_metadata_unref(&metadata);+ cardano_metadatum_unref(&metadatum);+ cardano_voting_procedures_unref(&votes);+ cardano_anchor_unref(&anchor);+ cardano_governance_action_id_unref(&action_id);+ cardano_drep_unref(&drep);+ cardano_utxo_unref(&utxo);+ cardano_witness_set_unref(&witnesses);+ cardano_transaction_output_unref(&tx_output);+ cardano_plutus_data_unref(&data);+ cardano_protocol_param_update_unref(&update);+ cardano_pool_params_unref(&pool);+ cardano_proposal_procedure_unref(&proposal);+ cardano_certificate_unref(&certificate);+ cardano_credential_unref(&credential);+ cardano_script_unref(&script);+ cardano_value_unref(&value);+ cardano_sub_transaction_body_unref(&sub_body);+ cardano_transaction_body_unref(&body);+ cardano_sub_transaction_unref(&sub);+ cardano_transaction_unref(&transaction);+ cardano_json_writer_unref(&writer);+ cardano_cbor_reader_unref(&reader);+ return (unsigned int)result;+}
@@ -0,0 +1,45 @@+/**+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+#ifndef COMETA_INSPECTION_H+#define COMETA_INSPECTION_H++#include <cardano/cardano.h>++/**+ * \brief Inspect one complete CBOR object with fresh operation-scoped owners.+ * \param operation 0 transaction, 1 subtransaction, 2 body, 3 subtransaction body;+ * 4 value, 5 script, 6 credential, 7 certificate, 8 proposal, 9 pool parameters,+ * 10 protocol update, 11 Plutus data, 12 output, 13 witnesses, 14 UTxO,+ * 15 DRep, 16 action id, 17 anchor, 18 voting procedures, 19 governance action,+ * 20 metadatum, 21 metadata, 22 auxiliary data, 23 input, 24 datum, 25 redeemer;+ * 26 execution units, 27 protocol version, 28 unit interval, 29 relay,+ * 30 pool metadata, 31 constitution, 32 voter, 33 voting procedure,+ * 34 verification witness, 35 bootstrap witness;+ * 36 cost model, 37 cost models, 38 execution prices, 39 pool thresholds,+ * 40 DRep thresholds, 41 legacy proposed updates, 42 legacy update proposal,+ * 43 balance interval, 44 account intervals, 45 direct deposits, 46 required guards;+ * 47 asset name, 48 BLAKE2b digest, 49 BLS key, 50 committee members,+ * 51 withdrawals, 52 digests, 53 guards, 54 subtransactions,+ * 55 assets object, 56 asset policy entries, 57 policy assets object,+ * 58 policy asset entries.+ * \param input Borrowed complete CBOR bytes, valid through return.+ * \param size Byte count of input.+ * \param output Transferred JSON byte buffer on success, NULL on failure.+ * \return Native status; every reader, parsed object and writer is released.+ */+unsigned int cometa_inspection_compute(unsigned int operation, const unsigned char* input, size_t size, cardano_buffer_t** output);+#endif
@@ -0,0 +1,150 @@+/**+ * \file cometa_key_handler.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/+#include "cometa_key_handler.h"+#include <cardano/cbor/cbor_reader.h>+#include <cardano/cbor/cbor_writer.h>+#include <cardano/transaction/sub_transaction.h>+#include <cardano/transaction/transaction.h>+#include <stdlib.h>++/* DEFINITIONS ***************************************************************/+unsigned int+cometa_handler_account(cardano_secure_key_handler_t* handler, uint32_t purpose, uint32_t coin, uint32_t account, unsigned char* output)+{+ cardano_account_derivation_path_t path = { purpose, coin, account };+ cardano_bip32_public_key_t* key = NULL;+ cardano_error_t result = cardano_secure_key_handler_bip32_get_extended_account_public_key(handler, path, &key);+ if (result == CARDANO_SUCCESS)+ {+ result = key == NULL ? CARDANO_ERROR_GENERIC : cardano_bip32_public_key_to_bytes(key, output, 64U);+ }+ cardano_bip32_public_key_unref(&key);+ return (unsigned int)result;+}++unsigned int+cometa_handler_public(cardano_secure_key_handler_t* handler, unsigned char* output)+{+ cardano_ed25519_public_key_t* key = NULL;+ cardano_error_t result = cardano_secure_key_handler_ed25519_get_public_key(handler, &key);+ if (result == CARDANO_SUCCESS)+ {+ result = key == NULL ? CARDANO_ERROR_GENERIC : cardano_ed25519_public_key_to_bytes(key, output, 32U);+ }+ cardano_ed25519_public_key_unref(&key);+ return (unsigned int)result;+}++unsigned int+cometa_handler_sign(cardano_secure_key_handler_t* handler, const unsigned char* bytes, size_t size, unsigned int kind, const uint32_t* components, size_t count, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ if ((handler == NULL) || (bytes == NULL) || (size == 0U) || (kind > 3U))+ {+ return (unsigned int)CARDANO_ERROR_INVALID_ARGUMENT;+ }+ const bool bip32 = (kind & 1U) != 0U;+ const bool sub = (kind & 2U) != 0U;+ if (bip32 && ((components == NULL) || (count == 0U) || (count > SIZE_MAX / sizeof(cardano_derivation_path_t))))+ {+ return (unsigned int)CARDANO_ERROR_INVALID_ARGUMENT;+ }+ cardano_derivation_path_t* paths = bip32 ? calloc(count, sizeof(cardano_derivation_path_t)) : NULL;+ if (bip32 && (paths == NULL))+ {+ return (unsigned int)CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ for (size_t i = 0U; bip32 && (i < count); ++i)+ {+ paths[i].purpose = components[5U * i];+ paths[i].coin_type = components[5U * i + 1U];+ paths[i].account = components[5U * i + 2U];+ paths[i].role = components[5U * i + 3U];+ paths[i].index = components[5U * i + 4U];+ }+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_cbor_writer_t* writer = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_sub_transaction_t* sub_transaction = NULL;+ cardano_vkey_witness_set_t* vkeys = NULL;+ cardano_witness_set_t* witnesses = NULL;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : CARDANO_SUCCESS;+ size_t remaining = 0U;+ if (result == CARDANO_SUCCESS)+ {+ result = sub ? cardano_sub_transaction_from_cbor(reader, &sub_transaction) : cardano_transaction_from_cbor(reader, &transaction);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if ((result == CARDANO_SUCCESS) && (remaining != 0U))+ {+ result = CARDANO_ERROR_DECODING;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ if (sub)+ {+ result = bip32 ? cardano_secure_key_handler_bip32_sign_sub_transaction(handler, sub_transaction, paths, count, &vkeys)+ : cardano_secure_key_handler_ed25519_sign_sub_transaction(handler, sub_transaction, &vkeys);+ }+ else+ {+ result = bip32 ? cardano_secure_key_handler_bip32_sign_transaction(handler, transaction, paths, count, &vkeys)+ : cardano_secure_key_handler_ed25519_sign_transaction(handler, transaction, &vkeys);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = vkeys == NULL ? CARDANO_ERROR_GENERIC : cardano_witness_set_new(&witnesses);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_set_vkeys(witnesses, vkeys);+ }+ if (result == CARDANO_SUCCESS)+ {+ writer = cardano_cbor_writer_new();+ result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_witness_set_to_cbor(witnesses, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_cbor_writer_unref(&writer);+ cardano_cbor_reader_unref(&reader);+ cardano_transaction_unref(&transaction);+ cardano_sub_transaction_unref(&sub_transaction);+ cardano_vkey_witness_set_unref(&vkeys);+ cardano_witness_set_unref(&witnesses);+ free(paths);+ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }+ return (unsigned int)result;+}
@@ -0,0 +1,55 @@+/**+ * \file cometa_key_handler.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_KEY_HANDLER_H+#define BIGLUP_LABS_INCLUDE_COMETA_KEY_HANDLER_H++/* INCLUDES ******************************************************************/+#include <cardano/buffer.h>+#include <cardano/key_handlers/software_secure_key_handler.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/+/** \brief Borrow live handler; copy owned temporary account key to 64 output bytes, releasing it on every exit.+ * \param handler Borrowed handler, valid through return.+ * \param purpose Unencoded purpose below 2^31.+ * \param coin Unencoded coin type below 2^31.+ * \param account Unencoded account below 2^31.+ * \param output Caller-owned 64-byte destination, valid through return.+ * \return Native status; output valid only on success.+ */+unsigned int cometa_handler_account(cardano_secure_key_handler_t* handler, uint32_t purpose, uint32_t coin, uint32_t account, unsigned char* output);+/** \brief Borrow live handler; copy owned temporary Ed25519 public key to 32 bytes, releasing it on every exit.+ * \param handler Borrowed handler, valid through return.+ * \param output Caller-owned 32-byte destination, valid through return.+ * \return Native status; output valid only on success.+ */+unsigned int cometa_handler_public(cardano_secure_key_handler_t* handler, unsigned char* output);+/** \brief Sign one exact top/sub transaction body and return a fresh encoded witness map.+ * \param handler Borrowed live handler; callbacks may run until return.+ * \param bytes Borrowed complete transaction CBOR.+ * \param size CBOR length in bytes.+ * \param kind Private dispatch: 0 Ed25519/top, 1 BIP32/top, 2 Ed25519/sub, 3 BIP32/sub.+ * \param components Borrowed flattened unencoded purpose/coin/account/role/index arrays.+ * \param count Number of five-component paths; positive for BIP32.+ * \param output Owned buffer on success; null on failure. Caller releases it.+ * \return Native status. All temporary native references are released on every exit.+ */+unsigned int cometa_handler_sign(cardano_secure_key_handler_t* handler, const unsigned char* bytes, size_t size, unsigned int kind, const uint32_t* components, size_t count, cardano_buffer_t** output);+#endif
@@ -0,0 +1,184 @@+/**+ * \file cometa_native_evaluation.c+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_native_evaluation.h"+#include <cardano/cardano.h>+#include <string.h>++/* STATIC FUNCTIONS **********************************************************/++/* Each transport contains exactly one complete CBOR item. */+static cardano_error_t+finish_reader(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if (result == CARDANO_SUCCESS && remaining != 0)+ {+ result = CARDANO_ERROR_DECODING;+ }+ return result;+}++/* List insertion retains each child; local children and partial lists remain+ * independently owned and are released on every parse result. */+static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ *output = NULL;+ int64_t size = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &size);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(output);+ }+ for (int64_t index = 0; result == CARDANO_SUCCESS; ++index)+ {+ cardano_cbor_reader_state_t state;+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result != CARDANO_SUCCESS || state == CARDANO_CBOR_READER_STATE_END_ARRAY)+ {+ break;+ }+ if (size >= 0 && index >= size)+ {+ result = CARDANO_ERROR_DECODING;+ break;+ }+ cardano_utxo_t* child = NULL;+ result = cardano_utxo_from_cbor(reader, &child);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, child);+ }+ cardano_utxo_unref(&child);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_native_evaluation_run(uint64_t zero_time, uint64_t zero_slot, uint64_t slot_length, uint64_t protocol_major, unsigned int is_sub, uint64_t sub_index, const unsigned char* models, size_t models_size, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic)+{+ if (output != NULL)+ {+ *output = NULL;+ }+ if (diagnostic != NULL)+ {+ *diagnostic = NULL;+ }+ if (output == NULL || diagnostic == NULL || models == NULL || transaction == NULL || utxos == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (slot_length == 0)+ {+ return (unsigned int)CARDANO_ERROR_INVALID_ARGUMENT;+ }+ cardano_slot_config_t slots = { zero_time, zero_slot, slot_length };+ cardano_tx_evaluator_t* evaluator = NULL;+ cardano_transaction_t* tx = NULL;+ cardano_utxo_list_t* additional = NULL;+ cardano_costmdls_t* costs = NULL;+ cardano_redeemer_list_t* redeemers = NULL;+ cardano_cbor_reader_t* tx_reader = cardano_cbor_reader_new(transaction, transaction_size);+ cardano_cbor_reader_t* utxo_reader = cardano_cbor_reader_new(utxos, utxos_size);+ cardano_cbor_reader_t* models_reader = cardano_cbor_reader_new(models, models_size);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ if (tx_reader == NULL || utxo_reader == NULL || models_reader == NULL || writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_transaction_from_cbor(tx_reader, &tx);+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(tx_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(utxo_reader, &additional);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(utxo_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_costmdls_from_cbor(models_reader, &costs);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = finish_reader(models_reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = is_sub == 0+ ? cardano_tx_evaluator_new_native(&slots, costs, protocol_major, &evaluator)+ : cardano_tx_evaluator_new_native_sub_transaction(&slots, costs, protocol_major, sub_index, &evaluator);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_tx_evaluator_evaluate(evaluator, tx, additional, &redeemers);+ }+ if (result == CARDANO_SUCCESS && redeemers == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_to_cbor(redeemers, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ const char* message = evaluator != NULL ? cardano_tx_evaluator_get_last_error(evaluator) : cardano_error_to_string(result);+ if (message == NULL || message[0] == '\0')+ {+ message = cardano_error_to_string(result);+ }+ *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));+ cardano_buffer_unref(output);+ *output = NULL;+ }+ cardano_redeemer_list_unref(&redeemers);+ cardano_tx_evaluator_unref(&evaluator);+ cardano_costmdls_unref(&costs);+ cardano_utxo_list_unref(&additional);+ cardano_transaction_unref(&tx);+ cardano_cbor_reader_unref(&models_reader);+ cardano_cbor_reader_unref(&utxo_reader);+ cardano_cbor_reader_unref(&tx_reader);+ cardano_cbor_writer_unref(&writer);+ return (unsigned int)result;+}
@@ -0,0 +1,54 @@+/**+ * \file cometa_native_evaluation.h+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_NATIVE_EVALUATION_H+#define BIGLUP_LABS_COMETA_NATIVE_EVALUATION_H++/* INCLUDES ******************************************************************/++#include <cardano/cardano.h>+#include <stddef.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Evaluate with operation-owned resources and borrowed CBOR inputs.+ * \param[in] zero_time Unix milliseconds at zero_slot.+ * \param[in] zero_slot Schedule reference slot.+ * \param[in] slot_length Positive slot duration in milliseconds.+ * \param[in] protocol_major Protocol major version selecting builtin semantics.+ * \param[in] is_sub Zero selects top-level; nonzero selects sub_index.+ * \param[in] sub_index Sub-transaction position when selected.+ * \param[in] models Borrowed cost-model map CBOR until return.+ * \param[in] models_size Complete cost-model byte count.+ * \param[in] transaction Borrowed transaction CBOR until return.+ * \param[in] transaction_size Complete transaction byte count.+ * \param[in] utxos Borrowed resolved UTxO array CBOR until return.+ * \param[in] utxos_size Complete UTxO array byte count.+ * \param[out] output Owned redeemer CBOR on success; NULL on failure.+ * \param[out] diagnostic Owned copied diagnostic on failure when allocation succeeds.+ * \return Native status. Both output slots initialize NULL; all parsed objects+ * and evaluator references are released before return, including partial errors.+ */+unsigned int cometa_native_evaluation_run(uint64_t zero_time, uint64_t zero_slot, uint64_t slot_length, uint64_t protocol_major, unsigned int is_sub, uint64_t sub_index, const unsigned char* models, size_t models_size, const unsigned char* transaction, size_t transaction_size, const unsigned char* utxos, size_t utxos_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic);++#endif
@@ -0,0 +1,787 @@+/**+ * \file cometa_parameters.c+ *+ * \author angel.castillo+ * \date Nov 05, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_parameters.h"+#include <cardano/cardano.h>+#include <limits.h>+#include <stdbool.h>++/* STRUCTURES ****************************************************************/++/** \brief Typed scalar-field operations. No function-pointer casts are used. */+typedef struct uint_field_t+{+ bool required;+ cardano_error_t (*read_update)(const cardano_protocol_param_update_t*, uint64_t*);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, uint64_t);+ uint64_t (*read_full)(const cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, const uint64_t*);+} uint_field_t;++/** \brief Typed buffer accessors; each getter output owns one reference. */+typedef struct buffer_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_buffer_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_buffer_t*);+ cardano_buffer_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_buffer_t*);+} buffer_field_t;++/** \brief Typed costmdls accessors; each getter output owns one reference. */+typedef struct costmdls_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_costmdls_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_costmdls_t*);+ cardano_costmdls_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_costmdls_t*);+} costmdls_field_t;++/** \brief Typed drep_voting_thresholds accessors; each getter output owns one reference. */+typedef struct drep_voting_thresholds_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_drep_voting_thresholds_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_drep_voting_thresholds_t*);+ cardano_drep_voting_thresholds_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_drep_voting_thresholds_t*);+} drep_voting_thresholds_field_t;++/** \brief Typed ex_unit_prices accessors; each getter output owns one reference. */+typedef struct ex_unit_prices_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_ex_unit_prices_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_ex_unit_prices_t*);+ cardano_ex_unit_prices_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_ex_unit_prices_t*);+} ex_unit_prices_field_t;++/** \brief Typed ex_units accessors; each getter output owns one reference. */+typedef struct ex_units_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_ex_units_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_ex_units_t*);+ cardano_ex_units_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_ex_units_t*);+} ex_units_field_t;++/** \brief Typed pool_voting_thresholds accessors; each getter output owns one reference. */+typedef struct pool_voting_thresholds_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_pool_voting_thresholds_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_pool_voting_thresholds_t*);+ cardano_pool_voting_thresholds_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_pool_voting_thresholds_t*);+} pool_voting_thresholds_field_t;++/** \brief Typed protocol_version accessors; each getter output owns one reference. */+typedef struct protocol_version_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_protocol_version_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_protocol_version_t*);+ cardano_protocol_version_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_protocol_version_t*);+} protocol_version_field_t;++/** \brief Typed unit_interval accessors; each getter output owns one reference. */+typedef struct unit_interval_field_t+{+ bool required;+ cardano_error_t (*read_update)(cardano_protocol_param_update_t*, cardano_unit_interval_t**);+ cardano_error_t (*write_full)(cardano_protocol_parameters_t*, cardano_unit_interval_t*);+ cardano_unit_interval_t* (*read_full)(cardano_protocol_parameters_t*);+ cardano_error_t (*write_update)(cardano_protocol_param_update_t*, cardano_unit_interval_t*);+} unit_interval_field_t;++/* STATIC FUNCTIONS **********************************************************/++/** \brief Parse one complete snapshot map; no input bytes escape the call. */+static cardano_error_t+read_snapshot(const unsigned char* bytes, size_t size, cardano_protocol_param_update_t** snapshot)+{+ *snapshot = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ if (reader == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ cardano_error_t result = cardano_protocol_param_update_from_cbor(reader, snapshot);+ size_t remaining = 0U;+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if ((result == CARDANO_SUCCESS) && (remaining != 0U))+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ }+ }+ cardano_cbor_reader_unref(&reader);+ if (result != CARDANO_SUCCESS)+ {+ cardano_protocol_param_update_unref(snapshot);+ }+ return result;+}++/** \brief Copy scalar values in one direction, preserving source presence.+ * Full scalar getters have no presence bits: exporting consults a supplied+ * availability template when known, otherwise materializes actual scalar values.+ */+static cardano_error_t+transfer_uint(const uint_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ uint64_t value = 0U;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ if (importing)+ {+ if ((field->read_full == cardano_protocol_parameters_get_ref_script_cost_stride) && (value == 0U))+ {+ return CARDANO_ERROR_INVALID_ARGUMENT;+ }+ return field->write_full(full, value);+ }+ value = field->read_full(full);+ /* Zero is an unset/unrepresentable sentinel for the positive-only stride.+ Native storage cannot distinguish unavailable from an invalid explicit zero. */+ if ((shape == NULL) && (field->read_full == cardano_protocol_parameters_get_ref_script_cost_stride) && (value == 0U))+ {+ return CARDANO_SUCCESS;+ }+ return field->write_update(output, &value);+}++/** \brief Transfer a typed buffer field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_buffer(const buffer_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_buffer_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_buffer_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_buffer_unref(&value);+ return result;+}++/** \brief Transfer a typed costmdls field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_costmdls(const costmdls_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_costmdls_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_costmdls_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_costmdls_unref(&value);+ return result;+}++/** \brief Transfer a typed drep_voting_thresholds field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_drep_voting_thresholds(const drep_voting_thresholds_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_drep_voting_thresholds_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_drep_voting_thresholds_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_drep_voting_thresholds_unref(&value);+ return result;+}++/** \brief Transfer a typed ex_unit_prices field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_ex_unit_prices(const ex_unit_prices_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_ex_unit_prices_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_ex_unit_prices_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_ex_unit_prices_unref(&value);+ return result;+}++/** \brief Transfer a typed ex_units field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_ex_units(const ex_units_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_ex_units_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_ex_units_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_ex_units_unref(&value);+ return result;+}++/** \brief Transfer a typed pool_voting_thresholds field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_pool_voting_thresholds(const pool_voting_thresholds_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_pool_voting_thresholds_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_pool_voting_thresholds_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_pool_voting_thresholds_unref(&value);+ return result;+}++/** \brief Transfer a typed protocol_version field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_protocol_version(const protocol_version_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_protocol_version_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_protocol_version_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_protocol_version_unref(&value);+ return result;+}++/** \brief Transfer a typed unit_interval field. Both getters return retained references.+ * Release the shape's reference before acquiring the full value; failed setters+ * do not consume either reference. NULL is invalid for a declared present field.+ */+static cardano_error_t+transfer_unit_interval(const unit_interval_field_t* field, cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_unit_interval_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : field->read_update(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return field->required ? CARDANO_ERROR_INVALID_ARGUMENT : CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = field->write_full(full, value);+ }+ else+ {+ cardano_unit_interval_unref(&value);+ value = NULL;+ value = field->read_full(full);+ result = value == NULL ? ((shape == NULL && !field->required) ? CARDANO_SUCCESS : CARDANO_ERROR_INVALID_ARGUMENT) : field->write_update(output, value);+ }+ }+ cardano_unit_interval_unref(&value);+ return result;+}++/** \brief Enforce the signed native max-value-size setter boundary without narrowing. */+static cardano_error_t+transfer_max_value_size(cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ uint64_t value = 0U;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : cardano_protocol_param_update_get_max_value_size(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return CARDANO_SUCCESS;+ }+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ if (importing)+ {+ return value > INT64_MAX ? CARDANO_ERROR_INVALID_ARGUMENT : cardano_protocol_parameters_set_max_value_size(full, (int64_t)value);+ }+ value = cardano_protocol_parameters_get_max_value_size(full);+ return cardano_protocol_param_update_set_max_value_size(output, &value);+}++/** \brief Transfer nullable leverage; NULL here explicitly means unbounded. */+static cardano_error_t+transfer_leverage(cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_unit_interval_t* value = NULL;+ cardano_error_t result = shape == NULL ? CARDANO_SUCCESS : cardano_protocol_param_update_get_max_pledge_leverage(shape, &value);+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ return CARDANO_SUCCESS;+ }+ if (result == CARDANO_SUCCESS)+ {+ if (importing)+ {+ result = cardano_protocol_parameters_set_max_pledge_leverage(full, value);+ }+ else+ {+ cardano_unit_interval_unref(&value);+ value = NULL;+ value = cardano_protocol_parameters_get_max_pledge_leverage(full);+ result = value == NULL ? cardano_protocol_param_update_set_max_pledge_leverage_unbounded(output) : cardano_protocol_param_update_set_max_pledge_leverage(output, value);+ }+ }+ cardano_unit_interval_unref(&value);+ return result;+}++/** \brief Transfer explicit-null bootstrap rounds. Full getter pointers borrow+ * their scalar storage only while the full parameter owner remains alive.+ */+static cardano_error_t+transfer_round(cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ if ((shape != NULL) && !cardano_protocol_param_update_has_peras_bootstrap_round(shape))+ {+ return CARDANO_SUCCESS;+ }+ uint64_t value = 0U;+ if (importing)+ {+ if (cardano_protocol_param_update_is_peras_bootstrap_round_null(shape))+ {+ return cardano_protocol_parameters_set_peras_bootstrap_round(full, NULL);+ }+ cardano_error_t result = cardano_protocol_param_update_get_peras_bootstrap_round(shape, &value);+ return result == CARDANO_SUCCESS ? cardano_protocol_parameters_set_peras_bootstrap_round(full, &value) : result;+ }+ const uint64_t* actual = cardano_protocol_parameters_get_peras_bootstrap_round(full);+ return actual == NULL ? cardano_protocol_param_update_set_peras_bootstrap_round_null(output) : cardano_protocol_param_update_set_peras_bootstrap_round(output, actual);+}++/* STATIC CONSTANTS **********************************************************/++static const uint_field_t uint_fields[] = {+ { true, cardano_protocol_param_update_get_min_fee_a, cardano_protocol_parameters_set_min_fee_a, cardano_protocol_parameters_get_min_fee_a, cardano_protocol_param_update_set_min_fee_a },+ { true, cardano_protocol_param_update_get_min_fee_b, cardano_protocol_parameters_set_min_fee_b, cardano_protocol_parameters_get_min_fee_b, cardano_protocol_param_update_set_min_fee_b },+ { true, cardano_protocol_param_update_get_max_block_body_size, cardano_protocol_parameters_set_max_block_body_size, cardano_protocol_parameters_get_max_block_body_size, cardano_protocol_param_update_set_max_block_body_size },+ { true, cardano_protocol_param_update_get_max_tx_size, cardano_protocol_parameters_set_max_tx_size, cardano_protocol_parameters_get_max_tx_size, cardano_protocol_param_update_set_max_tx_size },+ { true, cardano_protocol_param_update_get_max_block_header_size, cardano_protocol_parameters_set_max_block_header_size, cardano_protocol_parameters_get_max_block_header_size, cardano_protocol_param_update_set_max_block_header_size },+ { true, cardano_protocol_param_update_get_key_deposit, cardano_protocol_parameters_set_key_deposit, cardano_protocol_parameters_get_key_deposit, cardano_protocol_param_update_set_key_deposit },+ { true, cardano_protocol_param_update_get_pool_deposit, cardano_protocol_parameters_set_pool_deposit, cardano_protocol_parameters_get_pool_deposit, cardano_protocol_param_update_set_pool_deposit },+ { true, cardano_protocol_param_update_get_max_epoch, cardano_protocol_parameters_set_max_epoch, cardano_protocol_parameters_get_max_epoch, cardano_protocol_param_update_set_max_epoch },+ { true, cardano_protocol_param_update_get_n_opt, cardano_protocol_parameters_set_n_opt, cardano_protocol_parameters_get_n_opt, cardano_protocol_param_update_set_n_opt },+ { true, cardano_protocol_param_update_get_min_pool_cost, cardano_protocol_parameters_set_min_pool_cost, cardano_protocol_parameters_get_min_pool_cost, cardano_protocol_param_update_set_min_pool_cost },+ { false, cardano_protocol_param_update_get_ada_per_utxo_byte, cardano_protocol_parameters_set_ada_per_utxo_byte, cardano_protocol_parameters_get_ada_per_utxo_byte, cardano_protocol_param_update_set_ada_per_utxo_byte },+ { false, cardano_protocol_param_update_get_collateral_percentage, cardano_protocol_parameters_set_collateral_percentage, cardano_protocol_parameters_get_collateral_percentage, cardano_protocol_param_update_set_collateral_percentage },+ { false, cardano_protocol_param_update_get_max_collateral_inputs, cardano_protocol_parameters_set_max_collateral_inputs, cardano_protocol_parameters_get_max_collateral_inputs, cardano_protocol_param_update_set_max_collateral_inputs },+ { false, cardano_protocol_param_update_get_min_committee_size, cardano_protocol_parameters_set_min_committee_size, cardano_protocol_parameters_get_min_committee_size, cardano_protocol_param_update_set_min_committee_size },+ { false, cardano_protocol_param_update_get_committee_term_limit, cardano_protocol_parameters_set_committee_term_limit, cardano_protocol_parameters_get_committee_term_limit, cardano_protocol_param_update_set_committee_term_limit },+ { false, cardano_protocol_param_update_get_governance_action_validity_period, cardano_protocol_parameters_set_governance_action_validity_period, cardano_protocol_parameters_get_governance_action_validity_period, cardano_protocol_param_update_set_governance_action_validity_period },+ { false, cardano_protocol_param_update_get_governance_action_deposit, cardano_protocol_parameters_set_governance_action_deposit, cardano_protocol_parameters_get_governance_action_deposit, cardano_protocol_param_update_set_governance_action_deposit },+ { false, cardano_protocol_param_update_get_drep_deposit, cardano_protocol_parameters_set_drep_deposit, cardano_protocol_parameters_get_drep_deposit, cardano_protocol_param_update_set_drep_deposit },+ { false, cardano_protocol_param_update_get_drep_inactivity_period, cardano_protocol_parameters_set_drep_inactivity_period, cardano_protocol_parameters_get_drep_inactivity_period, cardano_protocol_param_update_set_drep_inactivity_period },+ { false, cardano_protocol_param_update_get_max_ref_script_size_per_block, cardano_protocol_parameters_set_max_ref_script_size_per_block, cardano_protocol_parameters_get_max_ref_script_size_per_block, cardano_protocol_param_update_set_max_ref_script_size_per_block },+ { false, cardano_protocol_param_update_get_max_ref_script_size_per_tx, cardano_protocol_parameters_set_max_ref_script_size_per_tx, cardano_protocol_parameters_get_max_ref_script_size_per_tx, cardano_protocol_param_update_set_max_ref_script_size_per_tx },+ { false, cardano_protocol_param_update_get_ref_script_cost_stride, cardano_protocol_parameters_set_ref_script_cost_stride, cardano_protocol_parameters_get_ref_script_cost_stride, cardano_protocol_param_update_set_ref_script_cost_stride },+ { false, cardano_protocol_param_update_get_leios_announcement_period_length, cardano_protocol_parameters_set_leios_announcement_period_length, cardano_protocol_parameters_get_leios_announcement_period_length, cardano_protocol_param_update_set_leios_announcement_period_length },+ { false, cardano_protocol_param_update_get_leios_vote_period_length, cardano_protocol_parameters_set_leios_vote_period_length, cardano_protocol_parameters_get_leios_vote_period_length, cardano_protocol_param_update_set_leios_vote_period_length },+ { false, cardano_protocol_param_update_get_leios_diffusion_period_length, cardano_protocol_parameters_set_leios_diffusion_period_length, cardano_protocol_parameters_get_leios_diffusion_period_length, cardano_protocol_param_update_set_leios_diffusion_period_length },+ { false, cardano_protocol_param_update_get_leios_committee_size, cardano_protocol_parameters_set_leios_committee_size, cardano_protocol_parameters_get_leios_committee_size, cardano_protocol_param_update_set_leios_committee_size },+ { false, cardano_protocol_param_update_get_max_endorser_block_references_size, cardano_protocol_parameters_set_max_endorser_block_references_size, cardano_protocol_parameters_get_max_endorser_block_references_size, cardano_protocol_param_update_set_max_endorser_block_references_size },+ { false, cardano_protocol_param_update_get_max_endorser_block_txs_size, cardano_protocol_parameters_set_max_endorser_block_txs_size, cardano_protocol_parameters_get_max_endorser_block_txs_size, cardano_protocol_param_update_set_max_endorser_block_txs_size },+ { false, cardano_protocol_param_update_get_max_ref_script_size_per_endorser_block, cardano_protocol_parameters_set_max_ref_script_size_per_endorser_block, cardano_protocol_parameters_get_max_ref_script_size_per_endorser_block, cardano_protocol_param_update_set_max_ref_script_size_per_endorser_block },+ { false, cardano_protocol_param_update_get_peras_min_candidate_block_age, cardano_protocol_parameters_set_peras_min_candidate_block_age, cardano_protocol_parameters_get_peras_min_candidate_block_age, cardano_protocol_param_update_set_peras_min_candidate_block_age },+ { false, cardano_protocol_param_update_get_peras_cert_boost, cardano_protocol_parameters_set_peras_cert_boost, cardano_protocol_parameters_get_peras_cert_boost, cardano_protocol_param_update_set_peras_cert_boost },+ { false, cardano_protocol_param_update_get_peras_target_committee_size, cardano_protocol_parameters_set_peras_target_committee_size, cardano_protocol_parameters_get_peras_target_committee_size, cardano_protocol_param_update_set_peras_target_committee_size },+ { false, cardano_protocol_param_update_get_ref_inputs_cost_per_multi_asset_byte, cardano_protocol_parameters_set_ref_inputs_cost_per_multi_asset_byte, cardano_protocol_parameters_get_ref_inputs_cost_per_multi_asset_byte, cardano_protocol_param_update_set_ref_inputs_cost_per_multi_asset_byte },+ { false, cardano_protocol_param_update_get_ref_inputs_cost_per_datum_byte, cardano_protocol_parameters_set_ref_inputs_cost_per_datum_byte, cardano_protocol_parameters_get_ref_inputs_cost_per_datum_byte, cardano_protocol_param_update_set_ref_inputs_cost_per_datum_byte },+};++static const buffer_field_t buffer_fields[] = {+ { false, cardano_protocol_param_update_get_extra_entropy, cardano_protocol_parameters_set_extra_entropy, cardano_protocol_parameters_get_extra_entropy, cardano_protocol_param_update_set_extra_entropy },+};++static const costmdls_field_t costmdls_fields[] = {+ { false, cardano_protocol_param_update_get_cost_models, cardano_protocol_parameters_set_cost_models, cardano_protocol_parameters_get_cost_models, cardano_protocol_param_update_set_cost_models },+};++static const drep_voting_thresholds_field_t drep_voting_thresholds_fields[] = {+ { false, cardano_protocol_param_update_get_drep_voting_thresholds, cardano_protocol_parameters_set_drep_voting_thresholds, cardano_protocol_parameters_get_drep_voting_thresholds, cardano_protocol_param_update_set_drep_voting_thresholds },+};++static const ex_unit_prices_field_t ex_unit_prices_fields[] = {+ { false, cardano_protocol_param_update_get_execution_costs, cardano_protocol_parameters_set_execution_costs, cardano_protocol_parameters_get_execution_costs, cardano_protocol_param_update_set_execution_costs },+};++static const ex_units_field_t ex_units_fields[] = {+ { false, cardano_protocol_param_update_get_max_tx_ex_units, cardano_protocol_parameters_set_max_tx_ex_units, cardano_protocol_parameters_get_max_tx_ex_units, cardano_protocol_param_update_set_max_tx_ex_units },+ { false, cardano_protocol_param_update_get_max_block_ex_units, cardano_protocol_parameters_set_max_block_ex_units, cardano_protocol_parameters_get_max_block_ex_units, cardano_protocol_param_update_set_max_block_ex_units },+ { false, cardano_protocol_param_update_get_max_endorser_block_execution_units, cardano_protocol_parameters_set_max_endorser_block_execution_units, cardano_protocol_parameters_get_max_endorser_block_execution_units, cardano_protocol_param_update_set_max_endorser_block_execution_units },+};++static const pool_voting_thresholds_field_t pool_voting_thresholds_fields[] = {+ { false, cardano_protocol_param_update_get_pool_voting_thresholds, cardano_protocol_parameters_set_pool_voting_thresholds, cardano_protocol_parameters_get_pool_voting_thresholds, cardano_protocol_param_update_set_pool_voting_thresholds },+};++static const protocol_version_field_t protocol_version_fields[] = {+ { true, cardano_protocol_param_update_get_protocol_version, cardano_protocol_parameters_set_protocol_version, cardano_protocol_parameters_get_protocol_version, cardano_protocol_param_update_set_protocol_version },+};++static const unit_interval_field_t unit_interval_fields[] = {+ { true, cardano_protocol_param_update_get_pool_pledge_influence, cardano_protocol_parameters_set_pool_pledge_influence, cardano_protocol_parameters_get_pool_pledge_influence, cardano_protocol_param_update_set_pool_pledge_influence },+ { true, cardano_protocol_param_update_get_expansion_rate, cardano_protocol_parameters_set_expansion_rate, cardano_protocol_parameters_get_expansion_rate, cardano_protocol_param_update_set_expansion_rate },+ { true, cardano_protocol_param_update_get_treasury_growth_rate, cardano_protocol_parameters_set_treasury_growth_rate, cardano_protocol_parameters_get_treasury_growth_rate, cardano_protocol_param_update_set_treasury_growth_rate },+ { false, cardano_protocol_param_update_get_d, cardano_protocol_parameters_set_d, cardano_protocol_parameters_get_d, cardano_protocol_param_update_set_d },+ { false, cardano_protocol_param_update_get_ref_script_cost_per_byte, cardano_protocol_parameters_set_ref_script_cost_per_byte, cardano_protocol_parameters_get_ref_script_cost_per_byte, cardano_protocol_param_update_set_ref_script_cost_per_byte },+ { false, cardano_protocol_param_update_get_ref_script_cost_multiplier, cardano_protocol_parameters_set_ref_script_cost_multiplier, cardano_protocol_parameters_get_ref_script_cost_multiplier, cardano_protocol_param_update_set_ref_script_cost_multiplier },+ { false, cardano_protocol_param_update_get_min_pool_margin, cardano_protocol_parameters_set_min_pool_margin, cardano_protocol_parameters_get_min_pool_margin, cardano_protocol_param_update_set_min_pool_margin },+ { false, cardano_protocol_param_update_get_leios_quorum_stake_threshold, cardano_protocol_parameters_set_leios_quorum_stake_threshold, cardano_protocol_parameters_get_leios_quorum_stake_threshold, cardano_protocol_param_update_set_leios_quorum_stake_threshold },+ { false, cardano_protocol_param_update_get_peras_healing_factor, cardano_protocol_parameters_set_peras_healing_factor, cardano_protocol_parameters_get_peras_healing_factor, cardano_protocol_param_update_set_peras_healing_factor },+ { false, cardano_protocol_param_update_get_peras_quorum_threshold_safety_margin, cardano_protocol_parameters_set_peras_quorum_threshold_safety_margin, cardano_protocol_parameters_get_peras_quorum_threshold_safety_margin, cardano_protocol_param_update_set_peras_quorum_threshold_safety_margin },+};++/* STATIC FUNCTIONS **********************************************************/++/** \brief Directional transfer through audited typed native accessors. */+static cardano_error_t+transfer_fields(cardano_protocol_param_update_t* shape, cardano_protocol_parameters_t* full, cardano_protocol_param_update_t* output, bool importing)+{+ cardano_error_t result = CARDANO_SUCCESS;+ for (size_t i = 0U; i < sizeof(uint_fields) / sizeof(uint_fields[0]); ++i)+ {+ result = transfer_uint(&uint_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(buffer_fields) / sizeof(buffer_fields[0]); ++i)+ {+ result = transfer_buffer(&buffer_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(costmdls_fields) / sizeof(costmdls_fields[0]); ++i)+ {+ result = transfer_costmdls(&costmdls_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(drep_voting_thresholds_fields) / sizeof(drep_voting_thresholds_fields[0]); ++i)+ {+ result = transfer_drep_voting_thresholds(&drep_voting_thresholds_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(ex_unit_prices_fields) / sizeof(ex_unit_prices_fields[0]); ++i)+ {+ result = transfer_ex_unit_prices(&ex_unit_prices_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(ex_units_fields) / sizeof(ex_units_fields[0]); ++i)+ {+ result = transfer_ex_units(&ex_units_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(pool_voting_thresholds_fields) / sizeof(pool_voting_thresholds_fields[0]); ++i)+ {+ result = transfer_pool_voting_thresholds(&pool_voting_thresholds_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(protocol_version_fields) / sizeof(protocol_version_fields[0]); ++i)+ {+ result = transfer_protocol_version(&protocol_version_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ for (size_t i = 0U; i < sizeof(unit_interval_fields) / sizeof(unit_interval_fields[0]); ++i)+ {+ result = transfer_unit_interval(&unit_interval_fields[i], shape, full, output, importing);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ }+ result = transfer_max_value_size(shape, full, output, importing);+ if (result == CARDANO_SUCCESS)+ {+ result = transfer_leverage(shape, full, output, importing);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = transfer_round(shape, full, output, importing);+ }+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_parameters_from_snapshot(const unsigned char* bytes, size_t size, cardano_protocol_parameters_t** output)+{+ *output = NULL;+ cardano_protocol_param_update_t* shape = NULL;+ cardano_error_t result = read_snapshot(bytes, size, &shape);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_protocol_parameters_new(output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = transfer_fields(shape, *output, NULL, true);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_protocol_parameters_unref(output);+ }+ cardano_protocol_param_update_unref(&shape);+ return (unsigned int)result;+}++unsigned int+cometa_parameters_to_snapshot(cardano_protocol_parameters_t* parameters, const unsigned char* template_bytes, size_t template_size, cardano_buffer_t** output)+{+ *output = NULL;+ if ((parameters == NULL) || ((template_bytes == NULL) != (template_size == 0U)))+ {+ return CARDANO_ERROR_INVALID_ARGUMENT;+ }+ cardano_protocol_param_update_t* shape = NULL;+ cardano_protocol_param_update_t* fresh = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_error_t result = template_bytes == NULL ? CARDANO_SUCCESS : read_snapshot(template_bytes, template_size, &shape);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_protocol_param_update_new(&fresh);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = transfer_fields(shape, parameters, fresh, false);+ }+ if (result == CARDANO_SUCCESS)+ {+ writer = cardano_cbor_writer_new();+ result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_protocol_param_update_to_cbor(fresh, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_cbor_writer_unref(&writer);+ cardano_protocol_param_update_unref(&fresh);+ cardano_protocol_param_update_unref(&shape);+ return (unsigned int)result;+}++unsigned int+cometa_parameters_update_to_plutus_data(const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ *output = NULL;++ if (bytes == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ cardano_protocol_param_update_t* update = NULL;+ cardano_plutus_data_t* data = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_error_t result = read_snapshot(bytes, size, &update);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_protocol_param_update_to_plutus_data(update, &data);+ }++ if (result == CARDANO_SUCCESS)+ {+ writer = cardano_cbor_writer_new();+ result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_plutus_data_to_cbor(data, writer);+ }++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }++ cardano_cbor_writer_unref(&writer);+ cardano_plutus_data_unref(&data);+ cardano_protocol_param_update_unref(&update);++ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }++ return (unsigned int)result;+}
@@ -0,0 +1,65 @@+/**+ * \file cometa_parameters.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_PARAMETERS_H+#define BIGLUP_LABS_INCLUDE_COMETA_PARAMETERS_H++/* INCLUDES ******************************************************************/++#include <cardano/cardano.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Materialize a complete owned parameter snapshot through typed setters.+ * \param[in] bytes Borrowed protocol-update-key snapshot CBOR until return.+ * \param[in] size Complete byte count. All required snapshot fields must exist.+ * \param[out] output Owned full parameters on success; NULL on every failure.+ * \return A native status. Missing required fields and max-value-size overflow+ * above INT64_MAX are errors; no parameter defaults are synthesized.+ */+unsigned int cometa_parameters_from_snapshot(const unsigned char* bytes, size_t size, cardano_protocol_parameters_t** output);++/**+ * \brief Snapshot actual typed getters with optional original availability.+ * \param[in] parameters Borrowed full parameters, kept alive until return.+ * \param[in] template_bytes Optional borrowed snapshot defining original field presence.+ * Full native scalars have no presence flags. Values always come from getters; a supplied template controls only presence.+ * Without a template, native scalars are present, optional NULL objects absent,+ * and nullable NULL leverage/bootstrap values explicitly unbounded/unset.+ * \param[in] template_size Byte count of the complete availability template.+ * \param[out] output Owned snapshot buffer on success; NULL on failure.+ * \return Native status. Required missing objects are rejected. All retained getter+ * references are released before return. Full native scalars cannot distinguish+ * unavailable fields from stored zero values; no availability claim is made.+ */+unsigned int cometa_parameters_to_snapshot(cardano_protocol_parameters_t* parameters, const unsigned char* template_bytes, size_t template_size, cardano_buffer_t** output);++/**+ * \brief Convert a sparse protocol update to its ChangedParameters Plutus data.+ * \param[in] bytes Borrowed complete protocol-update CBOR until return.+ * \param[in] size Number of input bytes.+ * \param[out] output Owned Plutus-data CBOR buffer on success; NULL on failure.+ * \return Native status. Temporary update, data and writer owners are released+ * before return. The caller releases the returned buffer.+ */+unsigned int cometa_parameters_update_to_plutus_data(const unsigned char* bytes, size_t size, cardano_buffer_t** output);++#endif /* BIGLUP_LABS_INCLUDE_COMETA_PARAMETERS_H */
@@ -0,0 +1,53 @@+/**+ * \file cometa_password_crypto.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_password_crypto.h"++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_pbkdf2(const unsigned char* password, size_t password_size, const unsigned char* salt, size_t salt_size, uint32_t iterations, unsigned char* output, size_t output_size)+{+ return (unsigned int)cardano_crypto_pbkdf2_hmac_sha512(password, password_size, salt, salt_size, iterations, output, output_size);+}++unsigned int+cometa_emip3_encrypt(const unsigned char* data, size_t size, const unsigned char* password, size_t password_size, cardano_buffer_t** output)+{+ return (unsigned int)cardano_crypto_emip3_encrypt(data, size, password, password_size, output);+}++unsigned int+cometa_emip3_decrypt(const unsigned char* data, size_t size, const unsigned char* password, size_t password_size, cardano_buffer_t** output)+{+ return (unsigned int)cardano_crypto_emip3_decrypt(data, size, password, password_size, output);+}++void+cometa_password_buffer_release(cardano_buffer_t** output)+{+ if ((output != NULL) && (*output != NULL))+ {+ cardano_buffer_memzero(*output);+ cardano_buffer_unref(output);+ *output = NULL;+ }+}
@@ -0,0 +1,81 @@+/**+ * \file cometa_password_crypto.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_PASSWORD_CRYPTO_H+#define BIGLUP_LABS_INCLUDE_COMETA_PASSWORD_CRYPTO_H++/* INCLUDES ******************************************************************/++#include <cardano/buffer.h>+#include <cardano/crypto/emip3.h>+#include <cardano/crypto/pbkdf2.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif++/**+ * \brief Derive into caller-owned scratch storage, with unsigned status ABI.+ * \param[in] password Borrowed password bytes; may be empty.+ * \param[in] password_size Password byte count.+ * \param[in] salt Borrowed nonempty salt.+ * \param[in] salt_size Salt byte count.+ * \param[in] iterations Validated positive iteration count through UINT32_MAX.+ * \param[out] output Caller-owned scratch; wipe on every exit.+ * \param[in] output_size Validated positive output byte count.+ * \return Native status converted to unsigned int.+ */+unsigned int cometa_pbkdf2(const unsigned char* password, size_t password_size, const unsigned char* salt, size_t salt_size, uint32_t iterations, unsigned char* output, size_t output_size);++/**+ * \brief Encrypt borrowed plaintext into one owned ciphertext reference.+ * \param[in] data Borrowed non-NULL plaintext; may be empty.+ * \param[in] size Plaintext byte count; size plus 60 must not overflow.+ * \param[in] password Borrowed password bytes; may be empty.+ * \param[in] password_size Password byte count.+ * \param[out] output Initialized null slot; owns one reference on success.+ * \return Native status converted to unsigned int.+ */+unsigned int cometa_emip3_encrypt(const unsigned char* data, size_t size, const unsigned char* password, size_t password_size, cardano_buffer_t** output);++/**+ * \brief Decrypt borrowed ciphertext into one owned plaintext reference.+ * \param[in] data Borrowed envelope of at least 60 bytes.+ * \param[in] size Envelope byte count.+ * \param[in] password Borrowed password bytes; may be empty.+ * \param[in] password_size Password byte count.+ * \param[out] output Initialized null slot; wipe before releasing success output.+ * \return Native status converted to unsigned int. Authentication failure zeros+ * the output before native release; see the pinned libsodium audit.+ */+unsigned int cometa_emip3_decrypt(const unsigned char* data, size_t size, const unsigned char* password, size_t password_size, cardano_buffer_t** output);++/**+ * \brief Wipe and release the locally owned reference, then clear its slot.+ * \param[in,out] output Local initialized slot; no borrowed alias may escape.+ */+void cometa_password_buffer_release(cardano_buffer_t** output);++#ifdef __cplusplus+}+#endif++#endif /* BIGLUP_LABS_INCLUDE_COMETA_PASSWORD_CRYPTO_H */
@@ -0,0 +1,254 @@+/**+ * \file cometa_provider.c+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_provider.h"++#include <cardano/crypto/blake2b_hash.h>+#include <cardano/object.h>++#include <stdatomic.h>+#include <stdlib.h>+#include <string.h>++/* STRUCTURES ****************************************************************/++/**+ * \brief Reference-counted context adopted by a native provider.+ *+ * The provider owns this context after successful construction. Its final destructor releases both+ * Haskell runtime handles only after every operation reference and retained provider alias is released.+ */+typedef struct cometa_provider_context_t+{+ /**+ * \brief Native reference-count header. Must be the first member for cardano_object_t compatibility.+ */+ cardano_object_t base;++ /**+ * \brief Owned stable pointer rooting the Haskell handler and active operation state.+ */+ HsStablePtr state;++ /**+ * \brief Owned Haskell callback trampoline, released only after the last possible invocation.+ */+ cometa_confirmation_callback_t callback;+} cometa_provider_context_t;++/* STATIC VARIABLES **********************************************************/++/**+ * \brief Number of adopted callback contexts whose final destruction has not completed.+ */+static atomic_size_t live_contexts = 0U;++/**+ * \brief Number of native confirmation calls that have returned and released temporary hashes.+ */+static atomic_size_t completed_calls = 0U;++/* STATIC FUNCTIONS **********************************************************/++/**+ * \brief Releases a provider context and its owned Haskell runtime handles.+ *+ * \param[in] object Context whose native reference count has reached zero. Must not be NULL.+ *+ * \note No callback is executing: each operation retains a provider reference until native unwind.+ * The matching HsFFI release functions dispose of the trampoline and stable root before the+ * context is freed with the same allocator family used at construction.+ */+static void+cometa_provider_context_deallocate(void* object)+{+ cometa_provider_context_t* context = (cometa_provider_context_t*)object;++ hs_free_fun_ptr((HsFunPtr)context->callback);+ hs_free_stable_ptr(context->state);++ atomic_fetch_sub(&live_contexts, 1U);++ free(context);+}++/**+ * \brief Adapts the native confirmation callback to the Haskell registration ABI.+ *+ * \param[in,out] impl Provider implementation containing the adopted callback context and error buffer.+ * \param[in] hash Borrowed transaction identifier. Must remain valid throughout the callback.+ * \param[in] timeout_ms Confirmation timeout in milliseconds.+ * \param[out] confirmed Pointer receiving the native confirmation result.+ *+ * \returns CARDANO_ERROR_POINTER_IS_NULL for a NULL argument, or the Haskell callback's native status.+ *+ * \note The Haskell bridge copies borrowed hash bytes, contains all exceptions, and waits for its user+ * worker before returning. A successful integer output is converted to native bool here.+ */+static cardano_error_t+cometa_provider_await(+ cardano_provider_impl_t* impl,+ cardano_blake2b_hash_t* hash,+ uint64_t timeout_ms,+ bool* confirmed)+{+ if ((impl == NULL) || (hash == NULL) || (confirmed == NULL))+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ cometa_provider_context_t* context = (cometa_provider_context_t*)impl->context;+ int value = 0;++ *confirmed = false;+ impl->error_message[0] = '\0';++ cardano_error_t result = (cardano_error_t)context->callback(+ context->state, cardano_blake2b_hash_get_data(hash), cardano_blake2b_hash_get_bytes_size(hash), timeout_ms, &value, impl->error_message, sizeof(impl->error_message));++ if (result == CARDANO_SUCCESS)+ {+ *confirmed = value != 0;+ }++ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_provider_new(+ HsStablePtr state,+ cometa_confirmation_callback_t callback,+ cardano_provider_t** provider)+{+ if ((state == NULL) || (callback == NULL) || (provider == NULL))+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ *provider = NULL;++ cometa_provider_context_t* context = calloc(1U, sizeof(cometa_provider_context_t));++ if (context == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ context->base.ref_count = 1U;+ context->base.deallocator = cometa_provider_context_deallocate;+ context->state = state;+ context->callback = callback;++ cardano_provider_impl_t impl = { 0 };++ memcpy(impl.name, "Cometa internal confirmation adapter", sizeof("Cometa internal confirmation adapter"));++ impl.context = &context->base;+ impl.await_transaction_confirmation = cometa_provider_await;++ cardano_error_t result = cardano_provider_new(impl, provider);++ if (result != CARDANO_SUCCESS)+ {+ // Native construction did not adopt the context or runtime handles.+ free(context);++ return result;+ }++ atomic_fetch_add(&live_contexts, 1U);++ return CARDANO_SUCCESS;+}++void+cometa_provider_ref(cardano_provider_t* provider)+{+ cardano_provider_ref(provider);+}++void+cometa_provider_release(cardano_provider_t* provider)+{+ cardano_provider_unref(&provider);+}++unsigned int+cometa_provider_confirm(+ cardano_provider_t* provider,+ const unsigned char* hash,+ size_t hash_size,+ uint64_t timeout_ms,+ int* confirmed)+{+ if ((provider == NULL) || (hash == NULL) || (confirmed == NULL))+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }++ *confirmed = 0;++ bool value = false;+ cardano_blake2b_hash_t* tx_id = NULL;+ cardano_error_t result = cardano_blake2b_hash_from_bytes(hash, hash_size, &tx_id);++ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_confirm_transaction(provider, tx_id, timeout_ms, &value);+ }++ cardano_blake2b_hash_unref(&tx_id);++ *confirmed = value ? 1 : 0;++ // Increment strictly after the native callback-capable operation unwinds.+ atomic_fetch_add(&completed_calls, 1U);++ return result;+}++const char*+cometa_provider_error(const cardano_provider_t* provider)+{+ return cardano_provider_get_last_error(provider);+}++const char*+cometa_error_message(unsigned int code)+{+ return cardano_error_to_string((cardano_error_t)code);+}++size_t+cometa_callback_live_contexts(void)+{+ return atomic_load(&live_contexts);+}++size_t+cometa_callback_completed_calls(void)+{+ return atomic_load(&completed_calls);+}
@@ -0,0 +1,187 @@+/**+ * \file cometa_provider.h+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_PROVIDER_H+#define BIGLUP_LABS_INCLUDE_COMETA_PROVIDER_H++/* INCLUDES ******************************************************************/++#include <cardano/providers/provider.h>++#include <HsFFI.h>+#include <stddef.h>+#include <stdint.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif /* __cplusplus */++/* CALLBACKS *****************************************************************/++/**+ * \brief Function pointer type for invoking a Haskell transaction confirmation handler.+ *+ * All inputs and output buffers are borrowed until the callback returns. The Haskell bridge+ * copies the hash, runs the handler in a scoped worker, and forces its result before returning.+ * No Haskell exception may cross this callback ABI.+ *+ * \param[in] state Stable pointer to the Haskell callback state. Must not be NULL.+ * \param[in] hash Transaction identifier bytes. Must not be NULL.+ * \param[in] hash_size Number of bytes available at \p hash.+ * \param[in] timeout_ms Confirmation timeout in milliseconds.+ * \param[out] confirmed Pointer receiving 0 or 1. Must not be NULL.+ * \param[out] error Buffer receiving a null-terminated failure diagnostic.+ * \param[in] error_size Capacity of \p error in bytes, including the null terminator.+ *+ * \returns A cardano-c status represented as an int. On success, \p confirmed contains the+ * confirmation result. On failure, the bridge preserves the original Haskell exception+ * or expected failure for the operation that initiated the callback.+ *+ * \note The native adapter provides a non-NULL error buffer with positive capacity. The callback+ * must not write beyond that capacity or release any borrowed input or output storage.+ */+typedef int (*cometa_confirmation_callback_t)(+ HsStablePtr state,+ const unsigned char* hash,+ size_t hash_size,+ uint64_t timeout_ms,+ int* confirmed,+ char* error,+ size_t error_size);++/* FUNCTIONS *****************************************************************/++/**+ * \brief Creates a native provider that owns a Haskell confirmation callback registration.+ *+ * The returned provider owns one reference to an implementation context containing both runtime+ * handles. Final context destruction releases the function pointer and stable pointer through HsFFI.+ *+ * \param[in] state Stable pointer to the Haskell callback state. Must not be NULL.+ * \param[in] callback Haskell callback trampoline. Must not be NULL.+ * \param[out] provider Pointer receiving one owned provider reference. Must not be NULL.+ *+ * \returns An unsigned status value: CARDANO_SUCCESS on success, CARDANO_ERROR_POINTER_IS_NULL for a NULL argument, or+ * CARDANO_ERROR_MEMORY_ALLOCATION_FAILED if context or provider allocation fails.+ *+ * \note On success, ownership of both runtime handles transfers to the native context. On failure,+ * neither handle transfers; the caller must release both. When all arguments are non-NULL,+ * the output slot is initialized to NULL before allocation.+ */+unsigned int cometa_provider_new(+ HsStablePtr state,+ cometa_confirmation_callback_t callback,+ cardano_provider_t** provider);++/**+ * \brief Acquires another owned reference to a provider.+ *+ * \param[in] provider Provider whose reference count is incremented. NULL has no effect.+ *+ * \note Native reference counts are not atomic. The Haskell adapter serializes reference-count+ * transitions for every alias of a provider through a shared ownership lock.+ */+void cometa_provider_ref(cardano_provider_t* provider);++/**+ * \brief Consumes one owned provider reference through a unary destructor adapter.+ *+ * This function releases exactly one reference even when another owner keeps the provider alive.+ * The caller must separately invalidate its local handle instead of relying on pointer nullness.+ *+ * \param[in] provider Provider reference to release. NULL has no effect.+ *+ * \note Each operation retains its own provider reference until its native worker has finished.+ * Final context destruction releases runtime handles without invoking user cleanup code.+ */+void cometa_provider_release(cardano_provider_t* provider);++/**+ * \brief Invokes native transaction confirmation without exposing native bool layout to Haskell.+ *+ * This synchronous adapter constructs a native hash, invokes the provider, and releases the hash+ * before returning. The provider and input bytes remain borrowed for the complete call.+ *+ * \param[in] provider Provider created by \ref cometa_provider_new. Must not be NULL.+ * \param[in] hash Transaction identifier bytes. Must not be NULL.+ * \param[in] hash_size Number of bytes available at \p hash. The Haskell adapter validates 32 bytes.+ * \param[in] timeout_ms Confirmation timeout in milliseconds.+ * \param[out] confirmed Pointer receiving 0 or 1. Must not be NULL. Initialized to 0 after argument validation.+ *+ * \returns An unsigned status value: CARDANO_ERROR_POINTER_IS_NULL for a NULL argument, or the status returned by hash+ * construction or native transaction confirmation.+ *+ * \note The caller must retain an operation reference until this call returns, including during+ * callback cancellation. A timeout does not authorize releasing state still used by C.+ */+unsigned int cometa_provider_confirm(+ cardano_provider_t* provider,+ const unsigned char* hash,+ size_t hash_size,+ uint64_t timeout_ms,+ int* confirmed);++/**+ * \brief Borrows the provider's last native failure diagnostic.+ *+ * \param[in] provider Provider whose diagnostic is requested. Must not be NULL and must remain valid until the string is copied.+ *+ * \returns A borrowed, null-terminated string owned by the provider. The caller must not modify or free it.+ *+ * \note Copy the string before releasing its owner or starting another operation that may overwrite it.+ */+const char* cometa_provider_error(const cardano_provider_t* provider);++/**+ * \brief Retrieves a native status diagnostic through the explicit unsigned status ABI.+ *+ * \param[in] code Numeric status converted to the native enum inside this adapter.+ *+ * \returns A borrowed static diagnostic string. The caller must not modify or free it.+ */+const char* cometa_error_message(unsigned int code);++/**+ * \brief Retrieves the process-wide number of live callback contexts.+ *+ * \returns The number of successfully adopted contexts whose final native destruction has not completed.+ *+ * \note This private diagnostic uses a C11 atomic counter so independent providers can run concurrently.+ */+size_t cometa_callback_live_contexts(void);++/**+ * \brief Retrieves the process-wide number of completed native confirmation calls.+ *+ * \returns The number of calls that completed native confirmation dispatch and temporary hash cleanup.+ *+ * \note This private atomic counter provides unwind evidence for tests. Calls rejected for NULL arguments+ * do not increment it; calls whose hash construction fails do increment it.+ */+size_t cometa_callback_completed_calls(void);++#ifdef __cplusplus+}+#endif /* __cplusplus */++#endif // BIGLUP_LABS_INCLUDE_COMETA_PROVIDER_H
@@ -0,0 +1,899 @@+/**+ * \file cometa_provider_runtime.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/+#include "cometa_provider_runtime.h"+#include "cometa_parameters.h"+#include <cardano/cardano.h>+#include <stdlib.h>+#include <string.h>++/* TYPES *********************************************************************/+typedef struct provider_context_t+{+ cardano_object_t base;+ cometa_runtime_t* runtime;+ cardano_buffer_t* parameter_template;+} provider_context_t;++/* STATIC FUNCTIONS **********************************************************/+/** \brief This provider owns its runtime reference and optional parameter availability sidecar. */+static void+destroy_provider_context(void* object)+{+ provider_context_t* context = (provider_context_t*)object;+ cardano_buffer_unref(&context->parameter_template);+ cometa_runtime_release(context->runtime);+ free(context);+}++/** \brief Reject trailing wire bytes before transferring any decoded output. */+static cardano_error_t+complete(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ return result == CARDANO_SUCCESS && remaining != 0U ? CARDANO_ERROR_DECODING : result;+}++/** \brief Copy a native address into a CBOR byte string. */+static cardano_error_t+write_address(cardano_cbor_writer_t* writer, cardano_address_t* address)+{+ size_t size = cardano_address_get_bytes_size(address);+ unsigned char* bytes = malloc(size == 0U ? 1U : size);+ if (bytes == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ cardano_error_t result = cardano_address_to_bytes(address, bytes, size);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bytestring(writer, bytes, size);+ }+ free(bytes);+ return result;+}++/** \brief Decode a borrowed wire address; byte buffer remains scoped until construction copies it. */+static cardano_error_t+read_address(cardano_cbor_reader_t* reader, cardano_address_t** address)+{+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), address);+ }+ cardano_buffer_unref(&bytes);+ return result;+}++/** \brief Empty bytes identify Ada; native assets carry policy bytes followed by name bytes. */+static cardano_error_t+read_asset(cardano_cbor_reader_t* reader, cardano_asset_id_t** asset)+{+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_buffer_get_size(bytes) == 0U ? cardano_asset_id_new_lovelace(asset)+ : cardano_asset_id_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), asset);+ }+ cardano_buffer_unref(&bytes);+ return result;+}++/** \brief Decode one owned digest from a wire byte string. */+static cardano_error_t+read_hash(cardano_cbor_reader_t* reader, cardano_blake2b_hash_t** hash)+{+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), hash);+ }+ cardano_buffer_unref(&bytes);+ return result;+}++/** \brief Serialize every resolved output through its native typed codec. */+static cardano_error_t+write_utxos(cardano_cbor_writer_t* writer, cardano_utxo_list_t* list)+{+ size_t count = cardano_utxo_list_get_length(list);+ cardano_error_t result = cardano_cbor_writer_write_start_array(writer, (int64_t)count);+ for (size_t index = 0U; result == CARDANO_SUCCESS && index < count; ++index)+ {+ cardano_utxo_t* value = NULL;+ result = cardano_utxo_list_get(list, index, &value);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(value, writer);+ }+ cardano_utxo_unref(&value);+ }+ return result;+}++/** \brief Construct an owned resolved-output list, releasing all partial elements on failure. */+static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** list)+{+ *list = NULL;+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(list);+ }+ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ while (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result != CARDANO_SUCCESS || state == CARDANO_CBOR_READER_STATE_END_ARRAY)+ {+ break;+ }+ cardano_utxo_t* value = NULL;+ result = cardano_utxo_from_cbor(reader, &value);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*list, value);+ }+ cardano_utxo_unref(&value);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_list_unref(list);+ *list = NULL;+ }+ return result;+}++/** \brief Encode a request then borrow the returned buffer through its reader lifetime. */+static cardano_error_t+dispatch(cardano_provider_impl_t* impl, uint32_t operation, cardano_cbor_writer_t* writer, cardano_cbor_reader_t** reader, cardano_buffer_t** reply)+{+ *reader = NULL;+ *reply = NULL;+ cardano_buffer_t* request = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_encode_in_buffer(writer, &request);+ if (result == CARDANO_SUCCESS)+ {+ provider_context_t* context = (provider_context_t*)impl->context;+ result = (cardano_error_t)cometa_runtime_dispatch(context->runtime, operation, cardano_buffer_get_data(request), cardano_buffer_get_size(request), reply, impl->error_message, sizeof(impl->error_message));+ }+ if (result == CARDANO_SUCCESS)+ {+ *reader = cardano_cbor_reader_new(cardano_buffer_get_data(*reply), cardano_buffer_get_size(*reply));+ if (*reader == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ }+ cardano_buffer_unref(&request);+ return result;+}++/** \brief Typed native parameters callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_parameters(cardano_provider_impl_t* impl, cardano_protocol_parameters_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 0);+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 0U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cometa_parameters_from_snapshot(cardano_buffer_get_data(reply), cardano_buffer_get_size(reply), output);+ if (result == CARDANO_SUCCESS)+ {+ provider_context_t* context = (provider_context_t*)impl->context;+ cardano_buffer_unref(&context->parameter_template);+ context->parameter_template = reply;+ cardano_buffer_ref(reply);+ }+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_protocol_parameters_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native utxos callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_utxos(cardano_provider_impl_t* impl, cardano_address_t* address, cardano_utxo_list_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : write_address(writer, address);+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 1U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_list_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native rewards callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_rewards(cardano_provider_impl_t* impl, cardano_reward_address_t* address, uint64_t* output)+{+ *output = 0U;+ cardano_address_t* generic = cardano_reward_address_to_address(address);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : write_address(writer, generic);+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 2U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ *output = 0U;+ }+ cardano_address_unref(&generic);+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native asset_utxos callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_asset_utxos(cardano_provider_impl_t* impl, cardano_address_t* address, cardano_asset_id_t* asset, cardano_utxo_list_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = write_address(writer, address);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bytestring(writer, cardano_asset_id_get_bytes(asset), cardano_asset_id_get_bytes_size(asset));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 3U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_list_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native nft callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_nft(cardano_provider_impl_t* impl, cardano_asset_id_t* asset, cardano_utxo_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_bytestring(writer, cardano_asset_id_get_bytes(asset), cardano_asset_id_get_bytes_size(asset));+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 4U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result == CARDANO_SUCCESS && state == CARDANO_CBOR_READER_STATE_NULL)+ {+ result = CARDANO_ERROR_ELEMENT_NOT_FOUND;+ }+ else if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_from_cbor(reader, output);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native resolve callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_resolve(cardano_provider_impl_t* impl, cardano_transaction_input_set_t* inputs, cardano_utxo_list_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_transaction_input_set_to_cbor(inputs, writer);+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 5U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_utxo_list_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native datum callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_datum(cardano_provider_impl_t* impl, cardano_blake2b_hash_t* hash, cardano_plutus_data_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_bytestring(writer, cardano_blake2b_hash_get_data(hash), cardano_blake2b_hash_get_bytes_size(hash));+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 6U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ cardano_cbor_reader_state_t state = CARDANO_CBOR_READER_STATE_UNDEFINED;+ result = cardano_cbor_reader_peek_state(reader, &state);+ if (result == CARDANO_SUCCESS && state == CARDANO_CBOR_READER_STATE_NULL)+ {+ result = CARDANO_ERROR_ELEMENT_NOT_FOUND;+ }+ else if (result == CARDANO_SUCCESS)+ {+ result = cardano_plutus_data_from_cbor(reader, output);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_plutus_data_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native confirm callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_confirm(cardano_provider_impl_t* impl, cardano_blake2b_hash_t* hash, uint64_t timeout, bool* output)+{+ *output = false;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bytestring(writer, cardano_blake2b_hash_get_data(hash), cardano_blake2b_hash_get_bytes_size(hash));+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, timeout);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 7U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_bool(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ *output = false;+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native submit callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_submit(cardano_provider_impl_t* impl, cardano_transaction_t* transaction, cardano_blake2b_hash_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_transaction_to_cbor(transaction, writer);+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 8U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_hash(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_blake2b_hash_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Typed native evaluate callback; temporaries remain operation-owned through decode/transfer. */+static cardano_error_t+callback_evaluate(cardano_provider_impl_t* impl, cardano_transaction_t* transaction, cardano_utxo_list_t* utxos, cardano_redeemer_list_t** output)+{+ *output = NULL;++ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_cbor_writer_write_start_array(writer, 2);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_to_cbor(transaction, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, utxos);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = dispatch(impl, 9U, writer, &reader, &reply);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_from_cbor(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_redeemer_list_unref(output);+ }++ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&reply);+ return result;+}++/* DEFINITIONS ***************************************************************/+static unsigned int+new_provider(cometa_runtime_t* runtime, const unsigned char* name, size_t name_size, uint32_t magic, cardano_provider_t** output, provider_context_t** context_output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ if (runtime == NULL || name == NULL || name_size > 255U || memchr(name, 0, name_size) != NULL)+ {+ return (unsigned int)CARDANO_ERROR_INVALID_ARGUMENT;+ }+ provider_context_t* context = calloc(1U, sizeof(provider_context_t));+ if (context == NULL)+ {+ return (unsigned int)CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ context->base.ref_count = 1U;+ context->base.deallocator = destroy_provider_context;+ context->runtime = runtime;+ cometa_runtime_ref(runtime);+ cardano_provider_impl_t impl = { 0 };+ memcpy(impl.name, name, name_size);+ impl.network_magic = magic;+ impl.context = &context->base;+ impl.get_parameters = callback_parameters;+ impl.get_unspent_outputs = callback_utxos;+ impl.get_rewards_balance = callback_rewards;+ impl.get_unspent_outputs_with_asset = callback_asset_utxos;+ impl.get_unspent_output_by_nft = callback_nft;+ impl.resolve_unspent_outputs = callback_resolve;+ impl.resolve_datum = callback_datum;+ impl.await_transaction_confirmation = callback_confirm;+ impl.post_transaction_to_chain = callback_submit;+ impl.evaluate_transaction = callback_evaluate;+ cardano_error_t result = cardano_provider_new(impl, output);+ if (result == CARDANO_SUCCESS && context_output != NULL)+ {+ *context_output = context;+ }+ if (result != CARDANO_SUCCESS)+ {+ cardano_object_t* object = &context->base;+ cardano_object_unref(&object);+ }+ return (unsigned int)result;+}++unsigned int+cometa_provider_runtime_new(cometa_runtime_t* runtime, const unsigned char* name, size_t name_size, uint32_t magic, cardano_provider_t** output)+{+ return new_provider(runtime, name, name_size, magic, output, NULL);+}++unsigned int+cometa_provider_runtime_call(cometa_runtime_t* runtime, const unsigned char* name, size_t name_size, uint32_t magic, uint32_t operation, const unsigned char* input, size_t size, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ cardano_provider_t* provider = NULL;+ provider_context_t* provider_context = NULL;+ cardano_cbor_reader_t* reader = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_error_t result = (cardano_error_t)new_provider(runtime, name, name_size, magic, &provider, &provider_context);+ cardano_protocol_parameters_t* parameters = NULL;+ cardano_address_t* address = NULL;+ cardano_reward_address_t* reward = NULL;+ cardano_asset_id_t* asset = NULL;+ cardano_utxo_list_t* utxos = NULL;+ cardano_utxo_list_t* additional = NULL;+ cardano_utxo_t* utxo = NULL;+ cardano_transaction_input_set_t* inputs = NULL;+ cardano_blake2b_hash_t* hash = NULL;+ cardano_plutus_data_t* datum = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_redeemer_list_t* redeemers = NULL;+ uint64_t scalar = 0U;+ bool confirmed = false;+ int64_t arity = 0;+ if (result == CARDANO_SUCCESS)+ {+ reader = cardano_cbor_reader_new(input, size);+ writer = cardano_cbor_writer_new();+ if (reader == NULL || writer == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ switch (operation)+ {+ case 0U:+ result = cardano_cbor_reader_read_start_array(reader, &arity);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_get_parameters(provider, ¶meters);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ /* The callback's exact snapshot supplies only availability; actual values are read from native parameters. */+ result = cometa_parameters_to_snapshot(parameters, cardano_buffer_get_data(provider_context->parameter_template), cardano_buffer_get_size(provider_context->parameter_template), output);+ }+ break;+ case 1U:+ case 2U:+ case 3U:+ if (operation == 3U)+ {+ result = cardano_cbor_reader_read_start_array(reader, &arity);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_address(reader, &address);+ }+ if (result == CARDANO_SUCCESS && operation == 1U)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_get_unspent_outputs(provider, address, &utxos);+ }+ }+ if (result == CARDANO_SUCCESS && operation == 2U)+ {+ result = cardano_reward_address_from_address(address, &reward);+ }+ if (result == CARDANO_SUCCESS && operation == 2U)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_get_rewards_available(provider, reward, &scalar);+ }+ }+ if (result == CARDANO_SUCCESS && operation == 3U)+ {+ result = read_asset(reader, &asset);+ }+ if (result == CARDANO_SUCCESS && operation == 3U)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS && operation == 3U)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_get_unspent_outputs_with_asset(provider, address, asset, &utxos);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = operation == 2U ? cardano_cbor_writer_write_uint(writer, scalar) : write_utxos(writer, utxos);+ }+ break;+ case 4U:+ result = read_asset(reader, &asset);+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_get_unspent_output_by_nft(provider, asset, &utxo);+ }+ }+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ result = cardano_cbor_writer_write_null(writer);+ }+ else if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(utxo, writer);+ }+ break;+ case 5U:+ result = cardano_transaction_input_set_from_cbor(reader, &inputs);+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_resolve_unspent_outputs(provider, inputs, &utxos);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = write_utxos(writer, utxos);+ }+ break;+ case 6U:+ result = read_hash(reader, &hash);+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_resolve_datum(provider, hash, &datum);+ }+ }+ if (result == CARDANO_ERROR_ELEMENT_NOT_FOUND)+ {+ result = cardano_cbor_writer_write_null(writer);+ }+ else if (result == CARDANO_SUCCESS)+ {+ result = cardano_plutus_data_to_cbor(datum, writer);+ }+ break;+ case 7U:+ result = cardano_cbor_reader_read_start_array(reader, &arity);+ if (result == CARDANO_SUCCESS)+ {+ result = read_hash(reader, &hash);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &scalar);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_confirm_transaction(provider, hash, scalar, &confirmed);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bool(writer, confirmed);+ }+ break;+ case 8U:+ result = cardano_transaction_from_cbor(reader, &transaction);+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_submit_transaction(provider, transaction, &hash);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_bytestring(writer, cardano_blake2b_hash_get_data(hash), cardano_blake2b_hash_get_bytes_size(hash));+ }+ break;+ case 9U:+ result = cardano_cbor_reader_read_start_array(reader, &arity);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_from_cbor(reader, &transaction);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_utxos(reader, &additional);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_provider_evaluate_transaction(provider, transaction, additional, &redeemers);+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_to_cbor(redeemers, writer);+ }+ break;+ default:+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ break;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+ if (result == CARDANO_SUCCESS && operation != 0U)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ }+ cardano_protocol_parameters_unref(¶meters);+ cardano_address_unref(&address);+ cardano_reward_address_unref(&reward);+ cardano_asset_id_unref(&asset);+ cardano_utxo_list_unref(&utxos);+ cardano_utxo_list_unref(&additional);+ cardano_utxo_unref(&utxo);+ cardano_transaction_input_set_unref(&inputs);+ cardano_blake2b_hash_unref(&hash);+ cardano_plutus_data_unref(&datum);+ cardano_transaction_unref(&transaction);+ cardano_redeemer_list_unref(&redeemers);+ cardano_provider_unref(&provider);+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ if (result != CARDANO_SUCCESS)+ {+ cardano_buffer_unref(output);+ *output = NULL;+ }+ return (unsigned int)result;+}
@@ -0,0 +1,47 @@+/**+ * \file cometa_provider_runtime.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_PROVIDER_RUNTIME_H+#define BIGLUP_LABS_COMETA_PROVIDER_RUNTIME_H+/* INCLUDES ******************************************************************/+#include "cometa_runtime.h"+#include <cardano/providers/provider.h>+/* DECLARATIONS **************************************************************/+/** \brief Construct an owned provider; its context retains runtime until final destruction.+ * \param runtime Borrowed callback runtime, valid through construction.+ * \param name Borrowed UTF8 diagnostic name, without NUL.+ * \param name_size Name byte count, at most255.+ * \param magic Explicit network magic.+ * \param output Owned provider output, initialized NULL.+ * \return Native status; failure releases every partial reference.+ */+unsigned int cometa_provider_runtime_new(cometa_runtime_t* runtime, const unsigned char* name, size_t name_size, uint32_t magic, cardano_provider_t** output);+/** \brief Dispatch through actual native provider methods; inputs borrowed, reply owned on success.+ * \param runtime Borrowed active runtime.+ * \param name Borrowed provider name.+ * \param name_size Name byte length.+ * \param magic Explicit network magic.+ * \param operation Private operation zero through nine.+ * \param input Complete encoded request.+ * \param size Request byte length.+ * \param output Owned reply buffer; initialized NULL and released on failure.+ * \return Native status. All typed temporaries and provider are released before return.+ */+unsigned int cometa_provider_runtime_call(cometa_runtime_t* runtime, const unsigned char* name, size_t name_size, uint32_t magic, uint32_t operation, const unsigned char* input, size_t size, cardano_buffer_t** output);+#endif
@@ -0,0 +1,106 @@+/**+ * \file cometa_reencode.c+ *+ * \author angel.castillo+ * \date Nov 09, 2026+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_reencode.h"++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_reencode(unsigned int kind, const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ if (output == NULL)+ return CARDANO_ERROR_POINTER_IS_NULL;+ *output = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(bytes, size);+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_native_script_t* script = NULL;+ cardano_native_script_list_t* scripts = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_sub_transaction_t* intent = NULL;+ size_t remaining = 0U;+ cardano_error_t result = reader == NULL || writer == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : CARDANO_SUCCESS;+ if (result == CARDANO_SUCCESS)+ {+ switch (kind)+ {+ case 0U:+ result = cardano_native_script_from_cbor(reader, &script);+ break;+ case 1U:+ result = cardano_native_script_list_from_cbor(reader, &scripts);+ break;+ case 2U:+ result = cardano_transaction_from_cbor(reader, &transaction);+ break;+ case 3U:+ result = cardano_sub_transaction_from_cbor(reader, &intent);+ break;+ default:+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ break;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if (result == CARDANO_SUCCESS && remaining != 0U)+ result = CARDANO_ERROR_DECODING;+ }+ if (result == CARDANO_SUCCESS)+ {+ switch (kind)+ {+ case 0U:+ cardano_native_script_clear_cbor_cache(script);+ result = cardano_native_script_to_cbor(script, writer);+ break;+ case 1U:+ cardano_native_script_list_clear_cbor_cache(scripts);+ result = cardano_native_script_list_to_cbor(scripts, writer);+ break;+ case 2U:+ cardano_transaction_clear_cbor_cache(transaction);+ result = cardano_transaction_to_cbor(transaction, writer);+ break;+ case 3U:+ cardano_sub_transaction_clear_cbor_cache(intent);+ result = cardano_sub_transaction_to_cbor(intent, writer);+ break;+ default:+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ break;+ }+ }+ if (result == CARDANO_SUCCESS)+ result = cardano_cbor_writer_encode_in_buffer(writer, output);+ if (result != CARDANO_SUCCESS)+ cardano_buffer_unref(output);+ cardano_native_script_unref(&script);+ cardano_native_script_list_unref(&scripts);+ cardano_transaction_unref(&transaction);+ cardano_sub_transaction_unref(&intent);+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ return (unsigned int)result;+}
@@ -0,0 +1,34 @@+/**+ * \file cometa_reencode.h+ *+ * \author angel.castillo+ * \date Nov 09, 2026+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+#ifndef COMETA_REENCODE_H+#define COMETA_REENCODE_H+#include <cardano/cardano.h>++/** \brief Re-encode one complete native schema with fresh scoped owners.+ * \param kind 0 native script, 1 native-script list, 2 transaction, 3 intent.+ * \param bytes Borrowed input bytes, valid through return.+ * \param size Input byte count.+ * \param output Transferred owned output buffer on success, null on failure.+ * \return Native status; all parsed owners and writers are released.+ */+unsigned int cometa_reencode(unsigned int kind, const unsigned char* bytes, size_t size, cardano_buffer_t** output);+#endif
@@ -0,0 +1,147 @@+/**+ * \file cometa_runtime.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/+#include "cometa_runtime.h"+#include <stdatomic.h>+#include <stdlib.h>++/* TYPES *********************************************************************/+struct cometa_runtime_t+{+ cardano_object_t base;+ HsStablePtr state;+ cometa_runtime_callback_t callback;+};++/* STATIC FUNCTIONS **********************************************************/+static atomic_size_t live_contexts = 0U;++/** \brief Final native owner releases the Haskell registration without user callbacks. */+static void+destroy(void* object)+{+ cometa_runtime_t* context = (cometa_runtime_t*)object;+ hs_free_fun_ptr((HsFunPtr)context->callback);+ hs_free_stable_ptr(context->state);+ atomic_fetch_sub(&live_contexts, 1U);+ free(context);+}++/* DEFINITIONS ***************************************************************/+unsigned int+cometa_runtime_new(HsStablePtr state, cometa_runtime_callback_t callback, cometa_runtime_t** output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ if ((state == NULL) || (callback == NULL))+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ cometa_runtime_t* context = calloc(1U, sizeof(cometa_runtime_t));+ if (context == NULL)+ {+ return (unsigned int)CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ context->base.ref_count = 1U;+ context->base.deallocator = destroy;+ context->state = state;+ context->callback = callback;+ atomic_fetch_add(&live_contexts, 1U);+ *output = context;+ return (unsigned int)CARDANO_SUCCESS;+}++void+cometa_runtime_ref(cometa_runtime_t* context)+{+ if (context != NULL)+ {+ cardano_object_ref(&context->base);+ }+}++void+cometa_runtime_release(cometa_runtime_t* context)+{+ if (context != NULL)+ {+ cardano_object_t* object = &context->base;+ cardano_object_unref(&object);+ }+}++cardano_object_t*+cometa_runtime_object(cometa_runtime_t* context)+{+ return context == NULL ? NULL : &context->base;+}++unsigned int+cometa_runtime_dispatch(cometa_runtime_t* context, uint32_t operation, const unsigned char* request, size_t size, cardano_buffer_t** reply, char* error, size_t capacity)+{+ if (reply == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *reply = NULL;+ if ((context == NULL) || ((request == NULL) && (size != 0U)))+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ return context->callback(context->state, operation, request, size, reply, error, capacity);+}++unsigned int+cometa_runtime_buffer_new(const unsigned char* bytes, size_t size, cardano_buffer_t** output)+{+ if (output == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = cardano_buffer_new_from(bytes, size);+ return (unsigned int)(*output == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : CARDANO_SUCCESS);+}++void+cometa_runtime_buffer_release(cardano_buffer_t** buffer)+{+ cardano_buffer_unref(buffer);+}++const unsigned char*+cometa_runtime_buffer_data(const cardano_buffer_t* buffer)+{+ return cardano_buffer_get_data(buffer);+}++size_t+cometa_runtime_buffer_size(const cardano_buffer_t* buffer)+{+ return cardano_buffer_get_size(buffer);+}++size_t+cometa_runtime_live_contexts(void)+{+ return atomic_load(&live_contexts);+}
@@ -0,0 +1,71 @@+/**+ * \file cometa_runtime.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_RUNTIME_H+#define BIGLUP_LABS_COMETA_RUNTIME_H++/* INCLUDES ******************************************************************/+#include <cardano/buffer.h>+#include <cardano/object.h>+#include <HsFFI.h>+#include <stddef.h>+#include <stdint.h>++/* TYPES *********************************************************************/+typedef struct cometa_runtime_t cometa_runtime_t;++/** \brief Borrow request storage and transfer one owned reply on success; exceptions never cross C.+ * \param state Adopted Haskell stable pointer.+ * \param operation Private family operation identifier.+ * \param request Borrowed request bytes through return.+ * \param size Request byte length.+ * \param reply Initialized-null output; owned by caller on success.+ * \param error Borrowed diagnostic storage.+ * \param capacity Diagnostic byte capacity including terminator.+ * \return Native status. Failure leaves reply null; original Haskell failure is saved separately.+ */+typedef unsigned int (*cometa_runtime_callback_t)(HsStablePtr state, uint32_t operation, const unsigned char* request, size_t size, cardano_buffer_t** reply, char* error, size_t capacity);++/* DECLARATIONS **************************************************************/+/** \brief Success adopts both runtime handles; failure adopts neither and initializes output null.+ * \param state Haskell callback state.+ * \param callback Rooted callback trampoline.+ * \param output Owned context output on success.+ * \return Native status.+ */+unsigned int cometa_runtime_new(HsStablePtr state, cometa_runtime_callback_t callback, cometa_runtime_t** output);+/** \brief Retain one context reference; caller serializes reference transitions. */+void cometa_runtime_ref(cometa_runtime_t* context);+/** \brief Consume one context reference; final destruction releases adopted Haskell handles. */+void cometa_runtime_release(cometa_runtime_t* context);+/** \brief Borrow the native object base for implementation context adoption; retain before transfer. */+cardano_object_t* cometa_runtime_object(cometa_runtime_t* context);+/** \brief Synchronous callback dispatch. Input borrowed; reply transfers to caller on success. */+unsigned int cometa_runtime_dispatch(cometa_runtime_t* context, uint32_t operation, const unsigned char* request, size_t size, cardano_buffer_t** reply, char* error, size_t capacity);+/** \brief Copy borrowed bytes into a newly owned buffer; initialize output null. */+unsigned int cometa_runtime_buffer_new(const unsigned char* bytes, size_t size, cardano_buffer_t** output);+/** \brief Consume and null an owned buffer slot. */+void cometa_runtime_buffer_release(cardano_buffer_t** buffer);+/** \brief Borrow buffer storage until its owner is released. */+const unsigned char* cometa_runtime_buffer_data(const cardano_buffer_t* buffer);+/** \brief Observe buffer size through an explicit size_t ABI. */+size_t cometa_runtime_buffer_size(const cardano_buffer_t* buffer);+/** \brief Test instrumentation: number of contexts still rooting Haskell registrations. */+size_t cometa_runtime_live_contexts(void);+#endif
@@ -0,0 +1,80 @@+/**+ * \file cometa_script.c+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_script.h"++#include <cardano/cbor/cbor_reader.h>+#include <cardano/plutus_data/plutus_list.h>+#include <cardano/uplc/uplc_apply_params.h>+#include <stdio.h>++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_script_apply_params(+ const unsigned char* script,+ size_t script_size,+ const unsigned char* params,+ size_t params_size,+ cardano_buffer_t** output,+ char* error,+ size_t error_size)+{+ *output = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(params, params_size);+ cardano_plutus_list_t* list = NULL;+ cardano_error_t result = CARDANO_SUCCESS;++ if (reader == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ else+ {+ result = cardano_plutus_list_from_cbor(reader, &list);+ if (result == CARDANO_SUCCESS)+ {+ size_t remaining = 0U;+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if ((result == CARDANO_SUCCESS) && (remaining != 0U))+ {+ result = CARDANO_ERROR_DECODING;+ }+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_uplc_apply_params_to_script(list, script, script_size, output);+ }+ }++ if ((result != CARDANO_SUCCESS) && (error != NULL) && (error_size > 0U))+ {+ const char* message = reader == NULL ? "" : cardano_cbor_reader_get_last_error(reader);+ (void)snprintf(error, error_size, "%s", message[0] == '\0' ? cardano_error_to_string(result) : message);+ }++ cardano_plutus_list_unref(&list);+ cardano_cbor_reader_unref(&reader);++ return (unsigned int)result;+}
@@ -0,0 +1,55 @@+/**+ * \file cometa_script.h+ *+ * \author angel.castillo+ * \date Nov 04, 2026+ *+ * Copyright 2026 Biglup Labs+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_SCRIPT_H+#define BIGLUP_LABS_INCLUDE_COMETA_SCRIPT_H++/* INCLUDES ******************************************************************/++#include <cardano/buffer.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Applies marshaled Plutus data parameters using the native UPLC VM.+ *+ * \param[in] script Borrowed nonempty single-CBOR-wrapped Flat program bytes.+ * \param[in] script_size Script byte count.+ * \param[in] params Borrowed CBOR array of Plutus data, valid through return.+ * \param[in] params_size Parameter encoding byte count.+ * \param[out] output Initialized to NULL; owns any resulting buffer reference even on failure.+ * \param[out] error Optional caller-owned diagnostic storage, copied before releasing readers.+ * \param[in] error_size Diagnostic capacity including terminator; zero disables copying.+ *+ * \return A cardano-c status converted to unsigned int. All temporary readers,+ * lists and VM arenas are released synchronously before return. No callbacks run.+ */+unsigned int cometa_script_apply_params(+ const unsigned char* script,+ size_t script_size,+ const unsigned char* params,+ size_t params_size,+ cardano_buffer_t** output,+ char* error,+ size_t error_size);++#endif // BIGLUP_LABS_INCLUDE_COMETA_SCRIPT_H
@@ -0,0 +1,122 @@+/**+ * \file cometa_signing_key.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_signing_key.h"+#include <cardano/crypto/ed25519_public_key.h>+#include <cardano/crypto/ed25519_signature.h>+#include <stdint.h>++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_signing_key_from_normal_bytes(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_ed25519_private_key_from_normal_bytes(data, size, key);+}++unsigned int+cometa_signing_key_from_extended_bytes(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_ed25519_private_key_from_extended_bytes(data, size, key);+}++unsigned int+cometa_signing_key_from_normal_hex(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_ed25519_private_key_from_normal_hex((const char*)data, size, key);+}++unsigned int+cometa_signing_key_from_extended_hex(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key)+{+ *key = NULL;+ return (unsigned int)cardano_ed25519_private_key_from_extended_hex((const char*)data, size, key);+}++unsigned int+cometa_signing_key_clone(const cardano_ed25519_private_key_t* source, cardano_ed25519_private_key_t** copy)+{+ *copy = NULL;+ return (unsigned int)cardano_ed25519_private_key_deep_clone(source, copy);+}++void+cometa_signing_key_unref(cardano_ed25519_private_key_t** key)+{+ cardano_ed25519_private_key_unref(key);+}++const unsigned char*+cometa_signing_key_data(const cardano_ed25519_private_key_t* key)+{+ return cardano_ed25519_private_key_get_data(key);+}++size_t+cometa_signing_key_size(const cardano_ed25519_private_key_t* key)+{+ return cardano_ed25519_private_key_get_bytes_size(key);+}++unsigned int+cometa_signing_key_public_key(const cardano_ed25519_private_key_t* key, unsigned char* output)+{+ cardano_ed25519_public_key_t* public_key = NULL;+ cardano_error_t result = cardano_ed25519_private_key_get_public_key(key, &public_key);++ if (result == CARDANO_SUCCESS)+ {+ result = public_key == NULL ? CARDANO_ERROR_GENERIC : cardano_ed25519_public_key_to_bytes(public_key, output, 32U);+ }++ cardano_ed25519_public_key_unref(&public_key);+ return (unsigned int)result;+}++unsigned int+cometa_signing_key_sign(const cardano_ed25519_private_key_t* key, const unsigned char* message, size_t size, unsigned char* output)+{+ if ((message == NULL) && (size != 0U))+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }++ /* Native extended signing forms buffers of size message_length + 64. */+ if (size > SIZE_MAX - 64U)+ {+ return (unsigned int)CARDANO_ERROR_INTEGER_OVERFLOW;+ }++ static const unsigned char empty_message = 0U;+ cardano_ed25519_signature_t* signature = NULL;+ cardano_error_t result = cardano_ed25519_private_key_sign(key, message == NULL ? &empty_message : message, size, &signature);++ if (result == CARDANO_SUCCESS)+ {+ result = signature == NULL ? CARDANO_ERROR_GENERIC : cardano_ed25519_signature_to_bytes(signature, output, 64U);+ }++ cardano_ed25519_signature_unref(&signature);+ return (unsigned int)result;+}
@@ -0,0 +1,121 @@+/**+ * \file cometa_signing_key.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_SIGNING_KEY_H+#define BIGLUP_LABS_INCLUDE_COMETA_SIGNING_KEY_H++/* INCLUDES ******************************************************************/++#include <cardano/crypto/ed25519_private_key.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++#ifdef __cplusplus+extern "C" {+#endif++/**+ * \brief Import one owned normal seed key from borrowed bytes.+ * \param[in] data Exactly 32 seed bytes, borrowed until return.+ * \param[in] size Byte length of data.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_signing_key_from_normal_bytes(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key);++/**+ * \brief Import one owned extended scalar/IV key from borrowed bytes.+ * \param[in] data Exactly 64 expanded bytes, borrowed until return.+ * \param[in] size Byte length of data.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_signing_key_from_extended_bytes(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key);++/**+ * \brief Import a normal seed key from validated borrowed ASCII hexadecimal.+ * \param[in] data Exactly 64 hex digits, borrowed until return.+ * \param[in] size Digit count, excluding any terminator.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_signing_key_from_normal_hex(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key);++/**+ * \brief Import an extended key from validated borrowed ASCII hexadecimal.+ * \param[in] data Exactly 128 hex digits, borrowed until return.+ * \param[in] size Digit count, excluding any terminator.+ * \param[out] key Initialized to NULL; receives one owned reference on success.+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_signing_key_from_extended_hex(const unsigned char* data, size_t size, cardano_ed25519_private_key_t** key);++/**+ * \brief Deep-copy secret storage into one independent owned key.+ * \param[in] source Live borrowed key, serialized by the Haskell key lock.+ * \param[out] copy Initialized to NULL; receives one owned reference on success.+ * \returns A cardano-c status converted to unsigned int.+ */+unsigned int cometa_signing_key_clone(const cardano_ed25519_private_key_t* source, cardano_ed25519_private_key_t** copy);++/**+ * \brief Consume one key reference; final release wipes native key storage.+ * \param[in,out] key Initialized local owned slot; NULL is tolerated.+ * \note A released alias must not be reused if native unref leaves it non-NULL.+ */+void cometa_signing_key_unref(cardano_ed25519_private_key_t** key);++/**+ * \brief Borrow raw secret storage only while holding the key lock.+ * \param[in] key Live borrowed key.+ * \returns Borrowed secret bytes; never release or mutate them.+ */+const unsigned char* cometa_signing_key_data(const cardano_ed25519_private_key_t* key);++/**+ * \brief Read the secret byte length without exporting secret data.+ * \param[in] key Live borrowed key.+ * \returns The native key length, zero for NULL.+ */+size_t cometa_signing_key_size(const cardano_ed25519_private_key_t* key);++/**+ * \brief Derive public bytes without transferring a native public-key object.+ * \param[in] key Live borrowed key, held under the key lock until return.+ * \param[out] output Caller-owned 32-byte buffer, valid until return.+ * \returns A cardano-c status converted to unsigned int; output is valid only on success.+ */+unsigned int cometa_signing_key_public_key(const cardano_ed25519_private_key_t* key, unsigned char* output);++/**+ * \brief Sign borrowed message bytes; release temporary native signature on every path.+ * \param[in] key Live borrowed key, held under the key lock until return.+ * \param[in] message Message bytes; NULL is permitted only for an empty message.+ * \param[in] size Message byte length.+ * \param[out] output Caller-owned 64-byte buffer, valid until return.+ * \returns A cardano-c status converted to unsigned int; output is valid only on success.+ */+unsigned int cometa_signing_key_sign(const cardano_ed25519_private_key_t* key, const unsigned char* message, size_t size, unsigned char* output);++#ifdef __cplusplus+}+#endif++#endif /* BIGLUP_LABS_INCLUDE_COMETA_SIGNING_KEY_H */
@@ -0,0 +1,568 @@+/**+ * \file cometa_sub_transaction_builder.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_sub_transaction_builder.h"+#include "cometa_parameters.h"+#include <limits.h>+#include <stdlib.h>+#include <string.h>++/* TYPES *********************************************************************/++/* Deferred contexts borrow the grouped runtime. Storage is allocated before+ * registration and freed only after builder destruction; native lists neither+ * retain nor release user_context. Each reply transfers a fresh payload. */+typedef struct+{+ cometa_runtime_t* runtime;+ uint64_t index;+ bool deferred_mint;+ bool deferred_vote;+} deferred_context_t;++/* STATIC FUNCTIONS **********************************************************/++/** \brief Reject trailing bytes in every embedded native object. */+static cardano_error_t+complete(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ return result == CARDANO_SUCCESS && remaining != 0U ? CARDANO_ERROR_DECODING : result;+}++/** \brief Read one complete definite array with the expected arity. */+static cardano_error_t+array(cardano_cbor_reader_t* reader, int64_t expected)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ return result == CARDANO_SUCCESS && count != expected ? CARDANO_ERROR_DECODING : result;+}++/** \brief Decode a byte-string-wrapped native object; empty data means absence+ * only for explicitly optional datum arguments. Each returned object is owned. */+#define READ_OBJECT(NAME, TYPE, FROM) \+ static cardano_error_t NAME(cardano_cbor_reader_t* reader, TYPE** output) \+ { \+ cardano_buffer_t* bytes = NULL; \+ cardano_cbor_reader_t* nested = NULL; \+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes); \+ *output = NULL; \+ if (result == CARDANO_SUCCESS && cardano_buffer_get_size(bytes) != 0U) \+ { \+ nested = cardano_cbor_reader_new(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes)); \+ result = nested == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : FROM(nested, output); \+ if (result == CARDANO_SUCCESS) \+ result = complete(nested); \+ } \+ cardano_cbor_reader_unref(&nested); \+ cardano_buffer_unref(&bytes); \+ return result; \+ }++READ_OBJECT(read_output, cardano_transaction_output_t, cardano_transaction_output_from_cbor)+READ_OBJECT(read_utxo, cardano_utxo_t, cardano_utxo_from_cbor)+READ_OBJECT(read_script, cardano_script_t, cardano_script_from_cbor)+READ_OBJECT(read_data, cardano_plutus_data_t, cardano_plutus_data_from_cbor)+READ_OBJECT(read_certificate, cardano_certificate_t, cardano_certificate_from_cbor)+READ_OBJECT(read_metadata, cardano_metadatum_t, cardano_metadatum_from_cbor)+READ_OBJECT(read_credential, cardano_credential_t, cardano_credential_from_cbor)+READ_OBJECT(read_interval, cardano_account_balance_interval_t, cardano_account_balance_interval_from_cbor)+READ_OBJECT(read_proposal, cardano_proposal_procedure_t, cardano_proposal_procedure_from_cbor)+READ_OBJECT(read_voter, cardano_voter_t, cardano_voter_from_cbor)+READ_OBJECT(read_action_id, cardano_governance_action_id_t, cardano_governance_action_id_from_cbor)+READ_OBJECT(read_procedure, cardano_voting_procedure_t, cardano_voting_procedure_from_cbor)+#undef READ_OBJECT++/** \brief Copy the local fee-zero draft into the protected callback and transfer its argument. */+static cardano_error_t+deferred_callback(void* opaque, cardano_transaction_t* transaction, cardano_utxo_list_t* inputs, cardano_plutus_data_t** output)+{+ deferred_context_t* context = (deferred_context_t*)opaque;+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* request = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ *output = NULL;+ if (writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_cbor_writer_write_start_array(writer, 3);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, context->index);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_to_cbor(transaction, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_start_array(writer, (int64_t)cardano_utxo_list_get_length(inputs));+ }+ for (size_t i = 0; result == CARDANO_SUCCESS && i < cardano_utxo_list_get_length(inputs); ++i)+ {+ cardano_utxo_t* input = NULL;+ result = cardano_utxo_list_get(inputs, i, &input);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(input, writer);+ }+ cardano_utxo_unref(&input);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, &request);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_runtime_dispatch(context->runtime, 110, cardano_buffer_get_data(request), cardano_buffer_get_size(request), &reply, NULL, 0);+ }+ if (result == CARDANO_SUCCESS && reply == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (result == CARDANO_SUCCESS)+ {+ reader = cardano_cbor_reader_new(cardano_buffer_get_data(reply), cardano_buffer_get_size(reply));+ result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_plutus_data_from_cbor(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ cardano_plutus_data_unref(output);+ }+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&request);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Apply one instruction, releasing local references after builder retention. */+static cardano_error_t+instruction(cardano_sub_tx_builder_t* builder, cardano_cbor_reader_t* reader, cardano_utxo_list_t* resolved, deferred_context_t* contexts, size_t position)+{+ deferred_context_t* context = &contexts[position];+ static const int64_t arities[] = { 2, 4, 2, 2, 5, 3, 2, 3, 4, 2, 2, 2, 4, 5, 3, 4, 3, 0, 3, 3, 3, 2, 3, 5, 5, 3, 3, 0, 3 };+ int64_t count = 0;+ uint64_t tag = 0U, number = 0U;+ int64_t signed_number = 0;+ cardano_transaction_output_t* output = NULL;+ cardano_utxo_t* utxo = NULL;+ cardano_script_t* script = NULL;+ cardano_plutus_data_t* redeemer = NULL;+ cardano_plutus_data_t* datum = NULL;+ cardano_certificate_t* certificate = NULL;+ cardano_metadatum_t* metadata = NULL;+ cardano_blake2b_hash_t* hash = NULL;+ cardano_asset_name_t* asset_name = NULL;+ cardano_reward_address_t* reward = NULL;+ cardano_credential_t* credential = NULL;+ cardano_account_balance_interval_t* interval = NULL;+ cardano_proposal_procedure_t* proposal = NULL;+ cardano_voter_t* voter = NULL;+ cardano_governance_action_id_t* action_id = NULL;+ cardano_voting_procedure_t* procedure = NULL;+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &tag);+ }+ if (result == CARDANO_SUCCESS && (tag >= sizeof(arities) / sizeof(arities[0]) || tag == 17 || tag == 20 || tag == 25 || count != arities[tag]))+ {+ result = CARDANO_ERROR_DECODING;+ }+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+#define TRY(CALL) \+ do \+ { \+ result = (CALL); \+ if (result != CARDANO_SUCCESS) \+ { \+ goto cleanup; \+ } \+ } \+ while (0)+ switch (tag)+ {+ case 0:+ TRY(read_output(reader, &output));+ cardano_sub_tx_builder_add_output(builder, output);+ break;+ case 12:+ case 1:+ TRY(read_utxo(reader, &utxo));+ if (tag == 12)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ }+ TRY(read_data(reader, &datum));+ TRY(cardano_utxo_list_add(resolved, utxo));+ if (tag == 12)+ {+ cardano_sub_tx_builder_add_input_with_deferred_redeemer(builder, utxo, deferred_callback, context, datum);+ }+ else+ {+ cardano_sub_tx_builder_add_input(builder, utxo, redeemer, datum);+ }+ break;+ case 2:+ TRY(read_utxo(reader, &utxo));+ TRY(cardano_utxo_list_add(resolved, utxo));+ cardano_sub_tx_builder_add_reference_input(builder, utxo);+ break;+ case 3:+ TRY(read_script(reader, &script));+ cardano_sub_tx_builder_add_script(builder, script);+ break;+ case 13:+ case 4:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));+ cardano_buffer_unref(&bytes);+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_asset_name_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &asset_name));+ TRY(cardano_cbor_reader_read_int(reader, &signed_number));+ if (tag == 13)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ bool registered = false;+ for (size_t i = 0; i < position; ++i)+ {+ if (contexts[i].deferred_mint && contexts[i].index == context->index)+ {+ registered = true;+ }+ }+ context->deferred_mint = true;+ if (registered)+ {+ cardano_sub_tx_builder_mint_token(builder, hash, asset_name, signed_number, NULL);+ }+ else+ {+ cardano_sub_tx_builder_mint_token_with_deferred_redeemer(builder, hash, asset_name, signed_number, deferred_callback, context);+ }+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_sub_tx_builder_mint_token(builder, hash, asset_name, signed_number, redeemer);+ }+ break;+ case 5:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ TRY(read_metadata(reader, &metadata));+ cardano_sub_tx_builder_set_metadata(builder, number, metadata);+ break;+ case 6:+ TRY(read_data(reader, &datum));+ cardano_sub_tx_builder_add_datum(builder, datum);+ break;+ case 14:+ case 7:+ TRY(read_certificate(reader, &certificate));+ if (tag == 14)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_sub_tx_builder_add_certificate_with_deferred_redeemer(builder, certificate, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_sub_tx_builder_add_certificate(builder, certificate, redeemer);+ }+ break;+ case 15:+ case 8:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ if (number > INT64_MAX)+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ if (tag == 15)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_sub_tx_builder_withdraw_rewards_with_deferred_redeemer(builder, reward, (int64_t)number, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_sub_tx_builder_withdraw_rewards(builder, reward, (int64_t)number, redeemer);+ }+ break;+ case 9:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));+ cardano_sub_tx_builder_add_signer(builder, hash);+ break;+ case 10:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_sub_tx_builder_set_invalid_before(builder, number);+ break;+ case 11:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_sub_tx_builder_set_invalid_after(builder, number);+ break;+ case 16:+ TRY(read_credential(reader, &credential));+ TRY(read_data(reader, &redeemer));+ if (redeemer == NULL)+ {+ cardano_sub_tx_builder_add_guard(builder, credential);+ }+ else+ {+ cardano_sub_tx_builder_add_guard_with_redeemer(builder, credential, redeemer);+ }+ break;+ case 18:+ case 19:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));+ if (tag == 18)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_sub_tx_builder_add_direct_deposit(builder, reward, number);+ }+ else+ {+ TRY(read_interval(reader, &interval));+ cardano_sub_tx_builder_add_account_balance_interval(builder, reward, interval);+ }+ break;+ case 21:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_sub_tx_builder_set_donation(builder, number);+ break;+ case 22:+ case 28:+ TRY(read_proposal(reader, &proposal));+ if (tag == 28U)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_sub_tx_builder_add_proposal_with_deferred_redeemer(builder, proposal, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_sub_tx_builder_add_proposal(builder, proposal, redeemer);+ }+ break;+ case 23:+ case 24:+ TRY(read_voter(reader, &voter));+ TRY(read_action_id(reader, &action_id));+ TRY(read_procedure(reader, &procedure));+ if (tag == 24)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ bool registered = false;+ for (size_t i = 0; i < position; ++i)+ {+ if (contexts[i].deferred_vote && contexts[i].index == context->index)+ {+ registered = true;+ }+ }+ context->deferred_vote = true;+ if (registered)+ {+ cardano_sub_tx_builder_vote(builder, voter, action_id, procedure, NULL);+ }+ else+ {+ cardano_sub_tx_builder_vote_with_deferred_redeemer(builder, voter, action_id, procedure, deferred_callback, context);+ }+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_sub_tx_builder_vote(builder, voter, action_id, procedure, redeemer);+ }+ break;+ case 26:+ TRY(read_credential(reader, &credential));+ TRY(read_data(reader, &datum));+ cardano_sub_tx_builder_require_top_level_guard(builder, credential, datum);+ break;+ default:+ result = CARDANO_ERROR_DECODING;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+cleanup:+ cardano_credential_unref(&credential);+ cardano_account_balance_interval_unref(&interval);+ cardano_proposal_procedure_unref(&proposal);+ cardano_voter_unref(&voter);+ cardano_governance_action_id_unref(&action_id);+ cardano_voting_procedure_unref(&procedure);+ cardano_transaction_output_unref(&output);+ cardano_utxo_unref(&utxo);+ cardano_script_unref(&script);+ cardano_plutus_data_unref(&redeemer);+ cardano_plutus_data_unref(&datum);+ cardano_certificate_unref(&certificate);+ cardano_metadatum_unref(&metadata);+ cardano_blake2b_hash_unref(&hash);+ cardano_asset_name_unref(&asset_name);+ cardano_reward_address_unref(&reward);+ cardano_buffer_unref(&bytes);+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_sub_transaction_builder_build(cometa_runtime_t* deferred_runtime, const unsigned char* config, size_t config_size, const unsigned char* plan, size_t plan_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic)+{+ if (output != NULL)+ {+ *output = NULL;+ }+ if (diagnostic != NULL)+ {+ *diagnostic = NULL;+ }+ if (deferred_runtime == NULL || config == NULL || plan == NULL || output == NULL || diagnostic == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(config, config_size);+ cardano_cbor_reader_t* instructions = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_buffer_t* parameter_bytes = NULL;+ cardano_protocol_parameters_t* parameters = NULL;+ cardano_utxo_list_t* resolved = NULL;+ cardano_sub_tx_builder_t* builder = NULL;+ cardano_sub_transaction_t* transaction = NULL;+ deferred_context_t* contexts = NULL;+ cardano_slot_config_t slots = { 0 };+ uint64_t network = 0U;+ int64_t count = 0;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : array(reader, 5);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ TRY(cardano_cbor_reader_read_bytestring(reader, ¶meter_bytes));+ TRY(cometa_parameters_from_snapshot(cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), ¶meters));+ TRY(cardano_cbor_reader_read_uint(reader, &network));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_time));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_slot));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.slot_length));+ TRY(cardano_cbor_reader_read_end_array(reader));+ TRY(complete(reader));+ if (slots.slot_length == 0U || network > 1U)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ goto cleanup;+ }+ builder = cardano_sub_tx_builder_new(parameters, &slots);+ if (builder == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ cardano_sub_tx_builder_set_network_id(builder, (cardano_network_id_t)network);+ TRY(cardano_utxo_list_new(&resolved));+ instructions = cardano_cbor_reader_new(plan, plan_size);+ if (instructions == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_cbor_reader_read_start_array(instructions, &count));+ if (count < 0 || (uint64_t)count > SIZE_MAX / sizeof(deferred_context_t))+ {+ result = CARDANO_ERROR_DECODING;+ goto cleanup;+ }+ contexts = calloc(count == 0 ? 1U : (size_t)count, sizeof(deferred_context_t));+ if (contexts == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ for (int64_t i = 0; i < count; ++i)+ {+ contexts[i].runtime = deferred_runtime;+ TRY(instruction(builder, instructions, resolved, contexts, (size_t)i));+ }+ TRY(cardano_cbor_reader_read_end_array(instructions));+ TRY(complete(instructions));+ TRY(cardano_sub_tx_builder_build(builder, &transaction));+ writer = cardano_cbor_writer_new();+ if (writer == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_sub_transaction_to_cbor(transaction, writer));+ TRY(cardano_cbor_writer_encode_in_buffer(writer, output));+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ const char* message = builder != NULL ? cardano_sub_tx_builder_get_last_error(builder) : cardano_error_to_string(result);+ if (message == NULL || message[0] == '\0')+ {+ message = cardano_error_to_string(result);+ }+ *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));+ cardano_buffer_unref(output);+ *output = NULL;+ }+ cardano_cbor_writer_unref(&writer);+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_reader_unref(&instructions);+ cardano_utxo_list_unref(&resolved);+ cardano_sub_tx_builder_unref(&builder);+ free(contexts);+ cardano_sub_transaction_unref(&transaction);+ cardano_protocol_parameters_unref(¶meters);+ cardano_buffer_unref(¶meter_bytes);+ return result;+}++#undef TRY
@@ -0,0 +1,45 @@+/**+ * \file cometa_sub_transaction_builder.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_COMETA_SUB_TRANSACTION_BUILDER_H+#define BIGLUP_LABS_COMETA_SUB_TRANSACTION_BUILDER_H++/* INCLUDES ******************************************************************/++#include "cometa_runtime.h"+#include <cardano/cardano.h>+#include <stddef.h>++/* DECLARATIONS **************************************************************/++/**+ * \brief Build a sub-transaction with operation-scoped deferred callbacks.+ * \param[in] deferred Borrowed active runtime, rooted through builder destruction.+ * \param[in] config Borrowed parameter, network and slot configuration snapshot.+ * \param[in] config_size Configuration byte count.+ * \param[in] plan Borrowed validated sub-transaction instruction snapshot.+ * \param[in] plan_size Instruction snapshot byte count.+ * \param[out] output Owned complete sub-transaction CBOR on success; NULL on failure.+ * \param[out] diagnostic Owned copied native diagnostic on failure when allocated.+ * \return Native status. All builders, retained children and callback contexts+ * are destroyed before returning; caller keeps the runtime gate active until then.+ */+unsigned int cometa_sub_transaction_builder_build(cometa_runtime_t* deferred, const unsigned char* config, size_t config_size, const unsigned char* plan, size_t plan_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic);++#endif
@@ -0,0 +1,297 @@+/**+ * \file cometa_transaction.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_transaction.h"+#include <cardano/buffer.h>+#include <cardano/cbor/cbor_reader.h>+#include <cardano/cbor/cbor_writer.h>+#include <cardano/transaction/transaction.h>+#include <stdlib.h>++/* TYPES *********************************************************************/++struct cometa_transaction_snapshot_t+{+ cardano_buffer_t* full;+ cardano_buffer_t* body;+ cardano_buffer_t* witnesses;+ cardano_blake2b_hash_t* hash;+ uint64_t fee;+};++/* STATIC FUNCTIONS **********************************************************/++/** \brief Decode a complete frame; no reader or partial transaction escapes failure. */+static cardano_error_t+decode_transaction(const unsigned char* data, size_t size, cardano_transaction_t** transaction)+{+ *transaction = NULL;++ if ((data == NULL) || (size == 0U))+ {+ return CARDANO_ERROR_DECODING;+ }++ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(data, size);+ if (reader == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = cardano_transaction_from_cbor(reader, transaction);+ size_t remaining = 0U;+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ if ((result == CARDANO_SUCCESS) && ((*transaction == NULL) || (remaining != 0U)))+ {+ result = CARDANO_ERROR_DECODING;+ }+ }++ cardano_cbor_reader_unref(&reader);+ if (result != CARDANO_SUCCESS)+ {+ cardano_transaction_unref(transaction);+ *transaction = NULL;+ }++ return result;+}++/** \brief Extract original body/witness spans from an already validated frame. */+static cardano_error_t+snapshot_parts(const unsigned char* data, size_t size, cometa_transaction_snapshot_t* snapshot)+{+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(data, size);+ if (reader == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ int64_t frame_size = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &frame_size);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_encoded_value(reader, &snapshot->body);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_encoded_value(reader, &snapshot->witnesses);+ }++ cardano_cbor_reader_unref(&reader);+ return result;+}++/** \brief Snapshot owned buffers/hash, releasing the complete partial result on failure. */+static cardano_error_t+snapshot_transaction(cardano_transaction_t* transaction, const unsigned char* data, size_t size, cometa_transaction_snapshot_t** output)+{+ cometa_transaction_snapshot_t* snapshot = calloc(1U, sizeof(cometa_transaction_snapshot_t));+ if (snapshot == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ snapshot->full = cardano_buffer_new_from(data, size);+ cardano_error_t result = snapshot->full == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : snapshot_parts(data, size, snapshot);+ if (result == CARDANO_SUCCESS)+ {+ snapshot->hash = cardano_transaction_get_id(transaction);+ cardano_transaction_body_t* body = cardano_transaction_get_body(transaction);+ if ((snapshot->hash == NULL) || (body == NULL))+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ else+ {+ snapshot->fee = cardano_transaction_body_get_fee(body);+ }+ cardano_transaction_body_unref(&body);+ }+ if (result != CARDANO_SUCCESS)+ {+ cometa_transaction_snapshot_free(&snapshot);+ return result;+ }++ *output = snapshot;+ return CARDANO_SUCCESS;+}++/** \brief Modify an independent native clone; leave source caches and witnesses untouched. */+static cardano_error_t+edit_fee(cardano_transaction_t* source, uint64_t fee, cardano_transaction_t** copy)+{+ cardano_error_t result = cardano_transaction_deep_clone(source, copy);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }++ cardano_transaction_body_t* body = cardano_transaction_get_body(*copy);+ cardano_witness_set_t* witnesses = cardano_transaction_get_witness_set(*copy);+ if ((body == NULL) || (witnesses == NULL))+ {+ result = CARDANO_ERROR_DECODING;+ }+ else+ {+ result = cardano_transaction_body_set_fee(body, fee);+ cardano_transaction_body_clear_cbor_cache(body);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_set_vkeys(witnesses, NULL);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_set_bootstrap(witnesses, NULL);+ }+ }++ cardano_witness_set_unref(&witnesses);+ cardano_transaction_body_unref(&body);+ return result;+}++/** \brief Materialize a transaction into one owned native byte buffer. */+static cardano_error_t+encode_transaction(cardano_transaction_t* transaction, cardano_buffer_t** encoded)+{+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ if (writer == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }++ cardano_error_t result = cardano_transaction_to_cbor(transaction, writer);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, encoded);+ }++ cardano_cbor_writer_unref(&writer);+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_transaction_decode(const unsigned char* data, size_t size, cometa_transaction_snapshot_t** snapshot)+{+ if (snapshot == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }++ *snapshot = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_error_t result = decode_transaction(data, size, &transaction);+ if (result == CARDANO_SUCCESS)+ {+ result = snapshot_transaction(transaction, data, size, snapshot);+ }++ cardano_transaction_unref(&transaction);+ return (unsigned int)result;+}++unsigned int+cometa_transaction_set_fee(const unsigned char* data, size_t size, uint64_t fee, cometa_transaction_snapshot_t** snapshot)+{+ if (snapshot == NULL)+ {+ return (unsigned int)CARDANO_ERROR_POINTER_IS_NULL;+ }++ *snapshot = NULL;+ cardano_transaction_t* source = NULL;+ cardano_transaction_t* copy = NULL;+ cardano_buffer_t* encoded = NULL;+ cardano_error_t result = decode_transaction(data, size, &source);+ if (result == CARDANO_SUCCESS)+ {+ result = edit_fee(source, fee, ©);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = encode_transaction(copy, &encoded);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = snapshot_transaction(copy, cardano_buffer_get_data(encoded), cardano_buffer_get_size(encoded), snapshot);+ }++ cardano_buffer_unref(&encoded);+ cardano_transaction_unref(©);+ cardano_transaction_unref(&source);+ return (unsigned int)result;+}++void+cometa_transaction_snapshot_free(cometa_transaction_snapshot_t** snapshot)+{+ if ((snapshot == NULL) || (*snapshot == NULL))+ {+ return;+ }++ cardano_buffer_unref(&(*snapshot)->full);+ cardano_buffer_unref(&(*snapshot)->body);+ cardano_buffer_unref(&(*snapshot)->witnesses);+ cardano_blake2b_hash_unref(&(*snapshot)->hash);+ free(*snapshot);+ *snapshot = NULL;+}++const unsigned char*+cometa_transaction_snapshot_bytes(const cometa_transaction_snapshot_t* snapshot, unsigned int field, size_t* size)+{+ if (size == NULL)+ {+ return NULL;+ }++ *size = 0U;+ if (snapshot == NULL)+ {+ return NULL;+ }++ if (field == 2U)+ {+ *size = cardano_blake2b_hash_get_bytes_size(snapshot->hash);+ return cardano_blake2b_hash_get_data(snapshot->hash);+ }++ const cardano_buffer_t* buffer = field == 0U ? snapshot->full : field == 1U ? snapshot->body+ : field == 3U ? snapshot->witnesses+ : NULL;+ *size = cardano_buffer_get_size(buffer);+ return cardano_buffer_get_data(buffer);+}++uint64_t+cometa_transaction_snapshot_fee(const cometa_transaction_snapshot_t* snapshot)+{+ return snapshot == NULL ? 0U : snapshot->fee;+}
@@ -0,0 +1,80 @@+/**+ * \file cometa_transaction.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef BIGLUP_LABS_INCLUDE_COMETA_TRANSACTION_H+#define BIGLUP_LABS_INCLUDE_COMETA_TRANSACTION_H++/* INCLUDES ******************************************************************/++#include <stddef.h>+#include <stdint.h>++/* TYPES *********************************************************************/++/** \brief Owned immutable byte snapshots; contains no Haskell handles. */+typedef struct cometa_transaction_snapshot_t cometa_transaction_snapshot_t;++/* FUNCTIONS *****************************************************************/++/**+ * \brief Validate one complete transaction and snapshot its original encoding.+ * \param[in] data Borrowed complete transaction CBOR, valid until return.+ * \param[in] size Input length in bytes.+ * \param[out] snapshot One owned result on success; NULL on failure.+ * \returns A cardano-c status through an explicit unsigned ABI.+ * \note Rejects trailing bytes. Original full/body/witness encodings are copied.+ */+unsigned int cometa_transaction_decode(const unsigned char* data, size_t size, cometa_transaction_snapshot_t** snapshot);++/**+ * \brief Deep-clone a decoded transaction, change its fee and strip signatures.+ * \param[in] data Borrowed complete transaction CBOR, valid until return.+ * \param[in] size Input length in bytes.+ * \param[in] fee New fee in lovelace.+ * \param[out] snapshot One owned result on success; NULL on failure.+ * \returns A cardano-c status through an explicit unsigned ABI.+ * \note Clears only the body's encoding cache and outer vkey/bootstrap witnesses.+ * Scripts, datums, redeemers and auxiliary data remain on the independent clone.+ * Callers implement same-fee no-op preservation before invoking this function.+ */+unsigned int cometa_transaction_set_fee(const unsigned char* data, size_t size, uint64_t fee, cometa_transaction_snapshot_t** snapshot);++/**+ * \brief Destroy one snapshot and clear its slot. NULL slots are tolerated.+ * \param[in,out] snapshot The local ownership obligation to consume.+ */+void cometa_transaction_snapshot_free(cometa_transaction_snapshot_t** snapshot);++/**+ * \brief Borrow a snapshot byte span until its owner is destroyed.+ * \param[in] snapshot Live immutable snapshot.+ * \param[in] field Private adapter ABI: 0 full CBOR, 1 body CBOR, 2 body hash, 3 witness CBOR.+ * \param[out] size Number of bytes; zero for an invalid field or snapshot.+ * \returns Borrowed bytes, or NULL for an invalid field or snapshot. Never free.+ */+const unsigned char* cometa_transaction_snapshot_bytes(const cometa_transaction_snapshot_t* snapshot, unsigned int field, size_t* size);++/**+ * \brief Read the snapshotted fee in lovelace.+ * \param[in] snapshot Live immutable snapshot; NULL yields zero.+ * \returns Exact unsigned 64-bit fee.+ */+uint64_t cometa_transaction_snapshot_fee(const cometa_transaction_snapshot_t* snapshot);++#endif /* BIGLUP_LABS_INCLUDE_COMETA_TRANSACTION_H */
@@ -0,0 +1,1102 @@+/**+ * \file cometa_transaction_builder.c+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/* INCLUDES ******************************************************************/++#include "cometa_transaction_builder.h"+#include "cometa_coin_selection.h"+#include "cometa_evaluation.h"+#include "cometa_parameters.h"+#include <limits.h>+#include <stdlib.h>+#include <string.h>++/* TYPES *********************************************************************/++/* Deferred contexts borrow the grouped runtime. Storage is allocated before+ * registration and freed only after builder destruction; native lists neither+ * retain nor release user_context. Each reply transfers a fresh payload. */+typedef struct+{+ cometa_runtime_t* runtime;+ uint64_t index;+ bool deferred_mint;+ bool deferred_vote;+} deferred_context_t;++/* STATIC FUNCTIONS **********************************************************/++/** \brief Reject trailing bytes in every embedded native object. */+static cardano_error_t+complete(cardano_cbor_reader_t* reader)+{+ size_t remaining = 0U;+ cardano_error_t result = cardano_cbor_reader_get_bytes_remaining(reader, &remaining);+ return result == CARDANO_SUCCESS && remaining != 0U ? CARDANO_ERROR_DECODING : result;+}++/** \brief Read one complete definite array with the expected arity. */+static cardano_error_t+array(cardano_cbor_reader_t* reader, int64_t expected)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ return result == CARDANO_SUCCESS && count != expected ? CARDANO_ERROR_DECODING : result;+}++/** \brief Decode a byte-string-wrapped native object; empty data means absence+ * only for explicitly optional datum arguments. Each returned object is owned. */+#define READ_OBJECT(NAME, TYPE, FROM) \+ static cardano_error_t NAME(cardano_cbor_reader_t* reader, TYPE** output) \+ { \+ cardano_buffer_t* bytes = NULL; \+ cardano_cbor_reader_t* nested = NULL; \+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes); \+ *output = NULL; \+ if (result == CARDANO_SUCCESS && cardano_buffer_get_size(bytes) != 0U) \+ { \+ nested = cardano_cbor_reader_new(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes)); \+ result = nested == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : FROM(nested, output); \+ if (result == CARDANO_SUCCESS) \+ result = complete(nested); \+ } \+ cardano_cbor_reader_unref(&nested); \+ cardano_buffer_unref(&bytes); \+ return result; \+ }++/**+ * \brief Decode the array framing used by Haskell-owned pool values.+ * \param reader Borrowed reader positioned at the parameter array.+ * \param output Receives an owned reference, including on trailing-framing failure.+ * \return Decoding status.+ */+static cardano_error_t+pool_parameters_from_array(cardano_cbor_reader_t* reader, cardano_pool_params_t** output)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ if (count != 9 && count != 10)+ {+ return CARDANO_ERROR_DECODING;+ }+ result = cardano_pool_params_from_cbor(reader, output);+ return result == CARDANO_SUCCESS ? cardano_cbor_reader_read_end_array(reader) : result;+}++READ_OBJECT(read_pool_parameters, cardano_pool_params_t, pool_parameters_from_array)+READ_OBJECT(read_balance_input, cardano_transaction_input_t, cardano_transaction_input_from_cbor)+READ_OBJECT(read_balance_transaction, cardano_transaction_t, cardano_transaction_from_cbor)+READ_OBJECT(read_output, cardano_transaction_output_t, cardano_transaction_output_from_cbor)+READ_OBJECT(read_utxo, cardano_utxo_t, cardano_utxo_from_cbor)+READ_OBJECT(read_script, cardano_script_t, cardano_script_from_cbor)+READ_OBJECT(read_data, cardano_plutus_data_t, cardano_plutus_data_from_cbor)+READ_OBJECT(read_certificate, cardano_certificate_t, cardano_certificate_from_cbor)+READ_OBJECT(read_metadata, cardano_metadatum_t, cardano_metadatum_from_cbor)+READ_OBJECT(read_credential, cardano_credential_t, cardano_credential_from_cbor)+READ_OBJECT(read_interval, cardano_account_balance_interval_t, cardano_account_balance_interval_from_cbor)+READ_OBJECT(read_proposal, cardano_proposal_procedure_t, cardano_proposal_procedure_from_cbor)+READ_OBJECT(read_voter, cardano_voter_t, cardano_voter_from_cbor)+READ_OBJECT(read_action_id, cardano_governance_action_id_t, cardano_governance_action_id_from_cbor)+READ_OBJECT(read_procedure, cardano_voting_procedure_t, cardano_voting_procedure_from_cbor)+READ_OBJECT(read_sub, cardano_sub_transaction_t, cardano_sub_transaction_from_cbor)+#undef READ_OBJECT++/** \brief Address factories copy their byte-string input before buffer release. */+static cardano_error_t+read_address(cardano_cbor_reader_t* reader, cardano_address_t** output)+{+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_bytestring(reader, &bytes);+ if (result == CARDANO_SUCCESS && cardano_buffer_get_size(bytes) != 0U)+ {+ result = cardano_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), output);+ }+ cardano_buffer_unref(&bytes);+ return result;+}++/** \brief Materialize a list; list insertion retains each locally released item. */+static cardano_error_t+read_utxos(cardano_cbor_reader_t* reader, cardano_utxo_list_t** output)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS && count < 0)+ {+ result = CARDANO_ERROR_DECODING;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_new(output);+ }+ for (int64_t i = 0; result == CARDANO_SUCCESS && i < count; ++i)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_from_cbor(reader, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(*output, item);+ }+ cardano_utxo_unref(&item);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ return result;+}++/** \brief Copy a balanced draft into the protected callback and transfer its argument. */+static cardano_error_t+deferred_callback(void* opaque, cardano_transaction_t* transaction, cardano_utxo_list_t* inputs, cardano_plutus_data_t** output)+{+ deferred_context_t* context = (deferred_context_t*)opaque;+ cardano_cbor_writer_t* writer = cardano_cbor_writer_new();+ cardano_cbor_reader_t* reader = NULL;+ cardano_buffer_t* request = NULL;+ cardano_buffer_t* reply = NULL;+ cardano_error_t result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ *output = NULL;+ if (writer == NULL)+ {+ goto cleanup;+ }+ result = cardano_cbor_writer_write_start_array(writer, 3);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_uint(writer, context->index);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_transaction_to_cbor(transaction, writer);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_write_start_array(writer, (int64_t)cardano_utxo_list_get_length(inputs));+ }+ for (size_t i = 0; result == CARDANO_SUCCESS && i < cardano_utxo_list_get_length(inputs); ++i)+ {+ cardano_utxo_t* input = NULL;+ result = cardano_utxo_list_get(inputs, i, &input);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_to_cbor(input, writer);+ }+ cardano_utxo_unref(&input);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_writer_encode_in_buffer(writer, &request);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = (cardano_error_t)cometa_runtime_dispatch(context->runtime, 110, cardano_buffer_get_data(request), cardano_buffer_get_size(request), &reply, NULL, 0);+ }+ if (result == CARDANO_SUCCESS && reply == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ }+ if (result == CARDANO_SUCCESS)+ {+ reader = cardano_cbor_reader_new(cardano_buffer_get_data(reply), cardano_buffer_get_size(reply));+ result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : cardano_plutus_data_from_cbor(reader, output);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = complete(reader);+ }+cleanup:+ if (result != CARDANO_SUCCESS)+ {+ cardano_plutus_data_unref(output);+ }+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(&request);+ cardano_buffer_unref(&reply);+ return result;+}++/** \brief Apply one instruction, releasing local references after builder retention. */+static cardano_error_t+instruction(cardano_tx_builder_t* builder, cardano_cbor_reader_t* reader, cardano_utxo_list_t* resolved, deferred_context_t* contexts, size_t position)+{+ deferred_context_t* context = &contexts[position];+ static const int64_t arities[] = { 2, 4, 2, 2, 5, 3, 2, 3, 4, 2, 2, 2, 4, 5, 3, 4, 3, 0, 3, 3, 3, 2, 3, 5, 5, 3, 0, 2, 3 };+ int64_t count = 0;+ uint64_t tag = 0U, number = 0U;+ int64_t signed_number = 0;+ cardano_transaction_output_t* output = NULL;+ cardano_utxo_t* utxo = NULL;+ cardano_script_t* script = NULL;+ cardano_plutus_data_t* redeemer = NULL;+ cardano_plutus_data_t* datum = NULL;+ cardano_certificate_t* certificate = NULL;+ cardano_metadatum_t* metadata = NULL;+ cardano_blake2b_hash_t* hash = NULL;+ cardano_asset_name_t* asset_name = NULL;+ cardano_reward_address_t* reward = NULL;+ cardano_credential_t* credential = NULL;+ cardano_account_balance_interval_t* interval = NULL;+ cardano_proposal_procedure_t* proposal = NULL;+ cardano_voter_t* voter = NULL;+ cardano_governance_action_id_t* action_id = NULL;+ cardano_voting_procedure_t* procedure = NULL;+ cardano_sub_transaction_t* sub = NULL;+ cardano_utxo_list_t* sub_resolved = NULL;+ cardano_buffer_t* bytes = NULL;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &tag);+ }+ if (result == CARDANO_SUCCESS && (tag >= sizeof(arities) / sizeof(arities[0]) || count != arities[tag]))+ {+ result = CARDANO_ERROR_DECODING;+ }+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+#define TRY(CALL) \+ do \+ { \+ result = (CALL); \+ if (result != CARDANO_SUCCESS) \+ { \+ goto cleanup; \+ } \+ } \+ while (0)+ switch (tag)+ {+ case 0:+ TRY(read_output(reader, &output));+ cardano_tx_builder_add_output(builder, output);+ break;+ case 12:+ case 1:+ TRY(read_utxo(reader, &utxo));+ if (tag == 12)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ }+ TRY(read_data(reader, &datum));+ TRY(cardano_utxo_list_add(resolved, utxo));+ if (tag == 12)+ {+ cardano_tx_builder_add_input_with_deferred_redeemer(builder, utxo, deferred_callback, context, datum);+ }+ else+ {+ cardano_tx_builder_add_input(builder, utxo, redeemer, datum);+ }+ break;+ case 2:+ TRY(read_utxo(reader, &utxo));+ TRY(cardano_utxo_list_add(resolved, utxo));+ cardano_tx_builder_add_reference_input(builder, utxo);+ break;+ case 3:+ TRY(read_script(reader, &script));+ cardano_tx_builder_add_script(builder, script);+ break;+ case 13:+ case 4:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));+ cardano_buffer_unref(&bytes);+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_asset_name_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &asset_name));+ TRY(cardano_cbor_reader_read_int(reader, &signed_number));+ if (tag == 13)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ bool registered = false;+ for (size_t i = 0; i < position; ++i)+ {+ if (contexts[i].deferred_mint && contexts[i].index == context->index)+ {+ registered = true;+ }+ }+ context->deferred_mint = true;+ if (registered)+ {+ cardano_tx_builder_mint_token(builder, hash, asset_name, signed_number, NULL);+ }+ else+ {+ cardano_tx_builder_mint_token_with_deferred_redeemer(builder, hash, asset_name, signed_number, deferred_callback, context);+ }+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_tx_builder_mint_token(builder, hash, asset_name, signed_number, redeemer);+ }+ break;+ case 5:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ TRY(read_metadata(reader, &metadata));+ cardano_tx_builder_set_metadata(builder, number, metadata);+ break;+ case 6:+ TRY(read_data(reader, &datum));+ cardano_tx_builder_add_datum(builder, datum);+ break;+ case 14:+ case 7:+ TRY(read_certificate(reader, &certificate));+ if (tag == 14)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_tx_builder_add_certificate_with_deferred_redeemer(builder, certificate, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_tx_builder_add_certificate(builder, certificate, redeemer);+ }+ break;+ case 15:+ case 8:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ if (number > INT64_MAX)+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ if (tag == 15)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_tx_builder_withdraw_rewards_with_deferred_redeemer(builder, reward, (int64_t)number, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_tx_builder_withdraw_rewards(builder, reward, (int64_t)number, redeemer);+ }+ break;+ case 9:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_blake2b_hash_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &hash));+ cardano_tx_builder_add_signer(builder, hash);+ break;+ case 10:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_tx_builder_set_invalid_before(builder, number);+ break;+ case 11:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_tx_builder_set_invalid_after(builder, number);+ break;+ case 16:+ TRY(read_credential(reader, &credential));+ TRY(read_data(reader, &redeemer));+ if (redeemer == NULL)+ {+ cardano_tx_builder_add_guard(builder, credential);+ }+ else+ {+ cardano_tx_builder_add_guard_with_redeemer(builder, credential, redeemer);+ }+ break;+ case 18:+ case 19:+ case 20:+ TRY(cardano_cbor_reader_read_bytestring(reader, &bytes));+ TRY(cardano_reward_address_from_bytes(cardano_buffer_get_data(bytes), cardano_buffer_get_size(bytes), &reward));+ if (tag == 18)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_tx_builder_add_direct_deposit(builder, reward, number);+ }+ else+ {+ TRY(read_interval(reader, &interval));+ if (tag == 19)+ {+ cardano_tx_builder_add_account_balance_interval(builder, reward, interval);+ }+ else+ {+ cardano_tx_builder_add_starting_account_balance_interval(builder, reward, interval);+ }+ }+ break;+ case 21:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_tx_builder_set_donation(builder, number);+ break;+ case 22:+ case 28:+ TRY(read_proposal(reader, &proposal));+ if (tag == 28U)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ cardano_tx_builder_add_proposal_with_deferred_redeemer(builder, proposal, deferred_callback, context);+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_tx_builder_add_proposal(builder, proposal, redeemer);+ }+ break;+ case 23:+ case 24:+ TRY(read_voter(reader, &voter));+ TRY(read_action_id(reader, &action_id));+ TRY(read_procedure(reader, &procedure));+ if (tag == 24)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &context->index));+ bool registered = false;+ for (size_t i = 0; i < position; ++i)+ {+ if (contexts[i].deferred_vote && contexts[i].index == context->index)+ {+ registered = true;+ }+ }+ context->deferred_vote = true;+ if (registered)+ {+ cardano_tx_builder_vote(builder, voter, action_id, procedure, NULL);+ }+ else+ {+ cardano_tx_builder_vote_with_deferred_redeemer(builder, voter, action_id, procedure, deferred_callback, context);+ }+ }+ else+ {+ TRY(read_data(reader, &redeemer));+ cardano_tx_builder_vote(builder, voter, action_id, procedure, redeemer);+ }+ break;+ case 27:+ TRY(cardano_cbor_reader_read_uint(reader, &number));+ cardano_tx_builder_set_current_treasury_value(builder, number);+ break;+ case 25:+ TRY(read_sub(reader, &sub));+ TRY(read_utxos(reader, &sub_resolved));+ for (size_t i = 0; i < cardano_utxo_list_get_length(sub_resolved); ++i)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_list_get(sub_resolved, i, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(resolved, item);+ }+ cardano_utxo_unref(&item);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ }+ cardano_tx_builder_add_sub_transaction(builder, sub, sub_resolved);+ break;+ default:+ result = CARDANO_ERROR_DECODING;+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+cleanup:+ cardano_credential_unref(&credential);+ cardano_account_balance_interval_unref(&interval);+ cardano_proposal_procedure_unref(&proposal);+ cardano_voter_unref(&voter);+ cardano_governance_action_id_unref(&action_id);+ cardano_voting_procedure_unref(&procedure);+ cardano_sub_transaction_unref(&sub);+ cardano_utxo_list_unref(&sub_resolved);+ cardano_transaction_output_unref(&output);+ cardano_utxo_unref(&utxo);+ cardano_script_unref(&script);+ cardano_plutus_data_unref(&redeemer);+ cardano_plutus_data_unref(&datum);+ cardano_certificate_unref(&certificate);+ cardano_metadatum_unref(&metadata);+ cardano_blake2b_hash_unref(&hash);+ cardano_asset_name_unref(&asset_name);+ cardano_reward_address_unref(&reward);+ cardano_buffer_unref(&bytes);+ return result;+}++/**+ * \brief Decode an owned pool snapshot, including partial results on failure.+ * \param reader Borrowed configuration reader.+ * \param pools Receives a zero-initialized owned array.+ * \param size Receives the array length; callers unref every entry and free the array.+ * \return Decoding or allocation status.+ */+static cardano_error_t+read_pool_state(cardano_cbor_reader_t* reader, cardano_pool_params_t*** pools, size_t* size)+{+ int64_t count = 0;+ cardano_error_t result = cardano_cbor_reader_read_start_array(reader, &count);+ if (result != CARDANO_SUCCESS)+ {+ return result;+ }+ if (count < 0 || (uint64_t)count > SIZE_MAX / sizeof(cardano_pool_params_t*))+ {+ return CARDANO_ERROR_DECODING;+ }+ if (count > 0)+ {+ *pools = calloc((size_t)count, sizeof(cardano_pool_params_t*));+ if (*pools == NULL)+ {+ return CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ }+ }+ *size = (size_t)count;+ for (size_t i = 0; result == CARDANO_SUCCESS && i < *size; ++i)+ {+ result = read_pool_parameters(reader, &(*pools)[i]);+ }+ return result == CARDANO_SUCCESS ? cardano_cbor_reader_read_end_array(reader) : result;+}++/**+ * \brief Read the protocol version and release the retained version reference.+ * \param parameters Borrowed protocol parameters.+ * \return Major version, or zero when unspecified.+ */+static uint64_t+protocol_major(cardano_protocol_parameters_t* parameters)+{+ cardano_protocol_version_t* version = cardano_protocol_parameters_get_protocol_version(parameters);+ uint64_t major = cardano_protocol_version_get_major(version);+ cardano_protocol_version_unref(&version);+ return major;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_transaction_builder_build(cometa_runtime_t* selector_runtime, cometa_runtime_t* evaluator_runtime, cometa_runtime_t* deferred_runtime, const unsigned char* config, size_t config_size, const unsigned char* plan, size_t plan_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count)+{+ if (output == NULL || diagnostic == NULL || key_count == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }+ cardano_pool_params_t** pools = NULL;+ size_t pool_count = 0U;+ *key_count = 0U;+ *output = NULL;+ *diagnostic = NULL;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(config, config_size);+ cardano_cbor_reader_t* instructions = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_buffer_t* parameter_bytes = NULL;+ cardano_protocol_parameters_t* parameters = NULL;+ cardano_address_t* change = NULL;+ cardano_address_t* collateral_change = NULL;+ cardano_utxo_list_t* available = NULL;+ cardano_utxo_list_t* collateral = NULL;+ cardano_utxo_list_t* resolved = NULL;+ cardano_blake2b_hash_set_t* unique_signers = NULL;+ cardano_tx_builder_t* builder = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_coin_selector_t* selector = NULL;+ cardano_tx_evaluator_t* evaluator = NULL;+ uint64_t fee = 0U, padding = 0U;+ cardano_slot_config_t slots = { 0 };+ int64_t count = 0;+ deferred_context_t* contexts = NULL;+ cardano_network_id_t network;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : array(reader, 11);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ TRY(cardano_cbor_reader_read_bytestring(reader, ¶meter_bytes));+ TRY(cometa_parameters_from_snapshot(cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), ¶meters));+ TRY(read_address(reader, &change));+ TRY(read_utxos(reader, &available));+ TRY(read_utxos(reader, &collateral));+ TRY(read_address(reader, &collateral_change));+ TRY(cardano_cbor_reader_read_uint(reader, &fee));+ TRY(cardano_cbor_reader_read_uint(reader, &padding));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_time));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.zero_slot));+ TRY(cardano_cbor_reader_read_uint(reader, &slots.slot_length));+ TRY(read_pool_state(reader, &pools, &pool_count));+ TRY(cardano_cbor_reader_read_end_array(reader));+ TRY(complete(reader));+ if (slots.slot_length == 0U || padding > SIZE_MAX)+ {+ result = CARDANO_ERROR_INVALID_ARGUMENT;+ goto cleanup;+ }+ builder = cardano_tx_builder_new(parameters, &slots);+ if (builder == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_tx_builder_set_pool_state(builder, pools, pool_count));+ TRY(cardano_address_get_network_id(change, &network));+ cardano_tx_builder_set_network_id(builder, network);+ cardano_tx_builder_set_change_address(builder, change);+ cardano_tx_builder_set_utxos(builder, available);+ cardano_tx_builder_set_collateral_utxos(builder, collateral);+ cardano_tx_builder_set_collateral_change_address(builder, collateral_change != NULL ? collateral_change : change);+ cardano_tx_builder_set_minimum_fee(builder, fee);+ cardano_tx_builder_pad_signer_count(builder, (size_t)padding);+ if (selector_runtime != NULL)+ {+ TRY(cometa_coin_selector_new(selector_runtime, cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &selector));+ cardano_tx_builder_set_coin_selector(builder, selector);+ }+ if (evaluator_runtime != NULL)+ {+ TRY(cometa_evaluation_new(evaluator_runtime, &evaluator));+ cardano_tx_builder_set_tx_evaluator(builder, evaluator);+ }+ TRY(cardano_utxo_list_new(&resolved));+ for (size_t i = 0; i < cardano_utxo_list_get_length(available) + cardano_utxo_list_get_length(collateral); ++i)+ {+ cardano_utxo_t* item = NULL;+ const size_t offset = cardano_utxo_list_get_length(available);+ result = i < offset ? cardano_utxo_list_get(available, i, &item) : cardano_utxo_list_get(collateral, i - offset, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(resolved, item);+ }+ cardano_utxo_unref(&item);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ }+ instructions = cardano_cbor_reader_new(plan, plan_size);+ if (instructions == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_cbor_reader_read_start_array(instructions, &count));+ if (count < 0)+ {+ result = CARDANO_ERROR_DECODING;+ goto cleanup;+ }+ if ((uint64_t)count > SIZE_MAX / sizeof(deferred_context_t))+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ contexts = calloc(count == 0 ? 1U : (size_t)count, sizeof(deferred_context_t));+ if (contexts == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ for (int64_t i = 0; i < count; ++i)+ {+ contexts[i].runtime = deferred_runtime;+ TRY(instruction(builder, instructions, resolved, contexts, (size_t)i));+ }+ TRY(cardano_cbor_reader_read_end_array(instructions));+ TRY(complete(instructions));+ TRY(cardano_tx_builder_build(builder, &transaction));+ TRY(cardano_transaction_get_unique_signers_with_pool_state(transaction, resolved, protocol_major(parameters), pools, pool_count, &unique_signers));+ if ((uint64_t)cardano_blake2b_hash_set_get_length(unique_signers) > UINT64_MAX - padding)+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ *key_count = (uint64_t)cardano_blake2b_hash_set_get_length(unique_signers) + padding;+ writer = cardano_cbor_writer_new();+ if (writer == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_transaction_to_cbor(transaction, writer));+ TRY(cardano_cbor_writer_encode_in_buffer(writer, output));+cleanup:+ if (result != CARDANO_SUCCESS && builder != NULL)+ {+ const char* message = cardano_tx_builder_get_last_error(builder);+ if (message != NULL && message[0] != '\0')+ {+ *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));+ }+ }+ cardano_cbor_writer_unref(&writer);+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_reader_unref(&instructions);+ cardano_blake2b_hash_set_unref(&unique_signers);+ cardano_utxo_list_unref(&resolved);+ cardano_tx_builder_unref(&builder);+ free(contexts);+ cardano_transaction_unref(&transaction);+ cardano_coin_selector_unref(&selector);+ cardano_tx_evaluator_unref(&evaluator);+ for (size_t i = 0; i < pool_count; ++i)+ {+ cardano_pool_params_unref(&pools[i]);+ }+ free(pools);+ cardano_protocol_parameters_unref(¶meters);+ cardano_address_unref(&change);+ cardano_address_unref(&collateral_change);+ cardano_utxo_list_unref(&available);+ cardano_utxo_list_unref(&collateral);+ cardano_buffer_unref(¶meter_bytes);+ return result;+}++/* Parsed redeemers and their collection cache their original CBOR. Native+ * setters do not invalidate those caches, so create fresh outer wrappers before+ * changing indices, payloads or budgets. Retain the existing data owners rather+ * than clearing recursively: their exact payload encoding remains observable.+ * The witness setter retains the replacement; the caller receives another owned+ * reference. On failure the original witness set remains installed unchanged. */+static cardano_error_t+fresh_balance_redeemers(cardano_witness_set_t* witnesses, cardano_redeemer_list_t** output)+{+ if (output == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }+ *output = NULL;+ cardano_redeemer_list_t* original = cardano_witness_set_get_redeemers(witnesses);+ if (original == NULL)+ {+ return CARDANO_SUCCESS;+ }++ cardano_redeemer_list_t* fresh = NULL;+ cardano_error_t result = cardano_redeemer_list_new(&fresh);+ for (size_t i = 0U; result == CARDANO_SUCCESS && i < cardano_redeemer_list_get_length(original); ++i)+ {+ cardano_redeemer_t* source = NULL;+ cardano_redeemer_t* replacement = NULL;+ cardano_plutus_data_t* data = NULL;+ cardano_ex_units_t* units = NULL;+ result = cardano_redeemer_list_get(original, i, &source);+ if (result == CARDANO_SUCCESS)+ {+ data = cardano_redeemer_get_data(source);+ units = cardano_redeemer_get_ex_units(source);+ result = cardano_redeemer_new(cardano_redeemer_get_tag(source), cardano_redeemer_get_index(source), data, units, &replacement);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_redeemer_list_add(fresh, replacement);+ }+ cardano_redeemer_unref(&replacement);+ cardano_plutus_data_unref(&data);+ cardano_ex_units_unref(&units);+ cardano_redeemer_unref(&source);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_witness_set_set_redeemers(witnesses, fresh);+ }+ if (result == CARDANO_SUCCESS)+ {+ *output = fresh;+ fresh = NULL;+ }+ cardano_redeemer_list_unref(&original);+ cardano_redeemer_list_unref(&fresh);+ return result;+}++/** \brief Bind a decoded witness redeemer to its input and optional callback. */+static cardano_error_t+balance_redeemer(cardano_cbor_reader_t* reader, cardano_redeemer_list_t* redeemers, cardano_input_to_redeemer_map_t* inputs, cardano_deferred_redeemer_list_t* deferred, deferred_context_t* context)+{+ uint64_t tag = 0U, index = 0U;+ bool callback = false;+ cardano_transaction_input_t* input = NULL;+ cardano_redeemer_t* found = NULL;+ cardano_error_t result = array(reader, 4);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &tag);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_uint(reader, &index);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = read_balance_input(reader, &input);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_bool(reader, &callback);+ }+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_cbor_reader_read_end_array(reader);+ }+ for (size_t i = 0U; result == CARDANO_SUCCESS && i < cardano_redeemer_list_get_length(redeemers); ++i)+ {+ cardano_redeemer_t* item = NULL;+ result = cardano_redeemer_list_get(redeemers, i, &item);+ if (result == CARDANO_SUCCESS && (uint64_t)cardano_redeemer_get_tag(item) == tag && cardano_redeemer_get_index(item) == index)+ {+ if (found != NULL)+ {+ result = CARDANO_ERROR_DUPLICATED_KEY;+ }+ else+ {+ found = item;+ cardano_redeemer_ref(found);+ }+ }+ cardano_redeemer_unref(&item);+ }+ if (result == CARDANO_SUCCESS && found == NULL)+ {+ result = CARDANO_ERROR_ELEMENT_NOT_FOUND;+ }+ if (result == CARDANO_SUCCESS && input != NULL)+ {+ result = cardano_input_to_redeemer_map_insert(inputs, input, found);+ }+ if (result == CARDANO_SUCCESS && callback)+ {+ result = cardano_deferred_redeemer_list_add(deferred, found, deferred_callback, context);+ }+ cardano_transaction_input_unref(&input);+ cardano_redeemer_unref(&found);+ return result;+}++/* DEFINITIONS ***************************************************************/++unsigned int+cometa_transaction_balance(cometa_runtime_t* selector_runtime, cometa_runtime_t* evaluator_runtime, cometa_runtime_t* deferred_runtime, const unsigned char* config, size_t config_size, const unsigned char* request, size_t request_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count)+{+ if (output == NULL || diagnostic == NULL || key_count == NULL)+ {+ return CARDANO_ERROR_POINTER_IS_NULL;+ }+ cardano_pool_params_t** pools = NULL;+ size_t pool_count = 0U;+ *output = NULL;+ *diagnostic = NULL;+ *key_count = 0U;+ cardano_cbor_reader_t* reader = cardano_cbor_reader_new(config, config_size);+ cardano_cbor_reader_t* payload = NULL;+ cardano_cbor_writer_t* writer = NULL;+ cardano_buffer_t* parameter_bytes = NULL;+ cardano_protocol_parameters_t* parameters = NULL;+ cardano_address_t* change = NULL;+ cardano_address_t* collateral_change = NULL;+ cardano_utxo_list_t* available = NULL;+ cardano_utxo_list_t* collateral = NULL;+ cardano_utxo_list_t* references = NULL;+ cardano_utxo_list_t* selected = NULL;+ cardano_utxo_list_t* resolved = NULL;+ cardano_transaction_t* transaction = NULL;+ cardano_transaction_body_t* body = NULL;+ cardano_witness_set_t* witnesses = NULL;+ cardano_redeemer_list_t* redeemers = NULL;+ cardano_input_to_redeemer_map_t* input_map = NULL;+ cardano_deferred_redeemer_list_t* deferred = NULL;+ cardano_coin_selector_t* selector = NULL;+ cardano_tx_evaluator_t* evaluator = NULL;+ cardano_blake2b_hash_set_t* signers = NULL;+ deferred_context_t* contexts = NULL;+ uint64_t fee = 0U, padding = 0U, ignored = 0U;+ int64_t count = 0;+ cardano_error_t result = reader == NULL ? CARDANO_ERROR_MEMORY_ALLOCATION_FAILED : array(reader, 11);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ TRY(cardano_cbor_reader_read_bytestring(reader, ¶meter_bytes));+ TRY(cometa_parameters_from_snapshot(cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), ¶meters));+ TRY(read_address(reader, &change));+ TRY(read_utxos(reader, &available));+ TRY(read_utxos(reader, &collateral));+ TRY(read_address(reader, &collateral_change));+ TRY(cardano_cbor_reader_read_uint(reader, &fee));+ TRY(cardano_cbor_reader_read_uint(reader, &padding));+ for (size_t i = 0U; i < 3U; ++i)+ {+ TRY(cardano_cbor_reader_read_uint(reader, &ignored));+ }+ TRY(read_pool_state(reader, &pools, &pool_count));+ TRY(cardano_cbor_reader_read_end_array(reader));+ TRY(complete(reader));+ if (padding > SIZE_MAX)+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ payload = cardano_cbor_reader_new(request, request_size);+ if (payload == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(array(payload, 4));+ TRY(read_balance_transaction(payload, &transaction));+ if (transaction == NULL)+ {+ result = CARDANO_ERROR_POINTER_IS_NULL;+ goto cleanup;+ }+ TRY(read_utxos(payload, &references));+ TRY(read_utxos(payload, &selected));+ TRY(cardano_input_to_redeemer_map_new(&input_map));+ TRY(cardano_deferred_redeemer_list_new(&deferred));+ witnesses = cardano_transaction_get_witness_set(transaction);+ TRY(fresh_balance_redeemers(witnesses, &redeemers));+ TRY(cardano_cbor_reader_read_start_array(payload, &count));+ if (count < 0 || (uint64_t)count > SIZE_MAX / sizeof(deferred_context_t))+ {+ result = CARDANO_ERROR_DECODING;+ goto cleanup;+ }+ contexts = calloc(count == 0 ? 1U : (size_t)count, sizeof(deferred_context_t));+ if (contexts == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ for (int64_t i = 0; i < count; ++i)+ {+ contexts[i].runtime = deferred_runtime;+ contexts[i].index = (uint64_t)i;+ TRY(balance_redeemer(payload, redeemers, input_map, deferred, &contexts[i]));+ }+ TRY(cardano_cbor_reader_read_end_array(payload));+ TRY(cardano_cbor_reader_read_end_array(payload));+ TRY(complete(payload));+ if (selector_runtime == NULL)+ {+ TRY(cardano_random_improve_coin_selector_new(&selector));+ }+ else+ {+ TRY(cometa_coin_selector_new(selector_runtime, cardano_buffer_get_data(parameter_bytes), cardano_buffer_get_size(parameter_bytes), &selector));+ }+ TRY(cometa_evaluation_new(evaluator_runtime, &evaluator));+ body = cardano_transaction_get_body(transaction);+ /* Invalidate only the mutable outer body; nested intent/data caches survive. */+ cardano_transaction_body_clear_cbor_cache(body);+ if (fee > cardano_transaction_body_get_fee(body))+ {+ TRY(cardano_transaction_body_set_fee(body, fee));+ }+ TRY(cardano_balance_transaction_with_pool_state(transaction, (size_t)padding, parameters, references, selected, input_map, available, selector, change, collateral, collateral_change != NULL ? collateral_change : change, evaluator, deferred, pools, pool_count));+ TRY(cardano_utxo_list_new(&resolved));+ cardano_utxo_list_t* sources[] = { available, collateral, selected, references };+ for (size_t i = 0U; i < 4U; ++i)+ {+ for (size_t j = 0U; j < cardano_utxo_list_get_length(sources[i]); ++j)+ {+ cardano_utxo_t* item = NULL;+ result = cardano_utxo_list_get(sources[i], j, &item);+ if (result == CARDANO_SUCCESS)+ {+ result = cardano_utxo_list_add(resolved, item);+ }+ cardano_utxo_unref(&item);+ if (result != CARDANO_SUCCESS)+ {+ goto cleanup;+ }+ }+ }+ TRY(cardano_transaction_get_unique_signers_with_pool_state(transaction, resolved, protocol_major(parameters), pools, pool_count, &signers));+ if (padding > UINT64_MAX - cardano_blake2b_hash_set_get_length(signers))+ {+ result = CARDANO_ERROR_INTEGER_OVERFLOW;+ goto cleanup;+ }+ *key_count = padding + cardano_blake2b_hash_set_get_length(signers);+ writer = cardano_cbor_writer_new();+ if (writer == NULL)+ {+ result = CARDANO_ERROR_MEMORY_ALLOCATION_FAILED;+ goto cleanup;+ }+ TRY(cardano_transaction_to_cbor(transaction, writer));+ TRY(cardano_cbor_writer_encode_in_buffer(writer, output));+cleanup:+ if (result != CARDANO_SUCCESS && transaction != NULL)+ {+ const char* message = cardano_transaction_get_last_error(transaction);+ if (message != NULL && message[0] != '\0')+ {+ *diagnostic = cardano_buffer_new_from((const byte_t*)message, strlen(message));+ }+ }+ cardano_cbor_reader_unref(&reader);+ cardano_cbor_reader_unref(&payload);+ cardano_cbor_writer_unref(&writer);+ cardano_buffer_unref(¶meter_bytes);+ for (size_t i = 0; i < pool_count; ++i)+ {+ cardano_pool_params_unref(&pools[i]);+ }+ free(pools);+ cardano_protocol_parameters_unref(¶meters);+ cardano_address_unref(&change);+ cardano_address_unref(&collateral_change);+ cardano_utxo_list_unref(&available);+ cardano_utxo_list_unref(&collateral);+ cardano_utxo_list_unref(&references);+ cardano_utxo_list_unref(&selected);+ cardano_utxo_list_unref(&resolved);+ cardano_deferred_redeemer_list_unref(&deferred);+ cardano_input_to_redeemer_map_unref(&input_map);+ cardano_redeemer_list_unref(&redeemers);+ cardano_witness_set_unref(&witnesses);+ cardano_transaction_body_unref(&body);+ cardano_transaction_unref(&transaction);+ cardano_coin_selector_unref(&selector);+ cardano_tx_evaluator_unref(&evaluator);+ cardano_blake2b_hash_set_unref(&signers);+ free(contexts);+ return result;+}++#undef TRY
@@ -0,0 +1,44 @@+/**+ * \file cometa_transaction_builder.h+ *+ * Copyright 2026 Biglup Labs+ * SPDX-License-Identifier: Apache-2.0+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++#ifndef COMETA_TRANSACTION_BUILDER_H+#define COMETA_TRANSACTION_BUILDER_H++#include "cometa_runtime.h"+#include <cardano/cardano.h>++/**+ * \brief Build a fresh transaction with scoped native callback adapters.+ * \param selector Borrowed active runtime, or NULL for the native default.+ * \param evaluator Borrowed active runtime, or NULL for the native default.+ * \param deferred Borrowed active deferred-argument runtime.+ * \param config Borrowed complete configuration snapshot.+ * \param config_size Configuration byte length.+ * \param plan Borrowed validated instruction snapshot.+ * \param plan_size Plan byte length.+ * \param output Owned transaction CBOR on success, NULL on failure.+ * \param diagnostic Owned copied builder diagnostic, possibly NULL.+ * \param key_count Unique native signing keys plus explicit padding on success.+ * \return Native status. All factories, callbacks and owner destruction finish+ * before return. Context gates must stay active for this entire operation.+ */+unsigned int cometa_transaction_builder_build(cometa_runtime_t* selector, cometa_runtime_t* evaluator, cometa_runtime_t* deferred, const unsigned char* config, size_t config_size, const unsigned char* plan, size_t plan_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count);+/** \brief Balance an independent decoded transaction using the same scoped result and runtime ownership contract as build. */+unsigned int cometa_transaction_balance(cometa_runtime_t* selector, cometa_runtime_t* evaluator, cometa_runtime_t* deferred, const unsigned char* config, size_t config_size, const unsigned char* request, size_t request_size, cardano_buffer_t** output, cardano_buffer_t** diagnostic, uint64_t* key_count);+#endif
@@ -0,0 +1,826 @@+cabal-version: 3.0+name: cometa+version: 0.2.0.0+synopsis: Idiomatic Haskell bindings to cardano-c+description:+ Haskell-owned Cardano values with transaction construction, signing, script+ evaluation and provider interfaces backed by cardano-c. Includes a+ Blockfrost provider.+license: Apache-2.0+license-file: LICENSE+author: Biglup Labs+maintainer: angel.castillob@protonmail.com+category: Blockchain+homepage: https://github.com/Biglup/cometa.hs+bug-reports: https://github.com/Biglup/cometa.hs/issues+build-type: Simple+extra-source-files:+ test/fixtures/providers/*.json+ test/fixtures/providers/README.md+ README.md+ examples/README.md+ CODING_CONVENTIONS.md+ AGENTS.md+ tools/*.py+ cbits/*.h+ .hlint.yaml+ .clang-format+ .readthedocs.yaml+ assets/*.png+ native/cardano-c.ref+ native/NOTICE+ native/*.json+ native/licenses/*.txt+ docs/requirements.txt+ docs/userguide/*.md+ docs/userguide/conf.py+ docs/userguide/_static/*.css+ docs/development/*.md+ test/Fixtures/*.md+ test/package-consumer/*.hs+ test/package-consumer/*.cabal+ test/valgrind/*.supp+ test/release/*.py++source-repository head+ type: git+ location: https://github.com/Biglup/cometa.hs.git++flag system-cardano-c+ description: Link an installed cardano-c instead of the bundled source package.+ default: False+ manual: True++common language+ default-language: Haskell2010+ ghc-options: -Wall -Wcompat -Wincomplete-uni-patterns -Wincomplete-record-updates++library core+ import: language+ visibility: private+ hs-source-dirs: internal+ exposed-modules:+ Cometa.Internal.Failure+ Cometa.Internal.Callback+ Cometa.Internal.Provider+ Cometa.Internal.FFI.Provider+ Cometa.Internal.FFI.Native+ Cometa.Internal.Ownership+ Cometa.Internal.Hex+ Cometa.Internal.FFI.Cbor+ Cometa.Internal.FFI.Reencode+ Cometa.Internal.Transaction+ Cometa.Internal.FFI.Transaction+ Cometa.Internal.SigningKey+ Cometa.Internal.FFI.SigningKey+ Cometa.Internal.FFI.Ed25519Values+ Cometa.Internal.FFI.Bip32+ Cometa.Internal.FFI.Bip39+ Cometa.Internal.Bip39+ Cometa.Internal.PasswordCrypto+ Cometa.Internal.FFI.PasswordCrypto+ Cometa.Internal.KeyHandler+ Cometa.Internal.FFI.KeyHandler+ Cometa.Internal.Bip32PrivateKey+ Cometa.Internal.FFI.Script+ Cometa.Internal.FFI.Runtime+ Cometa.Internal.FFI.ProviderRuntime+ Cometa.Internal.FFI.CoinSelection+ Cometa.Internal.FFI.Evaluation+ Cometa.Internal.FFI.NativeEvaluation+ Cometa.Internal.FFI.Building+ Cometa.Internal.FFI.ParameterUpdate+ Cometa.Internal.FFI.Inspection+ Cometa.Internal.FFI.Cip8+ Cometa.Internal.FFI.SubTransactionBuilder+ Cometa.Internal.FFI.ContextualTransaction+ Cometa.Internal.FFI.TransactionBuilder+ build-depends:+ base >=4.18 && <4.22,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2+ if flag(system-cardano-c)+ extra-libraries: cardano-c+ if os(linux) || os(osx)+ extra-libraries: m, pthread+ else+ build-depends: cardano-c-clib ==0.1.1.0+ c-sources:+ cbits/cometa_provider.c+ cbits/cometa_cbor.c+ cbits/cometa_reencode.c+ cbits/cometa_transaction.c+ cbits/cometa_signing_key.c+ cbits/cometa_ed25519_values.c+ cbits/cometa_key_handler.c+ cbits/cometa_bip32.c+ cbits/cometa_bip39.c+ cbits/cometa_password_crypto.c+ cbits/cometa_script.c+ cbits/cometa_runtime.c+ cbits/cometa_provider_runtime.c+ cbits/cometa_parameters.c+ cbits/cometa_inspection.c+ cbits/cometa_cip8.c+ cbits/cometa_coin_selection.c+ cbits/cometa_evaluation.c+ cbits/cometa_native_evaluation.c+ cbits/cometa_building.c+ cbits/cometa_sub_transaction_builder.c+ cbits/cometa_contextual_transaction.c+ cbits/cometa_transaction_builder.c+ include-dirs: cbits+ includes: cometa_provider.h+ cc-options: -std=c11 -Wall -Wextra++library+ import: language+ hs-source-dirs: src+ exposed-modules:+ Cometa.Provider.Blockfrost+ Cometa.Provider.Hydra+ Cometa.Provider.Koios+ Cometa.Provider.Kupmios+ Cometa+ Cometa.Crypto.Blake2b+ Cometa.Credential+ Cometa.Address+ Cometa.Address.Byron+ Cometa.Transaction+ Cometa.SubTransaction+ Cometa.Transaction.Signing+ Cometa.Transaction.Inspection+ Cometa.Inspection+ Cometa.Message.Cip8+ Cometa.Transaction.Input+ Cometa.Transaction.Indices+ Cometa.Transaction.Deferred+ Cometa.Transaction.Authority+ Cometa.SubTransaction.Indices+ Cometa.SubTransaction.Plan+ Cometa.SubTransaction.Builder+ Cometa.Transaction.Utxo+ Cometa.Transaction.Output+ Cometa.Transaction.Datum+ Cometa.Transaction.Fields+ Cometa.Transaction.Body+ Cometa.Transaction.Building+ Cometa.Transaction.Balancing+ Cometa.Transaction.Builder+ Cometa.Transaction.Plan+ Cometa.SubTransaction.Body+ Cometa.Transaction.Witness+ Cometa.Transaction.Witnesses+ Cometa.Transaction.Redeemer+ Cometa.Transaction.AuxiliaryData+ Cometa.Address.Shelley+ Cometa.Address.Reward+ Cometa.NetworkId+ Cometa.NetworkMagic+ Cometa.Diagnostics+ Cometa.AssetName+ Cometa.PolicyId+ Cometa.AssetId+ Cometa.Value+ Cometa.UnitInterval+ Cometa.Protocol.Rational+ Cometa.Protocol.ExUnits+ Cometa.Protocol.Version+ Cometa.Protocol.ExUnitPrices+ Cometa.Protocol.CostModels+ Cometa.Protocol.PoolVotingThresholds+ Cometa.Protocol.DRepVotingThresholds+ Cometa.Protocol.Parameters+ Cometa.Protocol.Parameters.Update+ Cometa.Certificate+ Cometa.Certificate.Collection+ Cometa.Pool.Parameters+ Cometa.Pool.Relay+ Cometa.Pool.Metadata+ Cometa.Pool.BlsKey+ Cometa.TransactionId+ Cometa.Governance.Action+ Cometa.Governance.Constitution+ Cometa.Governance.Committee+ Cometa.Governance.Proposal+ Cometa.Protocol.ProposedUpdates+ Cometa.Governance.Anchor+ Cometa.Governance.ActionId+ Cometa.Governance.DRep+ Cometa.Governance.Voting+ Cometa.PlutusData+ Cometa.Metadata+ Cometa.Script+ Cometa.Script.Native+ Cometa.Script.Plutus+ Cometa.Crypto.Ed25519.PublicKey+ Cometa.Crypto.Ed25519.Signature+ Cometa.Crypto.Ed25519.SigningKey+ Cometa.Crypto.Bip32+ Cometa.Crypto.Bip32.PublicKey+ Cometa.Crypto.Bip32.PrivateKey+ Cometa.Crypto.Bip39+ Cometa.Crypto.Pbkdf2+ Cometa.Crypto.Emip3+ Cometa.KeyHandler.Software+ Cometa.Crypto.DerivationPath+ Cometa.Error+ Cometa.Error.Code+ Cometa.Encoding.Cbor+ Cometa.Encoding.Integer+ Cometa.Encoding.Reencode+ Cometa.Value.Raw+ Cometa.Encoding.Hex+ Cometa.Encoding.Collections+ Cometa.Encoding.Set+ Cometa.Provider+ Cometa.Evaluation+ Cometa.Evaluation.Native+ Cometa.Signer+ Cometa.SlotConfig+ Cometa.CoinSelection+ other-modules:+ Cometa.Provider.Internal.Config+ Cometa.Provider.Internal.Protocol+ Cometa.Provider.Internal.Codec+ Cometa.Provider.Internal.Remote+ Cometa.Provider.Internal.Hydra+ Cometa.Provider.Blockfrost.Internal.Config+ Cometa.Provider.Blockfrost.Internal.Http+ Cometa.Provider.Blockfrost.Internal.Connection+ Cometa.Provider.Blockfrost.Internal.Protocol+ Cometa.Provider.Blockfrost.Internal.Json+ Cometa.Provider.Blockfrost.Internal.Provider+ Cometa.Internal.Runtime+ Cometa.Internal.Reencode+ Cometa.Internal.ProviderRuntime+ Cometa.Internal.CoinSelection+ Cometa.Internal.CoinSelection.Native+ Cometa.Internal.ParameterSnapshot+ Cometa.Internal.Evaluation+ Cometa.Internal.Evaluation.Native+ Cometa.Internal.Building+ Cometa.Internal.ParameterUpdate+ Cometa.Internal.Inspection+ Cometa.Internal.Message.Cip8+ Cometa.Internal.Balance+ Cometa.Internal.BatchValidation+ Cometa.Internal.SubTransactionPlan+ Cometa.Internal.SubTransactionBuilder+ Cometa.Internal.TransactionIndices+ Cometa.Internal.ContextualTransaction+ Cometa.Internal.TransactionPlan+ Cometa.Internal.TransactionBuilder+ Cometa.Internal.TransactionBalancing+ Cometa.Internal.BalancingScripts+ Cometa.Internal.EvaluationNative+ Cometa.Internal.TransactionCbor+ Cometa.Internal.SetEncoding+ Cometa.Internal.TransactionValue+ Cometa.Internal.TransactionFields+ Cometa.Internal.Error+ Cometa.Internal.ProtocolValues+ Cometa.Internal.CostModels+ Cometa.Internal.Certificate+ Cometa.Internal.Pool+ Cometa.Internal.ProposalCbor+ Cometa.Internal.Governance+ Cometa.Internal.AddressText+ Cometa.Internal.Bip39Pure+ Cometa.Internal.Pbkdf2Pure+ Cometa.Internal.Ed25519SigningKey+ build-depends:+ base >=4.18 && <4.22,+ bech32 >=1.1.10 && <1.2,+ cborg >=0.2.10 && <0.3,+ aeson >=2.2 && <2.3,+ scientific >=0.3.7 && <0.4,+ containers >=0.6.7 && <0.8,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa:core,+ network-uri >=2.6.4 && <2.7,+ http-client >=0.7.19 && <0.8,+ http-client-tls >=0.3.6 && <0.4,+ http-types >=0.12.3 && <0.13,+ async >=2.2 && <2.3,+ tls >=2.2 && <2.3,+ crypton-x509-store >=1.8 && <1.9,+ crypton-x509-system >=1.8 && <1.9,+ network >=3.2.12 && <3.3,+ stm >=2.5 && <2.6++executable cometa-bip39+ import: language+ hs-source-dirs: examples+ main-is: Bip39.hs+ build-depends:+ base >=4.18 && <4.22,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa++executable cometa-secure-key-handler+ import: language+ hs-source-dirs: examples+ main-is: SecureKeyHandler.hs+ other-modules: Support.Terminal+ build-depends:+ directory >=1.3 && <1.4,+ base >=4.18 && <4.22,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa++test-suite cometa-test+ import: language+ type: exitcode-stdio-1.0+ hs-source-dirs: test examples+ main-is: Main.hs+ c-sources:+ cbits/cometa_error_codes_test.c+ test/cbits/transaction_oracle.c+ test/cbits/transaction_witnesses_oracle.c+ test/cbits/transaction_body_oracle.c+ test/cbits/derivation_path_oracle.c+ test/cbits/address_oracle.c+ test/cbits/complete_address_oracle.c+ test/cbits/value_oracle.c+ test/cbits/asset_id_oracle.c+ test/cbits/plutus_data_oracle.c+ test/cbits/metadata_oracle.c+ test/cbits/script_oracle.c+ test/cbits/parameters_oracle.c+ test/cbits/protocol_values_oracle.c+ test/cbits/proposals_oracle.c+ test/cbits/pool_oracle.c+ test/cbits/certificates_oracle.c+ test/cbits/governance_oracle.c+ test/cbits/slot_config_oracle.c+ test/cbits/collections_oracle.c+ test/cbits/integer_semantics_oracle.c+ test/cbits/collection_operations_oracle.c+ test/cbits/transaction_collection_operations_oracle.c+ test/cbits/diagnostics_oracle.c+ test/cbits/numeric_conversions_oracle.c+ test/cbits/transaction_map_operations_oracle.c+ cc-options: -std=c11 -Wall -Wextra+ other-modules:+ Collections+ SetEncoding+ StandaloneSetEncoding+ TransactionDeferred+ TransactionAccountingProperties+ AccountingReliability+ SelectionReliability+ IdentityReliability+ IntegerSemantics+ CollectionOperations+ TransactionCollectionOperations+ Diagnostics+ NumericConversions+ TransactionMapOperations+ InspectionCollections+ HexEncoding+ NativeWorkflows+ ConnectedGovernance+ RewardAccountPubkey+ RewardAccountScript+ DeferredWithdrawZero+ DRepPubkey+ DRepScript+ VoteForProposalPubkey+ VoteForProposalScript+ DonateToTreasury+ ProposeTreasuryWithdrawal+ Fixtures.TransactionWorkflows+ SpendFromValidator+ DeferredRedeemerSelfIndex+ DeferredRedeemerBatch+ PlutusV4GuardedSubTransaction+ Support.Inputs+ Support.Wallet+ Support.Terminal+ Support.Configuration+ Support.Governance+ Support.Transaction+ Support.Scripts+ Fixtures.Workflow+ Fixtures.Swap+ Fixtures.ExampleParameters+ Value+ PlutusData+ Metadata+ Parameters+ ProtocolValues+ SlotConfig+ Governance+ Proposals+ Pool+ Certificates+ Fixtures.Governance+ Fixtures.ProtocolParameters+ Scripts+ Fixtures.Scripts+ Fixtures.PlutusData+ Address+ CompleteAddress+ AssetId+ Cip8+ Fixtures.Address+ ErrorCode+ Ownership+ Callback+ Cbor+ Transaction+ PublicTransaction+ TransactionWitnesses+ TransactionBody+ Fixtures.Transaction+ Fixtures.Ed25519+ Ed25519+ Bip32+ Fixtures.Bip32+ Bip39+ PasswordCrypto+ SoftwareKeyHandler+ DerivationPath+ Fixtures.Bip39+ ghc-options: -threaded -rtsopts+ build-depends:+ base >=4.18 && <4.22,+ containers >=0.6.7 && <0.8,+ aeson >=2.2 && <2.3,+ cborg >=0.2.10 && <0.3,+ scientific >=0.3.7 && <0.4,+ bech32 >=1.1.10 && <1.2,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa,+ cometa:core,+ tasty >=1.4 && <1.6,+ tasty-hunit >=0.10 && <0.11,+ tasty-hedgehog >=1.4 && <1.5,+ hedgehog >=1.2 && <1.6++test-suite cometa-runtime-test+ import: language+ type: exitcode-stdio-1.0+ hs-source-dirs: test src+ main-is: RuntimeMain.hs+ c-sources:+ test/cbits/parameter_snapshot_oracle.c+ test/cbits/runtime_oracle.c+ test/cbits/transaction_indices_oracle.c+ test/cbits/contextual_transaction_oracle.c+ test/cbits/encoding_normalization_oracle.c+ include-dirs: cbits+ cc-options: -std=c11 -Wall -Wextra+ ghc-options: -threaded -rtsopts+ other-modules:+ BlockfrostProtocol+ BlockfrostJson+ BlockfrostProvider+ AdditionalProviders+ Cometa.Provider.Blockfrost+ Cometa.Provider.Hydra+ Cometa.Provider.Koios+ Cometa.Provider.Kupmios+ BlockfrostHttp+ Cometa.Provider.Internal.Config+ Cometa.Provider.Internal.Protocol+ Cometa.Provider.Internal.Codec+ Cometa.Provider.Internal.Remote+ Cometa.Provider.Internal.Hydra+ Cometa.Provider.Blockfrost.Internal.Config+ Cometa.Provider.Blockfrost.Internal.Http+ Cometa.Provider.Blockfrost.Internal.Connection+ Cometa.Provider.Blockfrost.Internal.Protocol+ Cometa.Provider.Blockfrost.Internal.Json+ Cometa.Provider.Blockfrost.Internal.Provider+ TransactionInspection+ EncodingNormalization+ Fixtures.Inspection+ Cometa.Transaction.Inspection+ Cometa.Inspection+ Provider+ Runtime+ Evaluation+ CoinSelection+ ParameterSnapshot+ TransactionBuilding+ TransactionBuilder+ NativeCoinSelection+ NativeEvaluation+ DeferredRedeemer+ TransactionBalancing+ BalancingScriptLanguages+ TransactionIndices+ ContextualTransaction+ SubTransactionBuilder+ DijkstraBuilder+ Fixtures.ProtocolParameters+ Cometa+ Cometa.Address+ Cometa.Address.Byron+ Cometa.Address.Reward+ Cometa.Address.Shelley+ Cometa.AssetId+ Cometa.AssetName+ Cometa.Certificate+ Cometa.Certificate.Collection+ Cometa.CoinSelection+ Cometa.Credential+ Cometa.Crypto.Bip32+ Cometa.Crypto.Bip32.PrivateKey+ Cometa.Crypto.Bip32.PublicKey+ Cometa.Crypto.Bip39+ Cometa.Crypto.Blake2b+ Cometa.Crypto.DerivationPath+ Cometa.Crypto.Ed25519.PublicKey+ Cometa.Crypto.Ed25519.Signature+ Cometa.Crypto.Ed25519.SigningKey+ Cometa.Crypto.Emip3+ Cometa.Crypto.Pbkdf2+ Cometa.Encoding.Cbor+ Cometa.Encoding.Integer+ Cometa.Encoding.Reencode+ Cometa.Value.Raw+ Cometa.Encoding.Set+ Cometa.Encoding.Collections+ Cometa.Error+ Cometa.Error.Code+ Cometa.Evaluation+ Cometa.Evaluation.Native+ Cometa.Governance.Action+ Cometa.Governance.ActionId+ Cometa.Governance.Anchor+ Cometa.Governance.Committee+ Cometa.Governance.Constitution+ Cometa.Governance.DRep+ Cometa.Governance.Proposal+ Cometa.Governance.Voting+ Cometa.Internal.AddressText+ Cometa.Internal.Bip39Pure+ Cometa.Internal.Certificate+ Cometa.Internal.CoinSelection+ Cometa.Internal.CoinSelection.Native+ Cometa.Internal.CostModels+ Cometa.Internal.Ed25519SigningKey+ Cometa.Internal.Error+ Cometa.Internal.Evaluation+ Cometa.Internal.Evaluation.Native+ Cometa.Internal.Building+ Cometa.Internal.ParameterUpdate+ Cometa.Internal.Inspection+ Cometa.Internal.Message.Cip8+ Cometa.Internal.Balance+ Cometa.Internal.BatchValidation+ Cometa.Internal.SubTransactionPlan+ Cometa.Internal.SubTransactionBuilder+ Cometa.Internal.TransactionIndices+ Cometa.Internal.ContextualTransaction+ Cometa.Internal.TransactionPlan+ Cometa.Internal.TransactionBuilder+ Cometa.Internal.TransactionBalancing+ Cometa.Internal.BalancingScripts+ Cometa.Internal.EvaluationNative+ Cometa.Internal.Governance+ Cometa.Internal.ParameterSnapshot+ Cometa.Internal.Pbkdf2Pure+ Cometa.Internal.Pool+ Cometa.Internal.ProposalCbor+ Cometa.Internal.ProtocolValues+ Cometa.Internal.ProviderRuntime+ Cometa.Internal.Runtime+ Cometa.Internal.Reencode+ Cometa.Internal.TransactionCbor+ Cometa.Internal.SetEncoding+ Cometa.Internal.TransactionFields+ Cometa.Internal.TransactionValue+ Cometa.KeyHandler.Software+ Cometa.Metadata+ Cometa.NetworkId+ Cometa.NetworkMagic+ Cometa.Diagnostics+ Cometa.PlutusData+ Cometa.PolicyId+ Cometa.Pool.BlsKey+ Cometa.Pool.Metadata+ Cometa.Pool.Parameters+ Cometa.Pool.Relay+ Cometa.Protocol.CostModels+ Cometa.Protocol.DRepVotingThresholds+ Cometa.Protocol.ExUnitPrices+ Cometa.Protocol.ExUnits+ Cometa.Protocol.Parameters+ Cometa.Protocol.Parameters.Update+ Cometa.Protocol.PoolVotingThresholds+ Cometa.Protocol.ProposedUpdates+ Cometa.Protocol.Rational+ Cometa.Protocol.Version+ Cometa.Provider+ Cometa.Script+ Cometa.Script.Native+ Cometa.Script.Plutus+ Cometa.Signer+ Cometa.SlotConfig+ Cometa.SubTransaction+ Cometa.SubTransaction.Body+ Cometa.Transaction+ Cometa.Transaction.AuxiliaryData+ Cometa.Transaction.Body+ Cometa.Transaction.Building+ Cometa.Transaction.Balancing+ Cometa.Transaction.Builder+ Cometa.Transaction.Plan+ Cometa.Transaction.Datum+ Cometa.Transaction.Fields+ Cometa.Transaction.Input+ Cometa.Transaction.Indices+ Cometa.Transaction.Deferred+ Cometa.Transaction.Authority+ Cometa.SubTransaction.Indices+ Cometa.SubTransaction.Plan+ Cometa.SubTransaction.Builder+ Cometa.Transaction.Output+ Cometa.Transaction.Redeemer+ Cometa.Transaction.Signing+ Cometa.Transaction.Utxo+ Cometa.Transaction.Witness+ Cometa.Transaction.Witnesses+ Cometa.TransactionId+ Cometa.UnitInterval+ Cometa.Value+ build-depends:+ base >=4.18 && <4.22,+ containers >=0.6.7 && <0.8,+ aeson >=2.2 && <2.3,+ cborg >=0.2.10 && <0.3,+ scientific >=0.3.7 && <0.4,+ bech32 >=1.1.10 && <1.2,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa:core,+ tasty >=1.5 && <1.6,+ tasty-hunit >=0.10 && <0.11,+ tasty-hedgehog >=1.4 && <1.5,+ hedgehog >=1.2 && <1.6,+ network-uri >=2.6.4 && <2.7,+ http-client >=0.7.19 && <0.8,+ http-client-tls >=0.3.6 && <0.4,+ http-types >=0.12.3 && <0.13,+ async >=2.2 && <2.3,+ tls >=2.2 && <2.3,+ crypton-x509-store >=1.8 && <1.9,+ crypton-x509-system >=1.8 && <1.9,+ network >=3.2.12 && <3.3,+ stm >=2.5 && <2.6,+ crypton-x509 >=1.8 && <1.9++executable cometa-provider+ import: language+ hs-source-dirs: examples+ main-is: Provider.hs+ other-modules: Support.Configuration+ ghc-options: -threaded -rtsopts+ build-depends:+ base >=4.18 && <4.22,+ cometa,+ bytestring >=0.11 && <0.13,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7++executable cometa-sign-data+ import: language+ hs-source-dirs: examples+ main-is: SignData.hs+ build-depends:+ base >=4.18 && <4.22,+ bytestring >=0.11 && <0.13,+ transformers >=0.6 && <0.7,+ cometa++common connected-example+ import: language+ hs-source-dirs: examples+ ghc-options: -threaded -rtsopts+ other-modules:+ Support.Configuration+ Support.Wallet+ Support.Terminal+ Support.Governance+ Support.Inputs+ Support.Transaction+ Support.Scripts+ build-depends:+ base >=4.18 && <4.22,+ bytestring >=0.11 && <0.13,+ containers >=0.6.7 && <0.8,+ text >=2.0 && <2.2,+ transformers >=0.6 && <0.7,+ cometa++executable cometa-sub-transaction-batch+ import: connected-example+ main-is: SubTransactionBatch.hs++executable cometa-send-lovelace+ import: connected-example+ main-is: SendLovelace.hs++executable cometa-mint-burn-native-script+ import: connected-example+ main-is: MintBurnNativeScript.hs++executable cometa-mint-burn-plutus-script+ import: connected-example+ main-is: MintBurnPlutusScript.hs++executable cometa-spend-from-native-script+ import: connected-example+ main-is: SpendFromNativeScript.hs++executable cometa-spend-from-validator+ import: connected-example+ main-is: SpendFromValidator.hs+ ghc-options: -main-is SpendFromValidator++executable cometa-deferred-self-index+ import: connected-example+ main-is: DeferredRedeemerSelfIndex.hs+ ghc-options: -main-is DeferredRedeemerSelfIndex++executable cometa-deferred-batch+ import: connected-example+ main-is: DeferredRedeemerBatch.hs+ ghc-options: -main-is DeferredRedeemerBatch++executable cometa-reward-account-pubkey+ import: connected-example+ main-is: RewardAccountPubkey.hs+ ghc-options: -main-is RewardAccountPubkey++executable cometa-reward-account-script+ import: connected-example+ main-is: RewardAccountScript.hs+ ghc-options: -main-is RewardAccountScript++executable cometa-drep-pubkey+ import: connected-example+ main-is: DRepPubkey.hs+ ghc-options: -main-is DRepPubkey++executable cometa-drep-script+ import: connected-example+ main-is: DRepScript.hs+ ghc-options: -main-is DRepScript++executable cometa-vote-for-proposal-pubkey+ import: connected-example+ main-is: VoteForProposalPubkey.hs+ ghc-options: -main-is VoteForProposalPubkey++executable cometa-vote-for-proposal-script+ import: connected-example+ main-is: VoteForProposalScript.hs+ ghc-options: -main-is VoteForProposalScript++executable cometa-donate-to-treasury+ import: connected-example+ main-is: DonateToTreasury.hs+ ghc-options: -main-is DonateToTreasury++executable cometa-propose-treasury-withdrawal+ import: connected-example+ main-is: ProposeTreasuryWithdrawal.hs+ ghc-options: -main-is ProposeTreasuryWithdrawal++executable cometa-deferred-withdraw-zero+ import: connected-example+ main-is: DeferredWithdrawZero.hs+ ghc-options: -main-is DeferredWithdrawZero++executable cometa-plutus-v4-guarded-subtransaction+ import: connected-example+ main-is: PlutusV4GuardedSubTransaction.hs+ ghc-options: -main-is PlutusV4GuardedSubTransaction++benchmark cometa-performance+ import: language+ type: exitcode-stdio-1.0+ hs-source-dirs: benchmark test+ main-is: Main.hs+ other-modules: Fixtures.ProtocolParameters+ ghc-options: -rtsopts+ build-depends:+ base >=4.18 && <4.22,+ aeson >=2.2 && <2.3,+ bytestring >=0.11 && <0.13,+ transformers >=0.6 && <0.7,+ cometa
@@ -0,0 +1,118 @@+# Audited BIP39 purity exception++Rechecked 2026-11-26 for the cardano-c v2.0.0-rc.7 update. The reachable BIP39,+PBKDF2, SHA256/SHA512, HMAC, bounded-copy, endian, error and wipe sources are+unchanged from the previously bundled native revision+`c5edc7c8f16b3980b6e97ef7fda80fef94adf980`. The native package manifest and its+libsodium feature flags are unchanged. The existing purity boundaries and their+restrictions therefore remain applicable; the public and runtime suites pass+with GHC 9.6.7 on Linux x86-64.+++Reviewed 2026-11-05 for native pin+`7a65f2c7309bbba9e86f6aa73214b003fab88aee`. This exception covers only+`Cometa.Internal.Bip39Pure`'s three concrete monomorphic native boundaries:+`fromEntropy`, `fromWords`, and `exportEntropy`. `fromText` is pure splitting+followed by `fromWords`. It authorizes no other native operation or generic+`IO a -> a` helper. Keep providers, callbacks, key lifetimes and arbitrary+allocation/mutation in `IO`.++The pin update adds initialization locking and password-crypto validation.+The BIP39, SHA256 and wipe-helper sources are unchanged from the original+`8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d` review; the threading build change is+reviewed below.++The latest pin adds secret-buffer wiping in BIP32 root derivation and Ed25519+signing, plus key-handler storage validation. Those operations are outside this+pure boundary. The reachable hashing, PBKDF2, BIP39, error and wipe-helper sources+and native build configuration are unchanged from the prior+`7811fe94dad90f30478ed4b61d96677f188abaa8` audit.++## Reachable native code++- `lib/src/bip39/bip39.c`: standard bounds (16/20/24/28/32 bytes,+ 12/15/18/21/24 words), stack scratch, bounded loops, `strcmp`, `memcpy`,+ `cardano_safe_memcpy`, bundled `crypto_hash_sha256`, static English words.+ No logger, configured allocator, RNG, callback, reference counting,+ initialization requirement or mutable error state is reached.+- `lib/src/bip39/bip39_wordlist_en.h`: translation-unit-private pointer slots+ refer to literal strings; this source never writes the slots.+- `lib/src/string_safe.c`: the reachable `cardano_safe_memcpy` only guards+ null/bounds and copies bytes. Other functions' errno/stdio paths are not reached.+- `lib/external/libsodium/crypto_hash/sha256/cp/hash_sha256_cp.c`: init/update/final+ use stack state and constant tables, no implementation dispatch or sodium+ initialization, and always return success. Native BIP39 ignores SHA256 status;+ replacing this implementation requires review of that assumption.+- `lib/src/error.c`: `cardano_error_to_string` returns static literals by switch;+ the C adapter introduces no additional state.+- `lib/src/cardano.c` and bundled `sodium/utils.c`: `cardano_memzero` guards and+ forwards bounded writes to `sodium_memzero`. SHA256 also uses this wipe.+ Native checksum failure writes entropy before returning: the wrapper wipes+ all 32 scratch bytes even on error and never copies failed entropy out.++The inspected Linux x86-64 objects call only the audited helpers, memory/string+operations and compiler memory/stack-check helpers. They contain no allocator+or logger reference on this path.++## Native build and platform review++`tools/build-native.py` builds the pinned static target with IPO disabled.+The native CMake configuration defines `SODIUM_STATIC` and, on native Unix,+`HAVE_PTHREAD=1` for initialization locking. It defines no wipe-selection sodium+feature macros. On the reviewed Unix configuration `sodium_memzero` therefore+uses bounded volatile stores; disassembly confirmed that branch locally.+The threading flag changes `sodium_init`, which this BIP39 call graph never+reaches; it does not change SHA256 or the selected wipe implementation.+Linux ARM and macOS ARM/Intel select the same source fallback under this build.+Windows selects the Windows-header `SecureZeroMemory` bounded wipe when `_WIN32`+and not `__CRT_INLINE`, otherwise the same fallback. These are source reviews;+local execution evidence is Linux x86-64 only. CI must supply execution evidence+for its existing Linux x86-64/ARM, macOS ARM/Intel and Windows matrix.++Custom native builds may select `memset_s`, `explicit_bzero`, `memset_explicit`,+`explicit_memset`, or a weak dummy-symbol path. They are outside this reviewed+build contract: the `memset_s` failure path can reach `sodium_misuse`, and the weak+symbol can be interposed. Re-audit reachable code, selected macros/objects, SHA256,+wiping, linkage and diagnostics whenever the native pin, compiler/platform,+build flags or dependency implementation changes. A source pin by itself is+not sufficient evidence for arbitrary native build variants.++## Haskell boundary and evaluation++`Mnemonic` remains an opaque words-only value, with no `Show` or equality+instance, retained native owner, or hidden entropy copy. The private module uses+`unsafePerformIO` with `NOINLINE` on each concrete boundary and local `-fno-cse`+and `-fno-full-laziness`, following base's optimizer safeguards. There is no+`unsafeDupablePerformIO` and no exported arbitrary IO runner. These safeguards+are not the proof of purity: deterministic behavior and independence from+external mutable state on the audited path are essential.++Input buffers live through safe, non-interruptible foreign calls. Static words,+UTF-8 and entropy outputs are copied and forced before the operation returns;+word decoding is forced inside its scoped marshaling action. The full retained+word-list spine and each strict `Text` are forced directly, without exporting an+extra phrase. Entropy copies and complete public error payloads are forced before+the unsafe IO boundary returns. Exact unexpected native statuses, diagnostics+and contract failures remain `Either` values; no partial getter or impossible+status fallback is introduced.++The existing `finally` wipe runs on success/failure and asynchronous cancellation+after foreign unwind. Pure evaluation promises neither execution count nor+execution timing: calls may share, be duplicated, or restart after cancellation.+The audited path is safe under those choices. Sharing may extend secret+retention. No comprehensive erasure guarantee is made for Haskell values or+native stack intermediates.++## Regression evidence++The suite retains all 26 independently crosschecked vectors and exact invalid+input/domain errors. It adds concurrent workers contending on one shared result,+varied entropy conversions with GC before entropy export, varied repeated unknown+word failures, and cancellation followed by a fresh conversion. Cancellation is+a scheduling smoke test: these bounded C calls are too short to guarantee an+exception arrives during native execution. The CI matrix runs the BIP39 group+at `-O2` with two capabilities, in addition to the ordinary complete suite.++The Valgrind configuration suppresses only the known GHC 9.6.7 scheduler+shutdown allocation reproduced by an empty threaded executable. See+`test/valgrind/ghc-9.6.7.supp`; other allocation errors remain checked.
@@ -0,0 +1,87 @@+# PBKDF2-HMAC-SHA512 purity audit++Rechecked 2026-11-26 for the cardano-c v2.0.0-rc.7 update. The reachable BIP39,+PBKDF2, SHA256/SHA512, HMAC, bounded-copy, endian, error and wipe sources are+unchanged from the previously bundled native revision+`c5edc7c8f16b3980b6e97ef7fda80fef94adf980`. The native package manifest and its+libsodium feature flags are unchanged. The existing purity boundaries and their+restrictions therefore remain applicable; the public and runtime suites pass+with GHC 9.6.7 on Linux x86-64.+++Reviewed 2026-11-05 against native revision+`7a65f2c7309bbba9e86f6aa73214b003fab88aee` and the existing pinned static native+build. This is a separate, narrow exception alongside BIP39; it does not authorize+pure wrappers for arbitrary native operations or EMIP3.++The latest pin adds secret-buffer wiping in BIP32 root derivation and Ed25519+signing, plus key-handler storage validation. Those operations are outside this+pure boundary. The reachable hashing, PBKDF2, BIP39, error and wipe-helper sources+and native build configuration are unchanged from the prior+`7811fe94dad90f30478ed4b61d96677f188abaa8` audit.++## Reachable native path++`lib/src/crypto/pbkdf2.c` borrows password/salt, writes only the caller's derived+key buffer, and uses local HMAC state, block digests and counters. It allocates no+native owner, reads no allocator configuration, mutable global state, error slot,+RNG or logger, and invokes no callback. `lib/src/string_safe.c`'s bounded memcpy+and `lib/src/endian.c`'s counter encoding are deterministic. All native expected+validation failures precede output computation; public validation excludes zero+salt/output, zero iterations and overflowing block/counter ranges.++`lib/external/libsodium/crypto_auth/hmacsha512/auth_hmacsha512.c` initializes,+updates and finalizes caller-supplied SHA512 states. Its separate random keygen+function is unreachable. `crypto_hash/sha512/cp/hash_sha512_cp.c` uses stack state+and static constant tables without runtime dispatch. HMAC intermediate states+and PBKDF digests are wiped by native sodium_memzero. Public cardano_memzero+forwards to that bounded wipe. Its selected platform branches and build-variant+restrictions are the same ones audited in BIP39_PURITY.md: this build defines no+wipe-selection sodium HAVE_* feature macros, selecting volatile writes on Unix+or Windows SecureZeroMemory where enabled. HAVE_PTHREAD protects unrelated+initialization and RNG paths; it does not change this call graph. No sodium_init is reached or required by this+stateless path. Initialization of unrelated native crypto cannot change results.++The RFC block limit is `64 * (2^32 - 1)` output bytes. Output must also fit Haskell+Int. The iteration maximum is the complete uint32 range, `2^32 - 1`; native+iteration starts at one and compares strictly below the requested count,+preventing counter wrap on 32-bit targets. These are representation limits,+not advice to perform enormous derivations.++## Haskell boundary++Only monomorphic `Cometa.Internal.Pbkdf2Pure.deriveBytes` uses unsafePerformIO,+with NOINLINE, -fno-cse and -fno-full-laziness. No polymorphic IO runner or+unsafeDupablePerformIO exists. These optimizer safeguards supplement the native+state-independence audit; they do not replace it. Public validation remains pure.++Password/salt ByteStrings are borrowed in nested useAsCStringLen scopes. Heap+scratch is allocated with Haskell mallocBytes and bracketed before computation;+cardano_memzero and free execute on success, failure, copy exceptions and+cancellation after native unwind. Scratch is not input-sized stack storage. Safe,+non-interruptible FFI ensures no C operation continues using released buffers.+The strict ByteString result is copied and forced within the scratch scope;+complete public error payloads are forced before the concrete pure boundary+returns. Native diagnostics are static and copied before return. Unexpected+native statuses and contract errors remain structured Either values.++Host allocation exhaustion may raise an exception, as with ordinary pure+ByteString allocation. Evaluation can be shared, duplicated or restarted;+results and ownership are valid under each choice. No execution count/timing+promise is made. Cancellation may wait for the whole derivation. Shared thunks+can retain password/output values longer. Ordinary immutable Haskell inputs and+explicit secret output copies are not erased or protected from logging.++## Regression and re-audit++Tests retain a native known answer and an independent Python hashlib binary+multi-block answer, output-prefix properties crossing the 64-byte block boundary,+invalid bounds, empty passwords, cancellation followed by reuse, and shared+concurrent evaluation/GC. Native buffer ownership tests concern EMIP3 separately.+Cancellation is a scheduling smoke test, not proof the exception arrived inside C.++Re-audit the full reachable graph, build flags, wipe implementation, diagnostics,+linkage and marshaling whenever the native pin, native dependency implementation,+compiler/platform or build flags change. Custom builds selecting additional+sodium feature macros are outside this review. Local execution is Linux x86-64;+existing hosted compiler/platform matrix results must be reviewed independently.
@@ -0,0 +1,25 @@+# Performance baseline++The `cometa-performance` Cabal benchmark measures a small offline payment through+public APIs. It is a repeatable baseline, not a statistical performance guarantee.++## Reproduce++Configure the pinned native library as described in the installation guide, then:++```sh+cabal build bench:cometa-performance+cabal bench cometa-performance --benchmark-options="1000 +RTS -s -RTS"+```++The optional positive argument is the iteration count (default 100). Each operation+has one untimed warm-up and a collection before timing. Fixture preparation and+key acquisition are outside the timed operations. A strict checksum consumes every+output byte. The decoder reads its fixed input through IO each iteration to avoid+timing an already evaluated shared result.++The fixture has one ten-ADA funding input, a two-ADA payment and change. It uses+synthetic protocol parameters and an unfunded public signing seed. Signing includes+serialization of the signed transaction. Inspection includes native inspection,+Haskell JSON decoding and JSON encoding. CBOR measures Haskell decoding and exact+re-emission, preserving original bytes; it is not native canonicalization.
@@ -0,0 +1,84 @@+# Releasing Cometa++The `Release` workflow is manual. It does not publish on a pull request, a push,+or a tag push. Its `validate` job runs the complete reusable CI workflow at the+selected commit: Linux x64/ARM64, macOS Intel/ARM64, Windows, the additional GHC+9.10 build, installed-library compatibility, lint, documentation and Valgrind.+Every validation job must pass before release preparation or upload. Merge the+workflow into the default branch before its first manual invocation.++## Credentials++Create a Hackage account with uploader permission and maintainership of the+packages being updated. Store its API token as `HACKAGE_TOKEN` in the repository's+GitHub environment named `release`. Only the upload step receives that token.+The workflow uses the normal GitHub token for attaching release assets.++## Prepare a candidate++Update `cometa.cabal`, the changelog, and the native package metadata when needed.+`native/package.json` controls the native package version; Cometa must depend on+that exact version. A change to the bundled native payload requires a new native+package version. Keep `native/cardano-c.ref` synchronized with the intended source.++Open **Actions → Release → Run workflow**, select the branch to test, and+leave `mode` set to `candidate`. The workflow:++1. Runs the full platform matrix and repository checks.+2. Generates both source packages and validates an independent consumer of them.+3. Builds one API documentation archive, including the Blockfrost provider.+4. Records the source revision, native revision, archive hashes and versions.+5. Uploads the native candidate first, then Cometa and its documentation.++Download `release-packages` from the workflow to inspect the exact archives and+`SHA256SUMS`. Candidate uploads are outside the normal Hackage index; validation+uses both archives explicitly. An identical native version already published on+Hackage can be reused. Both packages are source distributions, not precompiled+Haskell binaries. Blockfrost is included in the main `cometa` library.++## Publish++Create and push a signed `vVERSION` tag at the intended release commit, with+`VERSION` matching `cometa.cabal`. Dispatch the workflow at that tag with GitHub+CLI (replace `VERSION`):++```sh+gh workflow run release.yml --repo Biglup/cometa.hs --ref vVERSION -f mode=publish -f github_prerelease=true+```++Set `github_prerelease=false` for a regular GitHub release. Publishing from a+branch or a mismatched version tag is rejected.++The full validation and artifact preparation run again. The upload job consumes+the prepared artifacts without rebuilding them. It publishes `cardano-c-clib`+before `cometa`, then uploads the API documentation. After a fresh consumer+resolves the exact Cometa version through Hackage, the workflow creates or updates+the GitHub release and attaches the same archives, manifest and checksums.++Published source versions cannot be replaced. On a retry, an existing source+version is skipped only when its archive hash matches exactly; a mismatch stops+the release. Both source versions are checked before either is uploaded.+Documentation can be uploaded again. If verification fails after publication,+the uploaded packages remain published; diagnose the failure and retry the same+tag rather than attempting to replace a source version.++The Read the Docs guide retains its existing deployment. Hackage hosts the+versioned Haddock API reference.++## Local checks++These commands prepare and validate artifacts without uploading:++```sh+python3 tools/package-native.py /path/to/pinned/cardano-c+cabal sdist all --output-directory=release-artifacts+python3 tools/check-source-package.py release-artifacts/cometa-*.tar.gz --native-archive release-artifacts/cardano-c-clib-*.tar.gz+python3 tools/build-api-docs.py --hackage+cp dist-newstyle/cometa-*-docs.tar.gz release-artifacts/+GITHUB_SHA="$(git rev-parse HEAD)" python3 tools/release.py prepare --mode candidate+python3 -m unittest discover -s test/release -v+```++After publication, `python3 tools/check-source-package.py --published-version+VERSION` updates the package index and builds the public consumer without local+source archives or native library paths.
@@ -0,0 +1,3 @@+Sphinx==7.2.6+myst-parser==4.0.1+sphinx-immaterial==0.11.11
@@ -0,0 +1,8 @@+/* Keep purple links alongside the white header in both color schemes. */+[data-md-color-scheme="default"][data-md-color-primary="white"] {+ --md-typeset-a-color: #673ab7;+}++[data-md-color-scheme="slate"][data-md-color-primary="white"] {+ --md-typeset-a-color: #b39ddb;+}
@@ -0,0 +1,17 @@+# API reference++The [Haddock reference on Hackage](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html)+is the primary API documentation. It includes the Blockfrost, Koios, Kupmios and Hydra providers and describes+arguments, units, bounds and errors for each operation. Version 0.1.0.0 is currently+a package candidate; it has not been published in the main package index.++## Build locally++To browse documentation matching your checkout:++```sh+python3 tools/build-api-docs.py+```++Open `docs/_build/api/index.html`. Configure the native dependency as for a normal+build first. `cabal haddock all` also generates local documentation.
@@ -0,0 +1,87 @@+# Query Cardano through Blockfrost++`cometa` includes `Cometa.Provider.Blockfrost`. The backend implements the+ordinary `Cometa.Provider` record, so query results can feed the existing+transaction builder and signer workflows.++Choose `Mainnet`, `Preprod`, or `Preview` for the chain's network magic.+`Blockfrost.defaultConfig network Nothing` uses its official endpoint without a+project header. For authenticated services, validate the project identifier with+`Blockfrost.mkProjectId` and pass `Just project` instead.++Set `endpoint` to use another Blockfrost-compatible service, proxy or local server.+It accepts an absolute HTTP or HTTPS URL, including a base path and query parameters.+The selected network remains independent of the URL. With `OverloadedStrings`:++```haskell+let config =+ (Blockfrost.defaultConfig Blockfrost.Preprod Nothing)+ { Blockfrost.endpoint = "http://localhost:3000/api/v0" }+```++The defaults are a 30-second request timeout and a one-second confirmation poll+interval; both can be set between 1 and 60000 milliseconds. Project identifiers+and complete configuration values have no `Show` instance. Without a project ID,+no `project_id` header is sent. Base URL query parameters are retained; operation+parameters such as pagination take precedence over the same names in the URL.++```haskell+result <- Blockfrost.withProvider config $ \provider ->+ Provider.utxosAt provider address+```++For a workflow with several operations, run `ExceptT` inside `withProvider` and+use `ExceptT (Provider.operation provider ...)` for each step. Expected errors+return through the same `Either Error` boundary. The scope shares its transport,+waits for active requests during cleanup, and rejects escaped provider operations+with `RuntimeClosed`. Cancellation propagates after request cleanup. Configuration+and project identifiers are not read implicitly from the environment or files.++Address and asset queries fetch ascending pages of 100 results. A query permits+at most 10000 pages and rejects repeated input identities rather than silently+returning duplicate or conflicting snapshots. Results retain response order.+Reference scripts are fetched as needed, checked against their advertised hashes,+and reused within the query. Inline datums with an advertised datum hash are also+checked before returning an output. Datum lookup retains exact returned CBOR and+verifies its requested hash.++`Provider.resolveInputs` returns distinct requested references in first-request+order and omits missing inputs. A historical transaction output does not establish+that it remains unspent: the backend obtains its address and checks the current+address UTxO list. A supplied `consumed_by_tx` also excludes a spent output. These+requests are separate observations, so chain updates can race the query; callers+must obtain a fresh snapshot when their workflow requires one.++A missing address yields `[]`, a missing datum or NFT yields `Nothing`, and an+unknown reward account has balance zero. NFT lookup requires a native asset and+rejects multiple matching outputs or a quantity other than one. Endpoint failures,+malformed responses and ambiguous results remain errors. HTTP status is retained+in `ProviderHttpError`; transport errors use a stable sanitized reason. Server+bodies, project identifiers and raw HTTP request exceptions are not included in+error diagnostics. There are no automatic retries, including for rate limits.++Submission sends the exact transaction CBOR once and checks the returned identifier+against the locally computed transaction ID. A failed response can leave submission+status uncertain, so callers must determine its status before deciding to retry.+Confirmation polls the on-chain transaction endpoint until its identifier matches+or the supplied millisecond timeout expires. Zero timeout returns `False` without+an HTTP request. Confirmation establishes block inclusion, not finality.++Remote evaluation uses the Blockfrost Ogmios v6 request dialect, including+inline datums and reference scripts in all supplied additional UTxOs. It encodes+Plutus V1–V4 scripts and all six redeemer purposes; execution support depends on+the hosted evaluator's active ledger era. Nested transactions and guarded account+features return `UnsupportedOperation` before the request. Evaluation budgets+must cover exactly the existing redeemer identities; partial successes are+rejected. `Cometa.Evaluation.Native` remains available for features supported by+the pinned local native VM.++Protocol snapshots decode the documented fields exactly, including decimal+execution prices without floating-point rounding. Optional fields that Blockfrost+does not supply remain `Nothing`; the backend does not invent Dijkstra, Leios or+Peras parameters. The available online schema therefore differs from the full+offline binding's capabilities.++See [the Blockfrost examples](api-reference.md) for command-line workflows+with explicit query, build and submission choices, and+[the native workflows](api-reference.md) for deterministic offline examples.
@@ -0,0 +1,42 @@+"""Narrative documentation; builds independently of the native library."""++project = "Cometa.hs"+author = "Biglup Labs"+copyright = "2026, Biglup Labs"+release = "0.1.0.0"+version = release+extensions = ["myst_parser", "sphinx_immaterial"]+source_suffix = {".md": "markdown"}+root_doc = "index"+exclude_patterns = ["_build"]+nitpicky = True+highlight_language = "haskell"+html_theme = "sphinx_immaterial"+html_title = "Cometa.hs"+html_logo = "../../assets/cometa_hs.png"+html_static_path = ["_static"]+html_css_files = ["custom.css"]+html_theme_options = {+ "repo_url": "https://github.com/Biglup/cometa.hs",+ "repo_name": "cometa.hs",+ "edit_uri": "edit/main/docs/userguide/",+ "icon": {"repo": "fontawesome/brands/github"},+ "font": {"text": "Roboto", "code": "Roboto Mono"},+ "features": ["navigation.sections", "navigation.top", "search.share", "toc.follow"],+ "palette": [+ {+ "media": "(prefers-color-scheme: light)",+ "scheme": "default",+ "primary": "white",+ "accent": "deep-purple",+ "toggle": {"icon": "material/lightbulb-outline", "name": "Switch to dark mode"},+ },+ {+ "media": "(prefers-color-scheme: dark)",+ "scheme": "slate",+ "primary": "white",+ "accent": "purple",+ "toggle": {"icon": "material/lightbulb", "name": "Switch to light mode"},+ },+ ],+}
@@ -0,0 +1,144 @@+# Run connected examples++The named runners in `examples` build, sign and confirm complete+transaction workflows using the included Blockfrost provider. They use your+configured encrypted wallet and prompt for its password with terminal echo disabled.+Running a transaction example without arguments builds, signs, submits and waits+for confirmation. Use `--help` to print usage without opening a wallet or making requests.++For example, inspect the configured payment wallet before running the payment+flow:++```sh+cabal run cometa-send-lovelace -- --describe+cabal run cometa-send-lovelace+```++`--describe` prints public payment, selected stake and DRep identities. Relevant+governance runners also print their script identities. It does not submit a+transaction. The default invocation (or the equivalent `--submit`) runs the entire named workflow, including later dependent+stages. The [staking and governance guide](connected-governance.md) lists those+runners, their required state and their cleanup stages.++## Configure the wallet and provider++Use `COMETA_NETWORK=preprod` for these connected test-network flows. Configure+`BLOCKFROST_PROJECT_ID` and, optionally, `BLOCKFROST_URL` as described in the+[provider guide](blockfrost.md). A custom endpoint may omit the project ID when+that service does not require it.++Create an encrypted wallet file once by importing your recovery phrase. Both the+phrase and password are entered at hidden terminal prompts:++```sh+cabal run cometa-secure-key-handler -- wallet.key+export COMETA_KEY_HANDLER_FILE="$PWD/wallet.key"+```++The setup example writes encrypted storage, reopens it and derives the account+public key to verify the password. It refuses to overwrite an existing file.+Transaction examples load that file and ask for its password when deriving public+keys and signing. Passwords are not supplied through environment variables.+The recovery phrase uses the empty BIP39 passphrase; the prompted password protects+the encrypted storage. Retain your recovery phrase separately.++| Variable | Meaning |+| --- | --- |+| `COMETA_KEY_HANDLER_FILE` | Path to your encrypted serialized BIP32 software handler. |+| `COMETA_INVALID_AFTER_SLOT` | Explicit upper validity slot on the configured network. Allow enough time for every stage's confirmation and indexing. |+| `COMETA_STAKE_INDEX` | Unhardened stake authority index; default `701`. |+| `COMETA_DREP_INDEX` | Unhardened DRep authority index; default `701`. |+| `COMETA_COLLATERAL` | Comma-separated `TXID#INDEX` references reserved as collateral; required for Plutus flows. |+| `COMETA_RESERVED_INPUTS` | Comma-separated `TXID#INDEX` references excluded from ordinary wallet selection in every stage. |++The funded payment address remains standard account zero, external key zero,+with stake key zero. Changing an authority index chooses a separate signing+credential; it does not change that wallet address. The signer includes the+payment path and both selected authority paths. No funded wallet, password or+private key is included in the example sources.++Every configured collateral reference must resolve. Collateral remains excluded+from ordinary selection independently of reserved inputs. Reserved inputs can+still be resolved explicitly, so this setting can preserve reusable reference+scripts for a later run. Use public identities and current chain queries to+choose unused stake and DRep credentials before starting a registration cycle.++## Payment and script workflows++`cometa-send-lovelace` also requires `COMETA_RECIPIENT` and `COMETA_LOVELACE`.+Its file includes both the payment plan and the build, sign, submit and+confirmation steps. Only wallet/provider setup and address-index polling are shared:++```{literalinclude} ../../examples/SendLovelace.hs+:language: haskell+:start-at: main ::+```++| Executable | Complete flow |+| --- | --- |+| `cometa-mint-burn-native-script` | Mint BerryOnyx and BerryRaspberry with metadata; burn Onyx. |+| `cometa-mint-burn-plutus-script` | Resolve `COMETA_MINT_REFERENCE`, mint both PlutusBerry assets with metadata; burn Onyx. |+| `cometa-spend-from-native-script` | Fund the source native script, confirm, then spend it with an explicit payout. |+| `cometa-spend-from-validator` | Fund the V3 validator and a reference-script output, then spend through that reference. |+| `cometa-deferred-self-index` | Fund the actual V3 self-index validator, then compute its redeemer from the balanced transaction. |+| `cometa-deferred-batch` | Fund two V3 order-pairing outputs, then settle them using their actual canonical input and payout indexes. |++The mint examples retain Raspberry, matching the C++ workflows. Their CIP-25+metadata uses the actual minting policy hash. `COMETA_MINT_REFERENCE` must carry+an executable Plutus policy suitable for the unit redeemer used by the recipe.+The validator and deferred workflows create their own funding outputs rather+than assuming that an old deployment still exists.++The validator-spending runner deliberately creates a fresh reference output+carrying the pinned native-example V3 program. The C++ runner instead resolves an+existing deployment. The new reference output holds 30 ADA under the wallet key+and can be retained for reuse or spent later. Deferred self-index and batch flows+use inline script witnesses, two-ADA locks and explicit payouts matching the C+++recipes; they do not create reference-script deployments.++The deferred self-index entrypoint uses the compiled source validator and the+deferred-redeemer recipe in the same file:++```{literalinclude} ../../examples/DeferredRedeemerSelfIndex.hs+:language: haskell+:start-at: main ::+```++Reference-script outputs can remain after their spending workflow finishes.+Reserve them before later independent runs if you intend to reuse them.++## Confirmation, indexing and recovery++Each stage prints and flushes its accepted transaction ID and confirmation result+before continuing. Confirmation and address indexing are separate observations:+the helper also waits until the created wallet outputs appear exactly and spent+wallet inputs disappear. Confirmation and indexing each have a bounded wait of+300 seconds. An indexing timeout stops dependent stages without resubmitting the+previous transaction. Submission is never blindly retried.++Keep the transaction journal when running a multi-stage flow. A later failure+does not undo an earlier confirmed transfer or registration. Inspect the recorded+IDs and current state before deciding how to finish a burn, spend or registration+cleanup. If a submission result is uncertain, resolve that outcome before+attempting another submission.++## Dijkstra workflows++`cometa-sub-transaction-batch` uses three encrypted wallets: the configured wallet+pays the batch fee, and `COMETA_BUYER_WALLET` / `COMETA_SELLER_WALLET` identify the+other two files. All three must have distinct addresses. It resolves real inputs,+builds and signs each local intent with that party's wallet, then builds, signs,+submits and confirms the enclosing batch with the batcher's wallet.++Set `COMETA_SWAP_POLICY` and `COMETA_SWAP_ASSET_NAME` to the token's policy ID and+hexadecimal asset name. `COMETA_BUYER_INPUT` must reference an output containing+exactly 100 ADA; `COMETA_SELLER_INPUT` must contain exactly 10 ADA and 5,000 units+of that token. No other assets may be present in those two outputs. The buyer+receives 50 ADA and 1,000 tokens, the seller receives 60 ADA and 4,000 tokens, and+the batcher supplies separate ordinary funds for the fee. Inputs must belong to+their respective wallets. This matches the three-party exchange in the native example.++Both batch and guarded-subtransaction examples check for protocol 12 or later+before submission. Networks running an earlier protocol cannot validate these+Dijkstra bodies. The offline tests retain synthetic swap fixtures to verify+signatures, local indexes and conservation independently of a live network.
@@ -0,0 +1,66 @@+# Connected staking and governance examples++The nine runners in `examples` port the corresponding Cometa.cpp+examples. Run a runner+with `--help` for configuration help. `--describe` prints public identities+for chain-state discovery; `--submit` executes the complete workflow on the+configured preprod wallet. Wallet storage comes from the shared configuration; passwords are requested+at hidden terminal prompts and are never embedded in these sources.++The shared wallet runner derives payment, stake and DRep authorities inside the+key-handler scope. Configurable stake and DRep indexes allow separate credentials+for each registration cycle. A fixed script has a fixed identity: changing a key+index does not change either script reward account. Current registration state,+active pools, proposal eligibility and constitution state must come from chain+queries; these examples do not infer them from a zero reward balance. The+provider's reward query alone does not establish whether an account is registered.++| Runner source | Confirmed stages | Required flow configuration |+| --- | --- | --- |+| `RewardAccountPubkey.hs` | Register, delegate stake and voting power; withdraw and unregister | `COMETA_POOL_ID_HEX` |+| `RewardAccountScript.hs` | Register and delegate the source V2 script; withdraw and unregister | `COMETA_POOL_ID_HEX` |+| `DeferredWithdrawZero.hs` | Register/delegate the source V3 script; deferred zero withdrawal and unregister | `COMETA_POOL_ID_HEX` |+| `DRepPubkey.hs` | Register DRep; register/delegate stake; clean up stake; clean up DRep | Fresh derived stake and DRep credentials |+| `DRepScript.hs` | The same four stages with the reference-sourced V3 DRep | `COMETA_GOVERNANCE_REFERENCE` |+| `VoteForProposalPubkey.hs` | Register DRep; vote Yes; unregister | `COMETA_GOVERNANCE_ACTION` |+| `VoteForProposalScript.hs` | The same three stages with the reference-sourced V3 DRep | `COMETA_GOVERNANCE_ACTION`, `COMETA_GOVERNANCE_REFERENCE` |+| `DonateToTreasury.hs` | Donate two ADA | Shared wallet configuration |+| `ProposeTreasuryWithdrawal.hs` | Submit a treasury withdrawal proposal with the actual constitution reference input | Treasury configuration below |++Input references and governance action IDs use `TXID#INDEX`. Pool IDs use their+28-byte hexadecimal hash. The script DRep and vote runners resolve the configured+reference and attach its V3 program inline, matching the C++ source. Treasury+uses the reference input itself and checks its script against+`COMETA_CONSTITUTION_SCRIPT_HASH`.++Treasury also requires `COMETA_CONSTITUTION_REFERENCE`,+`COMETA_TREASURY_RETURN_ACCOUNT` and `COMETA_TREASURY_WITHDRAWAL_LOVELACE`. The+last value is the proposed withdrawal amount; the C++ example uses+`1000000000000`. Submission pays transaction fees and locks the current governance+proposal deposit. It does not immediately withdraw the requested treasury funds.+Choose an account whose future reward-account access is available to the caller.+The policy hash and reference must match the current constitution rather than a+historical example deployment.++Each cycle queries current parameters and retains its registration deposits for+cleanup. It queries reward balances before cleanup where appropriate. The+withdraw-zero validator deliberately requests exactly zero and assumes the script+account has no outstanding rewards. It constructs its deferred redeemer from the+actual balanced inputs' sorted canonical indexes.++The shared provider journal records accepted transaction IDs and confirmation+results at every stage. A later failure stops dependent submissions and does not+roll back earlier confirmed registrations. Use the recorded transaction IDs,+public identities and registration deposit amounts to inspect and finish cleanup;+rerunning a cycle from its beginning against an existing registration is not a+recovery procedure. An uncertain submission result must be resolved before+resubmitting those signed bytes.++`test/ConnectedGovernance.hs` executes these recipes with the offline provider,+including native evaluation, signatures, conservation, treasury reference+preservation and constitution-hash rejection. That fixture does not emulate pool,+registration or governance ledger state. Live results must be recorded separately.++The two Dijkstra C++ examples use subtransactions and Plutus V4. Those workflows+are tested offline with the existing signed-batch and guarded-subtransaction+examples. They require a protocol supporting those ledger features; offline tests do not establish live-network support.
@@ -0,0 +1,39 @@+# Development++Follow `CODING_CONVENTIONS.md`. Configure the pinned native dependency using the+installation guide, then run:++```sh+cabal build all --ghc-options=-Werror+cabal test all --test-show-details=direct+cabal haddock all+cabal check+python3 -m unittest discover -s test/release -v+```++Use Ormolu 0.8.0.2 and HLint 3.8 with the repository configuration. Examples under+`examples/` are built by Cabal. Their shared support modules are exercised by the+offline workflow tests; fixture providers belong under `test/`.++## Native boundaries++Keep raw FFI declarations, marshaling and reference management internal. Preserve+exact integers, meaningful collection order, and original encodings where they+affect transaction identity. Public operations return structured domain errors.+Add boundary tests for validation and cancellation/failure tests for ownership.+Preserve test-vector licenses and provenance under `test/Fixtures`.++The BIP39 and PBKDF2 purity audits under `docs/development/` document the narrow+exceptions to effectful native calls. Revisit those audits when changing their+native dependency paths. Release and benchmark instructions are kept there too.++## Documentation++Public contracts live in Haddock and are uploaded to Hackage with the package.+The small Sphinx guide covers workflows without duplicating the API reference.+Read the Docs builds the guide from `main` using `.readthedocs.yaml`.++```sh+python3 -m pip install -r docs/requirements.txt+python3 -m sphinx -n -W --keep-going -b html docs/userguide docs/_build/html+```
@@ -0,0 +1,52 @@+# Validation and errors++Pure validation returns `Either Error a`. Combine related inputs in ordinary+`do` notation; once validated, reuse the resulting values.++```haskell+import qualified Cometa.AssetId as AssetId+import qualified Cometa.AssetName as AssetName+import Cometa.Error (Error)+import qualified Cometa.PolicyId as PolicyId+import Data.Text (Text)++assetFromText :: Text -> Text -> Either Error AssetId.AssetId+assetFromText policyText nameText = do+ policy <- PolicyId.fromHex policyText+ name <- AssetName.fromText nameText+ pure (AssetId.Native policy name)+```++Native and network operations return `IO (Either Error a)`. Use a `case` for a+single operation. For several dependent operations, `ExceptT` gives a straight+sequence that stops at the first error:++```haskell+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.TransactionId as TxId+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)++signAndIdentify :: Signer.Signer -> Tx.Transaction+ -> IO (Either Error (Tx.Transaction, TxId.TransactionId))+signAndIdentify signer unsigned = runExceptT $ do+ witnesses <- ExceptT (Signer.signTransaction signer unsigned)+ signed <- except (Tx.addWitnesses witnesses unsigned)+ identifier <- ExceptT (Tx.transactionId signed)+ pure (signed, identifier)+```++`except` lifts a pure `Either` into the sequence; it does not throw an IO+exception. Keep pure validation in its own function when several fields need+checking. Handle the final `Either` once in the application, and leave cancellation+and unexpected IO exceptions to the usual IO exception machinery.++This follows the separation used by+[Aeson's pure and file decoders](https://hackage-content.haskell.org/package/aeson-2.2.3.0/docs/Data-Aeson.html)+and the standard+[transformers error transformer](https://hackage-content.haskell.org/package/transformers-0.6.1.2/docs/Control-Monad-Trans-Except.html).+There is no Cometa-specific error monad or requirement to use transformers.++[Cryptonite 0.30](https://hackage-content.haskell.org/package/cryptonite-0.30/docs/Crypto-Error.html)+also represents expected validation failures as values, using its `CryptoFailable`+type. Cometa uses standard `Either Error` so callers need no extra conversion.
@@ -0,0 +1,20 @@+# Cometa.hs++Build, sign and inspect Cardano transactions with Haskell values and explicit+`IO`. The [Hackage API reference](https://hackage.haskell.org/package/cometa-0.1.0.0/candidate/docs/index.html)+documents the modules, types and functions. This guide covers installation and+complete workflows.++```{toctree}+:maxdepth: 2++installation+transaction-building+error-handling+blockfrost+providers+connected-examples+connected-governance+api-reference+development+```
@@ -0,0 +1,68 @@+# Installation++Cometa.hs has not been released on Hackage. Build the checked-out source with+GHC and Cabal. Consult the repository's `cabal.project` and package description+for its current compiler and dependency bounds; a platform is supported only+when the corresponding CI build has passed.++## Build a checkout++The default build compiles the pinned cardano-c source as the `cardano-c-clib`+Cabal dependency. You need a C toolchain as well as GHC, Cabal and Python 3 to+prepare a Git checkout. Obtain cardano-c at the revision recorded in+`native/cardano-c.ref`, then run these commands from the Cometa.hs directory:++```sh+python3 tools/package-native.py /path/to/pinned/cardano-c+cabal update+cabal build all+cabal test all --test-show-details=direct+```++The preparation command creates `.native/cardano-c-clib`, which the repository's+Cabal project includes automatically. No separate cardano-c installation or+include/library search flags are needed for this configuration.++The intended Hackage distribution uses a native source package dependency so+Cabal can build it automatically. Both packages are currently available as Hackage candidates; they are not yet+in the main package index. The checkout instructions above build the current+source.++## Use an installed cardano-c library++To use an existing native installation instead, enable `system-cardano-c` and+supply its include and library directories when necessary:++```sh+cabal build all -fsystem-cardano-c --extra-include-dirs=/path/to/cardano-c/include --extra-lib-dirs=/path/to/cardano-c/lib+```++Use the revision recorded in `native/cardano-c.ref`. Headers and library must+come from the same compatible installation; the include directory must contain+`cardano/cardano.h`. Keep the flag and native paths when running tests or building+Haddock. The repository's `tools/build-native.py` helper selects this configuration+when preparing an installed native library for development.++For a shared installation, make the library available to the runtime loader+through the installation location or the environment's search path+(`LD_LIBRARY_PATH` on Linux, `DYLD_LIBRARY_PATH` on macOS, or `PATH` on Windows).+Static installations may need additional native dependencies at link time;+follow the matching cardano-c build configuration.++If headers cannot be found, check the include prefix. If linking fails, check the+library directory and architecture. If a built program fails to load cardano-c,+check that the runtime search path resolves the library used during compilation.++## Use in an application++Until a release is available, add the checked-out Cometa.hs directory to your+application's Cabal project alongside its prepared `.native/cardano-c-clib`+directory, and declare `cometa` in the application's `build-depends`. Use explicit+source revisions for reproducible builds. See+the [API reference](api-reference.md) for declarations and local Haddock generation.++## Blockfrost++`Cometa.Provider.Blockfrost` is included in `cometa`; no additional package or+library component is required. It uses the same transaction values and+`Provider` interface as application-defined providers.
@@ -0,0 +1,67 @@+# Choose a provider++`Cometa.Provider.Koios`, `Cometa.Provider.Kupmios`, and `Cometa.Provider.Hydra`+implement the same scoped `Cometa.Provider` interface as Blockfrost.++```haskell+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Koios as Koios+import qualified Cometa.Provider.Kupmios as Kupmios+import qualified Cometa.Provider.Hydra as Hydra++-- Public Koios endpoint, with no API credential.+result <- Koios.withProvider (Koios.defaultConfig Koios.Preprod Nothing) $+ Provider.protocolParameters++-- Explicit local Kupo and Ogmios endpoints.+let kupmios = Kupmios.defaultConfig Kupmios.Preprod+ "http://localhost:1442" "http://localhost:1337"++-- An already-open Hydra Head.+let hydra = Hydra.defaultConfig Hydra.Preprod "http://localhost:4001"+```++Enable `OverloadedStrings` when using these endpoint literals. Supply credentials+through `mkApiKey`; validated credentials have no `Show` instance. Koios and Hydra+use bearer authentication. Kupmios has separate `kupoApiKey` and `ogmiosApiKey`+fields so credentials cannot accidentally cross endpoints. All configurations+allow request timeouts and polling intervals from 1 to 60,000 milliseconds;+the defaults are 30,000 and 1,000 milliseconds respectively. Custom endpoints+retain path prefixes and base query parameters, with operation parameters taking+precedence. Redirects, URL user information, and fragments are rejected.++`withProvider` owns the connection pools. Scope exit drains active requests;+asynchronous cancellation propagates after cleanup. Escaped operations return+`RuntimeClosed`, including operations that would otherwise need no HTTP request.++All three providers require an explicit network. They never infer it from an+endpoint URL, read credentials implicitly, or retry transaction submissions.+Protocol prices and monetary quantities retain their exact values. HTTP failures+remain errors rather than empty UTxO sets. Responses are limited to 8 MiB.++Koios uses its extended UTxO endpoints and Ogmios v6 HTTP service. Address, asset,+and input queries follow offset pages of 100, reject duplicate output identities,+and stop with an error after 10,000 pages. Separate requests are not an atomic+ledger snapshot. Kupmios combines Kupo 2.x with Ogmios v6 over HTTP; both endpoints+must use the selected network. Kupo must index the addresses and assets being+queried and retain history needed for confirmation. Large match sets exceeding+the response limit fail explicitly.++Hydra connects to an existing Conway Head over HTTP. It reads the Head's actual+protocol parameters, including its fee settings, and submits to `/transaction`+on layer 2. It does not open, commit to, close, or fan out a Head, and never uses+`/cardano-transaction` to submit to layer 1. A `202 SubmitTxSubmitted` response+acknowledges submission without claiming confirmation.++Hydra confirmation polls `/snapshot` for the transaction's CBOR in the latest+confirmed snapshot. It validates the transaction ID from those bytes. This API+cannot recover transactions that have already disappeared from the latest+snapshot's transaction list; a timeout means confirmation was not observed.+A committed L1 UTxO is not proof of an L2 transaction. Applications requiring a+complete history should consume and retain Hydra's `SnapshotConfirmed` event+stream. Snapshot confirmation is not L1 settlement.++Hydra has no remote evaluation endpoint or staking rewards. These operations+fail explicitly. Use a local script evaluator configured with the Head's ledger+parameters. Datum lookup searches inline datums in the current confirmed UTxO+set and cannot recover spent or hash-only datum bytes.
@@ -0,0 +1,73 @@+# Build a transaction++Assemble a `Cometa.Transaction.Plan` from owned values, then call+`Cometa.Transaction.Builder.build` once to obtain an unsigned transaction.+Payments keep their order and multiplicity. Repeated mint instructions add their+quantities; equal and opposite quantities cancel. Validity bounds intersect.+Conflicting spending requirements, metadata labels or reward withdrawals return+an error at the build boundary.++The builder takes complete protocol parameters, slot configuration, a change+address and resolved wallet outputs. These snapshots must describe the same+ledger state. You can obtain them through your provider, cache an appropriate+snapshot, or supply fixtures for offline tests.++```haskell+import Cometa.Address (Address)+import Cometa.Error (Error)+import qualified Cometa.Transaction as Tx+import Cometa.Transaction.Output (Output)+import Data.Word (Word64)+import qualified Cometa.Provider as Provider+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)++buildPayment :: Provider.Provider -> Address -> Output -> Word64+ -> IO (Either Error Tx.Transaction)+buildPayment provider wallet output expiry = runExceptT $ do+ parameters <- ExceptT (Provider.protocolParameters provider)+ available <- ExceptT (Provider.utxosAt provider wallet)+ let config = (Builder.defaultConfig parameters Slot.preview wallet)+ {Builder.availableUtxos = available}+ plan = Plan.payTo output <> Plan.validUntil expiry+ ExceptT (Builder.build config plan)+```++`Slot.preview` in this example selects Preview time conversion. Choose the+configuration corresponding to your network. Supply `expiry` as an absolute+future slot on that network, allowing time to sign, submit and confirm the+transaction. The builder does not query the current slot. The change address+determines the transaction body's network tag. The builder calculates fees and change and uses+its built-in selector and evaluator by default. It returns errors for insufficient+funds, invalid requirements or balancing failures. The result has no key+signatures; use the [signing workflow](api-reference.md) and submit it+explicitly through your provider.++For custom policies set `Builder.selector` to `Just selector` or+`Builder.evaluator` to `Just evaluator`. These are ordinary records of functions;+see [selection](api-reference.md) and [evaluation](api-reference.md).+A provider-backed evaluator can call `Provider.evaluateTransaction` within its+record. Callbacks can run repeatedly while balancing converges. Expected errors+are returned unchanged; exceptions propagate after cleanup, including ordinary+asynchronous cancellation.++`Plan.spend` takes a resolved key-controlled UTxO. For script spends,+`Plan.spendWith` takes the resolved UTxO, optional redeemer argument and optional+datum witness. Add script witnesses with `Plan.attachScript`, or supply reference+inputs with `Plan.referenceInput`. Supply eligible collateral through+`Builder.collateralUtxos`; `Builder.collateralChangeAddress` optionally chooses+its return destination. Evaluation receives the complete candidate transaction+and resolved inputs and provides budgets for its existing redeemers.++Other plan operations attach metadata, datums, staking certificates, reward+withdrawals and required key signers. `mintWithRedeemer`,+`certificateWithRedeemer` and `withdrawWithRedeemer` add Plutus arguments to the+corresponding operations. The builder checks signed 64-bit quantity+bounds before balancing, including aggregate sources and targets. Wallet and+collateral lists require unique input references. A mandatory spend may also+appear in the wallet snapshot; it is counted once. Complete transactions remain+subject to ledger rules and the state against which they are submitted.++See the {download}`payment example <../../examples/SendLovelace.hs>` for a complete connected workflow.
@@ -0,0 +1,50 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Bip32.PublicKey as Public+import qualified Cometa.Crypto.Bip39 as Bip39+import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.KeyHandler.Software as Software+import qualified Cometa.NetworkId as Network+-- Standard library and error handling.+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)+import qualified Data.Text.IO as Text+import System.Exit (die)++-- Public demonstration material. Never send funds to this address.+main :: IO ()+main = do+ let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"+ entropy = Bip39.fromText phrase >>= Bip39.exportEntropy+ password = "public demonstration password"+ result <- case entropy of+ Left failure -> pure (Left failure)+ Right bytes -> Software.withEntropy bytes password (pure password) $ \handler -> runExceptT $ do+ let account = Path.standardAccountPath minBound+ paymentPath = Path.derivationPath account Path.externalRole minBound+ stakePath = Path.derivationPath account Path.stakingRole minBound+ public <- ExceptT (Software.accountPublicKey handler account)+ paymentKey <- ExceptT (Public.derive public (Path.relativeIndices paymentPath))+ stakeKey <- ExceptT (Public.derive public (Path.relativeIndices stakePath))+ payment <- ExceptT (Credential.fromPublicKey (Public.toEd25519 paymentKey))+ stake <- ExceptT (Credential.fromPublicKey (Public.toEd25519 stakeKey))+ pure (Address.ShelleyAddress (Shelley.base Network.testnet payment stake))+ either (die . show) (Text.putStrLn . Address.toText) result
@@ -0,0 +1,143 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DRepPubkey (main, drepKey) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..), DRep, Stake)+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "DRepPubkey" (Inputs.describe Nothing) $ \wallet ->+ drepKey (Support.context wallet) (Support.drepCredential wallet) (Support.stakeCredential wallet)++-- | Register a DRep, delegate a fresh stake key, then clean up both registrations.+drepKey ::+ Workflow.Context ->+ Credential DRep ->+ Credential Stake ->+ IO (Either Error [Transaction])+drepKey context drep stake = runExceptT $ do+ (stakeAmount, drepAmount) <- ExceptT (deposits context)+ anchor <- except representativeAnchor++ let certify = Plan.certificate++ registered <- submitPlan context (certify (Certificate.RegisterDRep drep drepAmount (Just anchor)))++ let delegation =+ Plan.certificate (Certificate.Registration stake stakeAmount)+ <> Plan.certificate (Certificate.VoteDelegation stake (DRep.DRepCredential drep))++ delegated <- submitPlan context delegation++ let account = Reward.fromCredential (Workflow.network context) stake+ rewards <- ExceptT (Provider.rewardBalance (Workflow.provider context) account)++ cleanedStake <- submitPlan context (Plan.withdraw account rewards <> Plan.certificate (Certificate.Unregistration stake stakeAmount))++ cleanedDRep <- submitPlan context (certify (Certificate.UnregisterDRep drep drepAmount))++ pure [registered, delegated, cleanedStake, cleanedDRep]++deposits :: Workflow.Context -> IO (Either Error (Word64, Word64))+deposits context = runExceptT $ do+ parameters <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ drepAmount <- case Parameters.parameterDrepDeposit parameters of+ Just amount -> pure amount+ Nothing -> throwE (InvalidBuildingRequest "DRep deposit is unavailable in the current protocol parameters")+ pure (Parameters.parameterKeyDeposit parameters, drepAmount)++representativeAnchor :: Either Error Anchor.Anchor+representativeAnchor =+ makeAnchor+ "https://storage.googleapis.com/biglup/Angel_Castillo.jsonld"+ "26ce09df4e6f64fe5cf248968ab78f4b8a0092580c234d78f68c079c0fce34f0"++makeAnchor :: Text -> Text -> Either Error Anchor.Anchor+makeAnchor url hash = Anchor.Anchor <$> Anchor.mkUrl url <*> (Blake2b.fromHex hash >>= Anchor.dataHashFromBytes . Blake2b.toBytes)++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,159 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DRepScript (main, drepScript) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..), Stake)+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "DRepScript" (Inputs.describe (Just "COMETA_GOVERNANCE_REFERENCE")) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ reference <- ExceptT (Support.resolveReference context "COMETA_GOVERNANCE_REFERENCE")+ ExceptT (drepScript context reference (Support.stakeCredential wallet))++-- | Use the configured V3 script as the DRep authority for registration and cleanup.+drepScript :: Workflow.Context -> Utxo -> Credential Stake -> IO (Either Error [Transaction])+drepScript context reference stake = runExceptT $ do+ script <- except (governanceScript reference)+ hash <- ExceptT (Script.hash script)+ (stakeAmount, drepAmount) <- ExceptT (deposits context)+ anchor <- except representativeAnchor++ let drep = ScriptCredential hash+ certify certificate = Plan.attachScript script <> Plan.certificateWithRedeemer certificate voidArgument++ registered <- submitPlan context (certify (Certificate.RegisterDRep drep drepAmount (Just anchor)))++ let delegation =+ Plan.certificate (Certificate.Registration stake stakeAmount)+ <> Plan.certificate (Certificate.VoteDelegation stake (DRep.DRepCredential drep))++ delegated <- submitPlan context delegation++ let account = Reward.fromCredential (Workflow.network context) stake+ rewards <- ExceptT (Provider.rewardBalance (Workflow.provider context) account)++ cleanedStake <- submitPlan context (Plan.withdraw account rewards <> Plan.certificate (Certificate.Unregistration stake stakeAmount))++ cleanedDRep <- submitPlan context (certify (Certificate.UnregisterDRep drep drepAmount))++ pure [registered, delegated, cleanedStake, cleanedDRep]++deposits :: Workflow.Context -> IO (Either Error (Word64, Word64))+deposits context = runExceptT $ do+ parameters <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ drepAmount <- case Parameters.parameterDrepDeposit parameters of+ Just amount -> pure amount+ Nothing -> throwE (InvalidBuildingRequest "DRep deposit is unavailable in the current protocol parameters")+ pure (Parameters.parameterKeyDeposit parameters, drepAmount)++governanceScript :: Utxo -> Either Error Script+governanceScript reference = case Output.referenceScript (Utxo.output reference) of+ Just script@(Script.Plutus compiled) | Plutus.version compiled == Plutus.V3 -> Right script+ _ -> Left (InvalidBuildingRequest "Expected a resolved Plutus V3 governance reference script")++representativeAnchor :: Either Error Anchor.Anchor+representativeAnchor =+ makeAnchor+ "https://storage.googleapis.com/biglup/Angel_Castillo.jsonld"+ "26ce09df4e6f64fe5cf248968ab78f4b8a0092580c234d78f68c079c0fce34f0"++makeAnchor :: Text -> Text -> Either Error Anchor.Anchor+makeAnchor url hash = Anchor.Anchor <$> Anchor.mkUrl url <*> (Blake2b.fromHex hash >>= Anchor.dataHashFromBytes . Blake2b.toBytes)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,144 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DeferredRedeemerBatch (main, runDeferredBatch) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "DeferredRedeemerBatch" deferredBatch++deferredBatch :: WalletContext -> IO (Either Error [Tx.Transaction])+deferredBatch wallet = runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.orderPairing+ ExceptT (runDeferredBatch (Support.context wallet) script)++-- | Fund two orders, then resolve their input and payout indexes during balancing.+runDeferredBatch :: Workflow.Context -> Script -> IO (Either Error [Tx.Transaction])+runDeferredBatch context script = runExceptT $ do+ (first, funded) <- ExceptT (fundInlineScript context script)+ -- Each order is funded independently; both confirmations precede settlement.+ (second, fundedAgain) <- ExceptT (fundInlineScript context script)+ firstPayout <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 1200000) Datum.NoDatum Nothing)+ secondPayout <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 1500000) Datum.NoDatum Nothing)++ let callback input minimumAmount draft _ = do+ own <- maybe (Left (InvalidBuildingRequest "Order input disappeared")) Right (Indices.findInput (Utxo.input input) draft)+ payout <-+ maybe (Left (InvalidBuildingRequest "Order payout disappeared")) Right $+ Indices.findOutput (Workflow.wallet context) minimumAmount draft+ pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger own), Data.Integer (toInteger payout)]))+ plan =+ Plan.payTo firstPayout+ <> Plan.payTo secondPayout+ <> Plan.spendWithDeferredRedeemer first (callback first 1200000) Nothing+ <> Plan.spendWithDeferredRedeemer second (callback second 1500000) Nothing+ <> Plan.attachScript script++ settled <- submitPlan context plan++ pure [funded, fundedAgain, settled]++fundInlineScript :: Workflow.Context -> Script -> IO (Either Error (Utxo, Tx.Transaction))+fundInlineScript context script = runExceptT $ do+ digest <- ExceptT (Script.hash script)++ let destination = Address.ShelleyAddress (Shelley.enterprise (Workflow.network context) (Credential.ScriptCredential digest))+ output <- except (Output.mkOutput destination (Value.lovelace 2000000) (Datum.InlineDatum voidArgument) Nothing)++ funded <- submitPlan context (Plan.payTo output)+ locked <- ExceptT (Workflow.outputAt funded 0)+ pure (locked, funded)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,133 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DeferredRedeemerSelfIndex (main, runDeferredSelf) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "DeferredRedeemerSelfIndex" deferredSelf++deferredSelf :: WalletContext -> IO (Either Error [Tx.Transaction])+deferredSelf wallet = runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.selfIndex+ ExceptT (runDeferredSelf (Support.context wallet) script)++-- | Compute the spending redeemer from the final canonical input position.+runDeferredSelf :: Workflow.Context -> Script -> IO (Either Error [Tx.Transaction])+runDeferredSelf context script = runExceptT $ do+ (locked, funded) <- ExceptT (fundInlineScript context script)+ payout <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 1000000) Datum.NoDatum Nothing)++ let callback draft _ = do+ position <- maybe (Left (InvalidBuildingRequest "Deferred input disappeared")) Right (Indices.findInput (Utxo.input locked) draft)+ pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger position)]))+ plan = Plan.payTo payout <> Plan.spendWithDeferredRedeemer locked callback Nothing <> Plan.attachScript script++ spent <- submitPlan context plan++ pure [funded, spent]++fundInlineScript :: Workflow.Context -> Script -> IO (Either Error (Utxo, Tx.Transaction))+fundInlineScript context script = runExceptT $ do+ digest <- ExceptT (Script.hash script)++ let destination = Address.ShelleyAddress (Shelley.enterprise (Workflow.network context) (Credential.ScriptCredential digest))+ output <- except (Output.mkOutput destination (Value.lovelace 2000000) (Datum.InlineDatum voidArgument) Nothing)++ funded <- submitPlan context (Plan.payTo output)+ locked <- ExceptT (Workflow.outputAt funded 0)+ pure (locked, funded)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,147 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DeferredWithdrawZero (main, withdrawZero) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..), KeyHash, Stake, StakePool)+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Indices as Indices+import Cometa.Transaction.Plan (Plan)+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.List (sort)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "DeferredWithdrawZero" (Inputs.describe Nothing) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ pool <- ExceptT Inputs.poolId+ ExceptT (withdrawZero context pool)++withdrawZero :: Workflow.Context -> KeyHash StakePool -> IO (Either Error [Transaction])+withdrawZero context pool = runExceptT $ do+ script <- ExceptT (fmap (fmap Script.Plutus) Scripts.withdrawZero)+ hash <- ExceptT (Script.hash script)+ deposit <- ExceptT (stakeDeposit context)+ ExceptT (runWithdrawZero context (ScriptCredential hash) script pool deposit)++stakeDeposit :: Workflow.Context -> IO (Either Error Word64)+stakeDeposit context = fmap (fmap Parameters.parameterKeyDeposit) (Provider.protocolParameters (Workflow.provider context))++-- | Register and delegate, then withdraw zero with final input indexes and deregister.+runWithdrawZero ::+ Workflow.Context ->+ Credential Stake ->+ Script ->+ KeyHash StakePool ->+ Word64 ->+ IO (Either Error [Tx.Transaction])+runWithdrawZero context credential script pool deposit = runExceptT $ do+ let account = Reward.fromCredential (Workflow.network context) credential+ cert = authorize (Just script)++ registered <- submitPlan context (cert (Certificate.Registration credential deposit) <> cert (Certificate.StakeDelegation credential pool))++ let callback draft inputs = do+ let position input =+ maybe (Left (InvalidBuildingRequest "Forwarded input disappeared")) Right $+ Indices.findInput (Utxo.input input) draft++ positions <- traverse position inputs+ pure (Data.fromData (Data.Constr 0 [Data.List (map (Data.Integer . toInteger) (sort positions))]))+ plan = Plan.attachScript script <> Plan.withdrawWithDeferredRedeemer account 0 callback <> cert (Certificate.Unregistration credential deposit)++ cleaned <- submitPlan context plan++ pure [registered, cleaned]++authorize :: Maybe Script -> Certificate.Certificate -> Plan+authorize Nothing = Plan.certificate+authorize (Just script) = \certificate -> Plan.attachScript script <> Plan.certificateWithRedeemer certificate voidArgument++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,89 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module DonateToTreasury (main, donate) where++import Cometa.Error (Error (..))+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "DonateToTreasury" (donate . Support.context)++-- | Submit a two-ADA donation and wait for its confirmation.+donate :: Workflow.Context -> IO (Either Error Tx.Transaction)+donate ctx = runExceptT (submitPlan ctx (Plan.donate 2000000))++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,161 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import Cometa.Address (Address)+import Cometa.AssetId (AssetId (Native))+import qualified Cometa.AssetName as AssetName+import Cometa.Credential (ScriptHash)+import Cometa.Error (Error (..))+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Provider as Provider+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+-- Shared example setup.+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "MintBurnNativeScript" $ \wallet ->+ mintBerries wallet nativeScript Nothing ""++-- | Mint both named assets with CIP-25 metadata, confirm, then burn Onyx.+mintBerries ::+ WalletContext ->+ Script.Script ->+ Maybe Utxo.Utxo ->+ Text ->+ IO (Either Error [Tx.Transaction])+mintBerries wallet script reference prefix = runExceptT $ do+ digest <- ExceptT (Script.hash script)+ (mintPlan, burnPlan) <- except (berryPlans (Workflow.wallet (Support.context wallet)) script reference prefix digest)++ minted <- submitPlan (Support.context wallet) mintPlan++ burned <- submitPlan (Support.context wallet) burnPlan++ pure [minted, burned]++-- | Construct mint and burn plans using the actual policy hash in the metadata.+berryPlans ::+ Address ->+ Script.Script ->+ Maybe Utxo.Utxo ->+ Text ->+ ScriptHash ->+ Either Error (Plan.Plan, Plan.Plan)+berryPlans recipient script reference prefix digest = do+ onyxName <- AssetName.fromText (prefix <> "BerryOnyx")+ raspberryName <- AssetName.fromText (prefix <> "BerryRaspberry")++ let policy = Policy.fromScriptHash digest+ onyx = Native policy onyxName+ raspberry = Native policy raspberryName+ source = maybe (Plan.attachScript script) Plan.referenceInput reference+ mint asset amount = case script of+ Script.Native _ -> Plan.mint asset amount+ Script.Plutus _ -> Plan.mintWithRedeemer asset amount voidArgument+ text = Metadata.mkText+ pair key value = (,) <$> text key <*> text value+ record color image name = Metadata.map <$> traverse (uncurry pair) [("color", color), ("image", image), ("name", name)]+ onyxMetadata <- record "#0F0F0F" "ipfs://ipfs/QmS7w3Q5oVL9NE1gJnsMVPp6fcxia1e38cRT5pE5mmxawL" (prefix <> "Berry Onyx")+ raspberryMetadata <- record "#E30B5D" "ipfs://ipfs/QmXjegt568JqSUpAz9phxbXq5noWE3AeymZMUP43Ej2DRZ" (prefix <> "Berry Raspberry")+ policyKey <- text (Policy.toHex policy)+ onyxKey <- text (prefix <> "BerryOnyx")+ raspberryKey <- text (prefix <> "BerryRaspberry")++ let value = Value.lovelace 2000000 <> Value.fromList [(onyx, 1), (raspberry, 1)]+ output <- Output.mkOutput recipient value Datum.NoDatum Nothing++ let metadata = Metadata.map [(policyKey, Metadata.map [(onyxKey, onyxMetadata), (raspberryKey, raspberryMetadata)])]+ pure+ ( source <> mint onyx 1 <> mint raspberry 1 <> Plan.payTo output <> Plan.metadata 721 metadata,+ source <> mint onyx (-1)+ )++nativeScript :: Script.Script+nativeScript = Script.Native (NativeScript.allOf [NativeScript.invalidAfter 1001655683199])++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,164 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import Cometa.Address (Address)+import Cometa.AssetId (AssetId (Native))+import qualified Cometa.AssetName as AssetName+import Cometa.Credential (ScriptHash)+import Cometa.Error (Error (..))+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Provider as Provider+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+-- Shared example setup.+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext, resolveReference)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "MintBurnPlutusScript" mintPlutus++mintPlutus :: WalletContext -> IO (Either Error [Tx.Transaction])+mintPlutus wallet = runExceptT $ do+ reference <- ExceptT (resolveReference (Support.context wallet) "COMETA_MINT_REFERENCE")+ script <- except $ case Output.referenceScript (Utxo.output reference) of+ Just value@(Script.Plutus _) -> Right value+ _ -> Left (InvalidBuildingRequest "Minting reference must carry an executable Plutus script")+ ExceptT (mintBerries wallet script (Just reference) "Plutus")++-- | Mint both named assets with CIP-25 metadata, confirm, then burn Onyx.+mintBerries ::+ WalletContext ->+ Script.Script ->+ Maybe Utxo.Utxo ->+ Text ->+ IO (Either Error [Tx.Transaction])+mintBerries wallet script reference prefix = runExceptT $ do+ digest <- ExceptT (Script.hash script)+ (mintPlan, burnPlan) <- except (berryPlans (Workflow.wallet (Support.context wallet)) script reference prefix digest)++ minted <- submitPlan (Support.context wallet) mintPlan++ burned <- submitPlan (Support.context wallet) burnPlan++ pure [minted, burned]++-- | Construct mint and burn plans using the actual policy hash in the metadata.+berryPlans ::+ Address ->+ Script.Script ->+ Maybe Utxo.Utxo ->+ Text ->+ ScriptHash ->+ Either Error (Plan.Plan, Plan.Plan)+berryPlans recipient script reference prefix digest = do+ onyxName <- AssetName.fromText (prefix <> "BerryOnyx")+ raspberryName <- AssetName.fromText (prefix <> "BerryRaspberry")++ let policy = Policy.fromScriptHash digest+ onyx = Native policy onyxName+ raspberry = Native policy raspberryName+ source = maybe (Plan.attachScript script) Plan.referenceInput reference+ mint asset amount = case script of+ Script.Native _ -> Plan.mint asset amount+ Script.Plutus _ -> Plan.mintWithRedeemer asset amount voidArgument+ text = Metadata.mkText+ pair key value = (,) <$> text key <*> text value+ record color image name = Metadata.map <$> traverse (uncurry pair) [("color", color), ("image", image), ("name", name)]+ onyxMetadata <- record "#0F0F0F" "ipfs://ipfs/QmS7w3Q5oVL9NE1gJnsMVPp6fcxia1e38cRT5pE5mmxawL" (prefix <> "Berry Onyx")+ raspberryMetadata <- record "#E30B5D" "ipfs://ipfs/QmXjegt568JqSUpAz9phxbXq5noWE3AeymZMUP43Ej2DRZ" (prefix <> "Berry Raspberry")+ policyKey <- text (Policy.toHex policy)+ onyxKey <- text (prefix <> "BerryOnyx")+ raspberryKey <- text (prefix <> "BerryRaspberry")++ let value = Value.lovelace 2000000 <> Value.fromList [(onyx, 1), (raspberry, 1)]+ output <- Output.mkOutput recipient value Datum.NoDatum Nothing++ let metadata = Metadata.map [(policyKey, Metadata.map [(onyxKey, onyxMetadata), (raspberryKey, raspberryMetadata)])]+ pure+ ( source <> mint onyx 1 <> mint raspberry 1 <> Plan.payTo output <> Plan.metadata 721 metadata,+ source <> mint onyx (-1)+ )++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,174 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module PlutusV4GuardedSubTransaction (main, runGuardedSub, runSignedBatch) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction.Builder as SubBuilder+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Plan (Plan)+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "PlutusV4GuardedSubTransaction" guardedSub++guardedSub :: WalletContext -> IO (Either Error [Tx.Transaction])+guardedSub wallet = runExceptT $ do+ params <- ExceptT (Provider.protocolParameters (Workflow.provider (Support.context wallet)))++ let Version.ProtocolVersion major _ = Parameters.parameterProtocolVersion params+ unless (major >= 12) (throwE (InvalidBuildingRequest "Guarded subtransactions require protocol 12 or later"))+ validator <- Script.Plutus <$> ExceptT Scripts.v4Validator+ guard <- Script.Plutus <$> ExceptT Scripts.v4Guard+ ExceptT (runGuardedSub (Support.context wallet) validator guard (Support.signSubTransaction wallet))++-- | Fund the validator and submit a signed V4 intent inside a guarded batch.+runGuardedSub ::+ Workflow.Context ->+ Script ->+ Script ->+ (SubTransaction -> IO (Either Error SubTransaction)) ->+ IO (Either Error [Tx.Transaction])+runGuardedSub context validator guard signLocal = runExceptT $ do+ (locked, reference, funded) <- ExceptT (fundScript context validator 10000000)+ params <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ digest <- ExceptT (Script.hash guard)+ output <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 2000000) Datum.NoDatum Nothing)++ let source = maybe (SubPlan.attachScript validator) SubPlan.referenceInput reference+ plan =+ SubPlan.spendWith locked (Just voidArgument) Nothing+ <> SubPlan.payTo output+ <> source+ <> SubPlan.attachScript guard+ <> SubPlan.guardWithRedeemer digest voidArgument+ bodyNetwork = if Workflow.network context == Network.mainnet then Fields.Mainnet else Fields.Testnet+ local <- ExceptT (SubBuilder.build (SubBuilder.Config params (Workflow.slots context) bodyNetwork) plan)+ signed <- ExceptT (signLocal local)+ batch <- ExceptT (runSignedBatch context [(signed, SubPlan.resolvedInputs plan)] mempty)++ pure [funded, batch]++-- | Create the locked output and, for Plutus, a reusable reference-script output.+fundScript ::+ Workflow.Context ->+ Script ->+ Word64 ->+ IO (Either Error (Utxo, Maybe Utxo, Tx.Transaction))+fundScript context script amount = runExceptT $ do+ digest <- ExceptT (Script.hash script)++ let destination = Address.ShelleyAddress (Shelley.enterprise (Workflow.network context) (Credential.ScriptCredential digest))+ datum = case script of Script.Native _ -> Datum.NoDatum; Script.Plutus _ -> Datum.InlineDatum voidArgument+ output <- except (Output.mkOutput destination (Value.lovelace (toInteger amount)) datum Nothing)+ reference <- case script of+ Script.Native _ -> pure Nothing+ Script.Plutus _ -> Just <$> except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just script))++ funded <- submitPlan context (Plan.payTo output <> maybe mempty Plan.payTo reference)+ locked <- ExceptT (Workflow.outputAt funded 0)+ referenceUtxo <- traverse (const (ExceptT (Workflow.outputAt funded 1))) reference+ pure (locked, referenceUtxo, funded)++runSignedBatch ::+ Workflow.Context ->+ [(SubTransaction, [Utxo])] ->+ Plan ->+ IO (Either Error Tx.Transaction)+runSignedBatch context intents parent = runExceptT $ submitPlan context (foldMap (uncurry Plan.attachSubTransaction) intents <> parent)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,143 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module ProposeTreasuryWithdrawal (main, treasury) where++import qualified Cometa.Address.Reward as Reward+import Cometa.Credential (ScriptHash)+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main =+ Support.entrypointWithDescription+ "ProposeTreasuryWithdrawal"+ (Inputs.describe (Just "COMETA_CONSTITUTION_REFERENCE"))+ $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ reference <- ExceptT (Support.resolveReference context "COMETA_CONSTITUTION_REFERENCE")+ (reward, hash, amount) <- ExceptT Inputs.treasurySettings+ ExceptT (treasury context reward reference hash amount)++-- | Propose a withdrawal using the verified constitution reference; this is not a transfer.+treasury ::+ Workflow.Context ->+ Reward.RewardAddress ->+ Utxo ->+ ScriptHash ->+ Word64 ->+ IO (Either Error Transaction)+treasury context reward reference expectedHash amount = runExceptT $ do+ script <- except (governanceScript reference)+ actualHash <- ExceptT (Script.hash script)+ unless (actualHash == expectedHash) (throwE (InvalidBuildingRequest "Constitution reference script hash mismatch"))+ anchor <- except treasuryAnchor+ withdrawals <- except (Action.withdrawalsFromList [(reward, amount)])++ let proposal =+ Plan.referenceInput reference+ <> Plan.propose reward (Action.TreasuryWithdrawals withdrawals (Just actualHash)) anchor++ submitPlan context proposal++governanceScript :: Utxo -> Either Error Script+governanceScript reference = case Output.referenceScript (Utxo.output reference) of+ Just script@(Script.Plutus compiled) | Plutus.version compiled == Plutus.V3 -> Right script+ _ -> Left (InvalidBuildingRequest "Expected a resolved Plutus V3 governance reference script")++treasuryAnchor :: Either Error Anchor.Anchor+treasuryAnchor =+ makeAnchor+ "https://raw.githubusercontent.com/IntersectMBO/governance-actions/refs/heads/main/mainnet/2024-11-19-infohf/metadata.jsonld"+ "93106d082a93e94df5aff74f678438bae3a647dac63465fbfcde6a3058f41a1e"++makeAnchor :: Text -> Text -> Either Error Anchor.Anchor+makeAnchor url hash = Anchor.Anchor <$> Anchor.mkUrl url <*> (Blake2b.fromHex hash >>= Anchor.dataHashFromBytes . Blake2b.toBytes)++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,75 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Connected read-only queries. Run --query explicitly; no transaction is built.+module Main (main) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetId as Asset+import Cometa.Error (Error)+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost as Blockfrost+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)+import qualified Data.Text as Text+-- Shared example setup.+import qualified Support.Configuration as Common+import System.Environment (getArgs, lookupEnv)+import System.Exit (die)++-- DEFINITIONS ----------------------------------------------------------------++main :: IO ()+main = do+ arguments <- getArgs+ case arguments of+ ["--query"] -> query+ _ -> putStrLn "Set COMETA_NETWORK and COMETA_ADDRESS; optionally set BLOCKFROST_URL and BLOCKFROST_PROJECT_ID, then run with --query."++query :: IO ()+query = do+ configured <- Common.configuration+ addresses <- queryAddresses+ result <- case (,) <$> configured <*> addresses of+ Left failure -> pure (Left failure)+ Right (config, (address, reward)) -> Blockfrost.withProvider config $ \provider -> runExceptT $ do+ params <- ExceptT (Provider.protocolParameters provider)+ outputs <- ExceptT (Provider.utxosAt provider address)+ rewards <- traverse (ExceptT . Provider.rewardBalance provider) reward+ let totalLovelace =+ sum [Value.quantity Asset.Ada (Output.value (Utxo.output output)) | output <- outputs]++ pure (Parameters.parameterProtocolVersion params, length outputs, totalLovelace, rewards)+ case result of+ Left failure -> die (show failure)+ Right (version, count, lovelace, rewards) -> do+ putStrLn ("Protocol version: " <> show version)+ putStrLn ("Unspent outputs: " <> show count)+ putStrLn ("Lovelace: " <> show lovelace)+ maybe (pure ()) (\amount -> putStrLn ("Rewards: " <> show amount)) rewards++queryAddresses :: IO (Either Error (Address.Address, Maybe Reward.RewardAddress))+queryAddresses = do+ address <- Common.required "COMETA_ADDRESS"+ reward <- lookupEnv "COMETA_REWARD_ADDRESS"+ pure $ (,) <$> (address >>= Address.fromText) <*> traverse (Reward.fromText . Text.pack) reward
@@ -0,0 +1,57 @@+# Examples++Each file shows a complete runnable workflow: construct the plan, build, sign,+submit and confirm. Shared wallet/provider setup, compiled script programs and+address-index polling live in `Support/`. The C++ binding has the+same workflow set; `SignData.hs` corresponds to the Python/TypeScript CIP-8 example.++Local functions separate input validation, plan construction, building, signing,+submission and confirmation. They use standard `ExceptT` composition; the runner+reports errors at the outer boundary. These functions are repeated in each file+so the complete program can be read without following another example.++| Source | Cabal target |+| --- | --- |+| [Bip39.hs](Bip39.hs) | `cometa-bip39` |+| [SecureKeyHandler.hs](SecureKeyHandler.hs) | `cometa-secure-key-handler` |+| [Provider.hs](Provider.hs) | `cometa-provider` |+| [SubTransactionBatch.hs](SubTransactionBatch.hs) | `cometa-sub-transaction-batch` |+| [SignData.hs](SignData.hs) | `cometa-sign-data` |+| [SendLovelace.hs](SendLovelace.hs) | `cometa-send-lovelace` |+| [MintBurnNativeScript.hs](MintBurnNativeScript.hs) | `cometa-mint-burn-native-script` |+| [MintBurnPlutusScript.hs](MintBurnPlutusScript.hs) | `cometa-mint-burn-plutus-script` |+| [SpendFromNativeScript.hs](SpendFromNativeScript.hs) | `cometa-spend-from-native-script` |+| [SpendFromValidator.hs](SpendFromValidator.hs) | `cometa-spend-from-validator` |+| [DeferredRedeemerSelfIndex.hs](DeferredRedeemerSelfIndex.hs) | `cometa-deferred-self-index` |+| [DeferredRedeemerBatch.hs](DeferredRedeemerBatch.hs) | `cometa-deferred-batch` |+| [RewardAccountPubkey.hs](RewardAccountPubkey.hs) | `cometa-reward-account-pubkey` |+| [RewardAccountScript.hs](RewardAccountScript.hs) | `cometa-reward-account-script` |+| [DRepPubkey.hs](DRepPubkey.hs) | `cometa-drep-pubkey` |+| [DRepScript.hs](DRepScript.hs) | `cometa-drep-script` |+| [VoteForProposalPubkey.hs](VoteForProposalPubkey.hs) | `cometa-vote-for-proposal-pubkey` |+| [VoteForProposalScript.hs](VoteForProposalScript.hs) | `cometa-vote-for-proposal-script` |+| [DonateToTreasury.hs](DonateToTreasury.hs) | `cometa-donate-to-treasury` |+| [ProposeTreasuryWithdrawal.hs](ProposeTreasuryWithdrawal.hs) | `cometa-propose-treasury-withdrawal` |+| [DeferredWithdrawZero.hs](DeferredWithdrawZero.hs) | `cometa-deferred-withdraw-zero` |+| [PlutusV4GuardedSubTransaction.hs](PlutusV4GuardedSubTransaction.hs) | `cometa-plutus-v4-guarded-subtransaction` |++Transaction examples load an encrypted wallet, prompt for its password, build,+sign, submit and await confirmation when run without arguments. Use `--help` for+offline usage, or `--describe` to inspect public wallet/script identities.++```sh+cabal run cometa-secure-key-handler -- wallet.key+export COMETA_KEY_HANDLER_FILE="$PWD/wallet.key"+# Configure the provider, validity slot and workflow inputs as described below.+cabal run cometa-send-lovelace+```++`SecureKeyHandler` imports a recovery phrase into encrypted storage and reopens it.+`Bip39` and `SignData` are offline cryptography demonstrations using public material;+never fund their keys. `Provider --query` makes read-only chain queries. The+Dijkstra batch example uses three encrypted wallets and requires protocol 12+.++See [connected examples](../docs/userguide/connected-examples.md) for provider,+wallet and collateral configuration, and [governance examples](../docs/userguide/connected-governance.md)+for staking and proposal inputs. Multi-stage flows confirm each transaction before+continuing. Keep their printed transaction IDs if a later stage fails.
@@ -0,0 +1,121 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module RewardAccountPubkey (main, rewardKey) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..), KeyHash, Stake, StakePool)+import Cometa.Error (Error (..))+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "RewardAccountPubkey" (Inputs.describe Nothing) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ pool <- ExceptT Inputs.poolId+ ExceptT (rewardKey context (Support.stakeCredential wallet) pool)++-- | Register and delegate a fresh stake key, withdraw its rewards, then deregister.+rewardKey ::+ Workflow.Context ->+ Credential Stake ->+ KeyHash StakePool ->+ IO (Either Error [Transaction])+rewardKey ctx stake pool = runExceptT $ do+ let certify = Plan.certificate+ params <- ExceptT (Provider.protocolParameters (Workflow.provider ctx))++ let deposit = Parameters.parameterKeyDeposit params+ account = Reward.fromCredential (Workflow.network ctx) stake+ registration =+ certify (Certificate.Registration stake deposit)+ <> certify (Certificate.StakeDelegation stake pool)+ <> Plan.certificate (Certificate.VoteDelegation stake DRep.AlwaysAbstain)++ registered <- submitPlan ctx registration+ rewards <- ExceptT (Provider.rewardBalance (Workflow.provider ctx) account)++ let withdrawal = Plan.withdraw account rewards++ cleaned <- submitPlan ctx (withdrawal <> certify (Certificate.Unregistration stake deposit))++ pure [registered, cleaned]++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,126 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module RewardAccountScript (main, rewardScript) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (KeyHash, StakePool)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "RewardAccountScript" (Inputs.describe Nothing) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ pool <- ExceptT Inputs.poolId+ ExceptT (rewardScript context pool)++-- | Run the stake lifecycle using the V2 script credential and its redeemer.+rewardScript :: Workflow.Context -> KeyHash StakePool -> IO (Either Error [Transaction])+rewardScript ctx pool = runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.alwaysSucceedsV2+ hash <- ExceptT (Script.hash script)++ let stake = Credential.ScriptCredential hash+ certify certificate = Plan.attachScript script <> Plan.certificateWithRedeemer certificate voidArgument+ params <- ExceptT (Provider.protocolParameters (Workflow.provider ctx))++ let deposit = Parameters.parameterKeyDeposit params+ account = Reward.fromCredential (Workflow.network ctx) stake+ registration =+ certify (Certificate.Registration stake deposit)+ <> certify (Certificate.StakeDelegation stake pool)++ registered <- submitPlan ctx registration+ rewards <- ExceptT (Provider.rewardBalance (Workflow.provider ctx) account)++ let withdrawal = Plan.attachScript script <> Plan.withdrawWithRedeemer account rewards voidArgument++ cleaned <- submitPlan ctx (withdrawal <> certify (Certificate.Unregistration stake deposit))++ pure [registered, cleaned]++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,66 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Import a recovery phrase into encrypted storage, then reopen it.+module Main (main) where++import qualified Cometa.Crypto.Bip32.PublicKey as Public+import qualified Cometa.Crypto.Bip39 as Bip39+import qualified Cometa.Crypto.DerivationPath as Path+import Cometa.Error (Error (..))+import qualified Cometa.KeyHandler.Software as Software+-- Standard library and error handling.+import Control.Monad (unless, when)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.ByteString as Bytes+import qualified Data.Text.Encoding as Text+import qualified Data.Text.IO as Text+-- Shared example setup.+import Support.Terminal (password, secret)+import System.Directory (doesPathExist)+import System.Environment (getArgs)+import System.Exit (die)++main :: IO ()+main = do+ arguments <- getArgs+ case arguments of+ ["--help"] -> do+ putStrLn "Usage: cabal run cometa-secure-key-handler -- WALLET_FILE"+ putStrLn "Imports a recovery phrase into a new encrypted wallet."+ [file] -> createWallet file+ _ -> die "Supply a new wallet file path; use --help for usage."++-- | Encrypt a recovery phrase into a new file, then reopen it to verify the password.+createWallet :: FilePath -> IO ()+createWallet file = do+ exists <- doesPathExist file+ when exists (die "Wallet file already exists; choose a new path.")+ phrase <- secret "Recovery phrase: "+ encryptionPassword <- password file+ repeated <- secret "Repeat password: "+ unless (encryptionPassword == Text.encodeUtf8 repeated) (die "Passwords do not match.")+ result <- runExceptT $ do+ entropy <- except (Bip39.fromText phrase >>= Bip39.exportEntropy)+ stored <- ExceptT (Software.withEntropy entropy encryptionPassword (password file) Software.serialize)+ liftIO (Bytes.writeFile file stored)+ reloaded <- liftIO (Bytes.readFile file)+ ExceptT $ Software.withSerialized reloaded (password file) $ \case+ Software.Bip32Handler handler -> fmap Public.toHex <$> Software.accountPublicKey handler (Path.standardAccountPath minBound)+ Software.Ed25519Handler _ -> pure (Left (InvalidBuildingRequest "Expected a BIP32 wallet"))+ either (die . show) (\public -> Text.putStrLn ("Account public key: " <> public)) result
@@ -0,0 +1,108 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import qualified Cometa.Address as Address+import Cometa.Error (Error (..))+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+-- Shared example setup.+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext, required, unsigned)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "SendLovelace" (runExceptT . payment)++-- | Read a payment, then build, sign, submit and confirm it with the open wallet.+payment :: WalletContext -> ExceptT Error IO Tx.Transaction+payment wallet = do+ output <- readPaymentOutput++ submitPlan (Support.context wallet) (Plan.payTo output)++-- | Validate the recipient and integer lovelace amount before building a plan.+readPaymentOutput :: ExceptT Error IO Output.Output+readPaymentOutput = do+ recipient <- ExceptT (required "COMETA_RECIPIENT")+ amount <- ExceptT (required "COMETA_LOVELACE")++ except $ do+ destination <- Address.fromText recipient+ lovelace <- unsigned amount+ Output.mkOutput destination (Value.lovelace (toInteger lovelace)) Datum.NoDatum Nothing++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,46 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Public, unfunded demonstration seed. Applications supply their own scoped key.+module Main (main) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import qualified Cometa.Message.Cip8 as Cip8+import qualified Cometa.NetworkId as Network+-- Standard library and error handling.+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)+import qualified Data.ByteString as ByteString+import System.Exit (die)++-- DEFINITIONS ----------------------------------------------------------------++main :: IO ()+main = do+ result <- Key.withNormalKey (ByteString.replicate 32 7) $ \key -> runExceptT $ do+ public <- ExceptT (Key.publicKey key)+ payment <- ExceptT (Credential.fromPublicKey public)++ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet payment)+ ExceptT (Cip8.sign key (Cip8.addressBinding address) "Example authorization message")++ case result of+ Left failure -> die (show failure)+ Right signed -> print (ByteString.length (Cip8.coseSign1 signed), ByteString.length (Cip8.coseKey signed))
@@ -0,0 +1,138 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "SpendFromNativeScript" $ \wallet ->+ runLockSpend (Support.context wallet) nativeScript 2000000++-- | Fund the script first; spend its confirmed output in a separate transaction.+runLockSpend :: Workflow.Context -> Script -> Word64 -> IO (Either Error [Tx.Transaction])+runLockSpend context script amount = runExceptT $ do+ (locked, reference, funded) <- ExceptT (fundScript context script amount)++ let argument = case script of Script.Native _ -> Nothing; Script.Plutus _ -> Just voidArgument+ source = maybe (Plan.attachScript script) Plan.referenceInput reference+ payout <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 1000000) Datum.NoDatum Nothing)++ spent <- submitPlan context (Plan.payTo payout <> Plan.spendWith locked argument Nothing <> source)++ pure [funded, spent]++-- | Create the locked output and, for Plutus, a reusable reference-script output.+fundScript ::+ Workflow.Context ->+ Script ->+ Word64 ->+ IO (Either Error (Utxo, Maybe Utxo, Tx.Transaction))+fundScript context script amount = runExceptT $ do+ digest <- ExceptT (Script.hash script)++ let destination = Address.ShelleyAddress (Shelley.enterprise (Workflow.network context) (Credential.ScriptCredential digest))+ datum = case script of Script.Native _ -> Datum.NoDatum; Script.Plutus _ -> Datum.InlineDatum voidArgument+ output <- except (Output.mkOutput destination (Value.lovelace (toInteger amount)) datum Nothing)+ reference <- case script of+ Script.Native _ -> pure Nothing+ Script.Plutus _ -> Just <$> except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just script))++ funded <- submitPlan context (Plan.payTo output <> maybe mempty Plan.payTo reference)+ locked <- ExceptT (Workflow.outputAt funded 0)+ referenceUtxo <- traverse (const (ExceptT (Workflow.outputAt funded 1))) reference+ pure (locked, referenceUtxo, funded)++nativeScript :: Script.Script+nativeScript = Script.Native (NativeScript.allOf [NativeScript.invalidAfter 1001655683199])++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,140 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module SpendFromValidator (main, runLockSpend) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Scripts as Scripts+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypoint "SpendFromValidator" spendPlutus++spendPlutus :: WalletContext -> IO (Either Error [Tx.Transaction])+spendPlutus wallet = runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.alwaysSucceedsV3+ ExceptT (runLockSpend (Support.context wallet) script 2000000)++-- | Fund the script first; spend its confirmed output in a separate transaction.+runLockSpend :: Workflow.Context -> Script -> Word64 -> IO (Either Error [Tx.Transaction])+runLockSpend context script amount = runExceptT $ do+ (locked, reference, funded) <- ExceptT (fundScript context script amount)++ let argument = case script of Script.Native _ -> Nothing; Script.Plutus _ -> Just voidArgument+ source = maybe (Plan.attachScript script) Plan.referenceInput reference+ payout <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 1000000) Datum.NoDatum Nothing)++ spent <- submitPlan context (Plan.payTo payout <> Plan.spendWith locked argument Nothing <> source)++ pure [funded, spent]++-- | Create the locked output and, for Plutus, a reusable reference-script output.+fundScript ::+ Workflow.Context ->+ Script ->+ Word64 ->+ IO (Either Error (Utxo, Maybe Utxo, Tx.Transaction))+fundScript context script amount = runExceptT $ do+ digest <- ExceptT (Script.hash script)++ let destination = Address.ShelleyAddress (Shelley.enterprise (Workflow.network context) (Credential.ScriptCredential digest))+ datum = case script of Script.Native _ -> Datum.NoDatum; Script.Plutus _ -> Datum.InlineDatum voidArgument+ output <- except (Output.mkOutput destination (Value.lovelace (toInteger amount)) datum Nothing)+ reference <- case script of+ Script.Native _ -> pure Nothing+ Script.Plutus _ -> Just <$> except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just script))++ funded <- submitPlan context (Plan.payTo output <> maybe mempty Plan.payTo reference)+ locked <- ExceptT (Workflow.outputAt funded 0)+ referenceUtxo <- traverse (const (ExceptT (Workflow.outputAt funded 1))) reference+ pure (locked, referenceUtxo, funded)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,176 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Buyer and seller sign local intents; a third encrypted wallet submits the batch.+module Main (main) where++import Cometa.AssetId (AssetId (Native))+import qualified Cometa.AssetName as AssetName+import Cometa.Credential (Credential (..), Guard)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.NetworkId as Network+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Builder as SubBuilder+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import qualified Data.Text as Text+-- Shared example setup.+import qualified Support.Transaction as Workflow+import Support.Wallet (WalletContext)+import qualified Support.Wallet as Wallet++main :: IO ()+main = Wallet.entrypoint "SubTransactionBatch" batch++batch :: WalletContext -> IO (Either Error Tx.Transaction)+batch batcher = runExceptT $ do+ params <- ExceptT (Provider.protocolParameters (Workflow.provider (Wallet.context batcher)))++ let Version.ProtocolVersion major _ = Parameters.parameterProtocolVersion params+ unless+ (major >= 12)+ (throwE (UnsupportedOperation "Subtransaction batches require protocol 12 or later"))+ buyerFile <- ExceptT (Wallet.required "COMETA_BUYER_WALLET")+ sellerFile <- ExceptT (Wallet.required "COMETA_SELLER_WALLET")+ ExceptT $ Wallet.withWalletFile (Text.unpack buyerFile) $ \buyer ->+ Wallet.withWalletFile (Text.unpack sellerFile) $ \seller -> runExceptT $ do+ let addresses = map (Workflow.wallet . Wallet.context) [buyer, seller, batcher]+ unless+ (and [a /= b | (a, b) <- zip addresses (drop 1 addresses <> take 1 addresses)])+ (throwE (InvalidBuildingRequest "Buyer, seller and batcher must have distinct addresses"))+ policy <- ExceptT (Wallet.required "COMETA_SWAP_POLICY") >>= except . Policy.fromHex+ name <- ExceptT (Wallet.required "COMETA_SWAP_ASSET_NAME") >>= except . AssetName.fromHex++ let token = Native policy name+ buyerInput <- ExceptT (Wallet.resolveReference (Wallet.context buyer) "COMETA_BUYER_INPUT")+ sellerInput <- ExceptT (Wallet.resolveReference (Wallet.context seller) "COMETA_SELLER_INPUT")+ guard <- except $ case Wallet.paymentCredential batcher of+ Credential.KeyCredential hash -> Credential.KeyCredential <$> Credential.keyHashFromBytes (Credential.keyHashBytes hash)+ _ -> Left (InvalidBuildingRequest "The batcher must use a payment key")+ buyerIntent <-+ ExceptT $+ signedIntent+ params+ guard+ buyer+ buyerInput+ (Value.lovelace 100000000)+ (Value.lovelace 50000000 <> Value.singleton token 1000)+ sellerIntent <-+ ExceptT $+ signedIntent+ params+ guard+ seller+ sellerInput+ (Value.lovelace 10000000 <> Value.singleton token 5000)+ (Value.lovelace 60000000 <> Value.singleton token 4000)++ let batchPlan =+ Plan.attachSubTransaction buyerIntent [buyerInput]+ <> Plan.attachSubTransaction sellerIntent [sellerInput]+ <> Plan.requireGuard guard++ submitPlan (Wallet.context batcher) batchPlan++-- | Check the party owns the exact input value, then sign its guarded swap intent.+signedIntent ::+ Parameters.Parameters ->+ Credential Guard ->+ WalletContext ->+ Utxo.Utxo ->+ Value.Value ->+ Value.Value ->+ IO (Either Error Sub.SubTransaction)+signedIntent params guard wallet input expected payout = runExceptT $ do+ let ctx = Wallet.context wallet+ network = if Workflow.network ctx == Network.mainnet then Fields.Mainnet else Fields.Testnet+ unless+ (Output.address (Utxo.output input) == Workflow.wallet ctx && Output.value (Utxo.output input) == expected)+ (throwE (InvalidBuildingRequest "Swap input must belong to its wallet and contain exactly the documented coin/token amounts"))+ output <- except (Output.mkOutput (Workflow.wallet ctx) payout Datum.NoDatum Nothing)++ let plan = SubPlan.spend input <> SubPlan.payTo output <> SubPlan.requireTopLevelGuard guard Nothing+ unsigned <- ExceptT (SubBuilder.build (SubBuilder.Config params (Workflow.slots ctx) network) plan)+ ExceptT (Wallet.signSubTransaction wallet unsigned)++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,70 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Environment parsing shared by explicitly invoked connected examples.+module Support.Configuration (configuration, required, networkSlots, addressNetwork) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.NetworkId (NetworkId)+import qualified Cometa.NetworkId as Network+import qualified Cometa.Provider.Blockfrost as Blockfrost+import Cometa.SlotConfig (SlotConfig)+import qualified Cometa.SlotConfig as Slots+-- Standard library and error handling.+import Data.Text (Text)+import qualified Data.Text as Text+import System.Environment (lookupEnv)++-- DEFINITIONS ----------------------------------------------------------------++required :: String -> IO (Either Error Text)+required name = do+ value <- lookupEnv name+ pure $ case value of+ Nothing -> Left (InvalidProviderConfiguration ("Missing environment variable: " <> Text.pack name))+ Just "" -> Left (InvalidProviderConfiguration ("Empty environment variable: " <> Text.pack name))+ Just text -> Right (Text.pack text)++configuration :: IO (Either Error Blockfrost.Config)+configuration = do+ networkName <- required "COMETA_NETWORK"+ projectText <- lookupEnv "BLOCKFROST_PROJECT_ID"+ endpoint <- lookupEnv "BLOCKFROST_URL"+ pure $ do+ name <- networkName+ network <- case name of+ "mainnet" -> Right Blockfrost.Mainnet+ "preprod" -> Right Blockfrost.Preprod+ "preview" -> Right Blockfrost.Preview+ _ -> Left (InvalidProviderConfiguration "COMETA_NETWORK must be mainnet, preprod or preview")+ project <- traverse (Blockfrost.mkProjectId . Text.pack) projectText++ let defaults = Blockfrost.defaultConfig network project+ pure (maybe defaults (\url -> defaults {Blockfrost.endpoint = Text.pack url}) endpoint)++networkSlots :: Blockfrost.Network -> SlotConfig+networkSlots network = case network of+ Blockfrost.Mainnet -> Slots.mainnet+ Blockfrost.Preprod -> Slots.preprod+ Blockfrost.Preview -> Slots.preview++addressNetwork :: Blockfrost.Network -> NetworkId+addressNetwork network = case network of+ Blockfrost.Mainnet -> Network.mainnet+ Blockfrost.Preprod -> Network.testnet+ Blockfrost.Preview -> Network.testnet
@@ -0,0 +1,61 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Public script identities for inspecting configured governance examples.+module Support.Governance (describeScripts, describeReference) where++import qualified Cometa.Address.Reward as Reward+import Cometa.Credential (Credential (..))+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import Cometa.NetworkId (NetworkId)+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+-- Standard library and error handling.+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import Data.Text (Text)+-- Shared example setup.+import qualified Support.Scripts as Scripts++governanceScript :: Utxo -> Either Error Script+governanceScript reference = case Output.referenceScript (Utxo.output reference) of+ Just script@(Script.Plutus compiled) | Plutus.version compiled == Plutus.V3 -> Right script+ _ -> Left (InvalidBuildingRequest "Expected a resolved Plutus V3 governance reference script")++describeScripts :: NetworkId -> IO (Either Error [(Text, Text)])+describeScripts network = runExceptT $ do+ reward <- ExceptT (fmap (fmap Script.Plutus) Scripts.alwaysSucceedsV2)+ zero <- ExceptT (fmap (fmap Script.Plutus) Scripts.withdrawZero)+ rewardHash <- ExceptT (Script.hash reward)+ zeroHash <- ExceptT (Script.hash zero)++ pure+ [ ("reward-script", Reward.toText (Reward.fromCredential network (ScriptCredential rewardHash))),+ ("withdraw-zero-script", Reward.toText (Reward.fromCredential network (ScriptCredential zeroHash)))+ ]++describeReference :: Utxo -> IO (Either Error [(Text, Text)])+describeReference reference = runExceptT $ do+ script <- except (governanceScript reference)+ hash <- ExceptT (Script.hash script)+ digest <- except (Blake2b.fromBytes (Credential.scriptHashBytes hash))++ pure [("drep-script-hash", Blake2b.toHex digest)]
@@ -0,0 +1,69 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Support.Inputs (poolId, actionId, treasurySettings, describe) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.TransactionId as TransactionId+-- Standard library and error handling.+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Governance as Governance+import qualified Support.Transaction as Native+import qualified Support.Wallet as Support++poolId :: IO (Either Error (Credential.KeyHash Credential.StakePool))+poolId = do+ value <- Support.required "COMETA_POOL_ID_HEX"+ pure (value >>= Blake2b.fromHex >>= Credential.keyHashFromBytes . Blake2b.toBytes)++actionId :: IO (Either Error ActionId.ActionId)+actionId = do+ value <- Support.required "COMETA_GOVERNANCE_ACTION"+ pure $ do+ text <- value+ case Text.splitOn "#" text of+ [transaction, index] -> ActionId.ActionId <$> TransactionId.fromHex transaction <*> Support.unsigned index+ _ -> Left (InvalidBuildingRequest "COMETA_GOVERNANCE_ACTION must be TXID#INDEX")++treasurySettings :: IO (Either Error (Reward.RewardAddress, Credential.ScriptHash, Word64))+treasurySettings = do+ hash <- Support.required "COMETA_CONSTITUTION_SCRIPT_HASH"+ amount <- Support.required "COMETA_TREASURY_WITHDRAWAL_LOVELACE"+ reward <- Support.required "COMETA_TREASURY_RETURN_ACCOUNT"+ pure $ do+ parsedHash <- hash >>= Blake2b.fromHex >>= Credential.scriptHashFromBytes . Blake2b.toBytes+ parsedAmount <- amount >>= Support.unsigned+ parsedReward <- reward >>= Reward.fromText+ pure (parsedReward, parsedHash, parsedAmount)++describe :: Maybe String -> Support.WalletContext -> IO (Either Error [(Text, Text)])+describe referenceName wallet = runExceptT $ do+ let context = Support.context wallet+ identities <- ExceptT (Governance.describeScripts (Native.network context))+ case referenceName of+ Nothing -> pure identities+ Just name -> do+ reference <- ExceptT (Support.resolveReference context name)+ additional <- ExceptT (Governance.describeReference reference)+ pure (identities <> additional)
@@ -0,0 +1,69 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Exact compiled programs from the Apache-2.0 pinned native examples. The+-- serialized encrypted wallet material in those files is deliberately excluded.+module Support.Scripts (alwaysSucceedsV2, alwaysSucceedsV3, selfIndex, orderPairing, withdrawZero, v4Validator, v4Guard) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Error (Error)+import qualified Cometa.Script.Plutus as Plutus+-- Standard library and error handling.+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++program :: Plutus.Version -> Text -> IO (Either Error Plutus.PlutusScript)+program version text = do+ encoded <- Cbor.fromHex text+ pure (encoded >>= Plutus.fromBytes version . Cbor.toBytes)++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/reward_account_script_example.c, ALWAYS_SUCCEEDS_SCRIPT_V2.+alwaysSucceedsV2 :: IO (Either Error Plutus.PlutusScript)+alwaysSucceedsV2 = program Plutus.V2 "59079201000033232323232323232323232323232332232323232323232222232325335333006300800530070043333573466E1CD55CEA80124000466442466002006004646464646464646464646464646666AE68CDC39AAB9D500C480008CCCCCCCCCCCC88888888888848CCCCCCCCCCCC00403403002C02802402001C01801401000C008CD4060064D5D0A80619A80C00C9ABA1500B33501801A35742A014666AA038EB9406CD5D0A804999AA80E3AE501B35742A01066A0300466AE85401CCCD54070091D69ABA150063232323333573466E1CD55CEA801240004664424660020060046464646666AE68CDC39AAB9D5002480008CC8848CC00400C008CD40B9D69ABA15002302F357426AE8940088C98C80C8CD5CE01981901809AAB9E5001137540026AE854008C8C8C8CCCD5CD19B8735573AA004900011991091980080180119A8173AD35742A004605E6AE84D5D1280111931901919AB9C033032030135573CA00226EA8004D5D09ABA2500223263202E33573805E05C05826AAE7940044DD50009ABA1500533501875C6AE854010CCD540700808004D5D0A801999AA80E3AE200135742A00460446AE84D5D1280111931901519AB9C02B02A028135744A00226AE8940044D5D1280089ABA25001135744A00226AE8940044D5D1280089ABA25001135744A00226AE8940044D55CF280089BAA00135742A00460246AE84D5D1280111931900E19AB9C01D01C01A101B13263201B3357389201035054350001B135573CA00226EA80054049404448C88C008DD6000990009AA80A911999AAB9F0012500A233500930043574200460066AE880080548C8C8CCCD5CD19B8735573AA004900011991091980080180118061ABA150023005357426AE8940088C98C8054CD5CE00B00A80989AAB9E5001137540024646464646666AE68CDC39AAB9D5004480008CCCC888848CCCC00401401000C008C8C8C8CCCD5CD19B8735573AA0049000119910919800801801180A9ABA1500233500F014357426AE8940088C98C8068CD5CE00D80D00C09AAB9E5001137540026AE854010CCD54021D728039ABA150033232323333573466E1D4005200423212223002004357426AAE79400C8CCCD5CD19B875002480088C84888C004010DD71ABA135573CA00846666AE68CDC3A801A400042444006464C6403866AE700740700680640604D55CEA80089BAA00135742A00466A016EB8D5D09ABA2500223263201633573802E02C02826AE8940044D5D1280089AAB9E500113754002266AA002EB9D6889119118011BAB00132001355012223233335573E0044A010466A00E66442466002006004600C6AAE754008C014D55CF280118021ABA200301313574200222440042442446600200800624464646666AE68CDC3A800A40004642446004006600A6AE84D55CF280191999AB9A3370EA0049001109100091931900899AB9C01201100F00E135573AA00226EA80048C8C8CCCD5CD19B875001480188C848888C010014C01CD5D09AAB9E500323333573466E1D400920042321222230020053009357426AAE7940108CCCD5CD19B875003480088C848888C004014C01CD5D09AAB9E500523333573466E1D40112000232122223003005375C6AE84D55CF280311931900899AB9C01201100F00E00D00C135573AA00226EA80048C8C8CCCD5CD19B8735573AA004900011991091980080180118029ABA15002375A6AE84D5D1280111931900699AB9C00E00D00B135573CA00226EA80048C8CCCD5CD19B8735573AA002900011BAE357426AAE7940088C98C802CCD5CE00600580489BAA001232323232323333573466E1D4005200C21222222200323333573466E1D4009200A21222222200423333573466E1D400D2008233221222222233001009008375C6AE854014DD69ABA135744A00A46666AE68CDC3A8022400C4664424444444660040120106EB8D5D0A8039BAE357426AE89401C8CCCD5CD19B875005480108CC8848888888CC018024020C030D5D0A8049BAE357426AE8940248CCCD5CD19B875006480088C848888888C01C020C034D5D09AAB9E500B23333573466E1D401D2000232122222223005008300E357426AAE7940308C98C8050CD5CE00A80A00900880800780700680609AAB9D5004135573CA00626AAE7940084D55CF280089BAA0012323232323333573466E1D400520022333222122333001005004003375A6AE854010DD69ABA15003375A6AE84D5D1280191999AB9A3370EA0049000119091180100198041ABA135573CA00C464C6401A66AE7003803402C0284D55CEA80189ABA25001135573CA00226EA80048C8C8CCCD5CD19B875001480088C8488C00400CDD71ABA135573CA00646666AE68CDC3A8012400046424460040066EB8D5D09AAB9E500423263200A33573801601401000E26AAE7540044DD500089119191999AB9A3370EA00290021091100091999AB9A3370EA00490011190911180180218031ABA135573CA00846666AE68CDC3A801A400042444004464C6401666AE7003002C02402001C4D55CEA80089BAA0012323333573466E1D40052002212200223333573466E1D40092000212200123263200733573801000E00A00826AAE74DD5000891999AB9A3370E6AAE74DD5000A40004008464C6400866AE700140100092612001490103505431001123230010012233003300200200122212200201"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/spend_from_validator_example.c, ALWAYS_SUCCEEDS_SCRIPT_V3.+alwaysSucceedsV3 :: IO (Either Error Plutus.PlutusScript)+alwaysSucceedsV3 = program Plutus.V3 "590dff010000323232332232323232332232323232323232232498c8c8c94cd4ccd5cd19b874800000804c0484c8c8c8c8c8ccc88848ccc00401000c008c8c8c94cd4ccd5cd19b874800000806c0684c8c8c8c8c8c8c8c8c8c8c8c8c8c8c8c8cccccccccccc8ccc8cc8cc888888888888888848cccccccccccccccc00404404003c03803403002c02802402001c01801401000c008c004d5d080a18009aba1013302123232325335333573466e1d2000002031030133221233001003002301d35742002600a6ae84d5d1000898192481035054310035573c0046aae74004dd5000998108009aba101123232325335333573466e1d200000203002f13232333322221233330010050040030023232325335333573466e1d2000002035034133221233001003002302a35742002660564646464a66a666ae68cdc3a40000040720702642446004006605c6ae8400454cd4ccd5cd19b87480080080e40e04c8ccc888488ccc00401401000cdd69aba1002375a6ae84004dd69aba1357440026ae880044c0e92401035054310035573c0046aae74004dd50009aba1357440022606c9201035054310035573c0046aae74004dd51aba1003300735742004646464a66a666ae68cdc3a400000406a068224440062a66a666ae68cdc3a400400406a068264244460020086eb8d5d08008a99a999ab9a3370e900200101a81a099091118010021aba1001130364901035054310035573c0046aae74004dd51aba10013302875c6ae84d5d10009aba200135744002260629201035054310035573c0046aae74004dd50009bad3574201e60026ae84038c008c009d69980f80a9aba100c33302202075a6ae8402cc8c8c94cd4ccd5cd19b87480000080b80b44cc8848cc00400c008c8c8c94cd4ccd5cd19b87480000080c40c04cc8848cc00400c008cc0b9d69aba1001302d357426ae880044c0c9241035054310035573c0046aae74004dd51aba10013232325335333573466e1d20000020310301332212330010030023302e75a6ae84004c0b4d5d09aba200113032491035054310035573c0046aae74004dd51aba1357440022605e921035054310035573c0046aae74004dd51aba100a3301f75c6ae84024ccc0888c8c8c94cd4ccd5cd19b87480000080bc0b84c84888888c01401cdd71aba100115335333573466e1d200200202f02e13212222223002007301b357420022a66a666ae68cdc3a400800405e05c2642444444600600e60486ae8400454cd4ccd5cd19b87480180080bc0b84cc884888888cc01802001cdd69aba10013019357426ae8800454cd4ccd5cd19b87480200080bc0b84c84888888c00401cc068d5d08008a99a999ab9a3370e9005001017817099910911111198020040039bad3574200260306ae84d5d1000898182481035054310035573c0046aae74004dd50008131aba1008330020263574200e6eb8d5d080319981100b198110149191919299a999ab9a3370e9000001017817089110010a99a999ab9a3370e9001001017817089110008a99a999ab9a3370e900200101781708911001898182481035054310035573c0046aae74004dd50009aba10053301f0143574200860026ae8400cc004d5d09aba2003302075a6040eb8d5d10009aba2001357440026ae88004d5d10009aba2001357440026ae88004d5d10009aba2001357440026ae88004d5d10009aba20011301c491035054310035573c0046aae74004dd51aba10063574200a646464a66a666ae68cdc3a40000040360342642444444600a00e6eb8d5d08008a99a999ab9a3370e900100100d80d0999109111111980100400398039aba100133011016357426ae8800454cd4ccd5cd19b874801000806c0684c84888888c00c01cc040d5d08008a99a999ab9a3370e900300100d80d099910911111198030040039bad35742002600a6ae84d5d10008a99a999ab9a3370e900400100d80d0990911111180080398031aba100115335333573466e1d200a00201b01a13322122222233004008007375a6ae84004c010d5d09aba20011301c4901035054310035573c0046aae74004dd51aba13574400a4646464a66a666ae68cdc3a4000004036034264666444246660020080060046eb4d5d080118089aba10013232325335333573466e1d200000201f01e1323332221222222233300300a0090083301601e357420046ae84004cc059d71aba1357440026ae8800454cd4ccd5cd19b874800800807c0784cc8848888888cc01c024020cc054074d5d0800991919299a999ab9a3370e90000010110108999109198008018011bad357420026eb4d5d09aba200113023491035054310035573c0046aae74004dd51aba1357440022a66a666ae68cdc3a400800403e03c26644244444446600401201066602c028eb4d5d08009980abae357426ae8800454cd4ccd5cd19b874801800807c0784c848888888c010020cc054074d5d08008a99a999ab9a3370e900400100f80f09919199991110911111119998008058050048041980b80f9aba1003330150163574200466603002ceb4d5d08009a991919299a999ab9a3370e900000101201189980e1bad357420026eb4d5d09aba2001130254901035054310035573c0046aae74004dd51aba135744002446602a0040026ae88004d5d10008a99a999ab9a3370e900500100f80f0999109111111198028048041980a80e9aba10013232325335333573466e1d200000202202113301875c6ae840044c08d241035054310035573c0046aae74004dd51aba1357440022a66a666ae68cdc3a401800403e03c22444444400c26040921035054310035573c0046aae74004dd51aba1357440026ae880044c071241035054310035573c0046aae74004dd50009191919299a999ab9a3370e900000100d00c899910911111111111980280680618079aba10013301075a6ae84d5d10008a99a999ab9a3370e900100100d00c899910911111111111980100680618079aba10013301075a6ae84d5d10008a9919a999ab9a3370e900200180d80d099910911111111111980500680618081aba10023001357426ae8800854cd4ccd5cd19b874801800c06c0684c8ccc888488888888888ccc018038034030c044d5d080198011aba1001375a6ae84d5d10009aba200215335333573466e1d200800301b01a133221222222222223300700d00c3010357420046eb4d5d09aba200215335333573466e1d200a00301b01a132122222222222300100c3010357420042a66a666ae68cdc3a4018006036034266442444444444446600601a01860206ae84008dd69aba1357440042a66a666ae68cdc3a401c006036034266442444444444446601201a0186eb8d5d08011bae357426ae8800854cd4ccd5cd19b874804000c06c0684cc88488888888888cc020034030dd71aba1002375a6ae84d5d10010a99a999ab9a3370e900900180d80d099910911111111111980580680618081aba10023010357426ae8800854cd4ccd5cd19b874805000c06c0684c8488888888888c010030c040d5d08010980e2481035054310023232325335333573466e1d200000201e01d13212223003004375c6ae8400454c8cd4ccd5cd19b874800800c07c0784c84888c004010c004d5d08010a99a999ab9a3370e900200180f80f099910911198010028021bae3574200460026ae84d5d1001098102481035054310023232325335333573466e1d2000002022021132122230030043017357420022a66a666ae68cdc3a4004004044042224440042a66a666ae68cdc3a40080040440422244400226046921035054310035573c0046aae74004dd50009aab9e00235573a0026ea8004d55cf0011aab9d00137540024646464a66a666ae68cdc3a400000403203026424446006008601c6ae8400454cd4ccd5cd19b87480080080640604c84888c008010c038d5d08008a99a999ab9a3370e900200100c80c099091118008021bae3574200226034921035054310035573c0046aae74004dd50009191919299a999ab9a3370e900000100c00b8999109198008018011bae357420026eb4d5d09aba200113019491035054310035573c0046aae74004dd50009aba200113014491035054310035573c0046aae74004dd50009808911299a999ab9a3370e900000080880809809249035054330015335333573466e20005200001101013300333702900000119b81480000044c8cc8848cc00400c008cdc200180099b840020013300400200130102225335333573466e1d200000101000f10021330030013370c004002464460046eb0004c04088cccd55cf8009005119a80498021aba10023003357440040224646464a66a666ae68cdc3a400000401e01c26424460040066eb8d5d08008a99a999ab9a3370e900100100780709909118008019bae3574200226020921035054310035573c0046aae74004dd500091191919299a999ab9a3370e900100100780708910008a99a999ab9a3370e9000001007807099091180100198029aba1001130104901035054310035573c0046aae74004dd50009119118011bab001300e2233335573e002401046466a0106600e600c6aae74004c014d55cf00098021aba20033574200401e4424660020060042440042442446600200800640024646464a66a666ae68cdc3a400000401000e200e2a66a666ae68cdc3a400400401000e201026012921035054310035573c0046aae74004dd500091191919299a999ab9a3370e9000001004003889110010a99a999ab9a3370e90010010040038990911180180218029aba100115335333573466e1d200400200800711222001130094901035054310035573c0046aae74004dd50009191919299a999ab9a3370e90000010030028999109198008018011bae357420026eb4d5d09aba200113007491035054310035573c0046aae74004dd5000891001091000919319ab9c0010021200123230010012300223300200200101"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/deferred_redeemer_self_index_example.c, SELF_INDEX_VALIDATOR_V3.+selfIndex :: IO (Either Error Plutus.PlutusScript)+selfIndex = program Plutus.V3 "58f501010029800aba2aba1aba0aab9faab9eaab9dab9a488888896600264646644b30013370e900118031baa0018994c004c02c00660166018003370e90002444b30013001300a375400d1323259800980880144c9660026008601a6ea8006266ebcc044c038dd5180898071baa0010068b2018329800800cdd6180898071baa301100b9bad3011300e375401280088896600200514c103d87a80008acc004c018006266e9520003301230130024bd70466002007301400299b8048004005003201c40451640386eb4c03c004c02cdd50034590090c01cdd5000c59005180400098041804800980400098019baa0088a4d13656400401"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/deferred_redeemer_batch_example.c, ORDER_PAIRING_VALIDATOR_V3.+orderPairing :: IO (Either Error Plutus.PlutusScript)+orderPairing = program Plutus.V3 "59022c01010029800aba2aba1aba0aab9faab9eaab9dab9a488888896600264653001300800198041804800cdc3a400530080024888966002600460106ea800e2653001300d00198069807000cdc3a40009112cc004c004c030dd500444c8c8cc8966002602a007132323232598009804980a1baa001899192cc004c02cc058dd5000c56600266ebcc068c05cdd5180d180b9baa00300d899b894820225e8c9660026022602e6ea80062900044dd6980d980c1baa001405864b300130113017375400314c103d87a8000899198008009bab301c3019375400444b30010018a6103d87a8000899192cc004cdc8a45000018acc004cdc7a44100001898059980f180e00125eb82298103d87a80004069133004004302000340686eb8c068004c07400501b202c32330010013756600660306ea8c06cc060dd5001112cc004006298103d87a8000899192cc004cdc8a45000018acc004cdc7a44100001898051980e980d80125eb82298103d87a80004065133004004301f00340646eb8c064004c07000501a4528202a8b202a330033758603260346034602c6ea8038dd69800980b1baa01123019301a0018b2026330013758602e60286ea8030dd6980b980a1baa00f3001001222598008014530103d87a80008acc004c024006260086602e603000497ae08cc00400e6032005337009000800a006404c80b0dd2a40011640486eb4c048004dd69809001180900098069baa0088b201618049baa0038b200e180400098019baa0088a4d1365640041"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/deferred_redeemer_withdraw_zero_example.c, WITHDRAW_ZERO_VALIDATOR_V3.+withdrawZero :: IO (Either Error Plutus.PlutusScript)+withdrawZero = program Plutus.V3 "5901ad01010029800aba2aba1aba0aab9faab9eaab9dab9a4888888966002646465300130053754003300900398048012444b30013370e9002001c4cc8966002600260146ea800e264b30013010001899198008009bac30100022259800800c56600266e1cc8cc004004dd6180918079baa0072259800800c52000899b8048008cc008008c05000501119198008009bac3012300f375401044b30010018a4001133700900119801001180a000a022899199119914c00400a003480050021112cc00400a2946264b300133710004003159800acc004c02cc050dd519803002800c528c52820268cc0040126032007001401114a0809a29410131bad301700240546eb0c050c044dd500498008009bac3012300f3754010444b30010028a6103d87a80008acc004c01c006266e9520003301330140024bd70466002007301500299b8048004005003201e404914a080622646600600660260046eb4c04400500f45900d18059baa0038b2012300c300937540086e1d20008acc004cdc3a400c00713233224a26eb4c034004c034c038004c024dd5002459007200e18041804800980400098019baa0088a4d13656400401"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/plutus_v4_guarded_sub_transaction_example.c, ALWAYS_SUCCEEDS_VALIDATOR_V4.+v4Validator :: IO (Either Error Plutus.PlutusScript)+v4Validator = program Plutus.V4 "450100002499"++-- Source: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- examples/src/plutus_v4_guarded_sub_transaction_example.c, ALWAYS_SUCCEEDS_GUARD_V4.+v4Guard :: IO (Either Error Plutus.PlutusScript)+v4Guard = program Plutus.V4 "450101002499"
@@ -0,0 +1,38 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Terminal input for wallet secrets. Echo is restored even if reading fails.+module Support.Terminal (secret, password) where++import Control.Exception (bracket, finally)+import Control.Monad (unless)+import Data.ByteString (ByteString)+import Data.Text (Text)+import qualified Data.Text.Encoding as Text+import qualified Data.Text.IO as Text+import System.IO (hFlush, hGetEcho, hIsTerminalDevice, hSetEcho, stdin, stdout)++secret :: String -> IO Text+secret prompt = do+ terminal <- hIsTerminalDevice stdin+ unless terminal (ioError (userError "Wallet secrets require an interactive terminal"))+ bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do+ hSetEcho stdin False+ putStr prompt+ hFlush stdout+ Text.getLine `finally` putStrLn ""++password :: FilePath -> IO ByteString+password file = Text.encodeUtf8 <$> secret ("Password for " <> file <> ": ")
@@ -0,0 +1,111 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Wallet/provider setup and address-index synchronization for the examples.+module Support.Transaction (Context (..), builderConfig, awaitWallet, outputAt) where++import Cometa.Address (Address)+import Cometa.Error (Error (..))+import Cometa.NetworkId (NetworkId)+import qualified Cometa.Provider as Provider+import Cometa.Signer (Signer)+import Cometa.SlotConfig (SlotConfig)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Fields as Fields+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+-- Standard library and error handling.+import Control.Concurrent (threadDelay)+import Control.Monad (unless)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.List (sort)+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)++data Context = Context+ { provider :: Provider.Provider,+ wallet :: Address,+ signer :: Signer,+ network :: NetworkId,+ slots :: SlotConfig,+ invalidAfter :: Word64,+ collateral :: [Input],+ extraSigners :: Word64,+ confirmationTimeoutMillis :: Word64+ }++builderConfig :: Context -> IO (Either Error Builder.Config)+builderConfig context = runExceptT $ do+ let backend = provider context+ params <- ExceptT (Provider.protocolParameters backend)+ funds <- ExceptT (Provider.utxosAt backend (wallet context))+ reserved <- ExceptT (Provider.resolveInputs backend (collateral context))+ unless (sort (map Utxo.input reserved) == sort (collateral context)) $+ throwE (InvalidBuildingRequest "Every configured collateral input must resolve exactly once")++ let settings =+ (Builder.defaultConfig params (slots context) (wallet context))+ { Builder.availableUtxos = filter (\value -> Utxo.input value `notElem` collateral context) funds,+ Builder.collateralUtxos = reserved,+ Builder.extraSigners = extraSigners context+ }+ pure settings++awaitWallet :: Context -> Tx.Transaction -> IO (Either Error ())+awaitWallet = awaitWalletSnapshot getMonotonicTimeNSec (threadDelay 1000000)++awaitWalletSnapshot :: IO Word64 -> IO () -> Context -> Tx.Transaction -> IO (Either Error ())+awaitWalletSnapshot clock pause context transaction = runExceptT $ do+ identifier <- ExceptT (Tx.transactionId transaction)++ let fields = Body.bodyFields (Body.toBody (Tx.body transaction))+ expected =+ [ Utxo.utxo (Input.input identifier index) output+ | (index, output) <- zip [0 ..] (Fields.fieldOutputs fields),+ Output.address output == wallet context+ ]+ consumed = Fields.fieldInputs fields+ started <- liftIO clock++ let deadline = toInteger started + toInteger (confirmationTimeoutMillis context) * 1000000+ poll = runExceptT $ do+ current <- ExceptT (Provider.utxosAt (provider context) (wallet context))+ if all (`elem` current) expected && all ((`notElem` consumed) . Utxo.input) current+ then pure ()+ else do+ now <- liftIO clock+ if toInteger now >= deadline+ then throwE (InvalidBuildingRequest "Confirmed transaction is not yet reflected in the wallet index; dependent stages stopped")+ else liftIO pause >> ExceptT poll+ ExceptT poll++outputAt :: Tx.Transaction -> Word64 -> IO (Either Error Utxo)+outputAt transaction index = runExceptT $ do+ identifier <- ExceptT (Tx.transactionId transaction)++ let outputs = Fields.fieldOutputs (Body.bodyFields (Body.toBody (Tx.body transaction)))+ output <- except (at index outputs)+ pure (Utxo.utxo (Input.input identifier index) output)+ where+ at 0 (value : _) = Right value+ at n (_ : rest) = at (n - 1) rest+ at _ [] = Left (InvalidBuildingRequest "Workflow output index is absent")
@@ -0,0 +1,259 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Scoped configuration for the explicitly submitted connected examples.+module Support.Wallet (WalletContext (..), entrypoint, entrypointWithDescription, withWalletFile, required, unsigned, resolveReference) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import Cometa.Credential (Credential, DRep, Payment, Stake)+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Bip32.PublicKey as Public+import qualified Cometa.Crypto.DerivationPath as Path+import Cometa.Error (Error (..))+import qualified Cometa.KeyHandler.Software as Software+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost as Blockfrost+import qualified Cometa.Signer as Signer+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction.Input as Input+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (void)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.ByteString as Bytes+import Data.List.NonEmpty (NonEmpty (..))+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.IO as Text+import Data.Word (Word64)+import Numeric (showHex)+-- Shared example setup.+import qualified Support.Configuration as Common+import qualified Support.Terminal as Terminal+import qualified Support.Transaction as Native+import System.Environment (getArgs, lookupEnv)+import System.Exit (die)+import System.IO (hFlush, stdout)+import Text.Read (readMaybe)++-- TYPES ----------------------------------------------------------------------++data WalletContext = WalletContext+ { context :: Native.Context,+ paymentCredential :: Credential Payment,+ stakeCredential :: Credential Stake,+ drepCredential :: Credential DRep,+ signSubTransaction :: Sub.SubTransaction -> IO (Either Error Sub.SubTransaction)+ }++-- | Validated environment settings, kept separate from native resources.+data WalletSettings = WalletSettings+ { expirySlot :: Word64,+ reservedCollateral :: [Input.Input],+ protectedInputs :: [Input.Input],+ stakeAuthority :: Path.Index,+ drepAuthority :: Path.Index+ }++-- DEFINITIONS ----------------------------------------------------------------++required :: String -> IO (Either Error Text)+required = Common.required++unsigned :: Text -> Either Error Word64+unsigned text = case readMaybe (Text.unpack text) :: Maybe Integer of+ Just value | value >= 0 && value <= toInteger (maxBound :: Word64) -> Right (fromInteger value)+ _ -> Left (InvalidProviderConfiguration "Expected an unsigned 64-bit decimal value")++reference :: Text -> Either Error Input.Input+reference text = case Text.splitOn "#" text of+ [hash, index] -> Input.input <$> Id.fromHex hash <*> unsigned index+ _ -> Left (InvalidProviderConfiguration "Expected a transaction output reference TXID#INDEX")++resolveReference :: Native.Context -> String -> IO (Either Error Utxo)+resolveReference ctx variable = runExceptT $ do+ ref <- ExceptT (required variable) >>= except . reference+ values <- ExceptT (Provider.resolveInputs (Native.provider ctx) [ref])+ except $ case values of+ [value] -> Right value+ _ -> Left (InvalidBuildingRequest "Configured reference output is absent or spent")++-- | Open the wallet, run the example and report its error once. Results may have any shape.+entrypoint :: String -> (WalletContext -> IO (Either Error a)) -> IO ()+entrypoint name = entrypointWithDescription name (const (pure (Right [])))++entrypointWithDescription ::+ String ->+ (WalletContext -> IO (Either Error [(Text, Text)])) ->+ (WalletContext -> IO (Either Error a)) ->+ IO ()+entrypointWithDescription name describe run = do+ arguments <- getArgs+ case arguments of+ ["--describe"] -> execute $ \wallet -> runExceptT $ do+ liftIO (printWallet wallet)+ extra <- ExceptT (describe wallet)+ liftIO (mapM_ (\(label, value) -> Text.putStrLn (label <> ": " <> value)) extra)+ [] -> execute $ \wallet -> fmap void (run wallet)+ ["--submit"] -> execute $ \wallet -> fmap void (run wallet)+ ["--help"] -> do+ putStrLn (name <> ": unlock the wallet, build, sign, submit and confirm.")+ putStrLn "Run without arguments for the complete flow, or --describe for public identifiers."+ putStrLn "See the connected examples guide for configuration."+ _ -> die ("Unknown arguments; use " <> name <> " --help")+ where+ execute action = do+ configured <- Common.configuration+ result <- case configured of+ Left failure -> pure (Left failure)+ Right config -> do+ file <- required "COMETA_KEY_HANDLER_FILE"+ either (pure . Left) (\path -> openWallet config (Text.unpack path) action) file+ either (die . show) pure result++printWallet :: WalletContext -> IO ()+printWallet wallet = do+ Text.putStrLn ("Wallet: " <> Address.toText (Native.wallet (context wallet)))+ Text.putStrLn ("Stake account: " <> Reward.toText (Reward.fromCredential (Native.network (context wallet)) (stakeCredential wallet)))++ let bytes = case drepCredential wallet of+ Credential.KeyCredential hash -> Credential.keyHashBytes hash+ Credential.ScriptCredential hash -> Credential.scriptHashBytes hash+ hexByte value = let digits = showHex value "" in if length digits == 1 then '0' : digits else digits+ Text.putStrLn ("DRep credential hash: " <> Text.pack (concatMap hexByte (Bytes.unpack bytes)))++journal :: Provider.Provider -> Provider.Provider+journal backend =+ backend+ { Provider.submitTransaction = \tx -> do+ result <- Provider.submitTransaction backend tx+ case result of+ Right identifier -> Text.putStrLn ("Accepted: " <> Id.toHex identifier) >> hFlush stdout+ Left _ -> pure ()+ pure result,+ Provider.awaitTransaction = \identifier timeout -> do+ result <- Provider.awaitTransaction backend identifier timeout+ case result of+ Right True -> Text.putStrLn ("Confirmed: " <> Id.toHex identifier) >> hFlush stdout+ _ -> pure ()+ pure result+ }++-- | Open another encrypted wallet for independently signed batch intents.+withWalletFile :: FilePath -> (WalletContext -> IO (Either Error a)) -> IO (Either Error a)+withWalletFile file action = do+ configured <- Common.configuration+ either (pure . Left) (\config -> openWallet config file action) configured++openWallet ::+ Blockfrost.Config ->+ FilePath ->+ (WalletContext -> IO (Either Error a)) ->+ IO (Either Error a)+openWallet config file action = Blockfrost.withProvider config $ \backend -> withWallet config (journal backend) file action++withWallet ::+ Blockfrost.Config ->+ Provider.Provider ->+ FilePath ->+ (WalletContext -> IO (Either Error a)) ->+ IO (Either Error a)+withWallet config backend file action = do+ settings <- walletSettings+ case settings of+ Left failure -> pure (Left failure)+ Right+ WalletSettings+ { expirySlot = expiry,+ reservedCollateral = reserved,+ protectedInputs = protected,+ stakeAuthority = stakeIndex,+ drepAuthority = drepIndex+ } -> do+ stored <- Bytes.readFile file++ let network = Common.addressNetwork (Blockfrost.network config)+ selectionBackend = backend {Provider.utxosAt = fmap (fmap (filter ((`notElem` protected) . Utxo.input))) . Provider.utxosAt backend}+ makeContext address signer count =+ Native.Context+ { Native.provider = selectionBackend,+ Native.wallet = address,+ Native.signer = signer,+ Native.network = network,+ Native.slots = Common.networkSlots (Blockfrost.network config),+ Native.invalidAfter = expiry,+ Native.collateral = reserved,+ Native.extraSigners = count,+ Native.confirmationTimeoutMillis = 300000+ }+ finish payment stake drep address signer count signLocal = action (WalletContext (makeContext address signer count) payment stake drep signLocal)+ Software.withSerialized stored (Terminal.password file) $ \case+ Software.Ed25519Handler handler -> runExceptT $ do+ public <- ExceptT (Software.publicKey handler)+ payment <- ExceptT (Credential.fromPublicKey public)+ stake <- ExceptT (Credential.fromPublicKey public)+ drep <- ExceptT (Credential.fromPublicKey public)++ let address = Address.ShelleyAddress (Shelley.enterprise network payment)+ signLocal sub = fmap (>>= (`Sub.addWitnesses` sub)) (Software.signSubTransaction handler sub)+ ExceptT (finish payment stake drep address (Signer.software handler) 0 signLocal)+ Software.Bip32Handler handler -> runExceptT $ do+ let account = Path.standardAccountPath minBound+ paymentPath = Path.derivationPath account Path.externalRole minBound+ addressStakePath = Path.derivationPath account Path.stakingRole minBound+ stakePath = Path.derivationPath account Path.stakingRole stakeIndex+ drepPath = Path.derivationPath account Path.drepRole drepIndex+ paths = paymentPath :| [stakePath, drepPath]+ accountKey <- ExceptT (Software.accountPublicKey handler account)++ let credential path = ExceptT (Public.derive accountKey (Path.relativeIndices path)) >>= ExceptT . Credential.fromPublicKey . Public.toEd25519+ payment <- credential paymentPath+ addressStake <- credential addressStakePath+ stake <- credential stakePath+ drep <- credential drepPath++ let address = Address.ShelleyAddress (Shelley.base network payment addressStake)+ signLocal sub = fmap (>>= (`Sub.addWitnesses` sub)) (Software.signSubTransactionAt handler paths sub)+ ExceptT (finish payment stake drep address (Signer.bip32 handler paths) 2 signLocal)++walletSettings :: IO (Either Error WalletSettings)+walletSettings = do+ expiry <- required "COMETA_INVALID_AFTER_SLOT"+ collateral <- lookupEnv "COMETA_COLLATERAL"+ protected <- lookupEnv "COMETA_RESERVED_INPUTS"+ stakeIndex <- lookupEnv "COMETA_STAKE_INDEX"+ drepIndex <- lookupEnv "COMETA_DREP_INDEX"+ pure $ do+ validity <- expiry >>= unsigned+ reserved <- references collateral+ excluded <- references protected+ stake <- authorityIndex stakeIndex+ drep <- authorityIndex drepIndex+ pure WalletSettings {expirySlot = validity, reservedCollateral = reserved, protectedInputs = excluded, stakeAuthority = stake, drepAuthority = drep}+ where+ references = traverse reference . maybe [] (Text.splitOn "," . Text.pack)+ authorityIndex Nothing = Path.mkIndex 701+ authorityIndex (Just value) = case readMaybe value of+ Nothing -> Left (InvalidProviderConfiguration "Invalid authority derivation index")+ Just index -> Path.mkIndex index
@@ -0,0 +1,136 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module VoteForProposalPubkey (main, voteKey) where++import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..), DRep)+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import Cometa.Governance.ActionId (ActionId)+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "VoteForProposalPubkey" (Inputs.describe Nothing) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ action <- ExceptT Inputs.actionId+ ExceptT (voteKey context (Support.drepCredential wallet) action)++-- | Register a fresh DRep, vote on the supplied action, then reclaim its deposit.+voteKey :: Workflow.Context -> Credential DRep -> ActionId -> IO (Either Error [Transaction])+voteKey context drep action = runExceptT $ do+ (_, drepAmount) <- ExceptT (deposits context)+ anchor <- except representativeAnchor++ let certify = Plan.certificate++ registered <- submitPlan context (certify (Certificate.RegisterDRep drep drepAmount (Just anchor)))++ let voter = Voting.DRepVoter drep+ procedure = Voting.VotingProcedure Voting.Yes Nothing+ vote = Plan.vote voter action procedure++ voted <- submitPlan context vote++ cleaned <- submitPlan context (certify (Certificate.UnregisterDRep drep drepAmount))++ pure [registered, voted, cleaned]++deposits :: Workflow.Context -> IO (Either Error (Word64, Word64))+deposits context = runExceptT $ do+ parameters <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ drepAmount <- case Parameters.parameterDrepDeposit parameters of+ Just amount -> pure amount+ Nothing -> throwE (InvalidBuildingRequest "DRep deposit is unavailable in the current protocol parameters")+ pure (Parameters.parameterKeyDeposit parameters, drepAmount)++representativeAnchor :: Either Error Anchor.Anchor+representativeAnchor =+ makeAnchor+ "https://storage.googleapis.com/biglup/Angel_Castillo.jsonld"+ "26ce09df4e6f64fe5cf248968ab78f4b8a0092580c234d78f68c079c0fce34f0"++makeAnchor :: Text -> Text -> Either Error Anchor.Anchor+makeAnchor url hash = Anchor.Anchor <$> Anchor.mkUrl url <*> (Blake2b.fromHex hash >>= Anchor.dataHashFromBytes . Blake2b.toBytes)++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,155 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module VoteForProposalScript (main, voteScript) where++import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential (..))+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import Cometa.Governance.ActionId (ActionId)+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Signer as Signer+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+-- Standard library and error handling.+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Text (Text)+import Data.Word (Word64)+-- Shared example setup.+import qualified Support.Inputs as Inputs+import qualified Support.Transaction as Workflow+import qualified Support.Wallet as Support++main :: IO ()+main = Support.entrypointWithDescription "VoteForProposalScript" (Inputs.describe (Just "COMETA_GOVERNANCE_REFERENCE")) $ \wallet -> runExceptT $ do+ let context = Support.context wallet+ reference <- ExceptT (Support.resolveReference context "COMETA_GOVERNANCE_REFERENCE")+ action <- ExceptT Inputs.actionId+ ExceptT (voteScript context reference action)++-- | Register, vote and deregister using the configured V3 script authority.+voteScript :: Workflow.Context -> Utxo -> ActionId -> IO (Either Error [Transaction])+voteScript context reference action = runExceptT $ do+ script <- except (governanceScript reference)+ hash <- ExceptT (Script.hash script)+ (_, drepAmount) <- ExceptT (deposits context)+ anchor <- except representativeAnchor++ let drep = ScriptCredential hash+ certify certificate = Plan.attachScript script <> Plan.certificateWithRedeemer certificate voidArgument++ registered <- submitPlan context (certify (Certificate.RegisterDRep drep drepAmount (Just anchor)))++ let voter = Voting.DRepVoter drep+ procedure = Voting.VotingProcedure Voting.Yes Nothing+ vote = Plan.attachScript script <> Plan.voteWithRedeemer voter [(action, procedure)] voidArgument++ voted <- submitPlan context vote++ cleaned <- submitPlan context (certify (Certificate.UnregisterDRep drep drepAmount))++ pure [registered, voted, cleaned]++deposits :: Workflow.Context -> IO (Either Error (Word64, Word64))+deposits context = runExceptT $ do+ parameters <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ drepAmount <- case Parameters.parameterDrepDeposit parameters of+ Just amount -> pure amount+ Nothing -> throwE (InvalidBuildingRequest "DRep deposit is unavailable in the current protocol parameters")+ pure (Parameters.parameterKeyDeposit parameters, drepAmount)++governanceScript :: Utxo -> Either Error Script+governanceScript reference = case Output.referenceScript (Utxo.output reference) of+ Just script@(Script.Plutus compiled) | Plutus.version compiled == Plutus.V3 -> Right script+ _ -> Left (InvalidBuildingRequest "Expected a resolved Plutus V3 governance reference script")++representativeAnchor :: Either Error Anchor.Anchor+representativeAnchor =+ makeAnchor+ "https://storage.googleapis.com/biglup/Angel_Castillo.jsonld"+ "26ce09df4e6f64fe5cf248968ab78f4b8a0092580c234d78f68c079c0fce34f0"++makeAnchor :: Text -> Text -> Either Error Anchor.Anchor+makeAnchor url hash = Anchor.Anchor <$> Anchor.mkUrl url <*> (Blake2b.fromHex hash >>= Anchor.dataHashFromBytes . Blake2b.toBytes)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++-- | Run one stage; dependent stages start only after confirmation and indexing.+submitPlan :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+submitPlan ctx plan = do+ unsignedTx <- buildTransaction ctx plan+ signedTx <- signTransaction ctx unsignedTx++ txId <- submitTransaction ctx signedTx+ awaitConfirmation ctx signedTx txId++ pure signedTx++-- | Fetch current wallet inputs and parameters, then apply the configured expiry.+buildTransaction :: Workflow.Context -> Plan.Plan -> ExceptT Error IO Tx.Transaction+buildTransaction ctx plan = do+ settings <- ExceptT (Workflow.builderConfig ctx)+ ExceptT $+ Builder.build settings (plan <> Plan.validUntil (Workflow.invalidAfter ctx))++-- | The scoped wallet requests its password and supplies the required witnesses.+signTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Tx.Transaction+signTransaction ctx unsignedTx = do+ witnesses <-+ ExceptT (Signer.signTransaction (Workflow.signer ctx) unsignedTx)+ except (Tx.addWitnesses witnesses unsignedTx)++-- | Submit once and verify the provider accepted this exact transaction body.+submitTransaction :: Workflow.Context -> Tx.Transaction -> ExceptT Error IO Id.TransactionId+submitTransaction ctx signedTx = do+ expected <- ExceptT (Tx.transactionId signedTx)+ accepted <- ExceptT (Provider.submitTransaction (Workflow.provider ctx) signedTx)++ unless (accepted == expected) $+ throwE (InvalidProviderResponse "Submitted transaction ID mismatch")++ pure accepted++-- | Stop on timeout; wait for the wallet index before spending dependent outputs.+awaitConfirmation :: Workflow.Context -> Tx.Transaction -> Id.TransactionId -> ExceptT Error IO ()+awaitConfirmation ctx signedTx txId = do+ confirmed <-+ ExceptT $+ Provider.awaitTransaction+ (Workflow.provider ctx)+ txId+ (Workflow.confirmationTimeoutMillis ctx)++ unless confirmed $+ throwE (InvalidBuildingRequest "Transaction confirmation timed out")++ ExceptT (Workflow.awaitWallet ctx signedTx)
@@ -0,0 +1,271 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Deterministic secret-key lifetime. One lock protects the closed state and+-- spans every native use, including copying borrowed data. No public callback+-- runs under that lock. Closing waits for existing operations, then wipes and+-- releases the native allocation; escaped handles retain only the closed state.+module Cometa.Internal.Bip32PrivateKey+ ( Key,+ Failure (..),+ withBytesKey,+ withHexKey,+ withDerived,+ withEntropy,+ withSigningKey,+ withClone,+ close,+ publicKeyBytes,+ exportBytes,+ byteLength,+ withKey,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Bip32 as Native+import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.Failure as Failure+import Cometa.Internal.Ownership (copyStaticText)+import qualified Cometa.Internal.SigningKey as Signing+import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, withMVar)+import Control.Exception (bracket, evaluate, finally, mask, uninterruptibleMask_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Char (isDigit)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Marshal.Array (withArrayLen)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | No printable or equality instance: this contains a secret ownership state.+newtype Key = Key (MVar (Maybe (Ptr Native.NativeKey)))++-- | Sanitized failures. Lengths are expected then actual; no input is retained.+data Failure+ = Closed+ | InvalidLength !Int !Int+ | InvalidHex+ | NativeFailure !Failure.NativeFailure+ deriving (Eq, Show)++type Acquisition = Ptr (Ptr Native.NativeKey) -> IO (Either Failure ())++type Import = Ptr Word8 -> CSize -> Ptr (Ptr Native.NativeKey) -> IO Status.NativeCode++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 96 bytes; only the encoded length is checked.+withBytesKey :: ByteString -> (Key -> IO value) -> IO (Either Failure value)+withBytesKey = importBytes "bip32.withKey" 96 Native.cFromBytes++-- | Import validated ASCII hex without decoding an extra host secret buffer.+withHexKey :: Text -> (Key -> IO value) -> IO (Either Failure value)+withHexKey = importHex "bip32.withKeyHex" 96 Native.cFromHex++-- | Derive into independent ownership. Evaluate the complete caller-owned path+-- before taking the source lock; the continuation runs outside that lock.+withDerived :: Key -> [Word32] -> (Key -> IO value) -> IO (Either Failure value)+withDerived source [] = withClone source+withDerived source path = \action -> withArrayLen path $ \size indices ->+ withAcquiredKey+ "bip32.withDerived"+ ( \output ->+ withKey source $ \pointer ->+ checkStatus+ "bip32.withDerived"+ (Native.cDerive pointer indices (fromIntegral size) output)+ )+ action++-- | Root derivation borrows password and entropy through the complete call.+-- Length policy is imposed by the public layer before this internal seam.+withEntropy :: ByteString -> ByteString -> (Key -> IO value) -> IO (Either Failure value)+withEntropy password entropy action = withBytes password $ \passwordBytes passwordSize ->+ withBytes entropy $ \entropyBytes entropySize ->+ withAcquiredKey "bip32.withEntropy" (acquire passwordBytes passwordSize entropyBytes entropySize) action+ where+ acquire passwordBytes passwordSize entropyBytes entropySize output =+ checkStatus "bip32.withEntropy" (Native.cFromEntropy passwordBytes passwordSize entropyBytes entropySize output)++-- | Transfer a fresh native Ed25519 key directly into its independent scope.+-- No intermediate Haskell secret bytes are created. Neither callback holds a lock.+withSigningKey :: Key -> (Signing.Key -> IO value) -> IO (Either Failure value)+withSigningKey source action = do+ result <-+ Signing.withAcquiredKey+ "bip32.withSigningKey"+ ( \output -> do+ converted <- withKey source $ \pointer -> checkStatus "bip32.withSigningKey" (Native.cToSigningKey pointer output)+ pure (either (Left . toSigningFailure) Right converted)+ )+ action+ pure (either (Left . fromSigningFailure) Right result)+ where+ toSigningFailure Closed = Signing.Closed+ toSigningFailure (InvalidLength expected actual) = Signing.InvalidLength expected actual+ toSigningFailure InvalidHex = Signing.InvalidHex+ toSigningFailure (NativeFailure failure) = Signing.NativeFailure failure+ fromSigningFailure Signing.Closed = Closed+ fromSigningFailure (Signing.InvalidLength expected actual) = InvalidLength expected actual+ fromSigningFailure Signing.InvalidHex = InvalidHex+ fromSigningFailure (Signing.NativeFailure failure) = NativeFailure failure++-- | Clone while holding the source lock, then scope the independent key outside+-- that lock. Closing either key never invalidates the other one's native storage.+withClone :: Key -> (Key -> IO value) -> IO (Either Failure value)+withClone source = withAcquiredKey operation $ \output ->+ withKey source $ \pointer -> checkStatus operation (Native.cClone pointer output)+ where+ operation = "bip32.withClone"++-- | Wait for native operations, invalidate the local handle and release once.+-- Only trusted finite native work holds the lock; no application callback may do so.+close :: Key -> IO ()+close (Key state) = uninterruptibleMask_ $ modifyMVar_ state $ \current -> do+ maybe (pure ()) releasePointer current+ pure Nothing++-- | Derive and copy public bytes while holding the key alive.+publicKeyBytes :: Key -> IO (Either Failure ByteString)+publicKeyBytes key = withKey key $ \pointer ->+ copyOutput "bip32.publicKey" 64 (Native.cPublicKey pointer)++-- | Copy secret storage directly into a host ByteString, without an intermediate+-- native export buffer. The copy has no controlled erasure or lifetime guarantee.+exportBytes :: Key -> IO (Either Failure ByteString)+exportBytes key = withKey key $ \pointer -> do+ size <- Native.cSize pointer+ bytes <- Native.cData pointer+ if bytes == nullPtr || size /= 96+ then pure (contractFailure "bip32.exportBytes")+ else Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)++-- | Read only the fixed-size scalar metadata, without copying any secret bytes.+byteLength :: Key -> IO (Either Failure Int)+byteLength key = withKey key $ \pointer -> do+ size <- Native.cSize pointer+ pure $+ if size == 96+ then Right (fromIntegral size)+ else contractFailure "bip32.byteLength"++-- | Trusted internal operation/test seam. Holds the key lock through the entire+-- action; reject closed handles before exposing any pointer. The action must not+-- escape the pointer, run application callbacks or force application-owned input.+withKey :: Key -> (Ptr Native.NativeKey -> IO (Either Failure value)) -> IO (Either Failure value)+withKey (Key state) action = withMVar state $ \current ->+ maybe (pure (Left Closed)) action current++-- | Validate all application input before construction. Native import copies it.+importBytes :: Text -> Int -> Import -> ByteString -> (Key -> IO value) -> IO (Either Failure value)+importBytes operation expected importKey bytes action+ | actual /= expected = pure (Left (InvalidLength expected actual))+ | otherwise = withAcquiredKey operation acquire action+ where+ actual = ByteString.length bytes+ acquire output = withBytes bytes $ \pointer size ->+ checkStatus operation (importKey pointer size output)++-- | Validate ASCII hex without decoding it into an additional host secret byte+-- array. UTF-8 marshaling still creates host storage which Haskell does not erase.+importHex :: Text -> Int -> Import -> Text -> (Key -> IO value) -> IO (Either Failure value)+importHex operation expected importKey text action+ | Text.null text || odd digits || not (Text.all isHex text) = pure (Left InvalidHex)+ | actual /= expected = pure (Left (InvalidLength expected actual))+ | otherwise = withAcquiredKey operation acquire action+ where+ digits = Text.length text+ actual = digits `div` 2+ acquire output = withBytes (Text.encodeUtf8 text) $ \pointer size ->+ checkStatus operation (importKey pointer size output)+ isHex character =+ isDigit character+ || (character >= 'a' && character <= 'f')+ || (character >= 'A' && character <= 'F')++-- | Install ownership-aware cleanup before unmasked acquisition and retain it+-- through the callback. Publication is masked; the finalizer handles either+-- ownership state even if an exception arrives between publication and slot clear.+withAcquiredKey :: Text -> Acquisition -> (Key -> IO value) -> IO (Either Failure value)+withAcquiredKey operation acquire action = mask $ \restore -> do+ state <- newMVar Nothing+ key <- evaluate (Key state)+ alloca $ \slot ->+ bracket (poke slot nullPtr >> pure slot) (closeAcquiredKey key) $ \output -> do+ result <- restore (acquire output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ pointer <- peek output+ if pointer == nullPtr+ then pure (contractFailure operation)+ else do+ modifyMVar_ state (const (pure (Just pointer)))+ poke output nullPtr+ Right <$> restore (action key)++-- | Consume exactly one reference across publication. A populated state is the+-- authority even while the output slot temporarily aliases it. Otherwise the+-- slot owns any partial acquisition result. Early 'close' leaves both empty.+closeAcquiredKey :: Key -> Ptr (Ptr Native.NativeKey) -> IO ()+closeAcquiredKey (Key state) slot = uninterruptibleMask_ $ modifyMVar_ state $ \current -> do+ case current of+ Nothing -> releaseSlot slot+ Just pointer -> releasePointer pointer `finally` poke slot nullPtr+ pure Nothing++-- | Consume one local obligation, irrespective of whether native unref nulls it.+releaseSlot :: Ptr (Ptr Native.NativeKey) -> IO ()+releaseSlot slot = Native.cUnref slot `finally` poke slot nullPtr++-- | Release a state-owned reference through the typed pointer-to-pointer API.+releasePointer :: Ptr Native.NativeKey -> IO ()+releasePointer pointer = alloca $ \slot -> poke slot pointer >> releaseSlot slot++-- | Public outputs contain no secret material and have fixed length.+copyOutput :: Text -> Int -> (Ptr Word8 -> IO Status.NativeCode) -> IO (Either Failure ByteString)+copyOutput operation size call = allocaBytes size $ \output -> do+ result <- checkStatus operation (call output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> Right <$> ByteString.packCStringLen (castPtr output, size)++-- | Copy static native diagnostics; operation labels never contain key input.+checkStatus :: Text -> IO Status.NativeCode -> IO (Either Failure ())+checkStatus operation action = do+ code <- action+ if code == Status.success+ then pure (Right ())+ else do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (NativeFailure (Failure.NativeFailure operation (toInteger code) message)))++contractFailure :: Text -> Either Failure value+contractFailure = Left . NativeFailure . Failure.NativeContractFailure++-- | Keep marshaled bytes alive only through the chosen native action.+withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)
@@ -0,0 +1,111 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Operation-scoped BIP39 marshaling. Native conversion has no acquired owner.+-- Scratch entropy is wiped on success, failure and cancellation after foreign+-- unwind. Validation does not copy entropy into a hidden host ByteString.+-- Native stack intermediates and ordinary host secret values are not erased.+module Cometa.Internal.Bip39 (fromEntropy, validate, exportEntropy) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Bip39 as Native+import Cometa.Internal.FFI.Native (NativeCode, cErrorMessage, success)+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyStaticText)+import Control.Exception (evaluate, finally)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word8)+import Foreign.C.String (CString)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Marshal.Array (allocaArray, peekArray, pokeArray, withArray)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- DEFINITIONS ----------------------------------------------------------------++-- | Borrow validated entropy and copy static words before leaving the scope.+fromEntropy :: ByteString -> IO (Either NativeFailure [Text])+fromEntropy entropy = ByteString.useAsCString entropy $ \input ->+ allocaArray 24 $ \output -> alloca $ \count -> do+ pokeArray output (replicate 24 nullPtr)+ poke count 0+ status <- Native.cFromEntropy (castPtr input) (fromIntegral size) output count+ actual <- peek count+ if status /= success+ then Left <$> nativeFailure "bip39.fromEntropy" status+ else+ if actual /= fromIntegral (size * 3 `div` 4)+ then pure (Left (NativeContractFailure "bip39.fromEntropy"))+ else do+ pointers <- peekArray (fromIntegral actual) output+ if nullPtr `elem` pointers+ then pure (Left (NativeContractFailure "bip39.fromEntropy"))+ else do+ bytes <- mapM ByteString.packCString pointers+ evaluate $ case traverse Text.decodeUtf8' bytes of+ Left _ -> Left (NativeContractFailure "bip39.fromEntropy")+ Right words' -> forceWords words' `seq` Right words'+ where+ size = ByteString.length entropy++-- | Validate without exporting a host copy of the secret entropy.+validate :: [Text] -> IO (Either NativeFailure ())+validate words' = decodeEntropy words' (\_ _ -> pure ())++-- | Copy entropy only when explicitly requested by the public caller.+exportEntropy :: [Text] -> IO (Either NativeFailure ByteString)+exportEntropy words' = decodeEntropy words' $ \output size -> do+ bytes <- ByteString.packCStringLen (castPtr output, size)+ evaluate (ByteString.length bytes `seq` bytes)++decodeEntropy :: [Text] -> (Ptr Word8 -> Int -> IO a) -> IO (Either NativeFailure a)+decodeEntropy words' consume =+ withWords words' $ \inputs -> allocaBytes 32 $ \output ->+ decodeOutput words' inputs output consume `finally` Native.cClear output 32++decodeOutput :: [Text] -> Ptr CString -> Ptr Word8 -> (Ptr Word8 -> Int -> IO a) -> IO (Either NativeFailure a)+decodeOutput words' inputs output consume = alloca $ \size -> do+ poke size 0+ status <- Native.cToEntropy inputs (fromIntegral (length words')) output 32 size+ actual <- peek size+ if status == success+ then+ if actual == fromIntegral (length words' * 4 `div` 3)+ then Right <$> consume output (fromIntegral actual)+ else pure (Left (NativeContractFailure "bip39.toEntropy"))+ else Left <$> nativeFailure "bip39.toEntropy" status++-- Every temporary UTF-8 input is borrowed only within its nested scope.+withWords :: [Text] -> (Ptr CString -> IO a) -> IO a+withWords words' action = go words' []+ where+ go [] pointers = withArray (reverse pointers) action+ go (word : rest) pointers = ByteString.useAsCString (Text.encodeUtf8 word) $ \pointer -> go rest (pointer : pointers)++nativeFailure :: Text -> NativeCode -> IO NativeFailure+nativeFailure operation status = do+ diagnostic <- cErrorMessage status >>= copyStaticText+ evaluate (NativeFailure operation (fromIntegral status) diagnostic)++-- Complete strict decoded words before the static-pointer/input scope ends.+forceWords :: [Text] -> ()+forceWords = foldr (seq . Text.length) ()
@@ -0,0 +1,231 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Rooted callback state and exception containment. A native operation and a+-- callback's user action each have one scoped worker. Cancellation targets the+-- user worker; the ABI callback always waits for it before returning to C.+module Cometa.Internal.Callback+ ( -- * Callback state+ ConfirmationHandler,+ CallbackState,+ CallbackControl,+ newCallbackControl,+ newCallbackState,++ -- * Operation lifetime+ beginCallbackOperation,+ finishCallbackOperation,+ cancelCallbackOperation,+ rethrowCallbackException,++ -- * Native entry point+ confirmationCallback,++ -- * Callback execution+ runCallbackWorker,+ rememberCallbackException,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Provider as Native+import Control.Concurrent (ThreadId, forkIOWithUnmask, newEmptyMVar, putMVar, readMVar, takeMVar, throwTo)+import Control.Concurrent.MVar (MVar, modifyMVar, modifyMVar_, newMVar, withMVar)+import Control.Exception (MaskingState (..), SomeException, catch, evaluate, mask, mask_, throwIO, try, uninterruptibleMask_)+import Control.Monad (when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Foreign.C.String (CString)+import Foreign.C.Types (CChar, CSize)+import Foreign.Marshal.Utils (copyBytes)+import Foreign.Ptr (castPtr, nullPtr)+import Foreign.StablePtr (deRefStablePtr)+import Foreign.Storable (poke, pokeByteOff)++-- TYPES ----------------------------------------------------------------------++-- | Timeout is milliseconds; the hash is an owned 32-byte Haskell snapshot.+-- Expected failures return text. Thrown exceptions propagate after C returns.+-- The user action runs on its own Haskell thread, with the initiating caller's+-- masking state. It must finish before the callback and its native call finish.+type ConfirmationHandler = ByteString -> Word64 -> IO (Either Text Bool)++-- | One serialized operation: caller masking state, first callback exception,+-- pending cancellation, and the currently running user worker, respectively.+data Operation = Operation MaskingState (IORef (Maybe SomeException)) (Maybe SomeException) (Maybe ThreadId)++-- | Provider-wide state shared by retained aliases. 'Nothing' means no native+-- operation may invoke the callback; the provider's operation gate enforces this.+newtype CallbackControl = CallbackControl (MVar (Maybe Operation))++-- | Handler and operation state rooted by the native context's stable pointer.+data CallbackState = CallbackState ConfirmationHandler CallbackControl++-- DEFINITIONS ----------------------------------------------------------------++-- | Start with no active operation or retained exception.+newCallbackControl :: IO CallbackControl+newCallbackControl = CallbackControl <$> newMVar Nothing++-- | Pair the handler with the control shared by this provider's aliases.+newCallbackState :: ConfirmationHandler -> CallbackControl -> CallbackState+newCallbackState = CallbackState++-- | Each operation gets a fresh error/cancellation cell. The provider-wide gate+-- prevents overlap; the native-rooted callback reads only the active operation.+beginCallbackOperation :: CallbackControl -> MaskingState -> IO ()+beginCallbackOperation (CallbackControl control) masking = do+ exception <- newIORef Nothing+ modifyMVar_ control (const (pure (Just (Operation masking exception Nothing Nothing))))++-- | Clear operation state after the native worker and callback have joined.+finishCallbackOperation :: CallbackControl -> IO ()+finishCallbackOperation (CallbackControl control) = modifyMVar_ control (const (pure Nothing))++-- | Record cancellation even if the native callback has not started. Only the+-- user worker receives throwTo; a late exception can never enter an ABI thread.+cancelCallbackOperation :: CallbackControl -> SomeException -> IO ()+cancelCallbackOperation (CallbackControl control) cause = do+ target <- modifyMVar control $ \case+ Nothing -> pure (Nothing, Nothing)+ Just (Operation masking exception pending thread) -> do+ let original = fromMaybe cause pending+ pure (Just (Operation masking exception (Just original) thread), (,) original <$> thread)+ maybe (pure ()) (\(original, thread) -> throwTo thread original) target++-- | Consume and rethrow the first saved callback exception after native unwind.+-- The operation must still be active so its exception cell remains reachable.+rethrowCallbackException :: CallbackControl -> IO ()+rethrowCallbackException (CallbackControl control) = mask_ $ do+ cause <- withMVar control $ \case+ Nothing -> pure Nothing+ Just (Operation _ slot _ _) -> do+ current <- readIORef slot+ writeIORef slot Nothing+ pure current+ maybe (pure ()) throwIO cause++-- | Preserve the first exception without overwriting it during later cleanup.+rememberCallbackException :: CallbackControl -> SomeException -> IO ()+rememberCallbackException (CallbackControl control) cause =+ withMVar control $ \case+ Nothing -> pure ()+ Just (Operation _ slot _ _) -> do+ previous <- readIORef slot+ case previous of+ Nothing -> writeIORef slot (Just cause)+ Just _ -> pure ()++-- | Catch every user exception, including marshaling and lazy results, before+-- returning a native failure. Emergency handling does not render user values.+confirmationCallback :: Native.ConfirmationCallback CallbackState+confirmationCallback stable hash size timeout confirmed diagnostic capacity =+ mask_ $ do+ CallbackState handler exceptions <- deRefStablePtr stable+ let failed (cause :: SomeException) = uninterruptibleMask_ $ do+ rememberCallbackException exceptions cause+ poke confirmed 0+ when (diagnostic /= nullPtr && capacity > 0) $ poke diagnostic 0+ pure Native.failure+ runCallbackWorker+ exceptions+ ( do+ poke confirmed 0+ bytes <- ByteString.packCStringLen (castPtr hash, fromIntegral size)+ result <- handler bytes timeout+ case result of+ Left message -> writeDiagnostic diagnostic capacity message >> pure Native.failure+ Right value -> do+ forced <- evaluate value+ poke confirmed (if forced then 1 else 0)+ pure Native.success+ )+ `catch` failed++-- | The user worker's entire lifetime is enclosed by the ABI callback. Even an+-- unexpected asynchronous exception in the ABI thread cancels and joins this+-- worker before the callback's outer catch can return to C.+runCallbackWorker :: forall a. CallbackControl -> IO a -> IO a+runCallbackWorker (CallbackControl control) action = mask $ \restore -> do+ masking <- callbackMaskingState control+ start <- newEmptyMVar+ finished <- newEmptyMVar :: IO (MVar (Either SomeException a))+ worker <- forkIOWithUnmask $ \unmask -> do+ outcome <- try $ do+ takeMVar start+ case masking of+ Unmasked -> unmask action+ MaskedInterruptible -> mask_ action+ MaskedUninterruptible -> uninterruptibleMask_ action+ putMVar finished outcome++ ( do+ registerCallbackWorker control worker start++ outcome <- restore (readMVar finished)+ modifyMVar_ control $ \current -> pure $ case current of+ Just (Operation state exception cause _) -> Just (Operation state exception cause Nothing)+ Nothing -> Nothing+ either throwIO pure outcome+ )+ `catch` cancelAndJoinWorker worker finished++-- | Check that an operation is active before starting a user worker, preserving+-- an earlier callback exception instead of invoking the handler again.+callbackMaskingState :: MVar (Maybe Operation) -> IO MaskingState+callbackMaskingState control = withMVar control $ \case+ Just (Operation state exception _ _) -> do+ previous <- readIORef exception+ maybe (pure ()) throwIO previous+ pure state+ Nothing -> throwIO (userError "callback outside its operation")++-- | Publish the worker before opening its gate. Pending cancellation is delivered+-- instead of starting the user action. The caller keeps the ABI thread masked.+registerCallbackWorker :: MVar (Maybe Operation) -> ThreadId -> MVar () -> IO ()+registerCallbackWorker control worker start = do+ pending <- modifyMVar control $ \case+ Just (Operation state exception cause _) -> pure (Just (Operation state exception cause (Just worker)), cause)+ Nothing -> pure (Nothing, Nothing)+ maybe (putMVar start ()) (throwTo worker) pending++-- | Never let cancellation leave the ABI callback while its user worker lives.+cancelAndJoinWorker :: ThreadId -> MVar (Either SomeException a) -> SomeException -> IO b+cancelAndJoinWorker worker finished cause = uninterruptibleMask_ $ do+ throwTo worker cause+ _ <- readMVar finished+ throwIO cause++-- | Copy UTF-8 bytes into a borrowed C buffer, reserving a trailing NUL.+-- Truncation is by byte capacity and may split a multibyte UTF-8 sequence.+-- A null destination or zero capacity leaves the buffer untouched.+writeDiagnostic :: CString -> CSize -> Text -> IO ()+writeDiagnostic target capacity message = do+ let bytes = Text.encodeUtf8 message+ count = min (ByteString.length bytes) (fromIntegral capacity - 1)+ if target == nullPtr || capacity == 0+ then pure ()+ else ByteString.useAsCString bytes $ \source -> do+ copyBytes target source count+ pokeByteOff target count (0 :: CChar)
@@ -0,0 +1,88 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private BIP32 ABI. All inputs are borrowed until return. Owned secret outputs+-- are initialized to NULL and adopted by the locked scope. Safe imports permit+-- scheduling through derivation; no call retains host buffers or runs callbacks.+module Cometa.Internal.FFI.Bip32+ ( NativeKey,+ cFromBytes,+ cFromHex,+ cFromEntropy,+ cClone,+ cDerive,+ cToSigningKey,+ cUnref,+ cData,+ cSize,+ cPublicKey,+ cDerivePublic,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import qualified Cometa.Internal.FFI.SigningKey as Signing+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++-- | Native secret allocation, accessible only under its scope lock.+data NativeKey++-- Fixed encoded sizes are 96 private / 64 public bytes, audited against+-- BIP32_ED25519_PRIVATE_KEY_LENGTH and BIP32_ED25519_PUBLIC_KEY_LENGTH in+-- lib/src/crypto/bip32_private_key.c and bip32_public_key.c at native/cardano-c.ref.+-- Public known answers and the scoped native size observer verify these sizes.++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_bip32_from_bytes"+ cFromBytes :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_bip32_from_hex"+ cFromHex :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_bip32_from_entropy"+ cFromEntropy :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_bip32_clone"+ cClone :: Ptr NativeKey -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_bip32_derive"+ cDerive :: Ptr NativeKey -> Ptr Word32 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_bip32_to_signing_key"+ cToSigningKey :: Ptr NativeKey -> Ptr (Ptr Signing.NativeKey) -> IO NativeCode++foreign import ccall unsafe "cometa_bip32_unref"+ cUnref :: Ptr (Ptr NativeKey) -> IO ()++foreign import ccall unsafe "cometa_bip32_data"+ cData :: Ptr NativeKey -> IO (Ptr Word8)++foreign import ccall unsafe "cometa_bip32_size"+ cSize :: Ptr NativeKey -> IO CSize++foreign import ccall safe "cometa_bip32_public_key"+ cPublicKey :: Ptr NativeKey -> Ptr Word8 -> IO NativeCode++foreign import ccall safe "cometa_bip32_derive_public"+ cDerivePublic :: Ptr Word8 -> Ptr Word32 -> CSize -> Ptr Word8 -> IO NativeCode
@@ -0,0 +1,44 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private BIP39 ABI. Inputs are borrowed only for each bounded call. Returned+-- word pointers refer to static English strings: copy them, never free them.+-- Entropy output belongs to the caller and can be written even on checksum+-- failure. No function allocates an owner, retains buffers, or invokes callbacks.+module Cometa.Internal.FFI.Bip39 (cFromEntropy, cToEntropy, cClear) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_bip39_from_entropy"+ cFromEntropy :: Ptr Word8 -> CSize -> Ptr CString -> Ptr CSize -> IO NativeCode++foreign import ccall safe "cometa_bip39_to_entropy"+ cToEntropy :: Ptr CString -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO NativeCode++-- | Bounded scratch-buffer wipe; must run after native use and host copying,+-- including exceptions and failure after native output has been written.+foreign import capi unsafe "cardano/cardano.h cardano_memzero"+ cClear :: Ptr Word8 -> CSize -> IO ()
@@ -0,0 +1,28 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Standalone utilities have no callbacks and own no persistent handles.+module Cometa.Internal.FFI.Building (cCompute) where++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++foreign import ccall safe "cometa_building_compute"+ cCompute :: CUInt -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,144 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private, synchronous CBOR adapters. Native enums and bools are converted in+-- C. Input bytes are borrowed for each call; every output buffer and reader+-- owns one reference, including partial failure outputs. No user callback runs.+-- Native skip traversal uses an iterative loop and heap-backed nested frames;+-- collection extraction also iterates without recursive native descent.+module Cometa.Internal.FFI.Cbor+ ( NativeBuffer,+ NativeReader,+ cValidate,+ cEncodeInteger,+ cDecodeInteger,+ cEncodeString,+ cDecodeString,+ cEncodeBool,+ cDecodeBool,+ cEncodeUndefined,+ cDecodeDouble,+ cDecodeSimple,+ cEncodeCollection,+ cReaderNew,+ cCollectionStart,+ cCollectionAtEnd,+ cCollectionEnd,+ cReadItem,+ cReaderRemaining,+ cReadTextChunk,+ cReaderUnref,+ cBufferUnref,+ cBufferData,+ cBufferSize,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word64, Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CDouble (..), CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++-- | Opaque owned native byte storage.+data NativeBuffer++-- | Opaque owned reader containing a copy of its input bytes.+data NativeReader++-- FOREIGN IMPORTS ------------------------------------------------------------++-- All potentially input-proportional operations are safe and non-interruptible.+-- The final CString/CSize arguments are caller-owned diagnostic storage/capacity.+foreign import ccall safe "cometa_cbor_validate"+ cValidate :: Ptr Word8 -> CSize -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_encode_integer"+ cEncodeInteger :: CInt -> Word64 -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_decode_integer"+ cDecodeInteger :: Ptr Word8 -> CSize -> Ptr CInt -> Ptr Word64 -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_encode_string"+ cEncodeString :: CInt -> Ptr Word8 -> CSize -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_decode_string"+ cDecodeString :: CInt -> Ptr Word8 -> CSize -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_encode_bool"+ cEncodeBool :: CInt -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_decode_bool"+ cDecodeBool :: Ptr Word8 -> CSize -> Ptr CInt -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_encode_collection"+ cEncodeCollection :: CInt -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_reader_new"+ cReaderNew :: Ptr Word8 -> CSize -> Ptr (Ptr NativeReader) -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_collection_start"+ cCollectionStart :: Ptr NativeReader -> CInt -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_collection_at_end"+ cCollectionAtEnd :: Ptr NativeReader -> CInt -> Ptr CInt -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_collection_end"+ cCollectionEnd :: Ptr NativeReader -> CInt -> CString -> CSize -> IO NativeCode++foreign import ccall safe "cometa_cbor_read_item"+ cReadItem :: Ptr NativeReader -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++-- | Inspect unread bytes without exposing native reader state layout.+foreign import ccall safe "cometa_cbor_reader_remaining"+ cReaderRemaining :: Ptr NativeReader -> Ptr CSize -> CString -> CSize -> IO NativeCode++-- | Read one definite text chunk, rejecting tags and nested indefinite chunks.+foreign import ccall safe "cometa_cbor_read_text_chunk"+ cReadTextChunk :: Ptr NativeReader -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++-- | Reader destruction may release input-proportional nested frame storage.+foreign import ccall safe "cometa_cbor_reader_unref"+ cReaderUnref :: Ptr (Ptr NativeReader) -> IO ()++-- | Bounded buffer reference release; no callback or blocking operation runs.+foreign import ccall unsafe "cometa_cbor_buffer_unref"+ cBufferUnref :: Ptr (Ptr NativeBuffer) -> IO ()++-- | Borrow storage until buffer release; zero-length buffers may return null.+foreign import ccall unsafe "cometa_cbor_buffer_data"+ cBufferData :: Ptr NativeBuffer -> IO (Ptr Word8)++-- | Bounded buffer length observer.+foreign import ccall unsafe "cometa_cbor_buffer_size"+ cBufferSize :: Ptr NativeBuffer -> IO CSize++-- | Return an owned encoding of undefined; diagnostics use caller storage.+foreign import ccall safe "cometa_cbor_encode_undefined"+ cEncodeUndefined :: Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode++-- | Read a copied floating-point result; output is inspected only on success.+foreign import ccall safe "cometa_cbor_decode_double"+ cDecodeDouble :: Ptr Word8 -> CSize -> Ptr CDouble -> CString -> CSize -> IO NativeCode++-- | Read a simple-value number through a fixed-width byte, not an enum ABI.+foreign import ccall safe "cometa_cbor_decode_simple"+ cDecodeSimple :: Ptr Word8 -> CSize -> Ptr Word8 -> CString -> CSize -> IO NativeCode
@@ -0,0 +1,34 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Synchronous, callback-free native signing. Inputs remain borrowed until+-- return. Each output slot owns a buffer even if a later operation fails.+module Cometa.Internal.FFI.Cip8 (cSign) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.PasswordCrypto (Buffer)+import Cometa.Internal.FFI.SigningKey (NativeKey)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_cip8_sign"+ cSign :: Ptr NativeKey -> CUInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,35 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Raw selector adapter. Safe calls may re-enter Haskell through runtime dispatch.+module Cometa.Internal.FFI.CoinSelection (cMinimumAda, cSelect, cNativeSelect) where++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++foreign import ccall safe "cometa_coin_selection_minimum_ada"+ cMinimumAda :: Ptr Word8 -> CSize -> Word64 -> Ptr Word64 -> IO NativeCode++foreign import ccall safe "cometa_coin_selection_invoke"+ cSelect :: Ptr Context -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode++-- Independent operation-local native owners; no callbacks or borrowed state escape.+foreign import ccall safe "cometa_coin_selection_native"+ cNativeSelect :: CUInt -> Word64 -> CUInt -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,35 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Borrowed inputs and operation-owned outputs; no callbacks occur.+module Cometa.Internal.FFI.ContextualTransaction (cCertificateIndex, cRequiredKeys) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_contextual_certificate_index"+ cCertificateIndex :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word64 -> IO NativeCode++foreign import ccall safe "cometa_contextual_required_keys"+ cRequiredKeys :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,43 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Stateless Ed25519 value operations. The C adapter imports public bytes+-- into local native objects and releases them before returning. Status values+-- use an explicit unsigned C ABI, and Boolean output is converted to int.+-- The pinned native constructors use crypto_sign_PUBLICKEYBYTES (32) and+-- crypto_sign_BYTES (64) in lib/src/crypto/ed25519_public_key.c and+-- ed25519_signature.c. The pure public value constructors mirror those widths.+module Cometa.Internal.FFI.Ed25519Values (cVerify, cPublicKeyHash) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode, NativeHash)+import Data.Word (Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++-- | Borrow every input byte span for the complete synchronous operation.+-- Native false is represented by a successful status with output zero.+foreign import ccall safe "cometa_ed25519_verify"+ cVerify :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CInt -> IO NativeCode++-- | Return one owned hash reference, including any partial failure output.+-- The caller initializes its output slot and releases its own reference once.+foreign import ccall safe "cometa_ed25519_public_key_hash"+ cPublicKeyHash :: Ptr Word8 -> CSize -> Ptr (Ptr NativeHash) -> IO NativeCode
@@ -0,0 +1,36 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Callback-capable evaluation operation. Every input is borrowed until return;+-- the output buffer transfers one owner only on success.+module Cometa.Internal.FFI.Evaluation (cRun, cRunProvider) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_evaluation_run"+ cRun :: Ptr Context -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Word32 -> Ptr (Ptr Buffer) -> IO NativeCode++foreign import ccall safe "cometa_evaluation_run_provider"+ cRunProvider :: Ptr Context -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Word32 -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,33 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Callback-free native inspection of a fresh CBOR snapshot. The input borrows+-- through return and the result buffer transfers to the ordinary owned scope.+module Cometa.Internal.FFI.Inspection (cCompute) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_inspection_compute"+ cCompute :: CUInt -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,85 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Synchronous native handlers. Constructors copy input and borrow their callback+-- until final release. Every callback-capable entry is safe and non-interruptible.+module Cometa.Internal.FFI.KeyHandler+ ( NativeHandler,+ PassphraseCallback,+ wrapPassphrase,+ cNew,+ cEdNew,+ cDeserialize,+ cUnref,+ cName,+ cSerialize,+ cAccount,+ cPublic,+ cSign,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.PasswordCrypto (Buffer)+import Cometa.Internal.FFI.SigningKey (NativeKey)+import Data.Int (Int32)+import Data.Word (Word32, Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (FunPtr, Ptr)++-- TYPES ----------------------------------------------------------------------++data NativeHandler++type PassphraseCallback = Ptr Word8 -> CSize -> IO Int32++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall "wrapper" wrapPassphrase :: PassphraseCallback -> IO (FunPtr PassphraseCallback)++foreign import ccall safe "cardano_software_secure_key_handler_new"+ cNew :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> FunPtr PassphraseCallback -> Ptr (Ptr NativeHandler) -> IO NativeCode++foreign import ccall safe "cardano_software_secure_key_handler_ed25519_new"+ cEdNew :: Ptr NativeKey -> Ptr Word8 -> CSize -> FunPtr PassphraseCallback -> Ptr (Ptr NativeHandler) -> IO NativeCode++foreign import ccall safe "cardano_software_secure_key_handler_deserialize"+ cDeserialize :: Ptr Word8 -> CSize -> FunPtr PassphraseCallback -> Ptr (Ptr NativeHandler) -> IO NativeCode++foreign import ccall unsafe "cardano_secure_key_handler_unref"+ cUnref :: Ptr (Ptr NativeHandler) -> IO ()++foreign import ccall safe "cardano_secure_key_handler_serialize"+ cSerialize :: Ptr NativeHandler -> Ptr (Ptr Buffer) -> IO NativeCode++foreign import ccall safe "cometa_handler_account"+ cAccount :: Ptr NativeHandler -> Word32 -> Word32 -> Word32 -> Ptr Word8 -> IO NativeCode++foreign import ccall safe "cometa_handler_public"+ cPublic :: Ptr NativeHandler -> Ptr Word8 -> IO NativeCode++-- | Borrowed diagnostic name copied under the operation lock.+foreign import ccall unsafe "cardano_secure_key_handler_get_name"+ cName :: Ptr NativeHandler -> IO CString++-- | Borrow the handler, transaction bytes and flat path components through the+-- complete callback-capable call. Success transfers one public witness buffer.+foreign import ccall safe "cometa_handler_sign"+ cSign :: Ptr NativeHandler -> Ptr Word8 -> CSize -> CUInt -> Ptr Word32 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,87 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Raw, private declarations. Status values use an explicit unsigned C ABI.+-- All input buffers are borrowed for the call; successful hash+-- output owns one reference. The data observer borrows from that reference.+-- No function in this module retains a Haskell buffer or invokes a callback.+-- Const-pointer observers use ccall because GHC's CAPI wrappers discard const;+-- their signatures are audited against the same pinned headers.+module Cometa.Internal.FFI.Native+ ( NativeHash,+ NativeCode,+ success,+ cCompute,+ cUnref,+ cData,+ cSize,+ cErrorMessage,+ cVersion,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Data.Word (Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++-- | Opaque native allocation; never dereferenced by Haskell.+data {-# CTYPE "cardano/crypto/blake2b_hash.h" "cardano_blake2b_hash_t" #-} NativeHash++-- | Explicit unsigned C status ABI. CAPI calls convert native enum results;+-- the C adapter converts enum parameters and all raw status-returning calls.+-- No native enum representation is assumed by a direct Haskell import.+type NativeCode = CUInt++-- DEFINITIONS ---------------------------------------------------------------++-- | Successful native status.+success :: NativeCode+success = 0++-- FOREIGN IMPORTS ------------------------------------------------------------++-- | Safe because hashing can take time proportional to unbounded input length.+foreign import capi safe "cardano/crypto/blake2b_hash.h cardano_blake2b_compute_hash"+ cCompute :: Ptr Word8 -> CSize -> CSize -> Ptr (Ptr NativeHash) -> IO NativeCode++-- | Nonblocking bounded destructor. Decrements the reference in the slot and+-- clears it when that reference was the final one. A released alias must not+-- be used again, even when another owner leaves the pointer non-null.+foreign import capi unsafe "cardano/crypto/blake2b_hash.h cardano_blake2b_hash_unref"+ cUnref :: Ptr (Ptr NativeHash) -> IO ()++-- | Borrowed bytes remain valid only while an owner retains the hash.+foreign import ccall unsafe "cardano_blake2b_hash_get_data"+ cData :: Ptr NativeHash -> IO (Ptr Word8)++-- | Digest byte length; the native function returns zero for a null hash.+foreign import capi unsafe "cardano/crypto/blake2b_hash.h cardano_blake2b_hash_get_bytes_size"+ cSize :: Ptr NativeHash -> IO CSize++-- | Returned string is static and must be copied, never freed.+foreign import ccall unsafe "cometa_error_message"+ cErrorMessage :: NativeCode -> IO CString++-- | Borrowed static, NUL-terminated version string; copy it and never free it.+foreign import ccall unsafe "cardano_get_lib_version"+ cVersion :: IO CString
@@ -0,0 +1,34 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Operation-scoped VM call. Inputs borrow through safe return; both output+-- buffers transfer ownership and must be released, including on failure.+module Cometa.Internal.FFI.NativeEvaluation (cRun) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++-- Long-running VM work must leave other Haskell capabilities schedulable.+foreign import ccall safe "cometa_native_evaluation_run"+ cRun :: Word64 -> Word64 -> Word64 -> Word64 -> CUInt -> Word64 -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,34 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Callback-free conversion. Inputs are borrowed until return; a successful+-- output owns one buffer reference. The call may allocate proportionally to+-- cost-model size and uses the safe calling convention.+module Cometa.Internal.FFI.ParameterUpdate (cToPlutusData) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_parameters_update_to_plutus_data"+ cToPlutusData :: Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,57 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Borrowed byte inputs, caller-owned PBKDF scratch and operation-owned EMIP3+-- outputs. Calls are safe and non-interruptible: cancellation waits for native+-- unwind before scopes wipe and release their storage. No callbacks or retention.+module Cometa.Internal.FFI.PasswordCrypto (Buffer, cDerive, cEncrypt, cDecrypt, cRelease, cData, cSize, cClear) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++data {-# CTYPE "cardano/buffer.h" "cardano_buffer_t" #-} Buffer++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_pbkdf2"+ cDerive :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Word32 -> Ptr Word8 -> CSize -> IO NativeCode++foreign import ccall safe "cometa_emip3_encrypt"+ cEncrypt :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode++foreign import ccall safe "cometa_emip3_decrypt"+ cDecrypt :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode++-- | Wipes even on copy exceptions and cancellation; never throws or calls back.+foreign import ccall safe "cometa_password_buffer_release"+ cRelease :: Ptr (Ptr Buffer) -> IO ()++foreign import ccall unsafe "cardano_buffer_get_data"+ cData :: Ptr Buffer -> IO (Ptr Word8)++foreign import capi unsafe "cardano/buffer.h cardano_buffer_get_size"+ cSize :: Ptr Buffer -> IO CSize++foreign import capi safe "cardano/cardano.h cardano_memzero"+ cClear :: Ptr Word8 -> CSize -> IO ()
@@ -0,0 +1,122 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private C adapter. Explicit status values use an unsigned C ABI;+-- the adapter owns layout, native bool conversion and adopted runtime handles.+-- All entry points use safe calls, including reference destruction.+module Cometa.Internal.FFI.Provider+ ( -- * ABI types and callback registration+ NativeProvider,+ ConfirmationCallback,+ wrapConfirmation,++ -- * Native status values+ success,+ failure,++ -- * Provider references and operations+ cNew,+ cRef,+ cRelease,+ cConfirm,+ cError,++ -- * Lifecycle evidence+ cLiveContexts,+ cCompletedCalls,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word64, Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (FunPtr, Ptr)+import Foreign.StablePtr (StablePtr)++-- TYPES ----------------------------------------------------------------------++-- | Opaque native provider. Only the C adapter reads its representation.+data NativeProvider++-- | Synchronous callback ABI. All pointers are borrowed until return. The bridge+-- must contain exceptions and write a 0/1 confirmation plus a bounded diagnostic.+-- Native @bool@ never crosses this boundary.+type ConfirmationCallback state =+ StablePtr state ->+ -- | Transaction ID bytes and their length.+ Ptr Word8 ->+ CSize ->+ -- | Timeout in milliseconds.+ Word64 ->+ -- | Confirmation output and diagnostic buffer, including terminator capacity.+ Ptr CInt ->+ CString ->+ CSize ->+ IO CInt++-- DEFINITIONS ----------------------------------------------------------------++-- | Successful callback status.+success :: CInt+success = 0++-- | Generic callback failure status used after exception containment.+failure :: CInt+failure = 1++-- FOREIGN IMPORTS ------------------------------------------------------------++-- | Allocate a callable trampoline. The native context adopts it only after+-- 'cNew' succeeds; otherwise Haskell must free it along with its stable pointer.+foreign import ccall "wrapper"+ wrapConfirmation :: ConfirmationCallback state -> IO (FunPtr (ConfirmationCallback state))++-- | Construct one owned provider reference. Success adopts both runtime handles;+-- failure leaves both with the caller and leaves the initialized output null.+foreign import ccall safe "cometa_provider_new"+ cNew :: StablePtr state -> FunPtr (ConfirmationCallback state) -> Ptr (Ptr NativeProvider) -> IO NativeCode++-- | Acquire an additional reference. Serialize this non-atomic count transition+-- with every retain and release through aliases of the same provider.+foreign import ccall safe "cometa_provider_ref"+ cRef :: Ptr NativeProvider -> IO ()++-- | Consume one reference after its operations have joined. Final destruction+-- frees the adopted runtime handles without invoking user cleanup callbacks.+foreign import ccall safe "cometa_provider_release"+ cRelease :: Ptr NativeProvider -> IO ()++-- | Borrow the provider and hash bytes for a synchronous callback-capable call.+-- The caller holds an operation reference until this call returns.+foreign import ccall safe "cometa_provider_confirm"+ cConfirm :: Ptr NativeProvider -> Ptr Word8 -> CSize -> Word64 -> Ptr CInt -> IO NativeCode++-- | Borrow the provider's diagnostic. Copy it before releasing the provider or+-- starting another operation, which may overwrite the same storage.+foreign import ccall safe "cometa_provider_error"+ cError :: Ptr NativeProvider -> IO CString++-- | Atomically read the number of native contexts rooting callback registrations.+foreign import ccall safe "cometa_callback_live_contexts"+ cLiveContexts :: IO CSize++-- | Atomically read the count of completed native calls, including hash cleanup.+foreign import ccall safe "cometa_callback_completed_calls"+ cCompletedCalls :: IO CSize
@@ -0,0 +1,43 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Safe typed-provider dispatch adapter. Every input is borrowed through return;+-- success transfers one reply buffer, which the operation must copy and release.+module Cometa.Internal.FFI.ProviderRuntime (NativeProvider, cCall, cNew, cRelease) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++data NativeProvider++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_provider_runtime_call"+ cCall :: Ptr Context -> Ptr Word8 -> CSize -> Word32 -> Word32 -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode++foreign import ccall safe "cometa_provider_runtime_new"+ cNew :: Ptr Context -> Ptr Word8 -> CSize -> Word32 -> Ptr (Ptr NativeProvider) -> IO NativeCode++foreign import ccall safe "cardano_provider_unref"+ cRelease :: Ptr (Ptr NativeProvider) -> IO ()
@@ -0,0 +1,29 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Native re-encoding schemas. C borrows input through safe return and+-- transfers one owned output buffer; no callback or persistent handle escapes.+module Cometa.Internal.FFI.Reencode (cReencode) where++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++foreign import ccall safe "cometa_reencode"+ cReencode :: CUInt -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,82 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Generic adopted callback context and owned byte-buffer ABI. No native layout+-- crosses this boundary. Every callback-capable operation must use safe imports.+module Cometa.Internal.FFI.Runtime+ ( Context,+ Buffer,+ Callback,+ wrapCallback,+ cNew,+ cRef,+ cRelease,+ cBufferNew,+ cBufferRelease,+ cBufferData,+ cBufferSize,+ cLiveContexts,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word32, Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (FunPtr, Ptr)+import Foreign.StablePtr (StablePtr)++-- TYPES ----------------------------------------------------------------------++data Context++data Buffer++-- | Request borrowed until callback return; success transfers one reply buffer.+-- Failure diagnostic is bounded and the original Error stays in Haskell state.+type Callback state = StablePtr state -> Word32 -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> CString -> CSize -> IO NativeCode++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall "wrapper"+ wrapCallback :: Callback state -> IO (FunPtr (Callback state))++foreign import ccall safe "cometa_runtime_new"+ cNew :: StablePtr state -> FunPtr (Callback state) -> Ptr (Ptr Context) -> IO NativeCode++foreign import ccall unsafe "cometa_runtime_ref"+ cRef :: Ptr Context -> IO ()++foreign import ccall safe "cometa_runtime_release"+ cRelease :: Ptr Context -> IO ()++foreign import ccall safe "cometa_runtime_buffer_new"+ cBufferNew :: Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode++foreign import ccall safe "cometa_runtime_buffer_release"+ cBufferRelease :: Ptr (Ptr Buffer) -> IO ()++foreign import ccall unsafe "cometa_runtime_buffer_data"+ cBufferData :: Ptr Buffer -> IO (Ptr Word8)++foreign import ccall unsafe "cometa_runtime_buffer_size"+ cBufferSize :: Ptr Buffer -> IO CSize++foreign import ccall unsafe "cometa_runtime_live_contexts"+ cLiveContexts :: IO CSize
@@ -0,0 +1,36 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Synchronous native UPLC parameter marshaling. Inputs are borrowed until+-- return; the caller owns the output buffer even on partial failure. No callbacks+-- run. The safe non-interruptible import completes before cancellation unwinds+-- the caller's output scope, so no arena, list or output can escape cleanup.+module Cometa.Internal.FFI.Script (cApplyParams) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Cbor (NativeBuffer)+import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_script_apply_params"+ cApplyParams :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr NativeBuffer) -> CString -> CSize -> IO NativeCode
@@ -0,0 +1,86 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private synchronous secret-key ABI. Input storage is borrowed until return;+-- constructors and clone produce one owned reference. Key operations require the+-- resource lock, including observers, so closing cannot race a live pointer.+module Cometa.Internal.FFI.SigningKey+ ( NativeKey,+ cFromNormalBytes,+ cFromExtendedBytes,+ cFromNormalHex,+ cFromExtendedHex,+ cClone,+ cUnref,+ cData,+ cSize,+ cPublicKey,+ cSign,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++-- | Native secret allocation; never dereferenced or exposed publicly by Haskell.+data NativeKey++-- FOREIGN IMPORTS ------------------------------------------------------------++-- Constructors copy borrowed input; output slots are initialized by both layers.+foreign import ccall safe "cometa_signing_key_from_normal_bytes"+ cFromNormalBytes :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_signing_key_from_extended_bytes"+ cFromExtendedBytes :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_signing_key_from_normal_hex"+ cFromNormalHex :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++foreign import ccall safe "cometa_signing_key_from_extended_hex"+ cFromExtendedHex :: Ptr Word8 -> CSize -> Ptr (Ptr NativeKey) -> IO NativeCode++-- | Independent secret copy; no mutable storage or lifetime is shared.+foreign import ccall safe "cometa_signing_key_clone"+ cClone :: Ptr NativeKey -> Ptr (Ptr NativeKey) -> IO NativeCode++-- | Bounded release; final destruction wipes the native key buffer before free.+foreign import ccall unsafe "cometa_signing_key_unref"+ cUnref :: Ptr (Ptr NativeKey) -> IO ()++-- | Borrow secret bytes only while locked. Export copies have unmanaged lifetime.+foreign import ccall unsafe "cometa_signing_key_data"+ cData :: Ptr NativeKey -> IO (Ptr Word8)++-- | Fixed-size length observer, without exporting key contents.+foreign import ccall unsafe "cometa_signing_key_size"+ cSize :: Ptr NativeKey -> IO CSize++-- | Writes exactly 32 public bytes on success. Temporary native output is scoped.+foreign import ccall safe "cometa_signing_key_public_key"+ cPublicKey :: Ptr NativeKey -> Ptr Word8 -> IO NativeCode++-- | Writes exactly 64 signature bytes on success; message storage stays alive for+-- the complete safe call. No user callback or Haskell pointer is retained.+foreign import ccall safe "cometa_signing_key_sign"+ cSign :: Ptr NativeKey -> Ptr Word8 -> CSize -> Ptr Word8 -> IO NativeCode
@@ -0,0 +1,33 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Callback-capable sub-builder invocation. Inputs borrow through safe return;+-- output and diagnostic buffers transfer ownership even on partial failure.+module Cometa.Internal.FFI.SubTransactionBuilder (cBuild) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_sub_transaction_builder_build"+ cBuild :: Ptr Context -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,66 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private snapshot adapter with explicit scalar C ABI. Input buffers are+-- borrowed through each safe call; successful outputs own one snapshot. Byte+-- observers borrow storage which must be copied before freeing the snapshot.+module Cometa.Internal.FFI.Transaction+ ( NativeSnapshot,+ cDecode,+ cSetFee,+ cFree,+ cBytes,+ cFee,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++-- TYPES ----------------------------------------------------------------------++-- | Opaque allocation; native references and byte buffers never escape its scope.+data NativeSnapshot++-- FOREIGN IMPORTS ------------------------------------------------------------++-- | Validate complete input, rejecting trailing bytes; return an owned snapshot.+-- Safe because decoding and copying scale with the input and may allocate.+foreign import ccall safe "cometa_transaction_decode"+ cDecode :: Ptr Word8 -> CSize -> Ptr (Ptr NativeSnapshot) -> IO NativeCode++-- | Decode and deep-clone, change the fee, invalidate body encoding and strip+-- outer key signatures. The source bytes are borrowed and remain unchanged.+foreign import ccall safe "cometa_transaction_set_fee"+ cSetFee :: Ptr Word8 -> CSize -> Word64 -> Ptr (Ptr NativeSnapshot) -> IO NativeCode++-- | Bounded snapshot destructor. Consumes the local reference and clears its slot.+foreign import ccall unsafe "cometa_transaction_snapshot_free"+ cFree :: Ptr (Ptr NativeSnapshot) -> IO ()++-- | Borrow bytes: private adapter fields 0 full, 1 body, 2 hash, 3 witnesses.+-- Writes the byte length; null storage or zero length is an invalid snapshot.+foreign import ccall unsafe "cometa_transaction_snapshot_bytes"+ cBytes :: Ptr NativeSnapshot -> CUInt -> Ptr CSize -> IO (Ptr Word8)++-- | Snapshotted fee in lovelace, using an explicit unsigned 64-bit ABI.+foreign import ccall unsafe "cometa_transaction_snapshot_fee"+ cFee :: Ptr NativeSnapshot -> IO Word64
@@ -0,0 +1,34 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Callback-capable fresh native builder operation. Both contexts and byte+-- buffers borrow through return; transaction and diagnostic buffers transfer.+module Cometa.Internal.FFI.TransactionBuilder (cBuild, cBalance) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)++foreign import ccall safe "cometa_transaction_builder_build"+ cBuild :: Ptr Context -> Ptr Context -> Ptr Context -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> Ptr Word64 -> IO NativeCode++foreign import ccall safe "cometa_transaction_balance"+ cBalance :: Ptr Context -> Ptr Context -> Ptr Context -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> Ptr Word64 -> IO NativeCode
@@ -0,0 +1,37 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Private snapshots of native failures. Public domain adapters translate these+-- into their own error types after native diagnostics have been copied.+module Cometa.Internal.Failure+ ( NativeFailure (..),+ )+where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | Native status, copied context, and contract failures without a dependency on+-- a public domain API. Numeric codes remain exact, including unknown values.+data NativeFailure+ = -- | Operation label, exact native status, and copied diagnostic.+ NativeFailure !Text !Integer !Text+ | -- | Operation label for a successful status with an invalid native result.+ NativeContractFailure !Text+ deriving (Eq, Show)
@@ -0,0 +1,60 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Total ASCII hexadecimal conversion for immutable byte snapshots.+module Cometa.Internal.Hex (decodeHex, encodeHex) where++-- IMPORTS --------------------------------------------------------------------++import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Char (isDigit)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word8)++-- DEFINITIONS ----------------------------------------------------------------++-- | Decode pairs of ASCII digits, accepting either case. Empty text yields empty+-- bytes; odd lengths and nonhexadecimal characters fail without partial output.+decodeHex :: Text -> Maybe ByteString+decodeHex text = ByteString.pack <$> decodePairs [] (Text.unpack text)+ where+ decodePairs accumulated [] = Just (reverse accumulated)+ decodePairs accumulated (high : low : rest) = do+ first <- hexDigit high+ second <- hexDigit low+ decodePairs (first * 16 + second : accumulated) rest+ decodePairs _ [_] = Nothing++-- | Render each byte as two lowercase ASCII digits, without a prefix.+encodeHex :: ByteString -> Text+encodeHex = Text.pack . concatMap encodeByte . ByteString.unpack+ where+ encodeByte byte = [digit (byte `div` 16), digit (byte `mod` 16)]+ digit value+ | value < 10 = toEnum (fromIntegral value + fromEnum '0')+ | otherwise = toEnum (fromIntegral value - 10 + fromEnum 'a')++-- | Convert one ASCII hexadecimal digit without locale-sensitive parsing.+hexDigit :: Char -> Maybe Word8+hexDigit character+ | isDigit character = Just (offset '0')+ | character >= 'a' && character <= 'f' = Just (10 + offset 'a')+ | character >= 'A' && character <= 'F' = Just (10 + offset 'A')+ | otherwise = Nothing+ where+ offset start = fromIntegral (fromEnum character - fromEnum start)
@@ -0,0 +1,281 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_HADDOCK hide #-}++-- | One scoped native owner and one rooted wrapper per handler. The state lock+-- serializes all native access; tryTakeMVar makes overlap and reentry fail fast.+-- Scope cleanup waits for native/callback workers before freeing the wrapper.+module Cometa.Internal.KeyHandler+ ( Handler,+ Failure (..),+ withEntropy,+ withSigningKey,+ withSerialized,+ close,+ serialize,+ name,+ accountPublicKey,+ publicKey,+ signTransaction,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.Callback as Callback+import qualified Cometa.Internal.FFI.KeyHandler as Native+import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.FFI.PasswordCrypto as Buffer+import qualified Cometa.Internal.Failure as Failure+import Cometa.Internal.Ownership (copyStaticText)+import qualified Cometa.Internal.SigningKey as Signing+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, readMVar)+import Control.Concurrent.MVar (MVar, newMVar, takeMVar, tryTakeMVar)+import Control.Exception (Exception, SomeException, bracket, catch, finally, getMaskingState, mask, mask_, throwIO, uninterruptibleMask_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize, CUInt)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Marshal.Array (withArray)+import Foreign.Marshal.Utils (copyBytes)+import Foreign.Ptr (FunPtr, Ptr, castPtr, freeHaskellFunPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++data Handler = Handler (MVar (Maybe (Ptr Native.NativeHandler))) Callback.CallbackControl++data Failure = Closed | Busy | PasswordLength !Int | InvalidStorage | SourceClosed | NativeFailure !Failure.NativeFailure deriving (Eq, Show)++newtype InvalidPassword = InvalidPassword Int deriving (Show)++instance Exception InvalidPassword++type Acquisition = Ptr (Ptr Native.NativeHandler) -> IO (Either Failure ())++-- DEFINITIONS ----------------------------------------------------------------++-- | Inputs are completely marshaled before acquiring source locks. Native+-- constructors encrypt immediately and do not invoke the password callback.+withEntropy :: ByteString -> ByteString -> IO ByteString -> (Handler -> IO value) -> IO (Either Failure value)+withEntropy entropy password callback action =+ withValidPassword password $+ withAcquired callback acquire action+ where+ acquire fun output = withBytes entropy $ \bytes size ->+ withBytes password $ \pass passSize ->+ checkStatus "keyHandler.withEntropy" (Native.cNew bytes size pass passSize fun output)++withSigningKey :: Signing.Key -> ByteString -> IO ByteString -> (Handler -> IO value) -> IO (Either Failure value)+withSigningKey source password callback action =+ withValidPassword password $+ withAcquired callback acquire action+ where+ acquire fun output = withBytes password $ \pass passSize -> do+ result <- Signing.withKey source $ \key -> Right <$> Native.cEdNew key pass passSize fun output+ case result of+ Left Signing.Closed -> pure (Left SourceClosed)+ Left _ -> pure (contractFailure "keyHandler.withSigningKey")+ Right code -> status "keyHandler.withSigningKey" code++-- | Validate exact framing and canonical inner lengths before native allocation.+-- Native validates checksum. This format is binary, and outer metadata has CRC+-- protection only; deserialization does not authenticate the encrypted payload.+withSerialized :: ByteString -> IO ByteString -> (Bool -> Handler -> IO value) -> IO (Either Failure value)+withSerialized bytes callback action = case storageKind bytes of+ Nothing -> pure (Left InvalidStorage)+ Just bip32 -> withAcquired callback acquire (action bip32)+ where+ acquire fun output = withBytes bytes $ \pointer size ->+ checkStatus "keyHandler.withSerialized" (Native.cDeserialize pointer size fun output)++storageKind :: ByteString -> Maybe Bool+storageKind bytes = case ByteString.unpack (ByteString.take 10 bytes) of+ [10, 10, 10, 10, 1, kind, a, b, c, d]+ | kind <= 1 && size `elem` allowed && toInteger (ByteString.length bytes) == size + 14 -> Just (kind == 1)+ where+ size = foldl (\n x -> n * 256 + fromIntegral x) 0 [a, b, c, d] :: Integer+ allowed = if kind == 1 then [76, 80, 84, 88, 92] else [92, 124]+ _ -> Nothing++withValidPassword :: ByteString -> IO (Either Failure value) -> IO (Either Failure value)+withValidPassword password action+ | size < 1 || size > 128 = pure (Left (PasswordLength size))+ | otherwise = action+ where+ size = ByteString.length password++-- | The wrapper captures this handler's control; native has no context argument.+-- No callback registration or supplied password is kept beyond scope exit.+withAcquired :: IO ByteString -> (ForeignFun -> Acquisition) -> (Handler -> IO value) -> IO (Either Failure value)+withAcquired callback acquire action = mask $ \restore -> do+ control <- Callback.newCallbackControl+ state <- newMVar Nothing+ let handler = Handler state control+ bracket (Native.wrapPassphrase (passphraseCallback control callback)) freeHaskellFunPtr $ \fun ->+ alloca $ \slot -> bracket (poke slot nullPtr >> pure slot) (cleanup handler) $ \output -> do+ result <- restore (acquire fun output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ pointer <- peek output+ if pointer == nullPtr+ then pure (contractFailure "keyHandler.acquire")+ else do+ _ <- takeMVar state+ putMVar state (Just pointer)+ poke output nullPtr+ Right <$> restore (action handler)++type ForeignFun = FunPtr Native.PassphraseCallback++cleanup :: Handler -> Ptr (Ptr Native.NativeHandler) -> IO ()+cleanup (Handler state _) output = uninterruptibleMask_ $ do+ current <- takeMVar state+ case current of+ Nothing -> Native.cUnref output+ Just pointer -> release pointer `finally` poke output nullPtr+ poke output nullPtr+ putMVar state Nothing++close :: Handler -> IO (Either Failure ())+close (Handler state _) = mask_ $ do+ current <- tryTakeMVar state+ case current of+ Nothing -> pure (Left Busy)+ Just pointer -> (maybe (pure ()) release pointer >> pure (Right ())) `finally` putMVar state Nothing++release :: Ptr Native.NativeHandler -> IO ()+release pointer = alloca $ \slot -> poke slot pointer >> Native.cUnref slot++-- | Acquisition does not call back. Operations may, so cancellation is directed+-- to the user worker and both workers join before the state lock is returned.+withOperation :: Handler -> (Ptr Native.NativeHandler -> IO (Either Failure value)) -> IO (Either Failure value)+withOperation (Handler state control) action = do+ callerMasking <- getMaskingState+ mask $ \restore -> do+ current <- tryTakeMVar state+ case current of+ Nothing -> pure (Left Busy)+ Just Nothing -> putMVar state Nothing >> pure (Left Closed)+ Just (Just pointer) ->+ ( do+ Callback.beginCallbackOperation control callerMasking+ finished <- newEmptyMVar+ let nativeOperation = do+ result <- action pointer+ (Callback.rethrowCallbackException control >> pure result)+ `catch` invalidPassword+ invalidPassword (InvalidPassword size) = pure (Left (PasswordLength size))+ _ <- forkFinally nativeOperation (putMVar finished)+ outcome <- restore (readMVar finished) `catch` cancelAndJoin control finished+ either throwIO pure outcome+ )+ `finally` (Callback.finishCallbackOperation control >> putMVar state (Just pointer))++cancelAndJoin :: Callback.CallbackControl -> MVar (Either SomeException value) -> SomeException -> IO result+cancelAndJoin control finished cause = uninterruptibleMask_ $ do+ Callback.cancelCallbackOperation control cause+ _ <- readMVar finished+ throwIO cause++-- | Force bytes, length and copying inside the protected user worker. The ABI+-- callback catches every exception and returns -1; it never unwinds through C.+passphraseCallback :: Callback.CallbackControl -> IO ByteString -> Native.PassphraseCallback+passphraseCallback control callback output capacity =+ mask_ $+ Callback.runCallbackWorker+ control+ ( do+ bytes <- callback+ let size = ByteString.length bytes+ if size < 1 || size > 128 || toInteger size > toInteger capacity+ then throwIO (InvalidPassword size)+ else ByteString.useAsCString bytes $ \source -> copyBytes output (castPtr source) size >> pure (fromIntegral size)+ )+ `catch` \(cause :: SomeException) -> uninterruptibleMask_ (Callback.rememberCallbackException control cause >> pure (-1))++accountPublicKey :: Handler -> Word32 -> Word32 -> Word32 -> IO (Either Failure ByteString)+accountPublicKey handler purpose coin account = withOperation handler $ \pointer ->+ copyOutput "keyHandler.accountPublicKey" 64 (Native.cAccount pointer purpose coin account)++publicKey :: Handler -> IO (Either Failure ByteString)+publicKey handler = withOperation handler $ \pointer -> copyOutput "keyHandler.publicKey" 32 (Native.cPublic pointer)++name :: Handler -> IO (Either Failure Text)+name handler = withOperation handler $ \pointer -> Right <$> (Native.cName pointer >>= copyStaticText)++serialize :: Handler -> IO (Either Failure ByteString)+serialize handler = withOperation handler $ \pointer -> alloca $ \slot ->+ bracket (poke slot nullPtr >> pure slot) Buffer.cRelease $ \output -> do+ result <- checkStatus "keyHandler.serialize" (Native.cSerialize pointer output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ buffer <- peek output+ if buffer == nullPtr+ then pure (contractFailure "keyHandler.serialize")+ else do+ size <- Buffer.cSize buffer+ bytes <- Buffer.cData buffer+ Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)++-- | Reuse the established callback worker, cancellation join and state lock.+-- Every result buffer is copied before deterministic release; no transaction or+-- witness pointer survives the native call. kind is the adapter-private dispatch.+signTransaction :: Handler -> CUInt -> [[Word32]] -> ByteString -> IO (Either Failure ByteString)+signTransaction handler kind paths bytes = withOperation handler $ \pointer ->+ withBytes bytes $ \input size -> withArray (concat paths) $ \components ->+ alloca $ \slot -> bracket (poke slot nullPtr >> pure slot) Buffer.cRelease $ \output -> do+ result <- checkStatus "keyHandler.signTransaction" (Native.cSign pointer input size kind components (fromIntegral (length paths)) output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ buffer <- peek output+ if buffer == nullPtr+ then pure (contractFailure "keyHandler.signTransaction")+ else do+ count <- Buffer.cSize buffer+ source <- Buffer.cData buffer+ if source == nullPtr || count == 0 || toInteger count > toInteger (maxBound :: Int)+ then pure (contractFailure "keyHandler.signTransaction")+ else Right <$> ByteString.packCStringLen (castPtr source, fromIntegral count)++copyOutput :: Text -> Int -> (Ptr Word8 -> IO Status.NativeCode) -> IO (Either Failure ByteString)+copyOutput operation size call = allocaBytes size $ \output -> do+ result <- checkStatus operation (call output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> Right <$> ByteString.packCStringLen (castPtr output, size)++checkStatus :: Text -> IO Status.NativeCode -> IO (Either Failure ())+checkStatus operation call = call >>= status operation++status :: Text -> Status.NativeCode -> IO (Either Failure ())+status operation code+ | code == Status.success = pure (Right ())+ | otherwise = do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (NativeFailure (Failure.NativeFailure operation (toInteger code) message)))++contractFailure :: Text -> Either Failure value+contractFailure = Left . NativeFailure . Failure.NativeContractFailure++withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)
@@ -0,0 +1,102 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Scoped native acquisition. Initialize the output slot before calling C,+-- release even partial failure results, and copy data before releasing its owner.+-- 'bracket' installs cleanup before acquisition and restores the caller's masking+-- state around the acquisition and action.+-- A safe, non-interruptible FFI call finishes writing its output slot before a+-- pending asynchronous exception unwinds the scope and releases that output.+module Cometa.Internal.Ownership+ ( withOwnedOutput,+ copyHashResult,+ copyStaticText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Native as Native+import Cometa.Internal.Failure (NativeFailure (..))+import Control.Exception (bracket, finally)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text.Encoding as Text+import qualified Data.Text.Encoding.Error as Text+import Foreign.C.String (CString)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- DEFINITIONS ----------------------------------------------------------------++-- | Copy a static UTF-8 diagnostic. Native diagnostics are expected to be UTF-8;+-- invalid sequences are replaced rather than raising an unrelated exception.+copyStaticText :: CString -> IO Text+copyStaticText pointer =+ if pointer == nullPtr+ then pure ""+ else Text.decodeUtf8With Text.lenientDecode <$> ByteString.packCString pointer++-- | Scope one owned output reference, including a partial result written before+-- failure or an exception. Acquisition runs with the caller's masking state after+-- cleanup is installed. Safe, non-interruptible FFI must finish before unwinding;+-- interruptible foreign calls require a separate lifetime protocol.+--+-- The acquisition must leave either null or one locally owned reference in its+-- slot on every exit. The action borrows that reference and must not release,+-- transfer, or replace it. Its result must not contain a borrowed native view.+-- The bounded destructor must not throw or block interruptibly. Clearing the+-- slot records release even when another native owner keeps the object alive.+withOwnedOutput ::+ Text ->+ (Ptr (Ptr native) -> IO ()) ->+ (Ptr (Ptr native) -> IO Native.NativeCode) ->+ (Ptr native -> IO (Either NativeFailure value)) ->+ IO (Either NativeFailure value)+withOwnedOutput operation release acquire action =+ alloca $ \slot ->+ bracket (poke slot nullPtr >> pure slot) cleanup $ \output -> do+ code <- acquire output+ if code /= Native.success+ then do+ message <- Native.cErrorMessage code >>= copyStaticText+ pure (Left (NativeFailure operation (toInteger code) message))+ else do+ pointer <- peek output+ if pointer == nullPtr+ then pure (Left (NativeContractFailure operation))+ else action pointer+ where+ cleanup slot = do+ pointer <- peek slot+ if pointer == nullPtr+ then pure ()+ else release slot `finally` poke slot nullPtr++-- | Copy borrowed hash storage before releasing its owned output reference.+-- A null pointer, zero length, or length beyond Haskell's 'Int' range is a native+-- contract failure. No borrowed storage escapes in the returned bytes.+copyHashResult :: Text -> (Ptr (Ptr Native.NativeHash) -> IO Native.NativeCode) -> IO (Either NativeFailure ByteString)+copyHashResult operation acquire =+ withOwnedOutput operation Native.cUnref acquire $ \hash -> do+ size <- Native.cSize hash+ bytes <- Native.cData hash+ if bytes == nullPtr || size == 0 || toInteger size > toInteger (maxBound :: Int)+ then pure (Left (NativeContractFailure operation))+ else Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)
@@ -0,0 +1,86 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Scoped password crypto marshaling. Public validation precedes these calls.+-- PBKDF scratch uses heap allocation, not an input-sized stack allocation.+-- All plaintext native buffers are wiped on every exit after foreign unwind.+-- Explicitly exported immutable host copies have application-managed lifetime.+module Cometa.Internal.PasswordCrypto (deriveBytes, encrypt, decryptBytes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.FFI.Native (NativeCode, cErrorMessage, success)+import qualified Cometa.Internal.FFI.PasswordCrypto as Native+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyStaticText, withOwnedOutput)+import Control.Exception (bracket, evaluate, finally)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize)+import Foreign.Marshal.Alloc (free, mallocBytes)+import Foreign.Ptr (Ptr, castPtr, nullPtr)++-- DEFINITIONS ----------------------------------------------------------------++deriveBytes :: ByteString -> ByteString -> Word32 -> Int -> IO (Either NativeFailure ByteString)+deriveBytes password salt iterations size =+ withBytes password $ \passwordPtr passwordSize ->+ withBytes salt $ \saltPtr saltSize ->+ withScratch size $ \output -> do+ status <- Native.cDerive passwordPtr passwordSize saltPtr saltSize iterations output (fromIntegral size)+ if status == success+ then Right <$> copyBytes output size+ else Left <$> nativeFailure "pbkdf2.deriveBytes" status++-- Cleanup is installed before the native call can populate scratch storage.+withScratch :: Int -> (Ptr Word8 -> IO a) -> IO a+withScratch size = bracket (mallocBytes size) (\pointer -> Native.cClear pointer (fromIntegral size) `finally` free pointer)++encrypt :: ByteString -> ByteString -> IO (Either NativeFailure ByteString)+encrypt password plaintext = transform "emip3.encrypt" Native.cEncrypt password plaintext (ByteString.length plaintext + 60)++decryptBytes :: ByteString -> ByteString -> IO (Either NativeFailure ByteString)+decryptBytes password ciphertext = transform "emip3.decryptBytes" Native.cDecrypt password ciphertext (ByteString.length ciphertext - 60)++transform :: Text -> (Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr (Ptr Native.Buffer) -> IO NativeCode) -> ByteString -> ByteString -> Int -> IO (Either NativeFailure ByteString)+transform operation invoke password input expectedSize =+ withBytes password $ \passwordPtr passwordSize ->+ withBytes input $ \inputPtr inputSize ->+ withOwnedOutput operation Native.cRelease (invoke inputPtr inputSize passwordPtr passwordSize) $ \buffer -> do+ size <- Native.cSize buffer+ pointer <- Native.cData buffer+ if toInteger size /= toInteger expectedSize || (expectedSize > 0 && pointer == nullPtr)+ then pure (Left (NativeContractFailure operation))+ else+ if expectedSize == 0+ then pure (Right ByteString.empty)+ else Right <$> copyBytes pointer expectedSize++withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)++copyBytes :: Ptr Word8 -> Int -> IO ByteString+copyBytes pointer size = do+ bytes <- ByteString.packCStringLen (castPtr pointer, size)+ evaluate (ByteString.length bytes `seq` bytes)++nativeFailure :: Text -> NativeCode -> IO NativeFailure+nativeFailure operation status = do+ diagnostic <- cErrorMessage status >>= copyStaticText+ evaluate (NativeFailure operation (fromIntegral status) diagnostic)
@@ -0,0 +1,240 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Private confirmation adapter and scoped native ownership. This establishes+-- callback mechanics, not a public provider API. Handles close deterministically;+-- retaining creates an independent obligation and an operation temporarily owns+-- another reference. Native context destruction owns runtime-handle cleanup.+module Cometa.Internal.Provider+ ( -- * Scoped handles+ Provider,+ ProviderError (..),+ ConfirmationHandler,+ withProvider,+ withRetainedProvider,+ closeProvider,++ -- * Confirmation+ confirmTransaction,++ -- * Lifecycle evidence+ liveCallbackContexts,+ completedNativeCalls,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.Callback (CallbackControl, CallbackState, ConfirmationHandler)+import qualified Cometa.Internal.Callback as Callback+import qualified Cometa.Internal.FFI.Native as Native+import qualified Cometa.Internal.FFI.Provider as FFI+import Cometa.Internal.Ownership (copyStaticText)+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, readMVar)+import Control.Concurrent.MVar (MVar, newMVar, withMVar)+import Control.Exception (Exception, SomeException, bracket, catch, evaluate, finally, getMaskingState, mask, mask_, onException, throwIO, uninterruptibleMask_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)+import Data.Text (Text)+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, freeHaskellFunPtr, nullPtr)+import Foreign.StablePtr (freeStablePtr, newStablePtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Expected adapter failures. Acquisition failure is raised as an exception;+-- confirmation returns these failures explicitly. User exceptions stay original.+data ProviderError+ = -- | This handle has already released its reference.+ ProviderClosed+ | -- | An operation is already active on this provider or a retained alias.+ ProviderBusy+ | -- | Supplied transaction ID byte length; exactly 32 bytes are required.+ InvalidTransactionIdLength !Int+ | -- | Exact native status and a diagnostic copied before owner release.+ ProviderNativeFailure !Integer !Text+ deriving (Eq, Show)++instance Exception ProviderError++-- | All reference-count transitions for aliases of one native object share this+-- lock. Neither it nor the operation gate is held while running user callbacks.+-- The fields are the refcount lock, operation gate, and callback control. The+-- gate's occupied bit stays set; reentry fails instead of blocking.+data Shared = Shared (MVar ()) (IORef Bool) CallbackControl++-- | One independently closable reference plus shared alias synchronization.+-- Keeping a Haskell handle after its scope ends does not retain native ownership.+data Provider = Provider (IORef (Maybe (Ptr FFI.NativeProvider))) Shared++-- DEFINITIONS ----------------------------------------------------------------++-- | Acquire one provider reference and close it on every exit. The native+-- context roots the handler until the last retained reference is released.+-- Construction failures raise 'ProviderError'; user exceptions are preserved.+withProvider :: ConfirmationHandler -> (Provider -> IO a) -> IO a+withProvider handler = bracket (acquireProvider handler) closeProvider++-- | Give an independent scoped native reference to the continuation. Closing+-- the original handle leaves this handle usable; both share the operation gate.+withRetainedProvider :: Provider -> (Provider -> IO a) -> IO a+withRetainedProvider provider = bracket acquire closeProvider+ where+ acquire = mask_ $ do+ reference <- acquireReference provider+ case reference of+ Left failure -> throwIO failure+ Right pointer -> do+ let Provider _ shared = provider+ (Provider <$> newIORef (Just pointer) <*> pure shared)+ `onException` releaseReference shared pointer++-- | Idempotently invalidate this handle, regardless of whether native unref+-- leaves its local pointer non-null because another owner still exists.+closeProvider :: Provider -> IO ()+closeProvider (Provider handle (Shared lifetime _ _)) =+ uninterruptibleMask_ $ withMVar lifetime $ \() -> do+ pointer <- readIORef handle+ writeIORef handle Nothing+ maybe (pure ()) FFI.cRelease pointer++-- | Confirm through the synchronous native provider using scoped workers.+-- Independent providers can overlap. Overlap or callback reentry on aliases of+-- this provider returns ProviderBusy. A closed handle returns ProviderClosed.+--+-- Cancellation stops awaiting the result, asks the user worker to unwind, and+-- joins the native worker before rethrowing the original exception. A handler+-- that masks cancellation, or native code that has not returned, delays that+-- unwind; neither its native state nor its buffers can be released early.+confirmTransaction :: Provider -> ByteString -> Word64 -> IO (Either ProviderError Bool)+confirmTransaction provider hash timeout+ | ByteString.length hash /= 32 = pure (Left (InvalidTransactionIdLength (ByteString.length hash)))+ | otherwise = do+ callerMasking <- getMaskingState+ withReference provider $ \pointer ->+ mask $ \restore -> do+ let Provider _ (Shared _ busy state) = provider+ entered <- atomicModifyIORef' busy (\occupied -> (True, not occupied))+ if not entered+ then pure (Left ProviderBusy)+ else+ ( do+ Callback.beginCallbackOperation state callerMasking+ finished <- newEmptyMVar+ _ <- forkFinally (nativeConfirmation state pointer hash timeout) (putMVar finished)+ outcome <- restore (readMVar finished) `catch` cancelAndJoinNative state finished+ either throwIO pure outcome+ )+ `finally` (Callback.finishCallbackOperation state >> writeIORef busy False)++-- | Borrow buffers through the full native call, then rethrow saved callback+-- exceptions before translating the native status or reading its diagnostic.+nativeConfirmation :: CallbackControl -> Ptr FFI.NativeProvider -> ByteString -> Word64 -> IO (Either ProviderError Bool)+nativeConfirmation state pointer hash timeout =+ ByteString.useAsCStringLen hash $ \(bytes, size) ->+ alloca $ \confirmed -> do+ poke confirmed 0+ code <- FFI.cConfirm pointer (castPtr bytes) (fromIntegral size) timeout confirmed+ Callback.rethrowCallbackException state+ if code == Native.success+ then Right . (/= 0) <$> peek confirmed+ else do+ diagnostic <- FFI.cError pointer >>= copyStaticText+ pure (Left (ProviderNativeFailure (toInteger code) diagnostic))++-- | Request user cancellation and retain all native state until safe unwind.+cancelAndJoinNative :: CallbackControl -> MVar (Either SomeException a) -> SomeException -> IO b+cancelAndJoinNative state finished cause = uninterruptibleMask_ $ do+ Callback.cancelCallbackOperation state cause+ _ <- readMVar finished+ throwIO cause++-- | Number of native contexts still rooting Haskell callback registrations.+-- This instrumentation is lifecycle evidence, not a public API contract.+liveCallbackContexts :: IO Int+liveCallbackContexts = fromIntegral <$> FFI.cLiveContexts++-- | Increased by the C shim only after cardano_provider_confirm_transaction and+-- hash cleanup have returned. Used to establish safe exception unwind in tests.+completedNativeCalls :: IO Integer+completedNativeCalls = toInteger <$> FFI.cCompletedCalls++-- | Register runtime handles under masking. Successful native construction+-- adopts both handles; before that transfer, Haskell owns their cleanup.+acquireProvider :: ConfirmationHandler -> IO Provider+acquireProvider handler = mask_ $ do+ exceptions <- Callback.newCallbackControl+ let state = Callback.newCallbackState handler exceptions+ lifetime <- newMVar ()+ busy <- newIORef False+ handle <- newIORef Nothing+ shared <- evaluate (Shared lifetime busy exceptions)+ provider <- evaluate (Provider handle shared)+ registerProvider provider state++-- | Install the rooted callback while construction remains masked. Native+-- success transfers registration cleanup to the context before publication.+registerProvider :: Provider -> CallbackState -> IO Provider+registerProvider provider@(Provider handle _) state = do+ stable <- newStablePtr state+ function <- FFI.wrapConfirmation Callback.confirmationCallback `onException` freeStablePtr stable+ let freeRegistration = freeHaskellFunPtr function >> freeStablePtr stable++ alloca $ \output -> do+ poke output nullPtr+ code <- FFI.cNew stable function output `onException` freeRegistration+ if code /= Native.success+ then do+ freeRegistration+ message <- Native.cErrorMessage code >>= copyStaticText+ throwIO (ProviderNativeFailure (toInteger code) message)+ else do+ pointer <- peek output+ -- Success transferred both runtime handles to the native context.+ -- Publication can still allocate; its failure releases the native owner,+ -- whose destructor now owns registration cleanup.+ (writeIORef handle (Just pointer) >> pure provider)+ `onException` (writeIORef handle Nothing >> FFI.cRelease pointer)++-- | Retain an open handle while serializing non-atomic native refcounts.+acquireReference :: Provider -> IO (Either ProviderError (Ptr FFI.NativeProvider))+acquireReference (Provider handle (Shared lifetime _ _)) =+ -- The lock protects only bounded refcount operations. Its holder never runs+ -- user code, so cleanup cannot be cancelled while waiting for this short lock.+ uninterruptibleMask_ $ withMVar lifetime $ \() -> do+ current <- readIORef handle+ case current of+ Nothing -> pure (Left ProviderClosed)+ Just pointer -> FFI.cRef pointer >> pure (Right pointer)++-- | Release one operation reference under the same lock used for retention.+releaseReference :: Shared -> Ptr FFI.NativeProvider -> IO ()+releaseReference (Shared lifetime _ _) pointer =+ uninterruptibleMask_ $ withMVar lifetime $ \() -> FFI.cRelease pointer++-- | Keep the native object alive through the action, even if another alias+-- closes its handle. A closed input handle never runs the action.+withReference :: Provider -> (Ptr FFI.NativeProvider -> IO (Either ProviderError a)) -> IO (Either ProviderError a)+withReference provider action = mask $ \restore -> do+ acquired <- acquireReference provider+ case acquired of+ Left failure -> pure (Left failure)+ Right pointer -> do+ let Provider _ shared = provider+ restore (action pointer) `finally` releaseReference shared pointer
@@ -0,0 +1,236 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Deterministic secret-key lifetime. One lock protects the closed state and+-- spans every native use, including copying borrowed data. No public callback+-- runs under that lock. Closing waits for existing operations, then wipes and+-- releases the native allocation; escaped handles retain only the closed state.+module Cometa.Internal.SigningKey+ ( Key,+ Failure (..),+ withNormalKey,+ withExtendedKey,+ withNormalKeyHex,+ withExtendedKeyHex,+ withClone,+ close,+ publicKeyBytes,+ signBytes,+ exportBytes,+ byteLength,+ withKey,+ withAcquiredKey,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.FFI.SigningKey as Native+import qualified Cometa.Internal.Failure as Failure+import Cometa.Internal.Ownership (copyStaticText)+import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, withMVar)+import Control.Exception (bracket, evaluate, finally, mask, uninterruptibleMask_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Char (isDigit)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word8)+import Foreign.C.Types (CSize)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | No printable or equality instance: this contains a secret ownership state.+newtype Key = Key (MVar (Maybe (Ptr Native.NativeKey)))++-- | Sanitized failures. Lengths are expected then actual; no input is retained.+data Failure+ = Closed+ | InvalidLength !Int !Int+ | InvalidHex+ | NativeFailure !Failure.NativeFailure+ deriving (Eq, Show)++type Acquisition = Ptr (Ptr Native.NativeKey) -> IO (Either Failure ())++type Import = Ptr Word8 -> CSize -> Ptr (Ptr Native.NativeKey) -> IO Status.NativeCode++-- DEFINITIONS ----------------------------------------------------------------++-- | Import a normal 32-byte seed and close the key on every callback exit.+withNormalKey :: ByteString -> (Key -> IO value) -> IO (Either Failure value)+withNormalKey = withBytesKey "ed25519.withNormalKey" 32 Native.cFromNormalBytes++-- | Import an expanded 64-byte scalar/IV key. Length is checked, not scalar validity.+withExtendedKey :: ByteString -> (Key -> IO value) -> IO (Either Failure value)+withExtendedKey = withBytesKey "ed25519.withExtendedKey" 64 Native.cFromExtendedBytes++-- | Import normal seed ASCII hex, rejecting malformed text before native import.+withNormalKeyHex :: Text -> (Key -> IO value) -> IO (Either Failure value)+withNormalKeyHex = withHexKey "ed25519.withNormalKeyHex" 32 Native.cFromNormalHex++-- | Import expanded scalar/IV ASCII hex; input and UTF-8 copies have host lifetimes.+withExtendedKeyHex :: Text -> (Key -> IO value) -> IO (Either Failure value)+withExtendedKeyHex = withHexKey "ed25519.withExtendedKeyHex" 64 Native.cFromExtendedHex++-- | Clone while holding the source lock, then scope the independent key outside+-- that lock. Closing either key never invalidates the other one's native storage.+withClone :: Key -> (Key -> IO value) -> IO (Either Failure value)+withClone source = withAcquiredKey operation $ \output ->+ withKey source $ \pointer -> checkStatus operation (Native.cClone pointer output)+ where+ operation = "ed25519.withClone"++-- | Wait for native operations, invalidate the local handle and release once.+-- Only trusted finite native work holds the lock; no application callback may do so.+close :: Key -> IO ()+close (Key state) = uninterruptibleMask_ $ modifyMVar_ state $ \current -> do+ maybe (pure ()) releasePointer current+ pure Nothing++-- | Derive and copy public bytes while holding the key alive.+publicKeyBytes :: Key -> IO (Either Failure ByteString)+publicKeyBytes key = withKey key $ \pointer ->+ copyOutput "ed25519.publicKey" 32 (Native.cPublicKey pointer)++-- | Force and borrow the message before locking: evaluating a caller's thunk+-- must never prevent concurrent close from acquiring this non-reentrant lock.+signBytes :: Key -> ByteString -> IO (Either Failure ByteString)+signBytes key message = withBytes message $ \bytes size ->+ withKey key $ \pointer -> copyOutput "ed25519.sign" 64 (Native.cSign pointer bytes size)++-- | Copy secret storage directly into a host ByteString, without an intermediate+-- native export buffer. The copy has no controlled erasure or lifetime guarantee.+exportBytes :: Key -> IO (Either Failure ByteString)+exportBytes key = withKey key $ \pointer -> do+ size <- Native.cSize pointer+ bytes <- Native.cData pointer+ if bytes == nullPtr || (size /= 32 && size /= 64)+ then pure (contractFailure "ed25519.exportBytes")+ else Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)++-- | Read only the fixed-size scalar metadata, without copying any secret bytes.+byteLength :: Key -> IO (Either Failure Int)+byteLength key = withKey key $ \pointer -> do+ size <- Native.cSize pointer+ pure $+ if size == 32 || size == 64+ then Right (fromIntegral size)+ else contractFailure "ed25519.byteLength"++-- | Trusted internal operation/test seam. Holds the key lock through the entire+-- action; reject closed handles before exposing any pointer. The action must not+-- escape the pointer, run application callbacks or force application-owned input.+withKey :: Key -> (Ptr Native.NativeKey -> IO (Either Failure value)) -> IO (Either Failure value)+withKey (Key state) action = withMVar state $ \current ->+ maybe (pure (Left Closed)) action current++-- | Validate all application input before construction. Native import copies it.+withBytesKey :: Text -> Int -> Import -> ByteString -> (Key -> IO value) -> IO (Either Failure value)+withBytesKey operation expected importKey bytes action+ | actual /= expected = pure (Left (InvalidLength expected actual))+ | otherwise = withAcquiredKey operation acquire action+ where+ actual = ByteString.length bytes+ acquire output = withBytes bytes $ \pointer size ->+ checkStatus operation (importKey pointer size output)++-- | Validate ASCII hex without decoding it into an additional host secret byte+-- array. UTF-8 marshaling still creates host storage which Haskell does not erase.+withHexKey :: Text -> Int -> Import -> Text -> (Key -> IO value) -> IO (Either Failure value)+withHexKey operation expected importKey text action+ | Text.null text || odd digits || not (Text.all isHex text) = pure (Left InvalidHex)+ | actual /= expected = pure (Left (InvalidLength expected actual))+ | otherwise = withAcquiredKey operation acquire action+ where+ digits = Text.length text+ actual = digits `div` 2+ acquire output = withBytes (Text.encodeUtf8 text) $ \pointer size ->+ checkStatus operation (importKey pointer size output)+ isHex character =+ isDigit character+ || (character >= 'a' && character <= 'f')+ || (character >= 'A' && character <= 'F')++-- | Install ownership-aware cleanup before unmasked acquisition and retain it+-- through the callback. Publication is masked; the finalizer handles either+-- ownership state even if an exception arrives between publication and slot clear.+withAcquiredKey :: Text -> Acquisition -> (Key -> IO value) -> IO (Either Failure value)+withAcquiredKey operation acquire action = mask $ \restore -> do+ state <- newMVar Nothing+ key <- evaluate (Key state)+ alloca $ \slot ->+ bracket (poke slot nullPtr >> pure slot) (closeAcquiredKey key) $ \output -> do+ result <- restore (acquire output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ pointer <- peek output+ if pointer == nullPtr+ then pure (contractFailure operation)+ else do+ modifyMVar_ state (const (pure (Just pointer)))+ poke output nullPtr+ Right <$> restore (action key)++-- | Consume exactly one reference across publication. A populated state is the+-- authority even while the output slot temporarily aliases it. Otherwise the+-- slot owns any partial acquisition result. Early 'close' leaves both empty.+closeAcquiredKey :: Key -> Ptr (Ptr Native.NativeKey) -> IO ()+closeAcquiredKey (Key state) slot = uninterruptibleMask_ $ modifyMVar_ state $ \current -> do+ case current of+ Nothing -> releaseSlot slot+ Just pointer -> releasePointer pointer `finally` poke slot nullPtr+ pure Nothing++-- | Consume one local obligation, irrespective of whether native unref nulls it.+releaseSlot :: Ptr (Ptr Native.NativeKey) -> IO ()+releaseSlot slot = Native.cUnref slot `finally` poke slot nullPtr++-- | Release a state-owned reference through the typed pointer-to-pointer API.+releasePointer :: Ptr Native.NativeKey -> IO ()+releasePointer pointer = alloca $ \slot -> poke slot pointer >> releaseSlot slot++-- | Public/signature outputs contain no secret material and have fixed length.+copyOutput :: Text -> Int -> (Ptr Word8 -> IO Status.NativeCode) -> IO (Either Failure ByteString)+copyOutput operation size call = allocaBytes size $ \output -> do+ result <- checkStatus operation (call output)+ case result of+ Left failure -> pure (Left failure)+ Right () -> Right <$> ByteString.packCStringLen (castPtr output, size)++-- | Copy static native diagnostics; operation labels never contain key input.+checkStatus :: Text -> IO Status.NativeCode -> IO (Either Failure ())+checkStatus operation action = do+ code <- action+ if code == Status.success+ then pure (Right ())+ else do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (NativeFailure (Failure.NativeFailure operation (toInteger code) message)))++contractFailure :: Text -> Either Failure value+contractFailure = Left . NativeFailure . Failure.NativeContractFailure++-- | Keep marshaled bytes alive only through the chosen native action.+withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)
@@ -0,0 +1,131 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Encoding-preservation prototype, not a public transaction model. Every value+-- is a Haskell-owned immutable snapshot; no native handle survives an operation.+-- Unchanged values retain exact input bytes, including historical/block frames.+module Cometa.Internal.Transaction+ ( Transaction,+ decodeCbor,+ encodeCbor,+ bodyCbor,+ bodyHash,+ witnessCbor,+ fee,+ setFee,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Transaction as FFI+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (withOwnedOutput)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize, CUInt)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Original full encoding, body encoding/hash, fee and witness encoding.+-- Constructors stay private so callers cannot desynchronize these snapshots.+data Transaction = Transaction !ByteString !ByteString !ByteString !Word64 !ByteString+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate exactly one native transaction and copy its fee and identity bytes.+-- Native decoding supports historical 3-element, legacy/mempool 4-element and+-- Dijkstra block 4-element frames, including indefinite outer arrays. Accepted+-- body/witness contents follow the pinned native decoder, not a generic CBOR AST.+-- Malformed, incomplete and trailing input returns a native failure.+decodeCbor :: ByteString -> IO (Either NativeFailure Transaction)+decodeCbor bytes = withInput bytes $ \pointer size ->+ withOwnedOutput "transaction.decodeCbor" FFI.cFree (FFI.cDecode pointer size) (copySnapshot "transaction.decodeCbor")++-- | Exact original full input bytes, or the fresh encoding produced by an edit.+encodeCbor :: Transaction -> ByteString+encodeCbor (Transaction bytes _ _ _ _) = bytes++-- | Exact bytes hashed for the transaction ID, independent of the outer frame.+bodyCbor :: Transaction -> ByteString+bodyCbor (Transaction _ bytes _ _ _) = bytes++-- | BLAKE2b-256 of 'bodyCbor', copied from the native transaction ID.+bodyHash :: Transaction -> ByteString+bodyHash (Transaction _ _ digest _ _) = digest++-- | Exact encoded witness map retained from decoding or produced by an edit.+witnessCbor :: Transaction -> ByteString+witnessCbor (Transaction _ _ _ _ bytes) = bytes++-- | Fee in lovelace; no integer conversion or truncation is performed.+fee :: Transaction -> Word64+fee (Transaction _ _ _ lovelace _) = lovelace++-- | Change the fee on an independent native deep clone. A same-fee update is an+-- exact no-op, preserving the full encoding and signatures. A changed fee drops+-- outer vkey and bootstrap signatures and recomputes body encoding/hash. Scripts,+-- datums, redeemers and auxiliary data remain; this is not transaction balancing+-- or a guarantee that the edited transaction is valid for submission.+--+-- The native serializer preserves historical/block frame ordering but emits a+-- definite outer array. Body re-encoding may normalize noncanonical encodings.+-- The source snapshot remains unchanged on success, failure or cancellation.+setFee :: Word64 -> Transaction -> IO (Either NativeFailure Transaction)+setFee lovelace transaction+ | lovelace == fee transaction = pure (Right transaction)+ | otherwise = withInput (encodeCbor transaction) $ \pointer size ->+ withOwnedOutput "transaction.setFee" FFI.cFree (FFI.cSetFee pointer size lovelace) (copySnapshot "transaction.setFee")++-- | Keep input bytes alive through the complete safe native acquisition.+withInput :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withInput bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) ->+ action (castPtr pointer) (fromIntegral size)++-- | Snapshot the four borrowed spans before the native owner is released.+copySnapshot :: Text -> Ptr FFI.NativeSnapshot -> IO (Either NativeFailure Transaction)+copySnapshot operation pointer = do+ full <- copyPart operation pointer 0+ body <- copyPart operation pointer 1+ digest <- copyPart operation pointer 2+ witnesses <- copyPart operation pointer 3+ lovelace <- FFI.cFee pointer+ pure $ do+ fullBytes <- full+ bodyBytes <- body+ hashBytes <- digest+ witnessBytes <- witnesses+ if ByteString.length hashBytes /= 32+ then Left (NativeContractFailure operation)+ else Right (Transaction fullBytes bodyBytes hashBytes lovelace witnessBytes)++-- | Copy a nonempty bounded span; neither pointer nor native-size conversion+-- escapes the ownership scope. Field numbers belong only to the private adapter.+copyPart :: Text -> Ptr FFI.NativeSnapshot -> CUInt -> IO (Either NativeFailure ByteString)+copyPart operation pointer field = alloca $ \sizeSlot -> do+ poke sizeSlot 0+ bytes <- FFI.cBytes pointer field sizeSlot+ size <- peek sizeSlot+ if bytes == nullPtr || size == 0 || toInteger size > toInteger (maxBound :: Int)+ then pure (Left (NativeContractFailure operation))+ else Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)
@@ -0,0 +1,37 @@+Bundled cardano-c source package+===============================++cardano-c: Copyright Biglup Labs and contributors, Apache-2.0 (LICENSE).+The source revision is recorded in NATIVE_REVISION. Original source notices+are preserved. The Cabal description and config.h are generated by Cometa;+no upstream C implementation is modified by packaging.++This distribution contains multiple licenses. Its package license expression+lists the requirements of the combined source payload; it does not relicense+individual files. In particular, mini-gmp is not Apache-2.0 licensed.++vendor/external/libsodium: ISC (libsodium/LICENSE), with original public-domain+notices in individual files; SHA-256/SHA-512 by Colin Percival are BSD-2-Clause+(the full notice is reproduced in licenses/libsodium-sha-BSD-2-Clause.txt).+BLAKE2 reference files carry CC0 public-domain notices; CC0 is the selected+license where alternatives are offered (licenses/CC0-1.0.txt).++vendor/external/gmp: mini-gmp and mini-mpq by the Free Software Foundation and+contributors, LGPL-3.0-or-later OR GPL-2.0-or-later. See gmp/README and the source+headers, licenses/LGPL-3.0.txt, licenses/GPL-3.0.txt (incorporated by LGPL v3)+and licenses/GPL-2.0.txt. Consumers distributing linked applications must satisfy+the terms of their selected license, including its relinking/source provisions.++vendor/external/sha3: MIT (sha3/LICENSE).+vendor/external/secp256k1: MIT (secp256k1/COPYING).+vendor/external/blst: Apache-2.0 (blst/LICENSE).++vendor/external/ripemd160: public-domain dedication and fallback unrestricted+license with warranty disclaimer (ripemd160/LICENSE). This component imposes no+additional license conditions, so it adds no term to the package's SPDX license+expression. Hackage rejects custom LicenseRef identifiers. The original+dedication, fallback grant and disclaimer remain in the bundled LICENSE and+source headers; this metadata representation does not change those notices.++All paths above are relative to vendor/external unless given in full. Full+upstream provenance is retained in vendor/external/README and VERSION files.
@@ -0,0 +1,1 @@+a6f659d780f17b60ebafa170af919cca8173df09
@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+ HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++ i. the right to reproduce, adapt, distribute, perform, display,+ communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+ likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+ subject to the limitations in paragraph 4(a), below;+ v. rights protecting the extraction, dissemination, use and reuse of data+ in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+ European Parliament and of the Council of 11 March 1996 on the legal+ protection of databases, and under any national implementation+ thereof, including any amended or successor version of such+ directive); and+vii. other similar, equivalent or corresponding rights throughout the+ world based on applicable law or treaty, and any national+ implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+ surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+ warranties of any kind concerning the Work, express, implied,+ statutory or otherwise, including without limitation warranties of+ title, merchantability, fitness for a particular purpose, non+ infringement, or the absence of latent or other defects, accuracy, or+ the present or absence of errors, whether or not discoverable, all to+ the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+ that may apply to the Work or any use thereof, including without+ limitation any person's Copyright and Related Rights in the Work.+ Further, Affirmer disclaims responsibility for obtaining any necessary+ consents, permissions or other rights required for any use of the+ Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+ party to this document and has no duty or obligation with respect to+ this CC0 or use of the Work.
@@ -0,0 +1,339 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Lesser General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License.
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
@@ -0,0 +1,165 @@+ GNU LESSER GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.+++ This version of the GNU Lesser General Public License incorporates+the terms and conditions of version 3 of the GNU General Public+License, supplemented by the additional permissions listed below.++ 0. Additional Definitions.++ As used herein, "this License" refers to version 3 of the GNU Lesser+General Public License, and the "GNU GPL" refers to version 3 of the GNU+General Public License.++ "The Library" refers to a covered work governed by this License,+other than an Application or a Combined Work as defined below.++ An "Application" is any work that makes use of an interface provided+by the Library, but which is not otherwise based on the Library.+Defining a subclass of a class defined by the Library is deemed a mode+of using an interface provided by the Library.++ A "Combined Work" is a work produced by combining or linking an+Application with the Library. The particular version of the Library+with which the Combined Work was made is also called the "Linked+Version".++ The "Minimal Corresponding Source" for a Combined Work means the+Corresponding Source for the Combined Work, excluding any source code+for portions of the Combined Work that, considered in isolation, are+based on the Application, and not on the Linked Version.++ The "Corresponding Application Code" for a Combined Work means the+object code and/or source code for the Application, including any data+and utility programs needed for reproducing the Combined Work from the+Application, but excluding the System Libraries of the Combined Work.++ 1. Exception to Section 3 of the GNU GPL.++ You may convey a covered work under sections 3 and 4 of this License+without being bound by section 3 of the GNU GPL.++ 2. Conveying Modified Versions.++ If you modify a copy of the Library, and, in your modifications, a+facility refers to a function or data to be supplied by an Application+that uses the facility (other than as an argument passed when the+facility is invoked), then you may convey a copy of the modified+version:++ a) under this License, provided that you make a good faith effort to+ ensure that, in the event an Application does not supply the+ function or data, the facility still operates, and performs+ whatever part of its purpose remains meaningful, or++ b) under the GNU GPL, with none of the additional permissions of+ this License applicable to that copy.++ 3. Object Code Incorporating Material from Library Header Files.++ The object code form of an Application may incorporate material from+a header file that is part of the Library. You may convey such object+code under terms of your choice, provided that, if the incorporated+material is not limited to numerical parameters, data structure+layouts and accessors, or small macros, inline functions and templates+(ten or fewer lines in length), you do both of the following:++ a) Give prominent notice with each copy of the object code that the+ Library is used in it and that the Library and its use are+ covered by this License.++ b) Accompany the object code with a copy of the GNU GPL and this license+ document.++ 4. Combined Works.++ You may convey a Combined Work under terms of your choice that,+taken together, effectively do not restrict modification of the+portions of the Library contained in the Combined Work and reverse+engineering for debugging such modifications, if you also do each of+the following:++ a) Give prominent notice with each copy of the Combined Work that+ the Library is used in it and that the Library and its use are+ covered by this License.++ b) Accompany the Combined Work with a copy of the GNU GPL and this license+ document.++ c) For a Combined Work that displays copyright notices during+ execution, include the copyright notice for the Library among+ these notices, as well as a reference directing the user to the+ copies of the GNU GPL and this license document.++ d) Do one of the following:++ 0) Convey the Minimal Corresponding Source under the terms of this+ License, and the Corresponding Application Code in a form+ suitable for, and under terms that permit, the user to+ recombine or relink the Application with a modified version of+ the Linked Version to produce a modified Combined Work, in the+ manner specified by section 6 of the GNU GPL for conveying+ Corresponding Source.++ 1) Use a suitable shared library mechanism for linking with the+ Library. A suitable mechanism is one that (a) uses at run time+ a copy of the Library already present on the user's computer+ system, and (b) will operate properly with a modified version+ of the Library that is interface-compatible with the Linked+ Version.++ e) Provide Installation Information, but only if you would otherwise+ be required to provide such information under section 6 of the+ GNU GPL, and only to the extent that such information is+ necessary to install and execute a modified version of the+ Combined Work produced by recombining or relinking the+ Application with a modified version of the Linked Version. (If+ you use option 4d0, the Installation Information must accompany+ the Minimal Corresponding Source and Corresponding Application+ Code. If you use option 4d1, you must provide the Installation+ Information in the manner specified by section 6 of the GNU GPL+ for conveying Corresponding Source.)++ 5. Combined Libraries.++ You may place library facilities that are a work based on the+Library side by side in a single library together with other library+facilities that are not Applications and are not covered by this+License, and convey such a combined library under terms of your+choice, if you do both of the following:++ a) Accompany the combined library with a copy of the same work based+ on the Library, uncombined with any other library facilities,+ conveyed under the terms of this License.++ b) Give prominent notice with the combined library that part of it+ is a work based on the Library, and explaining where to find the+ accompanying uncombined form of the same work.++ 6. Revised Versions of the GNU Lesser General Public License.++ The Free Software Foundation may publish revised and/or new versions+of the GNU Lesser General Public License from time to time. Such new+versions will be similar in spirit to the present version, but may+differ in detail to address new problems or concerns.++ Each version is given a distinguishing version number. If the+Library as you received it specifies that a certain numbered version+of the GNU Lesser General Public License "or any later version"+applies to it, you have the option of following the terms and+conditions either of that published version or of any later version+published by the Free Software Foundation. If the Library as you+received it does not specify a version number of the GNU Lesser+General Public License, you may choose any version of the GNU Lesser+General Public License ever published by the Free Software Foundation.++ If the Library as you received it specifies that a proxy can decide+whether future versions of the GNU Lesser General Public License shall+apply, that proxy's public statement of acceptance of any version is+permanent authorization for you to choose that version for the+Library.
@@ -0,0 +1,27 @@+/*-+ * Copyright 2005,2007,2009 Colin Percival+ * All rights reserved.+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions+ * are met:+ * 1. Redistributions of source code must retain the above copyright+ * notice, this list of conditions and the following disclaimer.+ * 2. Redistributions in binary form must reproduce the above copyright+ * notice, this list of conditions and the following disclaimer in the+ * documentation and/or other materials provided with the distribution.+ *+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF+ * SUCH DAMAGE.+ *+ */+
@@ -0,0 +1,32 @@+{+ "name": "cardano-c-clib",+ "version": "0.1.1.0",+ "source_roots": ["include", "src", "external"],+ "source_extensions": [".c", ".h", ".inl"],+ "notice_prefixes": ["LICENSE", "COPYING", "NOTICE", "VERSION", "README"],+ "include_dirs": [+ "vendor", "vendor/include", "vendor/external/libsodium/include",+ "vendor/external/libsodium/include/sodium", "vendor/external/gmp",+ "vendor/external/sha3", "vendor/external/ripemd160",+ "vendor/external/secp256k1/include", "vendor/external/blst/bindings"+ ],+ "cc_options": ["-std=c99", "-DSODIUM_STATIC", "-DJSONC_STATIC"],+ "config_defaults": {+ "CARDANO_C_COLLECTION_GROW_FACTOR": "1.5",+ "CARDANO_C_MAX_JSON_DEPTH": "256"+ },+ "libraries": {+ "sodium": {"sources": ["vendor/external/libsodium/**/*.c"], "cc_options": []},+ "gmp": {"sources": ["vendor/external/gmp/*.c"], "cc_options": []},+ "sha3": {"sources": ["vendor/external/sha3/*.c"], "cc_options": []},+ "ripemd160": {"sources": ["vendor/external/ripemd160/*.c"], "cc_options": []},+ "secp256k1": {+ "sources": ["vendor/external/secp256k1/src/secp256k1.c", "vendor/external/secp256k1/src/precomputed_ecmult.c", "vendor/external/secp256k1/src/precomputed_ecmult_gen.c"],+ "cc_options": ["-DENABLE_MODULE_EXTRAKEYS=1", "-DENABLE_MODULE_SCHNORRSIG=1", "-DECMULT_WINDOW_SIZE=8", "-DSECP256K1_STATIC"]+ },+ "blst": {+ "sources": ["vendor/external/blst/src/server.c"],+ "cc_options": ["-D__BLST_NO_ASM__", "-D__BLST_PORTABLE__"]+ }+ }+}
@@ -0,0 +1,46 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Version information and shared operation errors. Import domain modules+-- qualified, for example @Cometa.Crypto.Blake2b@ as @Blake2b@.+--+-- @+-- import qualified Cometa+--+-- main :: IO ()+-- main = Cometa.nativeVersion >>= print+-- @+module Cometa+ ( -- * Version information+ nativeVersion,++ -- * Errors+ Error (..),+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.FFI.Native as Native+import Cometa.Internal.Ownership (copyStaticText)+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Return the version of cardano-c used by the running application. This is+-- independent of the Cometa.hs package version.+nativeVersion :: IO Text+nativeVersion = Native.cVersion >>= copyStaticText
@@ -0,0 +1,84 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Addresses across Shelley, Byron and reward-account forms. This sum retains+-- each family's validated representation; it does not establish whether an+-- address is an admissible transaction output for a particular ledger era.+--+-- @+-- import qualified Cometa.Address as Address+--+-- normalize text = Address.toText <$> Address.fromText text+-- @+module Cometa.Address (Address (..), fromBytes, toBytes, fromText, toText) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address.Byron as Byron+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import Cometa.Error (Error (..))+import Data.Bits (shiftR)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++-- | Address families. Equality and ordering compare constructors then values;+-- use 'toBytes' when serialization order is required.+data Address+ = -- | Base, enterprise or pointer payment address.+ ShelleyAddress !Shelley.Address+ | -- | Historical bootstrap address.+ ByronAddress !Byron.Address+ | -- | Reward account; assembly does not imply output admissibility.+ RewardAddress !Reward.RewardAddress+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Exact validated address bytes.+toBytes :: Address -> ByteString+toBytes (ShelleyAddress value) = Shelley.toBytes value+toBytes (ByronAddress value) = Byron.toBytes value+toBytes (RewardAddress value) = Reward.toBytes value++-- | Decode the complete address according to its header. Validation errors+-- retain the corresponding family's structured error.+fromBytes :: ByteString -> Either Error Address+fromBytes bytes = case ByteString.uncons bytes of+ Nothing -> Left InvalidShelleyAddress+ Just (header, _) -> case header `shiftR` 4 of+ kind | kind <= 7 -> ShelleyAddress <$> Shelley.fromBytes bytes+ kind | kind == 8 || kind == 9 -> ByronAddress <$> Byron.fromBytes bytes+ kind | kind == 14 || kind == 15 -> RewardAddress <$> Reward.fromBytes bytes+ kind -> Left (UnsupportedAddressType kind)++-- | Bech32 for Shelley/reward addresses and Base58 for Byron addresses.+toText :: Address -> Text+toText (ShelleyAddress value) = Shelley.toText value+toText (ByronAddress value) = Byron.toText value+toText (RewardAddress value) = Reward.toText value++-- | Decode Bech32 payment/reward forms or Base58 bootstrap addresses.+fromText :: Text -> Either Error Address+fromText text+ | Text.isPrefixOf (Text.pack "addr") lowered = ShelleyAddress <$> Shelley.fromText text+ | Text.isPrefixOf (Text.pack "stake") lowered = RewardAddress <$> Reward.fromText text+ | otherwise = ByronAddress <$> Byron.fromText text+ where+ lowered = Text.toLower text
@@ -0,0 +1,262 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Byron bootstrap addresses with checked payloads and checksums. Imported+-- encodings are retained exactly; construction assigns fresh CBOR and Base58.+--+-- @+-- import qualified Cometa.Address.Byron as Byron+--+-- inspectRoot text = Byron.root <$> Byron.fromText text+-- @+module Cometa.Address.Byron+ ( Address,+ Root,+ rootFromBytes,+ rootBytes,+ AddressType (..),+ Attributes,+ attributes,+ derivationPayload,+ networkMagic,+ address,+ root,+ addressType,+ addressAttributes,+ fromBytes,+ toBytes,+ fromText,+ toText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Write as W+import Cometa.Error (Error (..))+import Control.Monad (foldM, replicateM, unless)+import Data.Bits (complement, shiftR, xor, (.&.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Int (Int64)+import qualified Data.List as List+import Data.Maybe (isNothing)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | A 28-byte address root. Equality and ordering compare exact bytes.+newtype Root = Root ByteString deriving (Eq, Ord, Show)++-- | The authority used to spend a Byron output.+data AddressType+ = -- | Verification-key authority.+ PublicKey+ | -- | Script authority.+ Script+ | -- | Initial-distribution redemption key.+ Redeem+ deriving (Eq, Ord, Show, Enum, Bounded)++-- | Optional encrypted derivation payload and network magic. The payload is+-- at most 64 bytes; empty payloads are represented as absent. Magic ranges from+-- zero through 2^63-1. Absence identifies the main/staging network convention.+data Attributes = Attributes !(Maybe ByteString) !(Maybe Word64) deriving (Eq, Ord, Show)++-- | An address with its original checked encoding. Equality and ordering compare+-- address bytes; 'Show' is diagnostic output, not its Base58 representation.+data Address = Address !ByteString !Root !Attributes !AddressType deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import a 28-byte root without hashing; other lengths return 'InvalidByronAddress'.+rootFromBytes :: ByteString -> Either Error Root+rootFromBytes bytes+ | B.length bytes == 28 = Right (Root bytes)+ | otherwise = Left (InvalidByronAddress "Expected a 28-byte Byron root")++-- | Exact root bytes.+rootBytes :: Root -> ByteString+rootBytes (Root bytes) = bytes++-- | Validate an encrypted payload and network magic. Invalid bounds return+-- 'InvalidByronAddress'. This neither decrypts nor authenticates the payload.+attributes :: Maybe ByteString -> Maybe Word64 -> Either Error Attributes+attributes payload magic+ | maybe False ((> 64) . B.length) payload = Left (InvalidByronAddress "Derivation payload exceeds 64 bytes")+ | maybe False (> fromIntegral (maxBound :: Int64)) magic = Left (InvalidByronAddress "Network magic exceeds 2^63-1")+ | otherwise = Right (Attributes (payload >>= nonempty) magic)+ where+ nonempty bytes = if B.null bytes then Nothing else Just bytes++-- | Encrypted derivation payload, when present.+derivationPayload :: Attributes -> Maybe ByteString+derivationPayload (Attributes payload _) = payload++-- | Network magic; absence uses the main/staging network convention.+networkMagic :: Attributes -> Maybe Word64+networkMagic (Attributes _ magic) = magic++-- | Assemble an address with minimal CBOR and a checksum of the exact payload.+address :: Root -> Attributes -> AddressType -> Address+address digest attrs kind = Address bytes digest attrs kind+ where+ payload = W.toStrictByteString (E.encodeListLen 3 <> E.encodeBytes (rootBytes digest) <> encodeAttributes attrs <> E.encodeWord (fromIntegral (fromEnum kind)))+ bytes = W.toStrictByteString (E.encodeListLen 2 <> E.encodeTag 24 <> E.encodeBytes payload <> E.encodeWord32 (crc32 payload))++-- | Address root without recomputation.+root :: Address -> Root+root (Address _ value _ _) = value++-- | Spending-authority form.+addressType :: Address -> AddressType+addressType (Address _ _ _ value) = value++-- | Validated encrypted payload and network discriminator.+addressAttributes :: Address -> Attributes+addressAttributes (Address _ _ value _) = value++-- | Exact accepted address bytes, or fresh bytes assigned by 'address'.+toBytes :: Address -> ByteString+toBytes (Address bytes _ _ _) = bytes++-- | Validate complete outer and inner CBOR, tag 24, CRC32, root length, known+-- unique attributes and type. Malformed or trailing input returns+-- 'InvalidByronAddress'. Accepted nonminimal and indefinite array framing is+-- retained exactly; attribute values must each contain one complete value.+fromBytes :: ByteString -> Either Error Address+fromBytes bytes = do+ payload <- decode outer bytes+ (digest, attrs, kind) <- decode inner payload+ pure (Address bytes digest attrs kind)+ where+ outer = array 2 $ do+ tag <- D.decodeTag+ unless (tag == 24) (fail "Expected encoded-CBOR tag 24")+ payload <- D.decodeBytes+ checksum <- D.decodeWord32+ unless (checksum == crc32 payload) (fail "Byron checksum mismatch")+ pure payload+ inner = array 3 $ do+ digest <- D.decodeBytes >>= validate rootFromBytes+ attrs <- decodeAttributes+ code <- D.decodeWord+ kind <- case code of+ 0 -> pure PublicKey+ 1 -> pure Script+ 2 -> pure Redeem+ _ -> fail "Unknown Byron address type"+ pure (digest, attrs, kind)++-- | Encode Base58 with the Bitcoin alphabet, without whitespace or a prefix.+toText :: Address -> Text+toText = encodeBase58 . toBytes++-- | Parse Base58 and validate its address/checksum. Invalid characters, empty+-- input, more than 512 characters or malformed data return 'InvalidByronAddressText'.+fromText :: Text -> Either Error Address+fromText text+ | Text.null text || Text.length text > 512 = Left InvalidByronAddressText+ | otherwise = do+ bytes <- maybe (Left InvalidByronAddressText) Right (decodeBase58 text)+ either (const (Left InvalidByronAddressText)) Right (fromBytes bytes)++encodeAttributes :: Attributes -> E.Encoding+encodeAttributes (Attributes payload magic) = E.encodeMapLen count <> field 1 E.encodeBytes payload <> field 2 E.encodeWord64 magic+ where+ count = maybe 0 (const 1) payload + maybe 0 (const 1) magic+ field key encodeValue = maybe mempty (\value -> E.encodeWord key <> E.encodeBytes (W.toStrictByteString (encodeValue value)))++decodeAttributes :: D.Decoder s Attributes+decodeAttributes = do+ size <- D.decodeMapLenOrIndef+ pairs <- entries size+ (payload, magic) <- foldM insert (Nothing, Nothing) pairs+ validate (uncurry attributes) (payload, magic)+ where+ entries (Just count) = replicateM count pair+ entries Nothing = do+ end <- D.decodeBreakOr+ if end then pure [] else (:) <$> pair <*> entries Nothing+ pair = (,) <$> D.decodeWord <*> D.decodeBytes+ insert (payload, magic) (key, bytes) = case key of+ 1 | isNothing payload -> do+ value <- validate (decode D.decodeBytes) bytes+ pure (Just value, magic)+ 2 | isNothing magic -> do+ value <- validate (decode D.decodeWord64) bytes+ pure (payload, Just value)+ _ -> fail "Unknown or repeated Byron attribute"++array :: Int -> D.Decoder s a -> D.Decoder s a+array expected parser = do+ size <- D.decodeListLenOrIndef+ case size of+ Just count -> unless (count == expected) (fail "Incorrect Byron array length")+ Nothing -> pure ()+ result <- parser+ case size of+ Just _ -> pure ()+ Nothing -> D.decodeBreakOr >>= \end -> unless end (fail "Extra Byron array fields")+ pure result++validate :: (a -> Either Error b) -> a -> D.Decoder s b+validate parser = either (fail . show) pure . parser++decode :: (forall s. D.Decoder s a) -> ByteString -> Either Error a+decode parser bytes = case R.deserialiseFromBytes parser (L.fromStrict bytes) of+ Left err -> Left (InvalidByronAddress (Text.pack (show err)))+ Right (rest, value)+ | L.null rest -> Right value+ | otherwise -> Left (InvalidByronAddress "Trailing Byron CBOR")++-- Reflected CRC-32/ISO-HDLC polynomial, initial/final XOR 0xffffffff.+crc32 :: ByteString -> Word32+crc32 = complement . B.foldl' step maxBound+ where+ step checksum byte = List.foldl' (\value _ -> bit value) (checksum `xor` fromIntegral byte) [1 :: Int .. 8]+ bit value = if value .&. 1 == 1 then (value `shiftR` 1) `xor` 0xedb88320 else value `shiftR` 1++alphabet :: String+alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"++encodeBase58 :: ByteString -> Text+encodeBase58 bytes = Text.pack (replicate zeros '1' ++ reverse (List.unfoldr digit number))+ where+ zeros = B.length (B.takeWhile (== 0) bytes)+ number = B.foldl' (\n byte -> n * 256 + toInteger byte) 0 bytes+ digit 0 = Nothing+ digit value = do+ let (quotient, remainder) = value `divMod` 58+ character <- lookup remainder (zip [0 .. 57] alphabet)+ pure (character, quotient)++decodeBase58 :: Text -> Maybe ByteString+decodeBase58 text = do+ number <- foldM digit 0 (Text.unpack text)+ pure (B.pack (replicate zeros 0 ++ bytes number []))+ where+ zeros = Text.length (Text.takeWhile (== '1') text)+ digit value character = (value * 58 +) . toInteger <$> lookup character (zip alphabet [0 :: Int ..])+ bytes 0 result = result+ bytes value result = let (quotient, remainder) = value `divMod` 256 in bytes quotient (fromInteger remainder : result)
@@ -0,0 +1,112 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Staking reward accounts, distinct from payment addresses.+--+-- @+-- import qualified Cometa.Address.Reward as Reward+-- import qualified Cometa.Credential as Credential+-- import qualified Cometa.NetworkId as Network+--+-- rewardAccount :: Credential.Credential Credential.Stake -> Reward.RewardAddress+-- rewardAccount = Reward.fromCredential Network.testnet+-- @+module Cometa.Address.Reward+ ( RewardAddress,+ fromCredential,+ networkId,+ credential,+ fromBytes,+ toBytes,+ fromText,+ toText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Credential (Credential (..), Stake)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.AddressText as AddressText+import Cometa.NetworkId (NetworkId)+import qualified Cometa.NetworkId as Network+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | An immutable reward account. Equality and ordering compare network then+-- credential (key before script, then hash bytes); 'Show' is diagnostic.+data RewardAddress = RewardAddress !NetworkId !(Credential Stake)+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble a reward account from its network and staking authority.+fromCredential :: NetworkId -> Credential Stake -> RewardAddress+fromCredential = RewardAddress++-- | Four-bit network tag carried by the header.+networkId :: RewardAddress -> NetworkId+networkId (RewardAddress network _) = network++-- | Staking authority controlling the rewards.+credential :: RewardAddress -> Credential Stake+credential (RewardAddress _ value) = value++-- | Exact 29-byte header and credential encoding.+toBytes :: RewardAddress -> ByteString+toBytes (RewardAddress network value) = case value of+ KeyCredential hash -> encode 14 (Credential.keyHashBytes hash)+ ScriptCredential hash -> encode 15 (Credential.scriptHashBytes hash)+ where+ encode tag = ByteString.cons ((tag `shiftL` 4) .|. Network.networkIdValue network)++-- | Import exact reward-account bytes. Non-reward headers return+-- 'UnsupportedAddressType'; empty input or incorrect exact lengths return+-- 'InvalidShelleyAddress'. All four-bit network tags are retained.+fromBytes :: ByteString -> Either Error RewardAddress+fromBytes bytes = case ByteString.uncons bytes of+ Nothing -> Left InvalidShelleyAddress+ Just (header, payload) -> do+ let tag = header `shiftR` 4+ if tag /= 14 && tag /= 15+ then Left (UnsupportedAddressType tag)+ else+ if ByteString.length payload /= 28+ then Left InvalidShelleyAddress+ else do+ network <- Network.mkNetworkId (toInteger (header .&. 15))+ authority <-+ if tag == 14+ then KeyCredential <$> Credential.keyHashFromBytes payload+ else ScriptCredential <$> Credential.scriptHashFromBytes payload+ pure (RewardAddress network authority)++-- | Encode canonical lowercase Bech32, with @stake@ for tag 1 and+-- @stake_test@ for other tags.+toText :: RewardAddress -> Text+toText address = AddressText.toText True (networkId address == Network.mainnet) (toBytes address)++-- | Parse lowercase or all-uppercase Bech32. Mixed case, non-ASCII, empty,+-- overlong (more than 120 characters), or mismatched network/form prefixes+-- return 'InvalidShelleyAddressText'. Malformed encoding or checksum returns+-- 'InvalidShelleyAddressText'; non-reward headers return 'UnsupportedAddressType';+-- incorrect exact lengths return 'InvalidShelleyAddress'.+fromText :: Text -> Either Error RewardAddress+fromText = AddressText.fromText fromBytes toText
@@ -0,0 +1,224 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Base, enterprise and pointer payment addresses. Construction and byte conversion+-- are pure. Byron and reward addresses return 'UnsupportedAddressType' when imported as bytes.+--+-- @+-- import qualified Cometa.Address.Shelley as Address+-- import qualified Cometa.Credential as Credential+--+-- receivingAddress :: Credential.KeyHash Credential.Payment -> Address.Address+-- receivingAddress key = Address.enterprise Address.mainnet (Credential.KeyCredential key)+-- @+module Cometa.Address.Shelley+ ( -- * Networks+ NetworkId,+ mkNetworkId,+ networkIdValue,+ mainnet,+ testnet,++ -- * Construction+ Address,+ StakePointer (..),+ pointer,+ pointerRef,+ base,+ enterprise,++ -- * Inspection+ networkId,+ paymentCredential,+ stakeCredential,++ -- * Encoding+ fromBytes,+ toBytes,+ fromText,+ toText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Credential (Credential (..), Payment, Stake)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.AddressText as AddressText+import Cometa.NetworkId (NetworkId, mainnet, mkNetworkId, networkIdValue, testnet)+import Data.Bits (shiftL, shiftR, testBit, (.&.), (.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word32, Word8)++-- TYPES ----------------------------------------------------------------------++-- | An immutable address. Equality and ordering compare form (base,+-- enterprise, pointer), network, then credentials; 'Show' is diagnostic.+data Address+ = Base !NetworkId !(Credential Payment) !(Credential Stake)+ | Enterprise !NetworkId !(Credential Payment)+ | Pointer !NetworkId !(Credential Payment) !StakePointer+ deriving (Eq, Ord, Show)++-- | Location of a stake registration. Each component is an unsigned 32-bit value.+data StakePointer = StakePointer+ { -- | Absolute slot containing the registration.+ slot :: !Word32,+ -- | Zero-based transaction index within that slot.+ transactionIndex :: !Word32,+ -- | Zero-based certificate index within that transaction.+ certificateIndex :: !Word32+ }+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble a base address from network, payment authority and stake authority,+-- in that order. Key and script credentials are supported in both positions.+base :: NetworkId -> Credential Payment -> Credential Stake -> Address+base = Base++-- | Assemble an address with payment authority and no staking rights.+enterprise :: NetworkId -> Credential Payment -> Address+enterprise = Enterprise++-- | Assemble a pointer address from payment authority and a registration location.+pointer :: NetworkId -> Credential Payment -> StakePointer -> Address+pointer = Pointer++-- | Registration location, present only in pointer addresses.+pointerRef :: Address -> Maybe StakePointer+pointerRef (Pointer _ _ location) = Just location+pointerRef _ = Nothing++-- | Network tag carried by the header.+networkId :: Address -> NetworkId+networkId address = case address of+ Base network _ _ -> network+ Enterprise network _ -> network+ Pointer network _ _ -> network++-- | Payment authority carried by every payment address.+paymentCredential :: Address -> Credential Payment+paymentCredential address = case address of+ Base _ credential _ -> credential+ Enterprise _ credential -> credential+ Pointer _ credential _ -> credential++-- | Staking authority; absent for enterprise and pointer addresses.+stakeCredential :: Address -> Maybe (Credential Stake)+stakeCredential address = case address of+ Base _ _ credential -> Just credential+ Enterprise {} -> Nothing+ Pointer {} -> Nothing++-- | Serialize exact header and credential bytes: 57 bytes for base addresses,+-- 29 for enterprise addresses, and 32–44 for pointer addresses.+toBytes :: Address -> ByteString+toBytes address = case address of+ Base network payment stake -> encode network (kind payment + 2 * kind stake) [credentialBytes payment, credentialBytes stake]+ Enterprise network payment -> encode network (6 + kind payment) [credentialBytes payment]+ Pointer network payment (StakePointer a b c) -> encode network (4 + kind payment) [credentialBytes payment, variable a, variable b, variable c]+ where+ encode network tag parts = ByteString.cons ((tag `shiftL` 4) .|. networkIdValue network) (ByteString.concat parts)++-- | Import exact bytes. Byron, reward and reserved headers return+-- 'UnsupportedAddressType'. Empty input or incorrect exact lengths return+-- 'InvalidShelleyAddress'. Pointer components must be minimally encoded, fit+-- 32 bits and consume the full input. All four-bit network tags are retained.+fromBytes :: ByteString -> Either Error Address+fromBytes bytes = case ByteString.uncons bytes of+ Nothing -> Left InvalidShelleyAddress+ Just (header, payload) -> do+ let tag = header `shiftR` 4+ networkValue = header .&. 15+ (payment, stake) = ByteString.splitAt 28 payload+ network <- mkNetworkId (toInteger networkValue)+ case tag of+ value+ | value <= 3 ->+ if ByteString.length payload /= 56+ then Left InvalidShelleyAddress+ else Base network <$> decodeCredential (testBit tag 0) payment <*> decodeCredential (testBit tag 1) stake+ value | value == 4 || value == 5 -> do+ credential <- decodeCredential (testBit tag 0) payment+ (a, restA) <- readVariable stake+ (b, restB) <- readVariable restA+ (c, restC) <- readVariable restB+ if ByteString.null restC+ then Right (Pointer network credential (StakePointer a b c))+ else Left InvalidShelleyAddress+ value | value == 6 || value == 7 -> Enterprise network <$> decodeCredential (testBit tag 0) payload+ _ -> Left (UnsupportedAddressType tag)+ where+ decodeCredential script payload+ | ByteString.length payload /= 28 = Left InvalidShelleyAddress+ | script = ScriptCredential <$> Credential.scriptHashFromBytes payload+ | otherwise = KeyCredential <$> Credential.keyHashFromBytes payload++-- | Encode canonical lowercase Bech32, with @addr@ for tag 1 and+-- @addr_test@ for other tags.+toText :: Address -> Text+toText address = AddressText.toText False (networkId address == mainnet) (toBytes address)++-- | Parse lowercase or all-uppercase Bech32. Mixed case, non-ASCII, empty,+-- overlong (more than 120 characters), or mismatched network/form prefixes+-- return 'InvalidShelleyAddressText'. Malformed encoding or checksum returns+-- 'InvalidShelleyAddressText'; unsupported headers return 'UnsupportedAddressType';+-- incorrect exact lengths return 'InvalidShelleyAddress'.+fromText :: Text -> Either Error Address+fromText = AddressText.fromText fromBytes toText++kind :: Credential purpose -> Word8+kind credential = case credential of+ KeyCredential _ -> 0+ ScriptCredential _ -> 1++credentialBytes :: Credential purpose -> ByteString+credentialBytes credential = case credential of+ KeyCredential hash -> Credential.keyHashBytes hash+ ScriptCredential hash -> Credential.scriptHashBytes hash++variable :: Word32 -> ByteString+variable value = ByteString.pack (go value [])+ where+ go remaining tailBytes+ | remaining < 128 = fromIntegral remaining : tailBytes+ | otherwise = continue (remaining `shiftR` 7) [fromIntegral (remaining .&. 127)]+ continue remaining tailBytes+ | remaining < 128 = (fromIntegral remaining .|. 128) : tailBytes+ | otherwise = continue (remaining `shiftR` 7) ((fromIntegral (remaining .&. 127) .|. 128) : tailBytes)++readVariable :: ByteString -> Either Error (Word32, ByteString)+readVariable original = go (0 :: Int) 0 original+ where+ go count value bytes = case ByteString.uncons bytes of+ Nothing -> Left InvalidShelleyAddress+ Just (byte, rest)+ | count >= 5 -> Left InvalidShelleyAddress+ | value > (toInteger (maxBound :: Word32) - toInteger (byte .&. 127)) `div` 128 -> Left InvalidShelleyAddress+ | otherwise ->+ let next = value * 128 + toInteger (byte .&. 127)+ in if testBit byte 7+ then go (count + 1) next rest+ else+ let result = fromInteger next+ consumed = ByteString.length original - ByteString.length rest+ in if ByteString.take consumed original == variable result+ then Right (result, rest)+ else Left InvalidShelleyAddress
@@ -0,0 +1,110 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Ada and native assets with validated policy and name components.+--+-- @+-- import qualified Cometa.AssetId as AssetId+-- import qualified Cometa.AssetName as AssetName+-- import qualified Cometa.PolicyId as PolicyId+--+-- unnamedToken :: PolicyId.PolicyId -> AssetId.AssetId+-- unnamedToken policy = AssetId.Native policy AssetName.empty+-- @+module Cometa.AssetId+ ( AssetId (..),+ fromBytes,+ toBytes,+ fromHex,+ toHex,+ fingerprint,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import Cometa.AssetName (AssetName)+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Cometa.PolicyId (PolicyId)+import qualified Cometa.PolicyId as PolicyId+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | An asset's identity. Ordering places Ada first, then compares native policy+-- bytes and name bytes lexicographically. 'Show' is diagnostic output.+data AssetId+ = -- | Ada; its quantity is measured in lovelace (one millionth of an Ada).+ Ada+ | -- | A native asset, identified by policy and exact name bytes. An empty+ -- name under a policy is a native asset, distinct from Ada.+ Native !PolicyId !AssetName+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import a native asset as its 28-byte policy followed by zero through 32+-- exact name bytes. Other lengths, including empty input, return+-- 'InvalidAssetIdLength'. Ada has no encoding in this format.+fromBytes :: ByteString -> Either Error AssetId+fromBytes bytes+ | size < 28 || size > 60 = Left (InvalidAssetIdLength size)+ | otherwise = Native <$> PolicyId.fromBytes policy <*> AssetName.fromBytes name+ where+ size = ByteString.length bytes+ (policy, name) = ByteString.splitAt 28 bytes++-- | Export the policy bytes followed by the exact name bytes. Ada returns+-- 'UnsupportedOperation'; an empty native name still exports 28 policy bytes.+toBytes :: AssetId -> Either Error ByteString+toBytes Ada = Left (UnsupportedOperation "AssetId.toBytes: Ada has no native asset encoding")+toBytes (Native policy name) = Right (PolicyId.toBytes policy <> AssetName.toBytes name)++-- | Import 56 through 120 ASCII hexadecimal digits as a native asset.+-- Either case is accepted, without a prefix or whitespace. Malformed hex+-- returns 'InvalidHex'; other decoded lengths return 'InvalidAssetIdLength'.+-- Empty text does not represent Ada.+fromHex :: Text -> Either Error AssetId+fromHex text = maybe (Left InvalidHex) fromBytes (Hex.decodeHex text)++-- | Export the native asset as lowercase hexadecimal policy and name bytes,+-- without a separator. Ada returns 'UnsupportedOperation'.+toHex :: AssetId -> Either Error Text+toHex asset = Hex.encodeHex <$> toBytes asset++-- | Compute the CIP-14 user-facing native asset fingerprint: BLAKE2b-160 of+-- the policy followed by the exact name bytes, encoded as Bech32 with the+-- @asset@ prefix. Ada returns 'UnsupportedOperation'. Hashing failures return+-- the corresponding 'NativeError'.+--+-- The fingerprint is a display checksum. It cannot be decoded back to the policy+-- and name, and does not replace the full asset identity or prove authenticity.+fingerprint :: AssetId -> IO (Either Error Text)+fingerprint Ada = pure (Left (UnsupportedOperation "AssetId.fingerprint: Ada has no CIP-14 fingerprint"))+fingerprint asset = case toBytes asset of+ Left failure -> pure (Left failure)+ Right bytes -> do+ hashed <- Blake2b.compute 20 bytes+ pure $ do+ digest <- hashed+ prefix <- either (const (Left (NativeContractViolation "Invalid built-in asset fingerprint prefix"))) Right (Bech32.humanReadablePartFromText "asset")+ pure (Bech32.encodeLenient prefix (Bech32.dataPartFromBytes (Blake2b.toBytes digest)))
@@ -0,0 +1,103 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Validated native-asset names, containing zero through 32 arbitrary bytes.+-- Names identify assets by bytes; UTF-8 is an optional interpretation.+--+-- @+-- import qualified Cometa.AssetName as AssetName+--+-- roundTrip :: AssetName.AssetName -> Bool+-- roundTrip name = AssetName.fromBytes (AssetName.toBytes name) == Right name+-- @+module Cometa.AssetName+ ( AssetName,+ empty,+ fromBytes,+ toBytes,+ fromHex,+ toHex,+ fromText,+ toText,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.Internal.TransactionCbor as Cbor+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text.Encoding as Text++-- TYPES ----------------------------------------------------------------------++-- | Zero through 32 bytes. Equality and ordering compare exact bytes+-- lexicographically. 'Show' is diagnostic output.+newtype AssetName = AssetName ByteString deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | The empty native-asset name, distinct from the Ada asset.+empty :: AssetName+empty = AssetName ByteString.empty++-- | Import arbitrary bytes, including NUL and invalid UTF-8. More than 32 bytes+-- returns 'InvalidAssetNameLength' with the actual byte count.+fromBytes :: ByteString -> Either Error AssetName+fromBytes bytes+ | ByteString.length bytes > 32 = Left (InvalidAssetNameLength (ByteString.length bytes))+ | otherwise = Right (AssetName bytes)++-- | Exact name bytes.+toBytes :: AssetName -> ByteString+toBytes (AssetName bytes) = bytes++-- | Import zero through 64 ASCII hexadecimal digits, accepting either case.+-- Odd lengths, prefixes, whitespace and nonhexadecimal characters return+-- 'InvalidHex'; decoded names longer than 32 bytes return 'InvalidAssetNameLength'.+fromHex :: Text -> Either Error AssetName+fromHex text = maybe (Left InvalidHex) fromBytes (Hex.decodeHex text)++-- | Lowercase hexadecimal without a prefix. The empty name renders as empty text.+toHex :: AssetName -> Text+toHex = Hex.encodeHex . toBytes++-- | Encode text as UTF-8, then validate the 32-byte bound. The limit counts+-- encoded bytes, not characters. No Unicode normalization is performed.+fromText :: Text -> Either Error AssetName+fromText = fromBytes . Text.encodeUtf8++-- | Interpret exact bytes as UTF-8. Invalid UTF-8 returns 'Nothing'; no bytes+-- are replaced or discarded. An empty name returns @Just ""@.+toText :: AssetName -> Maybe Text+toText name = either (const Nothing) Just (Text.decodeUtf8' (toBytes name))++-- | Encode the exact name bytes as a shortest-length definite CBOR byte string.+encodeCbor :: AssetName -> ByteString+encodeCbor = Cbor.encode . E.encodeBytes . toBytes++-- | Decode exactly one CBOR byte string containing 0 through 32 bytes.+-- Nonminimal length encodings are accepted; invalid schemas, lengths or+-- trailing bytes return 'InvalidAssetNameCbor'. Fresh encoding is semantic+-- and does not retain the original CBOR representation.+decodeCbor :: ByteString -> Either Error AssetName+decodeCbor = Cbor.decodeAs InvalidAssetNameCbor (D.decodeBytes >>= either (fail . show) pure . fromBytes)
@@ -0,0 +1,67 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Assemble standalone staking and governance certificates from validated+-- credentials, delegation targets, pool parameters and optional anchors.+-- Deposits and refunds are explicit lovelace; protocol and era checks belong to+-- the transaction workflow. Fresh encoding may change imported transaction bytes.+--+-- @+-- import qualified Cometa.Certificate as Certificate+-- import qualified Cometa.Credential as Credential+-- import qualified Cometa.Governance.DRep as DRep+--+-- abstain :: Credential.Credential Credential.Stake -> Certificate.Certificate+-- abstain stake = Certificate.VoteDelegation stake DRep.AlwaysAbstain+-- @+module Cometa.Certificate+ ( Certificate (..),+ Mir (..),+ Pot (..),+ encodeCbor,+ EncodedCertificate,+ decodeCbor,+ fromCertificate,+ toCertificate,+ toCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.Certificate (Certificate (..), EncodedCertificate, Mir (..), Pot (..), fromCertificate, toCertificate)+import qualified Cometa.Internal.Certificate as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode semantic data as fresh definite CBOR with minimal unsigned integers.+-- Reward credentials are sorted by kind and hash. No ledger validation occurs.+encodeCbor :: Certificate -> ByteString+encodeCbor = Internal.encodeCertificate++-- | Validate one complete certificate and retain its exact CBOR. Accepts definite+-- and indefinite arrays, nonminimal integers, and all certificate kinds 0–18.+-- Credential/hash lengths, arity and unsigned 64-bit bounds are checked. MIR+-- signed amounts and duplicate reward credentials are rejected. Malformed input+-- or trailing bytes returns 'Cometa.Error.InvalidCertificateCbor'.+decodeCbor :: ByteString -> Either Error EncodedCertificate+decodeCbor = Internal.decodeCertificate++-- | Exact imported bytes, or fresh bytes for values built with 'fromCertificate'.+-- Use this when imported certificate encoding must remain unchanged.+toCbor :: EncodedCertificate -> ByteString+toCbor = Internal.certificateCbor
@@ -0,0 +1,94 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Ordered certificate collections. Order and duplicate certificates are+-- retained. An exact envelope preserves imported tagging and integer encodings.+--+-- @+-- import qualified Cometa.Certificate.Collection as Certificates+--+-- noCertificates :: Certificates.Certificates+-- noCertificates = Certificates.empty+-- @+module Cometa.Certificate.Collection+ ( Certificates,+ empty,+ fromList,+ toList,+ encodeCbor,+ encodeCborWith,+ setEncoding,+ withSetEncoding,+ EncodedCertificates,+ decodeCbor,+ fromCertificates,+ toCertificates,+ toCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Certificate (Certificate)+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error)+import Cometa.Internal.Certificate (Certificates (..), EncodedCertificates, fromCertificates, toCertificates)+import qualified Cometa.Internal.Certificate as Internal+import qualified Cometa.Internal.SetEncoding as SetEncoding+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | No certificates.+empty :: Certificates+empty = Certificates []++-- | Assemble certificates in transaction order, preserving duplicates.+fromList :: [Certificate] -> Certificates+fromList = Certificates++-- | Certificates in their original order, including duplicates.+toList :: Certificates -> [Certificate]+toList (Certificates values) = values++-- | Fresh definite array with set tag 258, preserving order and duplicates.+encodeCbor :: Certificates -> ByteString+encodeCbor = Internal.encodeCertificates++-- | Fresh definite array with the requested outer set tag. Nested certificates+-- keep their usual encoding; order and repeated certificates remain unchanged.+encodeCborWith :: SetEncoding -> Certificates -> ByteString+encodeCborWith requested = SetEncoding.withEncoding requested . encodeCbor++-- | Observe the exact envelope's outer set tag.+setEncoding :: EncodedCertificates -> SetEncoding+setEncoding = Internal.certificatesSetEncoding++-- | Change only the outer set tag, preserving every array and certificate byte.+-- Requesting the current representation preserves the complete encoding exactly.+withSetEncoding :: SetEncoding -> EncodedCertificates -> EncodedCertificates+withSetEncoding = Internal.withCertificatesSetEncoding++-- | Validate a complete certificate array with an optional set tag 258.+-- Definite and indefinite arrays are accepted. Certificates obey the checks in+-- 'Cometa.Certificate.decodeCbor'. Invalid input and trailing bytes return+-- 'Cometa.Error.InvalidCertificateCbor'. Exact bytes, including tag absence, remain+-- available through 'toCbor'.+decodeCbor :: ByteString -> Either Error EncodedCertificates+decodeCbor = Internal.decodeCertificates++-- | Return the exact imported or freshly assembled encoding.+toCbor :: EncodedCertificates -> ByteString+toCbor = Internal.certificatesCbor
@@ -0,0 +1,67 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Select spending inputs with largest-first, random-improve or an application+-- supplied selector. Validate a request once, then use 'select' to check full+-- selection and change laws. Target values include externally assessed fees+-- and deposits; this boundary selects inputs and change without submitting.+--+-- @+-- selectLargest = select largestFirst+-- @+module Cometa.CoinSelection+ ( Selector (..),+ Strategy (..),+ largestFirst,+ randomImprove,+ randomImproveWithSeed,+ randomImproveWithOptions,+ SelectionOptions (..),+ SelectionRequest,+ mkSelectionRequest,+ preselected,+ available,+ target,+ outputHints,+ changeAddress,+ parameters,+ Selection (..),+ validateSelection,+ select,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.CoinSelection+ ( Selection (..),+ SelectionOptions (..),+ SelectionRequest,+ Selector (..),+ Strategy (..),+ available,+ changeAddress,+ largestFirst,+ mkSelectionRequest,+ outputHints,+ parameters,+ preselected,+ randomImprove,+ randomImproveWithOptions,+ randomImproveWithSeed,+ select,+ target,+ validateSelection,+ )
@@ -0,0 +1,178 @@+{-# LANGUAGE OverloadedStrings #-}+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE RoleAnnotations #-}++-- | Role-specific credentials for payments, staking, governance and guards.+-- Hashes contain exactly 28 bytes. Equality and ordering compare kind and bytes;+-- diagnostic 'Show' output is not an interchange encoding.+--+-- @+-- import qualified Cometa.Credential as Credential+-- import qualified Cometa.Error+-- import qualified Data.ByteString as ByteString+--+-- payment :: Either Cometa.Error.Error (Credential.Credential Credential.Payment)+-- payment = Credential.KeyCredential <$> Credential.keyHashFromBytes (ByteString.replicate 28 0)+-- @+module Cometa.Credential+ ( Payment,+ Stake,+ Guard,+ DRep,+ CommitteeHot,+ CommitteeCold,+ Genesis,+ GenesisDelegate,+ StakePool,+ KeyHash,+ keyHashFromBytes,+ keyHashBytes,+ ScriptHash,+ scriptHashFromBytes,+ scriptHashBytes,+ Credential (..),+ fromPublicKey,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import qualified Codec.CBOR.Write as W+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import Cometa.Error (Error (InvalidCredentialCbor, InvalidCredentialHashLength))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++-- | Role of a payment key or credential.+data Payment++-- | Role of a staking key or credential.+data Stake++-- | Role of a Dijkstra transaction guard credential.+data Guard++-- | Role of a delegated representative's voting credential.+data DRep++-- | Role of a constitutional committee member's voting credential.+data CommitteeHot++-- | Role of a constitutional committee member's authorization credential.+data CommitteeCold++-- | Role of a genesis key authorizing delegation or a legacy protocol update.+data Genesis++-- | Role of a delegate authorized by a genesis key.+data GenesisDelegate++-- | Role of a stake pool operator's key hash.+data StakePool++-- | A 28-byte key hash. Hashes in different roles are distinct types;+-- importing bytes assigns their role.+type role KeyHash nominal++newtype KeyHash purpose = KeyHash ByteString deriving (Eq, Ord, Show)++-- | A 28-byte script hash, usable in any credential role.+newtype ScriptHash = ScriptHash ByteString deriving (Eq, Ord, Show)++-- | A key or script controlling the role selected by the type parameter.+-- Ordering places key credentials before script credentials, then compares bytes.+type role Credential nominal++data Credential purpose+ = -- | Authority identified by a key hash in this role.+ KeyCredential !(KeyHash purpose)+ | -- | Authority identified by a script hash.+ ScriptCredential !ScriptHash+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import a key hash without hashing. Any length except 28 returns+-- 'InvalidCredentialHashLength' with the actual byte count.+keyHashFromBytes :: ByteString -> Either Error (KeyHash purpose)+keyHashFromBytes bytes = KeyHash <$> validateHash bytes++-- | Exact key-hash bytes.+keyHashBytes :: KeyHash purpose -> ByteString+keyHashBytes (KeyHash bytes) = bytes++-- | Import a script hash without hashing. Any length except 28 returns+-- 'InvalidCredentialHashLength' with the actual byte count.+scriptHashFromBytes :: ByteString -> Either Error ScriptHash+scriptHashFromBytes bytes = ScriptHash <$> validateHash bytes++-- | Exact script-hash bytes.+scriptHashBytes :: ScriptHash -> ByteString+scriptHashBytes (ScriptHash bytes) = bytes++validateHash :: ByteString -> Either Error ByteString+validateHash bytes+ | ByteString.length bytes == 28 = Right bytes+ | otherwise = Left (InvalidCredentialHashLength (ByteString.length bytes))++-- | Hash a verification key using BLAKE2b-224 and assign the requested role.+-- The caller selects the credential role through the result type. Native failures+-- return 'Cometa.Error.NativeError'; unexpected digest lengths return+-- 'Cometa.Error.NativeContractViolation'.+fromPublicKey :: PublicKey.PublicKey -> IO (Either Error (Credential purpose))+fromPublicKey publicKey = fmap (fmap (KeyCredential . KeyHash . Blake2b.toBytes)) (PublicKey.hash publicKey)++-- | Encode the credential kind and 28-byte hash as a two-element CBOR array.+-- This produces a fresh definite-length encoding; it does not hash the value.+encodeCbor :: Credential purpose -> ByteString+encodeCbor credential =+ W.toStrictByteString $+ E.encodeListLen 2 <> case credential of+ KeyCredential hash -> E.encodeWord 0 <> E.encodeBytes (keyHashBytes hash)+ ScriptCredential hash -> E.encodeWord 1 <> E.encodeBytes (scriptHashBytes hash)++-- | Decode exactly one credential array, checking its kind and hash length.+-- Definite and indefinite arrays and byte strings are accepted. Trailing data+-- and other shapes return 'InvalidCredentialCbor'; invalid hash lengths return+-- 'InvalidCredentialHashLength'. The result type selects the credential role.+decodeCbor :: ByteString -> Either Error (Credential purpose)+decodeCbor bytes = case R.deserialiseFromBytes T.decodeTerm (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidCredentialCbor (Text.pack (show failure)))+ Right (rest, term)+ | not (Lazy.null rest) -> Left (InvalidCredentialCbor "Trailing credential CBOR")+ | otherwise -> case term of+ T.TList values -> decodeFields values+ T.TListI values -> decodeFields values+ _ -> Left (InvalidCredentialCbor "Expected credential array")+ where+ decodeFields [T.TInt kind, hash] = case hash of+ T.TBytes value -> construct kind value+ T.TBytesI value -> construct kind (Lazy.toStrict value)+ _ -> Left (InvalidCredentialCbor "Expected credential hash bytes")+ decodeFields _ = Left (InvalidCredentialCbor "Expected credential kind and hash")+ construct 0 value = KeyCredential <$> keyHashFromBytes value+ construct 1 value = ScriptCredential <$> scriptHashFromBytes value+ construct _ _ = Left (InvalidCredentialCbor "Unknown credential kind")
@@ -0,0 +1,63 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Derive Cardano Ed25519-BIP32 public keys from BIP39 entropy and validated+-- wallet paths. Passwords are raw bytes, without text normalization. These+-- operations accept entropy, not a mnemonic sentence or a 64-byte BIP39 seed.+--+-- @+-- import qualified Cometa.Crypto.Bip32 as Bip32+-- import qualified Cometa.Crypto.DerivationPath as Path+--+-- firstAccount password entropy =+-- Bip32.deriveAccountPublicKey password entropy (Path.standardAccountPath minBound)+-- @+module Cometa.Crypto.Bip32+ ( deriveAccountPublicKey,+ derivePublicKey,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PrivateKey as PrivateKey+import Cometa.Crypto.Bip32.PublicKey (PublicKey)+import Cometa.Crypto.DerivationPath (AccountPath, DerivationPath)+import qualified Cometa.Crypto.DerivationPath as Path+import Cometa.Error (Error)+import Data.ByteString (ByteString)+import Data.Word (Word32)++-- DEFINITIONS ----------------------------------------------------------------++-- | Derive an extended account public key from password bytes, BIP39 entropy+-- bytes and an account path, respectively. Entropy must contain 16, 20, 24, 28+-- or 32 bytes; other lengths return @InvalidBip39EntropyLength@. Passwords may+-- be empty or contain NUL bytes. Native failures return @NativeError@. The result+-- includes the chain code and supports public derivation of role/index suffixes.+deriveAccountPublicKey :: ByteString -> ByteString -> AccountPath -> IO (Either Error PublicKey)+deriveAccountPublicKey password entropy path = deriveIndices password entropy (Path.accountIndices path)++-- | Derive an extended public key from password bytes, BIP39 entropy bytes and+-- a five-component wallet path, respectively. Entropy and passwords follow+-- 'deriveAccountPublicKey'; native failures return @NativeError@. The result+-- includes the chain code and remains usable after this operation returns.+derivePublicKey :: ByteString -> ByteString -> DerivationPath -> IO (Either Error PublicKey)+derivePublicKey password entropy path = deriveIndices password entropy (Path.toIndices path)++deriveIndices :: ByteString -> ByteString -> [Word32] -> IO (Either Error PublicKey)+deriveIndices password entropy indices =+ PrivateKey.withEntropy password entropy $ \root ->+ PrivateKey.withDerived root indices PrivateKey.publicKey
@@ -0,0 +1,178 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Scoped Cardano Ed25519-BIP32 private keys. A key contains a 64-byte expanded+-- Ed25519 secret and a 32-byte chain code. It has no 'Show' or equality instance.+-- Handles reject operations after scope exit or explicit 'close'; escaped handles+-- do not extend usable lifetime. Exceptions and cancellation propagate after cleanup.+-- Closing cannot erase application inputs or explicitly exported copies.+--+-- @+-- import qualified Cometa.Crypto.Bip32.PrivateKey as PrivateKey+--+-- -- bytes must contain a 96-byte application key.+-- derivePublic bytes = PrivateKey.withKey bytes $ \root ->+-- PrivateKey.withDerived root [PrivateKey.harden 1852, PrivateKey.harden 1815,+-- PrivateKey.harden 0, 0, 0] PrivateKey.publicKey+-- @+module Cometa.Crypto.Bip32.PrivateKey+ ( PrivateKey,++ -- * Scoped acquisition+ withKey,+ withKeyHex,+ withEntropy,+ withClone,+ withDerived,+ withSigningKey,+ close,++ -- * Derivation indices+ harden,++ -- * Inspection+ byteLength,+ hexLength,+ publicKey,++ -- * Explicit secret export+ exportBytes,+ exportHex,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PublicKey as PublicKey+import Cometa.Crypto.Ed25519.SigningKey (SigningKey)+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Bip32PrivateKey as Internal+import qualified Cometa.Internal.Ed25519SigningKey as Signing+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.Hex as Hex+import Control.Monad (join)+import Data.Bits ((.|.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word32)++-- TYPES ----------------------------------------------------------------------++-- | Opaque scoped 96-byte secret. Independent derived keys and clones may outlive+-- the source's usable lifetime only within their own active scopes.+newtype PrivateKey = PrivateKey Internal.Key++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 96 bytes and run the continuation. Only encoded length is+-- checked; invalid scalars may fail later operations. Wrong lengths return+-- 'InvalidBip32PrivateKeyLength' without invoking the continuation. Acquisition+-- and callback failures share one 'Either'; callback exceptions propagate.+withKey :: ByteString -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)+withKey bytes action = flatten <$> Internal.withBytesKey bytes (action . PrivateKey)++-- | Import exactly 192 ASCII hexadecimal digits, accepting either case without+-- whitespace or prefix. Empty/malformed text returns 'InvalidHex'; valid hex of+-- another length returns 'InvalidBip32PrivateKeyLength'. Input text remains in+-- application memory after closure. Cleanup matches 'withKey'.+withKeyHex :: Text -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)+withKeyHex text action = flatten <$> Internal.withHexKey text (action . PrivateKey)++-- | Derive a root from raw password bytes and BIP39 entropy bytes, respectively.+-- Entropy must contain 16, 20, 24, 28 or 32 bytes; other lengths return+-- 'InvalidBip39EntropyLength'. Password may be empty and may contain NUL bytes.+-- This uses Cardano's PBKDF2-HMAC-SHA512 with 4096 iterations and 96 output bytes,+-- followed by scalar clamping. No text normalization is performed. This accepts+-- entropy, not a mnemonic sentence or a 64-byte BIP39 seed. Inputs remain in+-- application memory; failures and cleanup match 'withKey'.+withEntropy :: ByteString -> ByteString -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)+withEntropy password entropy action+ | ByteString.length entropy `notElem` [16, 20, 24, 28, 32] = pure (Left (InvalidBip39EntropyLength (ByteString.length entropy)))+ | otherwise = flatten <$> Internal.withEntropy password entropy (action . PrivateKey)++-- | Run the continuation with an independent copy. Closing either key does+-- not affect the other; the copy closes on every exit. Closed sources return+-- 'Bip32PrivateKeyClosed'.+withClone :: PrivateKey -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)+withClone (PrivateKey key) action = flatten <$> Internal.withClone key (action . PrivateKey)++-- | Derive indices in order into an independent scope. All 'Word32' values are+-- accepted: @0..2^31-1@ are soft and @2^31..2^32-1@ are hardened. Use 'harden' to+-- set the high bit. An empty path makes an independent clone. The source remains+-- unchanged. Closed sources return 'Bip32PrivateKeyClosed'; operation failures+-- return 'NativeError'. The derived key closes before callback exceptions propagate.+withDerived :: PrivateKey -> [Word32] -> (PrivateKey -> IO (Either Error value)) -> IO (Either Error value)+withDerived (PrivateKey key) path action = flatten <$> Internal.withDerived key path (action . PrivateKey)++-- | Run the continuation with an independent extended Ed25519 signing key,+-- discarding the chain code. Closing the source does not close the signing key.+-- The signing key closes on every exit and rejects escaped uses. Closed sources+-- return 'Bip32PrivateKeyClosed'; failures return 'NativeError'.+withSigningKey :: PrivateKey -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withSigningKey (PrivateKey key) action = flatten <$> Internal.withSigningKey key (action . Signing.SigningKey)++-- | Set the high bit of an encoded index. This is idempotent: an already hardened+-- index is unchanged. For example, @harden 1852 == 2147485500@.+harden :: Word32 -> Word32+harden index = index .|. 0x80000000++-- | Close this handle, waiting for active operations. Repeated closure is harmless.+-- Scope exit also closes it; no later operation can use this handle.+close :: PrivateKey -> IO ()+close (PrivateKey key) = Internal.close key++-- | Secret byte count, always 96. Closed handles return+-- 'Bip32PrivateKeyClosed'.+byteLength :: PrivateKey -> IO (Either Error Int)+byteLength (PrivateKey key) = mapFailure <$> Internal.byteLength key++-- | Hexadecimal digit count, always 192, excluding a terminator. Closed handles+-- return 'Bip32PrivateKeyClosed'.+hexLength :: PrivateKey -> IO (Either Error Int)+hexLength key = fmap (* 2) <$> byteLength key++-- | Derive an immutable 64-byte public key and chain code, usable after this+-- secret closes. A closed handle returns 'Bip32PrivateKeyClosed'; unusable scalar+-- or other operation failures return 'NativeError' without secret diagnostics.+publicKey :: PrivateKey -> IO (Either Error PublicKey.PublicKey)+publicKey (PrivateKey key) = do+ result <- Internal.publicKeyBytes key+ pure (mapFailure result >>= PublicKey.fromBytes)++-- | Explicitly copy all 96 secret bytes into a Haskell ByteString. The result can+-- outlive this scope; closing cannot erase it or control subsequent application+-- copies. A closed handle returns 'Bip32PrivateKeyClosed'.+exportBytes :: PrivateKey -> IO (Either Error ByteString)+exportBytes (PrivateKey key) = mapFailure <$> Internal.exportBytes key++-- | Explicitly export 192 lowercase ASCII hex digits without prefix. The text+-- has application-managed lifetime and is not erased on closure. A closed handle+-- returns 'Bip32PrivateKeyClosed'.+exportHex :: PrivateKey -> IO (Either Error Text)+exportHex key = fmap Hex.encodeHex <$> exportBytes key++flatten :: Either Internal.Failure (Either Error value) -> Either Error value+flatten = join . mapFailure++mapFailure :: Either Internal.Failure value -> Either Error value+mapFailure = either (Left . publicFailure) Right++publicFailure :: Internal.Failure -> Error+publicFailure failure = case failure of+ Internal.Closed -> Bip32PrivateKeyClosed+ Internal.InvalidLength _ actual -> InvalidBip32PrivateKeyLength actual+ Internal.InvalidHex -> InvalidHex+ Internal.NativeFailure failureValue -> fromNativeFailure failureValue
@@ -0,0 +1,135 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Cardano Ed25519-BIP32 public keys: a 32-byte verification key followed by a+-- 32-byte chain code. These are not secp256k1 Bitcoin BIP32 keys. Import validates+-- length only; an invalid curve point can fail later derivation.+--+-- @+-- import qualified Cometa.Crypto.Bip32.PublicKey as PublicKey+--+-- roundTrip key = PublicKey.fromBytes (PublicKey.toBytes key) == Right key+-- @+module Cometa.Crypto.Bip32.PublicKey+ ( PublicKey,++ -- * Import and serialization+ fromBytes,+ fromHex,+ toBytes,+ toHex,+ byteLength,+ hexLength,++ -- * Derivation and conversion+ derive,+ toEd25519,+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as Ed25519+import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Bip32 as Native+import qualified Cometa.Internal.FFI.Native as Status+import Cometa.Internal.Failure (NativeFailure (..))+import qualified Cometa.Internal.Hex as Hex+import Cometa.Internal.Ownership (copyStaticText)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Data.Word (Word32)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (withArrayLen)+import Foreign.Ptr (castPtr)++-- TYPES ----------------------------------------------------------------------++-- | Immutable 64-byte public key and chain code. Equality compares exact bytes;+-- ordering is lexicographic. 'Show' is diagnostic; 'toHex' is stable serialization.+data PublicKey = PublicKey !Ed25519.PublicKey !ByteString deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 64 bytes; other lengths return 'InvalidBip32PublicKeyLength'.+-- Curve-point validity is not checked.+fromBytes :: ByteString -> Either Error PublicKey+fromBytes bytes+ | ByteString.length bytes /= 64 = Left (InvalidBip32PublicKeyLength (ByteString.length bytes))+ | otherwise = do+ key <- Ed25519.fromBytes (ByteString.take 32 bytes)+ pure (PublicKey key (ByteString.drop 32 bytes))++-- | Import 128 ASCII hex digits in either case, without prefix or whitespace.+-- Empty or malformed text returns 'InvalidHex'; a well-formed wrong length returns+-- 'InvalidBip32PublicKeyLength'.+fromHex :: Text -> Either Error PublicKey+fromHex text = do+ bytes <- maybe (Left InvalidHex) Right (Hex.decodeHex text)+ if ByteString.null bytes then Left InvalidHex else fromBytes bytes++-- | Retrieve all 64 bytes, including the chain code.+toBytes :: PublicKey -> ByteString+toBytes (PublicKey key chainCode) = Ed25519.toBytes key <> chainCode++-- | Render 128 lowercase ASCII hexadecimal digits without prefix or whitespace.+toHex :: PublicKey -> Text+toHex = Hex.encodeHex . toBytes++-- | Encoded length, always 64 bytes.+byteLength :: PublicKey -> Int+byteLength _ = 64++-- | Hexadecimal digit count, always 128, excluding a terminator.+hexLength :: PublicKey -> Int+hexLength key = 2 * byteLength key++-- | Derive a path in order. Each encoded index must be in @0..2^31-1@;+-- any high-bit (hardened) index returns 'HardenedPublicDerivation' before native+-- work. An empty path returns the original value. Native derivation failures+-- return 'NativeError'. The source is unchanged.+derive :: PublicKey -> [Word32] -> IO (Either Error PublicKey)+derive key path+ | Just index <- firstHardened path = pure (Left (HardenedPublicDerivation index))+ | null path = pure (Right key)+ | otherwise = ByteString.useAsCString (toBytes key) $ \bytes ->+ withArrayLen path $ \size indices -> allocaBytes 64 $ \output -> do+ code <- Native.cDerivePublic (castPtr bytes) indices (fromIntegral size) output+ if code == Status.success+ then fromBytes <$> ByteString.packCStringLen (castPtr output, 64)+ else do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (fromNativeFailure (NativeFailure "bip32.publicKey.derive" (toInteger code) message)))+ where+ firstHardened [] = Nothing+ firstHardened (index : rest)+ | index >= 0x80000000 = Just index+ | otherwise = firstHardened rest++-- | Discard the chain code and return the first 32 bytes as an Ed25519 public+-- key. This does not validate curve membership or identity.+toEd25519 :: PublicKey -> Ed25519.PublicKey+toEd25519 (PublicKey key _) = key++-- | Compute BLAKE2b-224 over all 64 bytes, including the chain code, matching+-- the BIP32 public-key hash operation. For a payment/stake verification-key digest,+-- convert with 'toEd25519' and use 'Ed25519.hash' instead. Failures return 'NativeError'.+hash :: PublicKey -> IO (Either Error Blake2b.Blake2bHash)+hash = Blake2b.compute 28 . toBytes
@@ -0,0 +1,102 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | English BIP39 recovery phrases with validated word counts and checksums.+--+-- Mnemonics contain wallet secrets. They have no 'Show' or equality instance.+-- Import and export create ordinary Haskell text/byte values whose lifetimes+-- are managed by the caller; this API does not guarantee their erasure. Never+-- log exported phrases or use deterministic examples for real wallets.+-- Pure evaluation may share secret values and extend their retention; it does+-- not promise the timing or number of conversions.+--+-- @+-- import qualified Cometa.Crypto.Bip39 as Bip39+-- import qualified Data.ByteString as ByteString+--+-- main :: IO ()+-- main =+-- case Bip39.fromEntropy (ByteString.replicate 16 0) of -- test only+-- Left err -> print err+-- Right mnemonic -> print (Bip39.wordCount mnemonic)+-- @+module Cometa.Crypto.Bip39+ ( Mnemonic,++ -- * Construction+ fromEntropy,+ fromText,+ fromWords,++ -- * Inspection+ wordCount,++ -- * Explicit secret export+ exportText,+ exportEntropy,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.Bip39Pure (Mnemonic)+import qualified Cometa.Internal.Bip39Pure as Internal+import Data.ByteString (ByteString)+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Convert supplied entropy into a phrase. Exactly 16, 20, 24, 28 or 32 bytes+-- are accepted; other sizes return 'InvalidBip39EntropyLength'. This operation+-- does not generate randomness. The caller must supply securely generated+-- entropy for a real wallet. Native failures return 'NativeError'; a violated+-- result invariant returns 'NativeContractViolation'.+fromEntropy :: ByteString -> Either Error Mnemonic+fromEntropy = Internal.fromEntropy++-- | Parse a phrase, splitting on Unicode whitespace and discarding leading and+-- trailing whitespace. Words are case sensitive: only lowercase ASCII English+-- BIP39 words are accepted, without spelling correction or normalization.+-- Returns 'InvalidBip39WordCount', 'InvalidBip39Word' (one-based position),+-- 'UnknownBip39Word', or 'InvalidBip39Checksum'. Error values never include the+-- supplied words. Unexpected native failures return 'NativeError'; a violated+-- result invariant returns 'NativeContractViolation'.+fromText :: Text -> Either Error Mnemonic+fromText = Internal.fromText++-- | Validate individual words and their checksum. Each list element must be+-- one lowercase ASCII word; embedded whitespace, NUL, upper case and non-ASCII+-- characters return 'InvalidBip39Word'. Failures match 'fromText'.+fromWords :: [Text] -> Either Error Mnemonic+fromWords = Internal.fromWords++-- | Number of words in the validated phrase.+wordCount :: Mnemonic -> Int+wordCount = Internal.wordCount++-- | Export the secret phrase as lowercase words separated by single ASCII+-- spaces. The returned text is ordinary caller-managed secret material.+exportText :: Mnemonic -> Text+exportText = Internal.exportText++-- | Export the secret entropy bytes (16, 20, 24, 28 or 32 bytes). This is the+-- entropy accepted by @Cometa.Crypto.Bip32.PrivateKey.withEntropy@,+-- not the 64-byte seed produced by BIP39's separate passphrase KDF.+-- The returned bytes are ordinary caller-managed secret material. Native+-- failures return 'NativeError'; a violated result invariant returns+-- 'NativeContractViolation'.+exportEntropy :: Mnemonic -> Either Error ByteString+exportEntropy = Internal.exportEntropy
@@ -0,0 +1,160 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | BLAKE2b digests as immutable byte sequences. This general digest type does+-- not distinguish payment, stake, or script hashes.+--+-- @+-- import qualified Cometa.Crypto.Blake2b as Blake2b+-- import qualified Data.ByteString.Char8 as ByteString+--+-- main :: IO ()+-- main = do+-- result <- Blake2b.compute 32 (ByteString.pack "abc")+-- print (Blake2b.toHex <$> result)+-- @+module Cometa.Crypto.Blake2b+ ( Blake2bHash,++ -- * Hashing+ compute,++ -- * Importing digests+ fromBytes,+ fromHex,++ -- * Inspection+ toBytes,+ toHex,++ -- * CBOR+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import qualified Codec.CBOR.Write as W+import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Native as Native+import Cometa.Internal.Ownership (copyHashResult)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Char (isDigit)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word8)+import Foreign.Ptr (castPtr)++-- TYPES ----------------------------------------------------------------------++-- | A nonempty digest byte sequence. Equality compares bytes; ordering is+-- lexicographic byte ordering.+-- 'Show' is diagnostic; use 'toHex' for a stable textual encoding.+newtype Blake2bHash = Blake2bHash ByteString+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Compute an unkeyed digest with an output length of 16 through 64 bytes.+-- Invalid output lengths return 'InvalidHashLength'. Empty messages are currently+-- unsupported and return 'NativeError' with code @OutOfBoundsMemoryRead@.+-- Other cardano-c failures also return 'NativeError'.+compute ::+ -- | Digest length in bytes, from 16 through 64 inclusive.+ Int ->+ -- | Nonempty message to hash.+ ByteString ->+ -- | Digest with the requested length, or a validation or operation failure.+ IO (Either Error Blake2bHash)+compute hashLength bytes+ | hashLength < 16 || hashLength > 64 = pure (Left (InvalidHashLength hashLength))+ | otherwise =+ ByteString.useAsCStringLen bytes $ \(input, size) ->+ either (Left . fromNativeFailure) (Right . Blake2bHash)+ <$> copyHashResult "blake2b.compute" (Native.cCompute (castPtr input) (fromIntegral size) (fromIntegral hashLength))++-- | Import digest bytes without hashing them. Any nonempty length is accepted;+-- this operation does not assert a particular digest role or algorithm variant.+-- Empty input returns 'EmptyHash'.+fromBytes :: ByteString -> Either Error Blake2bHash+fromBytes bytes+ | ByteString.null bytes = Left EmptyHash+ | otherwise = Right (Blake2bHash bytes)++-- | Import nonempty, even-length ASCII hexadecimal text, accepting both cases.+-- Malformed text returns 'InvalidHex'. No whitespace or prefix is accepted.+fromHex :: Text -> Either Error Blake2bHash+fromHex text =+ case decodeHex (Text.unpack text) of+ Nothing -> Left InvalidHex+ Just [] -> Left InvalidHex+ Just bytes -> fromBytes (ByteString.pack bytes)++-- | Observe the immutable digest bytes.+toBytes :: Blake2bHash -> ByteString+toBytes (Blake2bHash bytes) = bytes++-- | Encode the digest as lowercase ASCII hex, without a prefix or whitespace.+toHex :: Blake2bHash -> Text+toHex = Text.pack . concatMap encodeByte . ByteString.unpack . toBytes+ where+ encodeByte byte = [digit (byte `div` 16), digit (byte `mod` 16)]+ digit value+ | value < 10 = toEnum (fromIntegral value + fromEnum '0')+ | otherwise = toEnum (fromIntegral value - 10 + fromEnum 'a')++-- | Total hexadecimal decoder: no unchecked indexing or partial digit conversion.+decodeHex :: String -> Maybe [Word8]+decodeHex [] = Just []+decodeHex (high : low : rest) = do+ highValue <- hexDigit high+ lowValue <- hexDigit low+ remaining <- decodeHex rest+ pure ((highValue * 16 + lowValue) : remaining)+decodeHex [_] = Nothing++hexDigit :: Char -> Maybe Word8+hexDigit character+ | isDigit character = Just (offset '0')+ | character >= 'a' && character <= 'f' = Just (10 + offset 'a')+ | character >= 'A' && character <= 'F' = Just (10 + offset 'A')+ | otherwise = Nothing+ where+ offset start = fromIntegral (fromEnum character - fromEnum start)++-- | Encode the digest as one definite-length CBOR byte string.+encodeCbor :: Blake2bHash -> ByteString+encodeCbor = W.toStrictByteString . E.encodeBytes . toBytes++-- | Import exactly one nonempty CBOR byte string without hashing it. Definite+-- and indefinite byte strings are accepted; invalid CBOR, other types and+-- trailing data return 'InvalidHashCbor'. Empty bytes return 'EmptyHash'.+decodeCbor :: ByteString -> Either Error Blake2bHash+decodeCbor bytes = case R.deserialiseFromBytes T.decodeTerm (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidHashCbor (Text.pack (show failure)))+ Right (rest, term)+ | not (Lazy.null rest) -> Left (InvalidHashCbor "Trailing digest CBOR")+ | otherwise -> case term of+ T.TBytes value -> fromBytes value+ T.TBytesI value -> fromBytes (Lazy.toStrict value)+ _ -> Left (InvalidHashCbor "Expected digest byte string")
@@ -0,0 +1,194 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Validated five-level wallet paths: @m / purpose' / coin_type' / account' /+-- role / index@. Components are unencoded numbers; the first three become+-- hardened when converted to BIP32 indices. Custom purposes, coins and roles+-- are supported within the same bounds as standard paths.+--+-- @+-- import qualified Cometa.Crypto.DerivationPath as Path+--+-- firstAccount :: Path.AccountPath+-- firstAccount = Path.standardAccountPath minBound+-- @+module Cometa.Crypto.DerivationPath+ ( -- * Components+ Index,+ mkIndex,+ indexValue,++ -- * Account paths+ AccountPath,+ accountPath,+ purpose,+ coinType,+ account,+ accountIndices,++ -- * Key paths+ DerivationPath,+ derivationPath,+ accountPrefix,+ role,+ index,+ toIndices,+ relativeIndices,++ -- * Cardano wallet components+ cardanoCoinType,+ standardPurpose,+ multisigPurpose,+ externalRole,+ internalRole,+ stakingRole,+ drepRole,+ committeeColdRole,+ committeeHotRole,+ standardAccountPath,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (InvalidDerivationIndex))+import Data.Bits ((.|.))+import Data.Word (Word32)++-- TYPES ----------------------------------------------------------------------++-- | An unencoded component in @0..2147483647@. Equality and ordering compare+-- the component number; 'Show' is diagnostic. 'minBound' is zero and 'maxBound'+-- is 2147483647.+newtype Index = Index Word32 deriving (Eq, Ord, Show)++instance Bounded Index where+ minBound = Index 0+ maxBound = Index 2147483647++-- | Three unencoded components in purpose, coin type, account order.+-- Equality and ordering compare components in that order; 'Show' is diagnostic.+data AccountPath = AccountPath !Index !Index !Index deriving (Eq, Ord, Show)++-- | An account prefix followed by an unhardened role and key index.+-- Equality and ordering compare all five components in derivation order;+-- 'Show' is diagnostic.+data DerivationPath = DerivationPath !AccountPath !Index !Index deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate an unencoded component. Negative values and values above+-- @2147483647@ return 'InvalidDerivationIndex', retaining the exact input.+mkIndex :: Integer -> Either Error Index+mkIndex value+ | value < 0 || value > 2147483647 = Left (InvalidDerivationIndex value)+ | otherwise = Right (Index (fromInteger value))++-- | The unencoded component number, without the hardening bit.+indexValue :: Index -> Word32+indexValue (Index value) = value++-- | Construct an account prefix from purpose, coin type and account number.+-- All three components will be hardened by 'accountIndices'.+accountPath :: Index -> Index -> Index -> AccountPath+accountPath = AccountPath++-- | Unencoded purpose number, for example 1852 or 1854.+purpose :: AccountPath -> Index+purpose (AccountPath value _ _) = value++-- | Unencoded coin type, for example 1815 for Cardano.+coinType :: AccountPath -> Index+coinType (AccountPath _ value _) = value++-- | Unencoded account number, numbered from zero.+account :: AccountPath -> Index+account (AccountPath _ _ value) = value++-- | Three encoded hardened indices in derivation order, suitable for private+-- BIP32 derivation from a root key. Each has its high bit set.+accountIndices :: AccountPath -> [Word32]+accountIndices path = map ((.|. 0x80000000) . indexValue) [purpose path, coinType path, account path]++-- | Extend an account prefix with an unhardened role and key index, in that order.+derivationPath :: AccountPath -> Index -> Index -> DerivationPath+derivationPath = DerivationPath++-- | The three-component account prefix.+accountPrefix :: DerivationPath -> AccountPath+accountPrefix (DerivationPath value _ _) = value++-- | Unhardened role number. Standard roles are named in this module.+role :: DerivationPath -> Index+role (DerivationPath _ value _) = value++-- | Unhardened key index, numbered from zero.+index :: DerivationPath -> Index+index (DerivationPath _ _ value) = value++-- | Five encoded indices in derivation order, suitable for private BIP32+-- derivation from the root. Only the first three indices are hardened.+toIndices :: DerivationPath -> [Word32]+toIndices path = accountIndices (accountPrefix path) ++ relativeIndices path++-- | The two unhardened indices, role then key index, relative to an already+-- derived account key. Suitable for private or public BIP32 derivation.+relativeIndices :: DerivationPath -> [Word32]+relativeIndices path = map indexValue [role path, index path]++-- Values audited against key_handlers/cip_1852_constants.h at native revision+-- 7811fe94dad90f30478ed4b61d96677f188abaa8; native-oracle tests verify agreement.++-- | Cardano coin type.+cardanoCoinType :: Index+cardanoCoinType = Index 1815++-- | Standard wallet purpose.+standardPurpose :: Index+standardPurpose = Index 1852++-- | CIP-1854 multisignature wallet purpose.+multisigPurpose :: Index+multisigPurpose = Index 1854++-- | External payment chain role.+externalRole :: Index+externalRole = Index 0++-- | Internal change chain role.+internalRole :: Index+internalRole = Index 1++-- | Staking key role (CIP-0011).+stakingRole :: Index+stakingRole = Index 2++-- | Delegated representative key role (CIP-0105).+drepRole :: Index+drepRole = Index 3++-- | Constitutional committee cold key role (CIP-0105).+committeeColdRole :: Index+committeeColdRole = Index 4++-- | Constitutional committee hot key role (CIP-0105).+committeeHotRole :: Index+committeeHotRole = Index 5++-- | Standard Cardano account prefix for the supplied unencoded account number.+-- Uses purpose 1852 and coin type 1815. For multisignature or custom purposes,+-- use 'accountPath' with the desired components.+standardAccountPath :: Index -> AccountPath+standardAccountPath = accountPath standardPurpose cardanoCoinType
@@ -0,0 +1,134 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Ed25519 public keys as immutable 32-byte values. Import checks encoded+-- length; it does not establish that a key belongs to a particular person or+-- that a signature verifies. Use 'verify' to check a message and signature.+--+-- @+-- import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+--+-- roundTrip :: PublicKey.PublicKey -> Bool+-- roundTrip value = PublicKey.fromBytes (PublicKey.toBytes value) == Right value+-- @+module Cometa.Crypto.Ed25519.PublicKey+ ( PublicKey,++ -- * Import+ fromBytes,+ fromHex,++ -- * Inspection+ toBytes,+ toHex,+ byteLength,+ hexLength,++ -- * Verification and hashing+ verify,+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Crypto.Ed25519.Signature (Signature)+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Ed25519Values as Native+import qualified Cometa.Internal.FFI.Native as Status+import Cometa.Internal.Failure (NativeFailure (..))+import qualified Cometa.Internal.Hex as Hex+import Cometa.Internal.Ownership (copyHashResult, copyStaticText)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (castPtr)+import Foreign.Storable (peek)++-- TYPES ----------------------------------------------------------------------++-- | An immutable 32-byte Ed25519 public key. Equality compares bytes;+-- ordering is lexicographic byte ordering. 'Show' is diagnostic; use 'toHex'+-- for a stable textual representation.+newtype PublicKey = PublicKey ByteString+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 32 bytes. Other lengths return 'InvalidEd25519PublicKeyLength'.+-- Only length is validated; this constructor does not check curve-point validity.+fromBytes :: ByteString -> Either Error PublicKey+fromBytes bytes+ | ByteString.length bytes /= 32 = Left (InvalidEd25519PublicKeyLength (ByteString.length bytes))+ | otherwise = Right (PublicKey bytes)++-- | Import 64 ASCII hexadecimal digits, accepting either case. No whitespace+-- or prefix is accepted. Empty, odd-length or nonhexadecimal text returns+-- 'InvalidHex'; valid hex of another byte length returns 'InvalidEd25519PublicKeyLength'.+fromHex :: Text -> Either Error PublicKey+fromHex text = do+ bytes <- maybe (Left InvalidHex) Right (Hex.decodeHex text)+ if ByteString.null bytes then Left InvalidHex else fromBytes bytes++-- | Retrieve the exact encoded bytes.+toBytes :: PublicKey -> ByteString+toBytes (PublicKey bytes) = bytes++-- | Render lowercase ASCII hexadecimal digits without a prefix or whitespace.+toHex :: PublicKey -> Text+toHex = Hex.encodeHex . toBytes++-- | Encoded byte length, always 32.+byteLength :: PublicKey -> Int+byteLength = ByteString.length . toBytes++-- | Hexadecimal digit count, always 64. No terminator is included.+hexLength :: PublicKey -> Int+hexLength value = 2 * byteLength value++-- | Check an Ed25519 signature for the exact message bytes. Empty messages and+-- embedded NUL bytes are supported. 'Right' 'True' means verification succeeded;+-- 'Right' 'False' means it did not. Allocation or other operation failures return+-- 'NativeError'. This operation uses ordinary Ed25519 on the supplied message.+verify :: PublicKey -> ByteString -> Signature -> IO (Either Error Bool)+verify publicKey message signature =+ ByteString.useAsCStringLen (toBytes publicKey) $ \(keyBytes, keySize) ->+ ByteString.useAsCStringLen (Signature.toBytes signature) $ \(signatureBytes, signatureSize) ->+ ByteString.useAsCStringLen message $ \(messageBytes, messageSize) ->+ alloca $ \verified -> do+ code <- Native.cVerify (castPtr keyBytes) (fromIntegral keySize) (castPtr signatureBytes) (fromIntegral signatureSize) (castPtr messageBytes) (fromIntegral messageSize) verified+ if code == Status.success+ then Right . (/= 0) <$> peek verified+ else do+ diagnostic <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (fromNativeFailure (NativeFailure "ed25519.publicKey.verify" (toInteger code) diagnostic)))++-- | Compute the 28-byte BLAKE2b-224 digest of the encoded public key. The result+-- is a general digest, without a payment/stake role distinction. Operation+-- failures return 'NativeError'.+hash :: PublicKey -> IO (Either Error Blake2b.Blake2bHash)+hash publicKey =+ ByteString.useAsCStringLen (toBytes publicKey) $ \(input, size) -> do+ result <- copyHashResult "ed25519.publicKey.hash" (Native.cPublicKeyHash (castPtr input) (fromIntegral size))+ pure $ case result of+ Left failure -> Left (fromNativeFailure failure)+ Right bytes+ | ByteString.length bytes /= 28 -> Left (NativeContractViolation "ed25519.publicKey.hash")+ | otherwise -> Blake2b.fromBytes bytes
@@ -0,0 +1,87 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Ed25519 signatures as immutable 64-byte values. Import checks encoded+-- length, not whether a signature verifies against a particular key/message.+--+-- @+-- import qualified Cometa.Crypto.Ed25519.Signature as Signature+--+-- roundTrip :: Signature.Signature -> Bool+-- roundTrip value = Signature.fromBytes (Signature.toBytes value) == Right value+-- @+module Cometa.Crypto.Ed25519.Signature+ ( Signature,++ -- * Import+ fromBytes,+ fromHex,++ -- * Inspection+ toBytes,+ toHex,+ byteLength,+ hexLength,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | An immutable 64-byte Ed25519 signature. Equality compares bytes;+-- ordering is lexicographic byte ordering. 'Show' is diagnostic; use 'toHex'+-- for a stable textual representation.+newtype Signature = Signature ByteString+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 64 bytes. Other lengths return 'InvalidEd25519SignatureLength'.+-- No cryptographic verification is performed.+fromBytes :: ByteString -> Either Error Signature+fromBytes bytes+ | ByteString.length bytes /= 64 = Left (InvalidEd25519SignatureLength (ByteString.length bytes))+ | otherwise = Right (Signature bytes)++-- | Import 128 ASCII hexadecimal digits, accepting either case. No whitespace+-- or prefix is accepted. Empty, odd-length or nonhexadecimal text returns+-- 'InvalidHex'; valid hex of another byte length returns 'InvalidEd25519SignatureLength'.+fromHex :: Text -> Either Error Signature+fromHex text = do+ bytes <- maybe (Left InvalidHex) Right (Hex.decodeHex text)+ if ByteString.null bytes then Left InvalidHex else fromBytes bytes++-- | Retrieve the exact encoded bytes.+toBytes :: Signature -> ByteString+toBytes (Signature bytes) = bytes++-- | Render lowercase ASCII hexadecimal digits without a prefix or whitespace.+toHex :: Signature -> Text+toHex = Hex.encodeHex . toBytes++-- | Encoded byte length, always 64.+byteLength :: Signature -> Int+byteLength = ByteString.length . toBytes++-- | Hexadecimal digit count, always 128. No terminator is included.+hexLength :: Signature -> Int+hexLength value = 2 * byteLength value
@@ -0,0 +1,165 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Scoped Ed25519 signing keys. Normal keys contain a 32-byte seed; extended+-- keys contain a 64-byte expanded scalar and nonce prefix, rather than a seed/public-key+-- pair. Keys have no printable or equality representation.+--+-- The continuation receives a key valid until its scope exits. Keeping the+-- handle afterward is possible, but all subsequent operations return+-- 'SigningKeyClosed'. Scope exit and 'close' wait for ongoing operations.+-- Callback exceptions, including cancellation, propagate after cleanup.+--+-- Closing a key ends access through its handle. It does not erase the input+-- bytes or text supplied by the application, or any explicitly exported copies.+--+-- @+-- import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey+--+-- -- seed must contain exactly 32 bytes obtained from the application.+-- signMessage seed message =+-- SigningKey.withNormalKey seed $ \key -> SigningKey.sign key message+-- @+module Cometa.Crypto.Ed25519.SigningKey+ ( SigningKey,++ -- * Scoped import and copying+ withNormalKey,+ withExtendedKey,+ withNormalKeyHex,+ withExtendedKeyHex,+ withClone,+ close,++ -- * Inspection and signing+ byteLength,+ hexLength,+ publicKey,+ sign,++ -- * Explicit secret export+ exportBytes,+ exportHex,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Crypto.Ed25519.PublicKey (PublicKey)+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import Cometa.Crypto.Ed25519.Signature (Signature)+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import Cometa.Error (Error (..))+import Cometa.Internal.Ed25519SigningKey (SigningKey (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.Internal.SigningKey as Internal+import Control.Monad (join)+import Data.ByteString (ByteString)+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 32 seed bytes and run the continuation. Invalid length returns+-- 'InvalidEd25519SigningKeyLength' with expected then actual byte counts, without+-- invoking the continuation. Its expected failures are returned directly.+-- Imported bytes remain in application memory after the scoped key closes.+withNormalKey :: ByteString -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withNormalKey bytes action = flatten <$> Internal.withNormalKey bytes (action . SigningKey)++-- | Import exactly 64 expanded scalar and nonce-prefix bytes and run the continuation. This is+-- the Cardano extended format, not a normal seed followed by a public key.+-- Length is validated; an unusable scalar can fail later derivation or signing.+-- Failure and cleanup behavior matches 'withNormalKey'.+withExtendedKey :: ByteString -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withExtendedKey bytes action = flatten <$> Internal.withExtendedKey bytes (action . SigningKey)++-- | Import 64 ASCII hex digits representing a normal 32-byte seed. Both letter+-- cases are accepted; no prefix or whitespace is allowed. Malformed or empty+-- text returns 'InvalidHex'; well-formed wrong length returns+-- 'InvalidEd25519SigningKeyLength'. Closing the key does not erase the supplied text.+withNormalKeyHex :: Text -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withNormalKeyHex text action = flatten <$> Internal.withNormalKeyHex text (action . SigningKey)++-- | Import 128 ASCII hex digits representing an expanded 64-byte scalar and nonce-prefix key.+-- Validation and lifetime limitations match 'withNormalKeyHex'.+withExtendedKeyHex :: Text -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withExtendedKeyHex text action = flatten <$> Internal.withExtendedKeyHex text (action . SigningKey)++-- | Run a continuation with an independent secret copy. Closing the source does+-- not close the copy, and closing the copy does not close its source. The copy+-- closes on every exit. A closed source returns 'SigningKeyClosed'.+withClone :: SigningKey -> (SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withClone (SigningKey key) action = flatten <$> Internal.withClone key (action . SigningKey)++-- | Close the key; repeated calls have no effect. Wait for ongoing operations before returning;+-- no new operation can use the closed handle. Scope exit also closes it.+close :: SigningKey -> IO ()+close (SigningKey key) = Internal.close key++-- | Number of secret bytes: 32 for a normal seed, 64 for an extended key.+-- This reveals no secret contents. A closed handle returns 'SigningKeyClosed'.+byteLength :: SigningKey -> IO (Either Error Int)+byteLength (SigningKey key) = mapFailure <$> Internal.byteLength key++-- | Number of hexadecimal digits, excluding any terminator: 64 or 128. No secret+-- copy is created. A closed handle returns 'SigningKeyClosed'.+hexLength :: SigningKey -> IO (Either Error Int)+hexLength key = fmap (* 2) <$> byteLength key++-- | Derive an immutable public key which remains usable after this key closes.+-- A closed handle returns 'SigningKeyClosed'; derivation failures retain their+-- structured native status without including any secret input.+publicKey :: SigningKey -> IO (Either Error PublicKey)+publicKey (SigningKey key) = do+ result <- Internal.publicKeyBytes key+ pure (mapFailure result >>= PublicKey.fromBytes)++-- | Sign the exact message bytes. Empty messages are supported. The returned+-- signature remains usable after this key closes. This does not prehash or encode+-- a message on the caller's behalf: transaction signing requires the raw body+-- digest, rather than full transaction CBOR or its hexadecimal representation.+-- A closed handle returns 'SigningKeyClosed'; failures never include key bytes.+sign :: SigningKey -> ByteString -> IO (Either Error Signature)+sign (SigningKey key) message = do+ result <- Internal.signBytes key message+ pure (mapFailure result >>= Signature.fromBytes)++-- | Explicitly copy the secret into a new Haskell ByteString. The result can+-- outlive this key and its scope. Closing cannot erase that copy or control+-- copies made by the application; use this only when secret export is intended.+-- A closed handle returns 'SigningKeyClosed'.+exportBytes :: SigningKey -> IO (Either Error ByteString)+exportBytes (SigningKey key) = mapFailure <$> Internal.exportBytes key++-- | Explicitly export lowercase ASCII hexadecimal secret text without a prefix.+-- The exported text remains available after this key closes; closure does not erase it.+-- A closed handle returns 'SigningKeyClosed'.+exportHex :: SigningKey -> IO (Either Error Text)+exportHex key = fmap Hex.encodeHex <$> exportBytes key++-- | Keep acquisition failures flat with the continuation's expected failures.+flatten :: Either Internal.Failure (Either Error value) -> Either Error value+flatten result = join (mapFailure result)++mapFailure :: Either Internal.Failure value -> Either Error value+mapFailure = either (Left . publicFailure) Right++publicFailure :: Internal.Failure -> Error+publicFailure failure = case failure of+ Internal.Closed -> SigningKeyClosed+ Internal.InvalidLength expected actual -> InvalidEd25519SigningKeyLength expected actual+ Internal.InvalidHex -> InvalidHex+ Internal.NativeFailure failureValue -> fromNativeFailure failureValue
@@ -0,0 +1,65 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Password-encrypted storage using EMIP-003: PBKDF2-HMAC-SHA512 with+-- 19162 iterations and a 32-byte key, then ChaCha20-Poly1305 with empty AAD.+-- The encoded envelope is salt (32 bytes), nonce (12), tag (16), ciphertext.+-- Passwords and plaintext are raw bytes with no normalization. Plaintext and+-- passwords supplied by the caller, and exported plaintext, are not erased.+--+-- @+-- import qualified Cometa.Crypto.Emip3 as Emip3+-- store password bytes = Emip3.encrypt password bytes+-- load password envelope = Emip3.decryptBytes password envelope+-- @+module Cometa.Crypto.Emip3 (encrypt, decryptBytes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.PasswordCrypto as Internal+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString++-- DEFINITIONS ----------------------------------------------------------------++-- | Encrypt plaintext, including empty data, using a fresh random salt and+-- nonce. Password comes first and may be empty or contain NUL. Plaintext must+-- contain @0..min(maxBound - 60, 274877906880)@ bytes, where @maxBound :: Int@;+-- other lengths return 'InvalidEmip3PlaintextLength' before encryption.+-- Success is exactly 60 bytes longer than the plaintext. Random generation+-- and allocation occur in 'IO'. Other failures return 'NativeError'; allocation+-- exceptions propagate. Cancellation waits for the operation and cleanup.+encrypt :: ByteString -> ByteString -> IO (Either Error ByteString)+encrypt password plaintext+ | toInteger size > min (toInteger (maxBound :: Int) - 60) 274877906880 = pure (Left (InvalidEmip3PlaintextLength size))+ | otherwise = either (Left . fromNativeFailure) Right <$> Internal.encrypt password plaintext+ where+ size = ByteString.length plaintext++-- | Authenticate and explicitly export plaintext from an encoded envelope.+-- Password comes first and may be empty or contain NUL. Envelopes must contain+-- 60 through 274877906940 bytes; other lengths return+-- 'InvalidEmip3EnvelopeLength'. A 60-byte envelope authenticates empty plaintext.+-- A wrong password or modified envelope+-- returns 'NativeError' with the native generic failure code and never returns+-- plaintext. Allocation exceptions propagate. Cancellation waits for native+-- completion and cleanup. Returned plaintext has application-managed lifetime;+-- this function cannot erase it or subsequent copies.+decryptBytes :: ByteString -> ByteString -> IO (Either Error ByteString)+decryptBytes password envelope+ | ByteString.length envelope < 60 || toInteger (ByteString.length envelope) > 274877906940 = pure (Left (InvalidEmip3EnvelopeLength (ByteString.length envelope)))+ | otherwise = either (Left . fromNativeFailure) Right <$> Internal.decryptBytes password envelope
@@ -0,0 +1,51 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Password-based key derivation using PBKDF2-HMAC-SHA512. Inputs are raw bytes;+-- no text encoding or normalization is applied. This module deliberately exports+-- secret bytes: callers control their lifetime and must avoid logging them.+--+-- @+-- import qualified Cometa.Crypto.Pbkdf2 as Pbkdf2+-- -- Deterministic example data only; choose cost and salt for your application.+-- derive password salt = Pbkdf2.deriveBytes password salt 100000 32+-- @+module Cometa.Crypto.Pbkdf2 (deriveBytes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.Pbkdf2Pure as Internal+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString++-- DEFINITIONS ----------------------------------------------------------------++-- | Explicitly derive and export secret bytes from password, salt, iteration+-- count and output byte count, in that order. Password may be empty or contain+-- NUL; salt must be nonempty. Iterations must be @1..4294967295@. Output must be+-- @1..min(maxBound :: Int, 64 * (2^32 - 1))@ bytes, the PBKDF2 block limit.+-- Invalid inputs return 'EmptyPbkdf2Salt', 'InvalidPbkdf2Iterations' or+-- 'InvalidPbkdf2OutputLength' before derivation. Other failures return+-- 'NativeError'; allocation exceptions propagate. No default cost is chosen.+-- Large requests can require substantial memory and computation. Cancellation+-- waits for the ongoing derivation and cleanup. Input and returned Haskell+-- bytes are not erased by this operation.+deriveBytes :: ByteString -> ByteString -> Integer -> Integer -> Either Error ByteString+deriveBytes password salt iterations size+ | ByteString.null salt = Left EmptyPbkdf2Salt+ | iterations < 1 || iterations > 4294967295 = Left (InvalidPbkdf2Iterations iterations)+ | size < 1 || size > min (toInteger (maxBound :: Int)) (64 * (2 ^ (32 :: Int) - 1)) = Left (InvalidPbkdf2OutputLength size)+ | otherwise = Internal.deriveBytes password salt (fromInteger iterations) (fromInteger size)
@@ -0,0 +1,84 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Human-readable category labels for logs and error messages. Unlike 'Show',+-- these functions describe only the category and never include hashes, keys or+-- payloads. They use the English cardano-c diagnostic vocabulary, not CIP-116+-- JSON tags. Use the domain encoders for machine interchange.+module Cometa.Diagnostics (certificateKind, nativeScriptKind, vote, voterKind) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Certificate as Certificate+import qualified Cometa.Credential as Credential+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Script.Native as Native+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Certificate category, for example @"Certificate Type: Stake Registration"@.+-- Field contents and registration/deposit state do not affect the label.+certificateKind :: Certificate.Certificate -> Text+certificateKind value = case value of+ Certificate.StakeRegistration {} -> "Certificate Type: Stake Registration"+ Certificate.StakeDeregistration {} -> "Certificate Type: Stake Deregistration"+ Certificate.StakeDelegation {} -> "Certificate Type: Stake Delegation"+ Certificate.PoolRegistration {} -> "Certificate Type: Pool Registration"+ Certificate.PoolRetirement {} -> "Certificate Type: Pool Retirement"+ Certificate.GenesisKeyDelegation {} -> "Certificate Type: Genesis Key Delegation"+ Certificate.MoveInstantaneousRewards {} -> "Certificate Type: Move Instantaneous Rewards"+ Certificate.Registration {} -> "Certificate Type: Registration"+ Certificate.Unregistration {} -> "Certificate Type: Unregistration"+ Certificate.VoteDelegation {} -> "Certificate Type: Vote Delegation"+ Certificate.StakeVoteDelegation {} -> "Certificate Type: Stake Vote Delegation"+ Certificate.StakeRegistrationDelegation {} -> "Certificate Type: Stake Registration Delegation"+ Certificate.VoteRegistrationDelegation {} -> "Certificate Type: Vote Registration Delegation"+ Certificate.StakeVoteRegistrationDelegation {} -> "Certificate Type: Stake Vote Registration Delegation"+ Certificate.AuthorizeCommitteeHot {} -> "Certificate Type: Auth Committee Hot"+ Certificate.ResignCommitteeCold {} -> "Certificate Type: Resign Committee Cold"+ Certificate.RegisterDRep {} -> "Certificate Type: DRep Registration"+ Certificate.UnregisterDRep {} -> "Certificate Type: DRep Unregistration"+ Certificate.UpdateDRep {} -> "Certificate Type: Update DRep"++-- | Native script condition, for example @"Native Script Type: Require All Of"@.+-- Does not evaluate the script or expose any child condition or credential.+nativeScriptKind :: Native.NativeScript -> Text+nativeScriptKind value = case Native.view value of+ Native.RequireSignature {} -> "Native Script Type: Require Pubkey"+ Native.RequireAll {} -> "Native Script Type: Require All Of"+ Native.RequireAny {} -> "Native Script Type: Require Any Of"+ Native.RequireAtLeast {} -> "Native Script Type: Require N Of K"+ Native.InvalidBefore {} -> "Native Script Type: Invalid Before"+ Native.InvalidAfter {} -> "Native Script Type: Invalid After"+ Native.RequireGuard {} -> "Native Script Type: Require Guard"++-- | Voting choice as @"Vote: No"@, @"Vote: Yes"@ or @"Vote: Abstain"@.+vote :: Voting.Vote -> Text+vote value = case value of+ Voting.No -> "Vote: No"+ Voting.Yes -> "Vote: Yes"+ Voting.Abstain -> "Vote: Abstain"++-- | Voting authority kind, distinguishing committee and DRep key/script+-- credentials from stake pool keys. The credential hash is never included.+voterKind :: Voting.Voter -> Text+voterKind value = case value of+ Voting.CommitteeVoter (Credential.KeyCredential _) -> "Voter Type: Constitutional Committee Key Hash"+ Voting.CommitteeVoter (Credential.ScriptCredential _) -> "Voter Type: Constitutional Committee Script Hash"+ Voting.DRepVoter (Credential.KeyCredential _) -> "Voter Type: DRep Key Hash"+ Voting.DRepVoter (Credential.ScriptCredential _) -> "Voter Type: DRep Script Hash"+ Voting.StakePoolVoter _ -> "Voter Type: Stake Pool Key Hash"
@@ -0,0 +1,382 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | One CBOR item with its exact encoding preserved. Equality and ordering+-- compare encoded bytes, so different encodings of the same value can differ.+-- Construction checks that the native reader accepts exactly one complete item;+-- it does not enforce canonical encoding, schema rules, tag semantics, or UTF-8+-- validity of arbitrary nested text. 'decodeText' validates UTF-8 explicitly.+--+-- Scalar codecs and ordered collection codecs construct and inspect ordinary+-- Haskell values. Collection encoding preserves the exact bytes of each child.+--+-- @+-- import qualified Cometa.Encoding.Cbor as Cbor+--+-- main :: IO ()+-- main = do+-- result <- Cbor.encodeInteger 42+-- print (Cbor.toHex <$> result)+-- @+module Cometa.Encoding.Cbor+ ( Cbor,++ -- * Import and exact representation+ fromBytes,+ fromHex,+ toBytes,+ toHex,++ -- * Primitive values+ encodeInteger,+ decodeInteger,+ encodeByteString,+ decodeByteString,+ encodeText,+ decodeText,+ encodeBool,+ decodeBool,+ decodeDouble,+ decodeSimple,+ encodeUndefined,++ -- * Ordered collections+ encodeArray,+ decodeArray,+ encodeMap,+ decodeMap,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Cbor as Native+import qualified Cometa.Internal.FFI.Native as Status+import Cometa.Internal.Failure (NativeFailure (..))+import qualified Cometa.Internal.Hex as Hex+import Cometa.Internal.Ownership (copyStaticText, withOwnedOutput)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word8)+import Foreign.C.String (CString)+import Foreign.C.Types (CDouble (..), CInt, CSize)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | A complete, native-reader-accepted CBOR item. Encoded bytes are retained+-- without normalization. Equality is representation-sensitive; ordering is+-- lexicographic byte ordering. 'Show' is diagnostic, not an interchange format.+newtype Cbor = Cbor ByteString+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Accept exactly one complete item, preserving all input bytes. Empty input,+-- malformed structures and trailing bytes return 'NativeError'. This structural+-- check does not assert schema, tag semantics, canonicality, or nested UTF-8.+-- Allocation and decoding failures return 'NativeError'.+fromBytes :: ByteString -> IO (Either Error Cbor)+fromBytes bytes = withBytes bytes $ \input size ->+ fmap (const (Cbor bytes)) <$> runStatus "cbor.fromBytes" (Native.cValidate input size)++-- | Accept nonempty, even-length ASCII hexadecimal text in either case, with+-- no whitespace or prefix, then perform 'fromBytes' validation. Malformed hex+-- returns 'InvalidHex'. The resulting bytes retain their original CBOR form.+fromHex :: Text -> IO (Either Error Cbor)+fromHex text+ | Text.null text = pure (Left InvalidHex)+ | otherwise = maybe (pure (Left InvalidHex)) fromBytes (Hex.decodeHex text)++-- | Retrieve the exact encoded item bytes without normalization.+toBytes :: Cbor -> ByteString+toBytes (Cbor bytes) = bytes++-- | Encode the exact item bytes as lowercase ASCII hex, without a prefix.+toHex :: Cbor -> Text+toHex = Hex.encodeHex . toBytes++-- | Encode an untagged primitive integer using the shortest native encoding.+-- The supported inclusive range is @-2^64@ through @2^64 - 1@. Values outside+-- this range return 'InvalidCborInteger'; tagged bignums are not encoded here.+encodeInteger :: Integer -> IO (Either Error Cbor)+encodeInteger value+ | value < negate (2 ^ (64 :: Int)) || value >= 2 ^ (64 :: Int) = pure (Left (InvalidCborInteger value))+ | otherwise = encodeResult "cbor.encodeInteger" (Native.cEncodeInteger (flag (value < 0)) argument)+ where+ argument = fromInteger (if value < 0 then negate value - 1 else value)++-- | Decode an untagged primitive integer exactly, including the full unsigned+-- and negative 64-bit CBOR ranges. Tagged bignums and other types return+-- 'NativeError'. Nonminimal integer encodings are accepted without modification.+decodeInteger :: Cbor -> IO (Either Error Integer)+decodeInteger cbor = withBytes (toBytes cbor) $ \input size ->+ alloca $ \negative -> alloca $ \argument ->+ withDiagnostic $ \diagnostic capacity -> do+ code <- Native.cDecodeInteger input size negative argument diagnostic capacity+ statusResult "cbor.decodeInteger" code $ do+ sign <- peek negative+ magnitude <- toInteger <$> peek argument+ pure (if sign /= 0 then negate magnitude - 1 else magnitude)++-- | Encode bytes as a definite-length CBOR byte string. Empty bytes are valid.+encodeByteString :: ByteString -> IO (Either Error Cbor)+encodeByteString = encodeString "cbor.encodeByteString" False++-- | Decode a CBOR byte string, concatenating indefinite-length chunks in order.+-- Empty strings are valid. Other types return 'NativeError'.+decodeByteString :: Cbor -> IO (Either Error ByteString)+decodeByteString = decodeString "cbor.decodeByteString" False++-- | Encode Unicode text as one definite-length UTF-8 CBOR text string.+-- Empty text and embedded NUL characters are preserved.+encodeText :: Text -> IO (Either Error Cbor)+encodeText = encodeString "cbor.encodeText" True . Text.encodeUtf8++-- | Decode a CBOR text string and validate UTF-8. Each indefinite-length+-- chunk must independently contain valid UTF-8; multibyte sequences cannot span+-- chunk boundaries. Invalid UTF-8 returns 'InvalidCborUtf8'; structural or type+-- failures return 'NativeError'. Empty text and embedded NUL characters survive.+decodeText :: Cbor -> IO (Either Error Text)+decodeText cbor = case ByteString.uncons (toBytes cbor) of+ Just (127, body) -> case ByteString.unsnoc body of+ Just (interior, 255) -> do+ chunks <- readTextChunks interior+ case chunks of+ Left failure -> pure (Left failure)+ Right values -> decodeTextValues [] values+ _ -> pure (Left (NativeContractViolation "cbor.decodeText"))+ _ -> decodeTextValue cbor++-- | Encode a Boolean as its native CBOR simple value.+encodeBool :: Bool -> IO (Either Error Cbor)+encodeBool value = encodeResult "cbor.encodeBool" (Native.cEncodeBool (flag value))++-- | Decode an untagged Boolean. Null, undefined and other types return 'NativeError'.+decodeBool :: Cbor -> IO (Either Error Bool)+decodeBool cbor = withBytes (toBytes cbor) $ \input size -> alloca $ \output ->+ withDiagnostic $ \diagnostic capacity -> do+ code <- Native.cDecodeBool input size output diagnostic capacity+ statusResult "cbor.decodeBool" code ((/= 0) <$> peek output)++-- | Decode an untagged IEEE half-, single- or double-precision value as a+-- 'Double'. Signed zero, infinities and NaN are accepted. Integer items are not+-- coerced to floating point; other types return 'NativeError'. The original+-- encoding remains unchanged. NaN payload bits are not an interchange guarantee.+decodeDouble :: Cbor -> IO (Either Error Double)+decodeDouble cbor = withBytes (toBytes cbor) $ \input size -> alloca $ \output ->+ withDiagnostic $ \diagnostic capacity -> do+ code <- Native.cDecodeDouble input size output diagnostic capacity+ statusResult "cbor.decodeDouble" code ((\(CDouble value) -> value) <$> peek output)++-- | Decode the number of a simple value: false is 20, true is 21, null is 22+-- and undefined is 23. Unassigned byte values and nonminimal two-byte encodings+-- accepted by the reader are retained. Floating-point and other major types+-- return 'NativeError'. This does not interpret application-specific meanings.+decodeSimple :: Cbor -> IO (Either Error Word8)+decodeSimple cbor = withBytes (toBytes cbor) $ \input size -> alloca $ \output ->+ withDiagnostic $ \diagnostic capacity -> do+ code <- Native.cDecodeSimple input size output diagnostic capacity+ statusResult "cbor.decodeSimple" code (peek output)++-- | Encode CBOR undefined (@f7@), distinct from null, an absent field and false.+-- Use 'decodeSimple' to inspect its simple-value number, 23.+encodeUndefined :: IO (Either Error Cbor)+encodeUndefined = encodeResult "cbor.encodeUndefined" Native.cEncodeUndefined++-- | Encode an array in list order with a definite-length outer encoding.+-- Every child's bytes remain exact, including nonminimal or indefinite forms.+encodeArray :: [Cbor] -> IO (Either Error Cbor)+encodeArray items = encodeCollection "cbor.encodeArray" False (length items) items++-- | Decode a definite or indefinite array into its ordered encoded children.+-- Child bytes remain exact. Other types return 'NativeError'.+decodeArray :: Cbor -> IO (Either Error [Cbor])+decodeArray = decodeCollection "cbor.decodeArray" False++-- | Encode map entries in list order, preserving duplicate keys. The outer+-- map uses definite length; every encoded key and value remains byte-exact.+-- No sorting, key deduplication, or schema validation is performed.+encodeMap :: [(Cbor, Cbor)] -> IO (Either Error Cbor)+encodeMap entries = encodeCollection "cbor.encodeMap" True (length entries) (concatMap (\(key, value) -> [key, value]) entries)++-- | Decode a definite or indefinite map into ordered key/value pairs,+-- preserving duplicate keys and each child's exact encoding. Other types+-- return 'NativeError'. Missing values are structural decoding failures.+decodeMap :: Cbor -> IO (Either Error [(Cbor, Cbor)])+decodeMap cbor = do+ result <- decodeCollection "cbor.decodeMap" True cbor+ pure (result >>= pairEntries [])+ where+ pairEntries accumulated [] = Right (reverse accumulated)+ pairEntries accumulated (key : value : rest) = pairEntries ((key, value) : accumulated) rest+ pairEntries _ [_] = Left (NativeContractViolation "cbor.decodeMap")++-- | Validate chunks one at a time, stopping at the first failure. Only copied+-- Haskell values remain live while the final text is concatenated.+decodeTextValues :: [Text] -> [Cbor] -> IO (Either Error Text)+decodeTextValues accumulated [] = pure (Right (Text.concat (reverse accumulated)))+decodeTextValues accumulated (value : rest) = do+ result <- decodeTextValue value+ case result of+ Left failure -> pure (Left failure)+ Right text -> decodeTextValues (text : accumulated) rest++-- | Check UTF-8 after the native text buffer has been copied and released.+decodeTextValue :: Cbor -> IO (Either Error Text)+decodeTextValue cbor = do+ result <- decodeString "cbor.decodeText" True cbor+ pure $ case result of+ Left failure -> Left failure+ Right bytes -> case Text.decodeUtf8' bytes of+ Left _ -> Left InvalidCborUtf8+ Right text -> Right text++encodeString :: Text -> Bool -> ByteString -> IO (Either Error Cbor)+encodeString operation text bytes = withBytes bytes $ \input size ->+ encodeResult operation (Native.cEncodeString (flag text) input size)++decodeString :: Text -> Bool -> Cbor -> IO (Either Error ByteString)+decodeString operation text cbor = withBytes (toBytes cbor) $ \input size ->+ withDiagnostic $ \diagnostic capacity ->+ copyBuffer operation (\output -> Native.cDecodeString (flag text) input size output diagnostic capacity)++encodeCollection :: Text -> Bool -> Int -> [Cbor] -> IO (Either Error Cbor)+encodeCollection operation mapEntries count items =+ withBytes (ByteString.concat (map toBytes items)) $ \input size ->+ encodeResult operation (Native.cEncodeCollection (flag mapEntries) (fromIntegral count) input size)++-- | Keep one reader alive through the complete cursor loop. Each child buffer+-- is copied and released before the next iteration; one end-state slot is reused.+decodeCollection :: Text -> Bool -> Cbor -> IO (Either Error [Cbor])+decodeCollection operation mapEntries cbor = withBytes (toBytes cbor) $ \input size ->+ withDiagnostic $ \diagnostic capacity ->+ withOwnedOutput operation Native.cReaderUnref (\output -> Native.cReaderNew input size output diagnostic capacity) $ \reader -> do+ code <- Native.cCollectionStart reader (flag mapEntries) diagnostic capacity+ if code /= Status.success+ then statusResult operation code (pure [])+ else alloca $ \atEnd -> readChildren reader diagnostic capacity atEnd []+ where+ readChildren reader diagnostic capacity atEnd accumulated = do+ code <- Native.cCollectionAtEnd reader (flag mapEntries) atEnd diagnostic capacity+ if code /= Status.success+ then statusResult operation code (pure [])+ else do+ finished <- (/= 0) <$> peek atEnd+ if finished+ then do+ endCode <- Native.cCollectionEnd reader (flag mapEntries) diagnostic capacity+ statusResult operation endCode (pure (reverse accumulated))+ else do+ child <- copyBuffer operation (\output -> Native.cReadItem reader output diagnostic capacity)+ case child of+ Left failure -> pure (Left failure)+ Right bytes -> readChildren reader diagnostic capacity atEnd (Cbor bytes : accumulated)++-- | Re-read the interior of a validated indefinite text item as definite text+-- chunks. Each copied chunk outlives its native buffer; one scoped reader owns+-- the cursor. A decreasing byte count prevents a non-advancing native loop.+readTextChunks :: ByteString -> IO (Either Error [Cbor])+readTextChunks bytes+ | ByteString.null bytes = pure (Right [])+ | otherwise = withBytes bytes $ \input size ->+ withDiagnostic $ \diagnostic capacity ->+ withOwnedOutput "cbor.decodeText" Native.cReaderUnref (\output -> Native.cReaderNew input size output diagnostic capacity) $ \reader ->+ alloca $ \remaining -> readChunks reader diagnostic capacity remaining Nothing []+ where+ readChunks reader diagnostic capacity remaining previous accumulated = do+ code <- Native.cReaderRemaining reader remaining diagnostic capacity+ if code /= Status.success+ then statusResult "cbor.decodeText" code (pure [])+ else do+ count <- peek remaining+ if count == 0+ then pure (Right (reverse accumulated))+ else+ if maybe False (count >=) previous+ then pure (Left (NativeContractFailure "cbor.decodeText"))+ else do+ chunk <- copyBuffer "cbor.decodeText" (\output -> Native.cReadTextChunk reader output diagnostic capacity)+ case chunk of+ Left failure -> pure (Left failure)+ Right value -> readChunks reader diagnostic capacity remaining (Just count) (Cbor value : accumulated)++-- | Copy and release one owned writer result before constructing a Cbor value.+-- Unlike decoded string content, an encoded item must never be empty.+encodeResult :: Text -> (Ptr (Ptr Native.NativeBuffer) -> CString -> CSize -> IO Status.NativeCode) -> IO (Either Error Cbor)+encodeResult operation encode = do+ result <- withDiagnostic $ \diagnostic capacity -> copyBuffer operation (\output -> encode output diagnostic capacity)+ pure $ case result of+ Left failure -> Left failure+ Right bytes+ | ByteString.null bytes -> Left (NativeContractViolation operation)+ | otherwise -> Right (Cbor bytes)++-- | Consume one output reference on every exit, including partial native+-- failures. Copy borrowed storage before release; a zero-length decoded string+-- is valid even when its native buffer has no data pointer.+copyBuffer :: Text -> (Ptr (Ptr Native.NativeBuffer) -> IO Status.NativeCode) -> IO (Either NativeFailure ByteString)+copyBuffer operation acquire = withOwnedOutput operation Native.cBufferUnref acquire $ \buffer -> do+ size <- Native.cBufferSize buffer+ storage <- Native.cBufferData buffer+ if toInteger size > toInteger (maxBound :: Int) || (size /= 0 && storage == nullPtr)+ then pure (Left (NativeContractFailure operation))+ else+ if size == 0+ then pure (Right ByteString.empty)+ else Right <$> ByteString.packCStringLen (castPtr storage, fromIntegral size)++runStatus :: Text -> (CString -> CSize -> IO Status.NativeCode) -> IO (Either Error ())+runStatus operation call = withDiagnostic $ \diagnostic capacity -> do+ code <- call diagnostic capacity+ statusResult operation code (pure ())++-- | Inspect output slots only after success; preserve exact native status codes.+statusResult :: Text -> Status.NativeCode -> IO value -> IO (Either NativeFailure value)+statusResult operation code action+ | code == Status.success = Right <$> action+ | otherwise = do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (NativeFailure operation (toInteger code) message))++-- | Keep caller-owned diagnostic storage alive through the native operation+-- and its cleanup, then copy a failure message before releasing that storage.+-- Acquisition helpers retain responsibility for all owned output references.+withDiagnostic :: (CString -> CSize -> IO (Either NativeFailure value)) -> IO (Either Error value)+withDiagnostic action = allocaBytes 1024 $ \diagnostic -> do+ poke diagnostic 0+ result <- action diagnostic 1024+ case result of+ Right value -> pure (Right value)+ Left failure@(NativeContractFailure _) -> pure (Left (fromNativeFailure failure))+ Left (NativeFailure operation code fallback) -> do+ message <- copyStaticText diagnostic+ pure (Left (fromNativeFailure (NativeFailure operation code (if Text.null message then fallback else message))))++-- | Borrow immutable Haskell bytes for one synchronous native scope. C must+-- finish using the pointer before this continuation returns.+withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(storage, size) -> action (castPtr storage) (fromIntegral size)++flag :: Bool -> CInt+flag value = if value then 1 else 0
@@ -0,0 +1,139 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Standalone CBOR for native collection shapes. Association lists retain+-- explicit zero and repeated keys, unlike normalized asset bundles. All codecs+-- sort stably by encoded key byte length then lexicographic bytes. Equal keys+-- keep their relative order. These are semantic encodings, not original bytes.+--+-- @+-- import qualified Cometa.Encoding.Collections as Collections+--+-- emptyWithdrawals = Collections.encodeWithdrawalsCbor []+-- @+module Cometa.Encoding.Collections+ ( encodeAssetNamesCbor,+ decodeAssetNamesCbor,+ encodeWithdrawalsCbor,+ decodeWithdrawalsCbor,+ encodeHashesCbor,+ encodeHashesCborWith,+ decodeHashesCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Term as T+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetName (AssetName)+import qualified Cometa.AssetName as Name+import Cometa.Crypto.Blake2b (Blake2bHash)+import qualified Cometa.Crypto.Blake2b as Hash+import Cometa.Encoding.Set (SetEncoding (..))+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as Cbor+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Int (Int64)+import Data.List (sortOn)+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode one policy's asset-name quantities. Zero and duplicate entries are+-- retained, including empty names. Quantities must fit signed 64 bits;+-- otherwise return 'InvalidValueQuantity'. Empty input encodes an empty map.+encodeAssetNamesCbor :: [(AssetName, Integer)] -> Either Error ByteString+encodeAssetNamesCbor pairs = do+ mapM_ validate pairs+ pure (encodeMap Name.toBytes E.encodeInteger pairs)+ where+ validate (_, amount)+ | amount < toInteger (minBound :: Int64) || amount > toInteger (maxBound :: Int64) = Left (InvalidValueQuantity amount)+ | otherwise = Right ()++-- | Decode a complete definite or indefinite asset-name map, retaining zero and+-- duplicate entries. Names must contain at most 32 bytes and quantities must fit+-- signed 64 bits. Malformed maps return 'InvalidValueCbor'.+decodeAssetNamesCbor :: ByteString -> Either Error [(AssetName, Integer)]+decodeAssetNamesCbor = Cbor.decodeAs InvalidValueCbor $ do+ pairs <- Cbor.entries ((,) <$> checked Name.fromBytes <*> (toInteger <$> D.decodeInt64))+ pure (ordered (Name.toBytes . fst) pairs)++-- | Encode reward accounts and unsigned lovelace amounts. Zero and duplicate+-- entries are retained; empty input is an empty map, not absent withdrawals.+-- Amounts span the full unsigned 64-bit range, independent of builder limits.+encodeWithdrawalsCbor :: [(RewardAddress, Word64)] -> ByteString+encodeWithdrawalsCbor = encodeMap Reward.toBytes E.encodeWord64++-- | Decode a complete definite or indefinite withdrawal map, including empty+-- maps, zero and duplicate entries. Keys must be exact reward-account bytes;+-- negative or oversized amounts and malformed keys return 'InvalidTransactionCbor'.+decodeWithdrawalsCbor :: ByteString -> Either Error [(RewardAddress, Word64)]+decodeWithdrawalsCbor = Cbor.decodeAs InvalidTransactionCbor $ do+ pairs <- Cbor.entries ((,) <$> checked Reward.fromBytes <*> D.decodeWord64)+ pure (ordered (Reward.toBytes . fst) pairs)++-- | Encode variable-length nonempty digests as a tag-258 array. Despite the+-- native name “hash set”, duplicate digests are retained. Empty input is valid.+encodeHashesCbor :: [Blake2bHash] -> ByteString+encodeHashesCbor = encodeHashesCborWith TaggedSet++-- | Choose whether a freshly encoded digest array carries tag 258. Ordering+-- and duplicate retention match 'encodeHashesCbor'.+encodeHashesCborWith :: SetEncoding -> [Blake2bHash] -> ByteString+encodeHashesCborWith style hashes =+ Cbor.encode $+ tag+ <> E.encodeListLen (fromIntegral (length hashes))+ <> foldMap (E.encodeBytes . Hash.toBytes) (ordered Hash.toBytes hashes)+ where+ tag = case style of+ TaggedSet -> E.encodeTag 258+ UntaggedSet -> mempty++-- | Decode a complete definite or indefinite digest array, optionally tagged+-- 258. Each digest must be a definite-length nonempty byte string, matching+-- the native hash reader; hash lengths may differ. Duplicate hashes+-- survive decoding. Wrong tags, empty hashes and malformed input return+-- 'InvalidHashCbor'. The tag is not retained by this semantic decoder.+decodeHashesCbor :: ByteString -> Either Error [Blake2bHash]+decodeHashesCbor =+ Cbor.decodeAs InvalidHashCbor $+ ordered Hash.toBytes <$> Cbor.setList (D.decodeBytes >>= either (fail . show) pure . Hash.fromBytes)++encodeMap :: (a -> ByteString) -> (b -> E.Encoding) -> [(a, b)] -> ByteString+encodeMap key value pairs =+ Cbor.encode $+ E.encodeMapLen (fromIntegral (length pairs))+ <> foldMap (\(k, v) -> E.encodeBytes (key k) <> value v) (ordered (key . fst) pairs)++ordered :: (a -> ByteString) -> [a] -> [a]+ordered bytes = sortOn (\value -> let key = bytes value in (B.length key, key))++checked :: (ByteString -> Either Error a) -> D.Decoder s a+checked constructor = do+ term <- T.decodeTerm+ bytes <- case term of+ T.TBytes value -> pure value+ T.TBytesI value -> pure (L.toStrict value)+ _ -> fail "Expected byte string"+ either (fail . show) pure (constructor bytes)
@@ -0,0 +1,49 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Strict hexadecimal conversion for raw bytes. Decode a textual payload,+-- then pass the bytes to the domain's ordinary validator. Hexadecimal syntax+-- does not establish a script, hash role, CBOR schema or ledger validity.+--+-- @+-- import qualified Cometa.Encoding.Hex as Hex+-- import qualified Cometa.Script.Plutus as Plutus+--+-- readScript text = Hex.decode text >>= Plutus.fromBytes Plutus.V3+-- @+module Cometa.Encoding.Hex (encode, decode) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (InvalidHex))+import qualified Cometa.Internal.Hex as Internal+import Data.ByteString (ByteString)+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Render every byte as two lowercase ASCII hexadecimal digits, without a+-- prefix or whitespace. Empty bytes produce empty text. For all byte strings,+-- @decode (encode bytes) == Right bytes@.+encode :: ByteString -> Text+encode = Internal.encodeHex++-- | Decode a complete even-length sequence of ASCII hexadecimal digits,+-- accepting either letter case. Empty text produces empty bytes. Odd length,+-- non-ASCII characters, whitespace, prefixes and embedded NUL characters return+-- 'InvalidHex'; no partial payload is returned. A successful result still needs+-- validation by the intended domain decoder.+decode :: Text -> Either Error ByteString+decode = maybe (Left InvalidHex) Right . Internal.decodeHex
@@ -0,0 +1,205 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Exact integer text, magnitude bytes and modular arithmetic. Values are+-- ordinary Haskell 'Integer's; no native object or mutable buffer is exposed.+--+-- Validate a 'Radix' once, parse text with 'fromText', then pass the integer to+-- metadata or Plutus-data constructors. 'fromTextAuto' recognizes native-style+-- radix prefixes. Modular operations report invalid domains through 'Either'.+module Cometa.Encoding.Integer+ ( Radix,+ mkRadix,+ radixValue,+ binary,+ decimal,+ hexadecimal,+ fromText,+ fromTextAuto,+ toText,+ toUpperText,+ ByteOrder (..),+ fromBytes,+ toBytes,+ modularInverse,+ modularPower,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Char (chr, isAsciiLower, isAsciiUpper, isDigit, ord)+import Data.List (unfoldr)+import Data.Text (Text)+import qualified Data.Text as T+import Numeric (showIntAtBase)++-- TYPES ----------------------------------------------------------------------++-- | A radix from 2 through 62. Above 36, uppercase digits precede lowercase.+newtype Radix = Radix Int deriving (Eq, Ord, Show)++-- | Order of unsigned magnitude bytes. Neither order carries a sign bit.+data ByteOrder = LittleEndian | BigEndian deriving (Eq, Ord, Show, Enum, Bounded)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate a radix; other values return 'InvalidIntegerRadix'.+mkRadix :: Int -> Either Error Radix+mkRadix n+ | n >= 2 && n <= 62 = Right (Radix n)+ | otherwise = Left (InvalidIntegerRadix n)++-- | Observe the validated radix.+radixValue :: Radix -> Int+radixValue (Radix n) = n++-- | Base 2.+binary :: Radix+binary = Radix 2++-- | Base 10.+decimal :: Radix+decimal = Radix 10++-- | Base 16.+hexadecimal :: Radix+hexadecimal = Radix 16++-- | Parse a native-compatible complete textual prefix: an optional minus sign,+-- digits, and ASCII whitespace. A plus sign and explicit radix prefixes are+-- rejected. Parsing stops at the first NUL. Letter case is ignored through+-- base 36; bases 37..62 use @0..9,A..Z,a..z@. Empty or invalid digits return+-- 'InvalidIntegerText'. Whitespace before the minus sign is accepted.+fromText :: Radix -> Text -> Either Error Integer+fromText (Radix radix) text = let (negative, digits) = signed text in parseDigits radix negative digits++-- | Detect base 16 from @0x@/@0X@, base 2 from @0b@/@0B@, base 8 from a+-- leading zero, and base 10 otherwise. Prefix detection follows the optional+-- minus sign before internal whitespace is removed, matching native base 0.+fromTextAuto :: Text -> Either Error Integer+fromTextAuto text =+ let (negative, digits) = signed text+ (radix, remaining) = case T.unpack (T.take 2 digits) of+ ['0', 'x'] -> (16, T.drop 2 digits)+ ['0', 'X'] -> (16, T.drop 2 digits)+ ['0', 'b'] -> (2, T.drop 2 digits)+ ['0', 'B'] -> (2, T.drop 2 digits)+ _ | T.isPrefixOf "0" digits -> (8, digits)+ _ -> (10, digits)+ in parseDigits radix negative remaining++-- | Render the exact integer without a radix prefix or whitespace. Bases+-- 2..36 use lowercase letters; bases 37..62 use @0..9,A..Z,a..z@. Zero is @0@.+-- The minus sign is outside the unsigned digit conversion.+toText :: Radix -> Integer -> Text+toText (Radix radix) number =+ T.pack ((if number < 0 then "-" else "") ++ showIntAtBase (toInteger radix) (digitCharacter radix) (abs number) "")++-- | Uppercase rendering for bases 2..36, equivalent to native negative+-- rendering bases -2..-36. Larger radices return 'InvalidIntegerRadix' with+-- the corresponding negative base, since changing case would change digits.+toUpperText :: Radix -> Integer -> Either Error Text+toUpperText radix number+ | radixValue radix > 36 = Left (InvalidIntegerRadix (negate (radixValue radix)))+ | otherwise = Right (T.toUpper (toText radix number))++-- | Decode unsigned magnitude bytes; empty input denotes zero. Leading zero+-- bytes are accepted. This is independent of host byte order.+fromBytes :: ByteOrder -> ByteString -> Integer+fromBytes order = B.foldl' (\n b -> n * 256 + toInteger b) 0 . ordered+ where+ ordered = case order of LittleEndian -> B.reverse; BigEndian -> id++-- | Minimal unsigned magnitude bytes of the absolute value. Zero has one+-- zero byte; positive and negative integers with the same magnitude agree.+toBytes :: ByteOrder -> Integer -> ByteString+toBytes order number =+ let little = if number == 0 then [0] else unfoldr step (abs number)+ in B.pack (case order of LittleEndian -> little; BigEndian -> reverse little)+ where+ step 0 = Nothing+ step n = let (q, r) = n `quotRem` 256 in Just (fromInteger r, q)++-- | Inverse in @[0,abs modulus)@. Moduli 0 and +/-1 return 'InvalidModulus';+-- zero or noncoprime values return 'NoModularInverse'. Unlike the native void+-- function, failure never leaves an unspecified previous result. Variable time.+modularInverse :: Integer -> Integer -> Either Error Integer+modularInverse value modulus+ | abs modulus <= 1 = Left (InvalidModulus modulus)+ | otherwise =+ let (divisor, coefficient) = euclid (abs modulus) (value `mod` abs modulus) 0 1+ in if divisor == 1 then Right (coefficient `mod` abs modulus) else Left (NoModularInverse value modulus)+ where+ euclid a 0 x _ = (a, x)+ euclid a b x y = let (q, r) = a `quotRem` b; next = x - q * y in next `seq` euclid b r y next++-- | Exact modular power using repeated squaring, with negative exponents+-- interpreted through 'modularInverse'. Zero modulus returns 'InvalidModulus';+-- a missing inverse returns 'NoModularInverse'. Negative moduli use their+-- absolute magnitude. Exponent zero returns 1, including modulus +/-1, as in+-- the native API; nonzero powers modulo +/-1 return 0. Negative exponents+-- with those moduli are rejected. Variable time; no constant-time guarantee.+modularPower :: Integer -> Integer -> Integer -> Either Error Integer+modularPower value power modulus+ | modulus == 0 = Left (InvalidModulus modulus)+ | power == 0 = Right 1+ | power < 0 = do+ inverse <- modularInverse value modulus+ pure (square inverse (negate power) 1)+ | otherwise = Right (square (value `mod` magnitude) power 1)+ where+ magnitude = abs modulus+ square _ 0 result = result+ square factor remaining result =+ let productValue = if odd remaining then (result * factor) `mod` magnitude else result+ nextFactor = (factor * factor) `mod` magnitude+ in productValue `seq` nextFactor `seq` square nextFactor (remaining `quot` 2) productValue++-- FUNCTIONS ------------------------------------------------------------------++asciiSpace :: Char -> Bool+asciiSpace c = c `elem` [' ', '\t', '\n', '\r', '\f', '\v']++signed :: Text -> (Bool, Text)+signed text =+ let prefix = T.dropWhile asciiSpace (T.takeWhile (/= '\0') text)+ in case T.stripPrefix "-" prefix of Just rest -> (True, rest); Nothing -> (False, prefix)++parseDigits :: Int -> Bool -> Text -> Either Error Integer+parseDigits radix negative text+ | T.null digits = Left (InvalidIntegerText "missing digits")+ | otherwise = (if negative then negate else id) <$> T.foldl' consume (Right 0) digits+ where+ digits = T.filter (not . asciiSpace) text+ consume failure@(Left _) _ = failure+ consume (Right accumulated) c = do+ digit <- case () of+ _ | isDigit c -> Right (ord c - ord '0')+ _ | isAsciiUpper c -> Right (ord c - ord 'A' + 10)+ _ | isAsciiLower c -> Right (ord c - ord 'a' + if radix <= 36 then 10 else 36)+ _ -> Left (InvalidIntegerText "invalid digit")+ if digit >= radix then Left (InvalidIntegerText "digit exceeds radix") else let next = accumulated * toInteger radix + toInteger digit in next `seq` Right next++digitCharacter :: Int -> Int -> Char+digitCharacter radix digit+ | digit < 10 = chr (ord '0' + digit)+ | radix <= 36 = chr (ord 'a' + digit - 10)+ | digit < 36 = chr (ord 'A' + digit - 10)+ | otherwise = chr (ord 'a' + digit - 36)
@@ -0,0 +1,85 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Explicit native representation changes for advanced encoding workflows.+-- These operations produce distinct snapshots; their source values remain exact.+-- They follow native representation policy, including retained indefinite script+-- lists and mixed-depth transaction rules. They are not canonical-CBOR codecs.+--+-- Re-encoding can change script hashes, transaction IDs, auxiliary-data hashes+-- and script-data commitments. Transaction signatures are retained verbatim and+-- may become invalid. No commitment, signature or ledger rule is repaired.+-- Inspect the result and assemble/sign a new transaction when identity changes.+-- Ordinary transaction setters remain the interface for normal body edits.+--+-- @+-- import qualified Cometa.Encoding.Reencode as Reencode+-- import qualified Cometa.Script.Native as Native+--+-- reencodedCondition = Reencode.nativeScript (Native.invalidBefore 100)+-- @+module Cometa.Encoding.Reencode+ ( nativeScript,+ nativeScripts,+ transaction,+ subTransaction,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Error (Error)+import qualified Cometa.Internal.Reencode as Internal+import qualified Cometa.Script.Native as Native+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction as Tx++-- DEFINITIONS ----------------------------------------------------------------++-- | Re-encode native condition nodes with fresh definite node arrays and+-- shortest scalar encodings, recursively retaining each child list's existing+-- definite/indefinite shape, order and duplicates. The resulting script hash may+-- differ. Native parsing/encoding failures are explicit; the source is unchanged.+nativeScript :: Native.NativeScript -> IO (Either Error Native.NativeScript)+nativeScript source = fmap (>>= Native.decodeCbor) (Internal.reencode "encoding.reencode.nativeScript" 0 (Native.encodeCbor source))++-- | Validate and re-encode an encoded native-script list. Retain the outer+-- list's definite/indefinite shape and recursively apply 'nativeScript' policy+-- to its children. Definite lengths use their shortest encoding. Empty lists,+-- order and duplicates are retained. A non-list or invalid script returns a+-- native error. Source bytes remain unchanged.+nativeScripts :: Cbor.Cbor -> IO (Either Error Cbor.Cbor)+nativeScripts source = do+ result <- Internal.reencode "encoding.reencode.nativeScripts" 1 (Cbor.toBytes source)+ either (pure . Left) Cbor.fromBytes result++-- | Re-encode an outer transaction body, witness collections and auxiliary+-- container under native policy. Nested intent bodies remain exact. Witness+-- datum/redeemer data are re-encoded recursively; native-script child encodings+-- in witnesses are retained and witness set tags are freshly emitted.+-- Existing signatures and commitments are retained, so they may become invalid.+-- Native decoding failures include unsupported source representations, such as+-- indefinite body maps. The original transaction is unchanged.+transaction :: Tx.Transaction -> IO (Either Error Tx.Transaction)+transaction source = fmap (>>= Tx.decodeCbor) (Internal.reencode "encoding.reencode.transaction" 2 (Tx.encodeCbor source))++-- | Re-encode one intent's body, witness collections and auxiliary container+-- with the same policy and signature/commitment caveats as 'transaction'. Its+-- body ID may change. This operation does not alter an enclosing transaction or+-- the original intent; native parsing/encoding failures remain explicit.+subTransaction :: Sub.SubTransaction -> IO (Either Error Sub.SubTransaction)+subTransaction source = fmap (>>= Sub.decodeCbor) (Internal.reencode "encoding.reencode.subTransaction" 3 (Sub.encodeCbor source))
@@ -0,0 +1,30 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | CBOR representation of ledger set collections. This choice controls the+-- optional tag only; ordering and duplicate handling belong to each collection.+module Cometa.Encoding.Set (SetEncoding (..)) where++-- TYPES ----------------------------------------------------------------------++-- | Whether a set array carries CBOR tag 258. Choose the representation required+-- by the target protocol; accepting both when decoding does not imply both are+-- valid on every network or protocol version.+data SetEncoding+ = -- | Prefix the array with CBOR tag 258.+ TaggedSet+ | -- | Encode the array without a set tag.+ UntaggedSet+ deriving (Eq, Ord, Show, Enum, Bounded)
@@ -0,0 +1,331 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Validation and operation failures. Match constructors and status codes to+-- handle errors; diagnostic messages are intended for people.+--+-- @+-- import qualified Cometa.Crypto.Blake2b as Blake2b+-- import qualified Data.ByteString as ByteString+--+-- main :: IO ()+-- main = case Blake2b.fromBytes ByteString.empty of+-- Left err -> print err+-- Right digest -> print digest+-- @+module Cometa.Error+ ( Error (..),+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error.Code (ErrorCode)+import Data.Text (Text)+import Data.Word (Word32, Word64, Word8)++-- TYPES ----------------------------------------------------------------------++-- | Expected failures returned by Cometa operations. Equality compares every+-- payload, including diagnostic text. 'Show' is diagnostic output.+data Error+ = -- | An operation failed with a cardano-c status code. Unknown numeric codes+ -- remain available through @toNumber@ in "Cometa.Error.Code".+ NativeError+ -- | Operation name, such as @blake2b.compute@; excludes user input.+ !Text+ -- | Exact status code, with a name when recognized.+ !ErrorCode+ -- | Diagnostic message; do not parse it to determine the failure.+ !Text+ | -- | A transaction-building request has invalid context or inconsistent inputs.+ InvalidBuildingRequest !Text+ | -- | Transaction requirements conflict or cannot form a valid build request.+ InvalidTransactionPlan !Text+ | -- | A slot configuration or conversion is outside its supported time range.+ InvalidSlotConfig !Text+ | -- | The requested BLAKE2b digest length is outside 16 through 64 bytes.+ InvalidHashLength+ -- | Requested digest length in bytes.+ !Int+ | -- | The digest byte sequence is empty.+ EmptyHash+ | -- | Hexadecimal input is empty, has an odd number of digits, or contains+ -- characters other than ASCII hexadecimal digits. Both cases are accepted.+ InvalidHex+ | -- | An Ed25519 signing-key operation used a handle that has been closed.+ SigningKeyClosed+ | -- | An Ed25519 signing-key input has the wrong byte length for its format.+ InvalidEd25519SigningKeyLength+ -- | Expected byte length: 32 for normal keys, or 64 for extended keys.+ !Int+ -- | Actual input byte length.+ !Int+ | -- | A software key handler has closed.+ KeyHandlerClosed+ | -- | A software key handler already has an active operation.+ KeyHandlerBusy+ | -- | A software handler password is outside 1 through 128 bytes.+ InvalidKeyHandlerPasswordLength !Int+ | -- | Software storage framing, type or secret length is invalid.+ InvalidKeyHandlerStorage+ | -- | An Ed25519 public key does not contain exactly 32 bytes.+ InvalidEd25519PublicKeyLength+ -- | Actual encoded byte length.+ !Int+ | -- | An Ed25519 signature does not contain exactly 64 bytes.+ InvalidEd25519SignatureLength+ -- | Actual encoded byte length.+ !Int+ | -- | A BIP32 private-key handle has closed.+ Bip32PrivateKeyClosed+ | -- | A BIP32 private key must contain exactly 96 bytes.+ InvalidBip32PrivateKeyLength+ -- | Actual byte count.+ !Int+ | -- | A BIP32 public key must contain exactly 64 bytes.+ InvalidBip32PublicKeyLength+ -- | Actual byte count.+ !Int+ | -- | BIP39 entropy must contain 16, 20, 24, 28 or 32 bytes.+ InvalidBip39EntropyLength+ -- | Actual byte count.+ !Int+ | -- | A mnemonic requires 12, 15, 18, 21 or 24 words.+ InvalidBip39WordCount+ -- | Actual number of words.+ !Int+ | -- | A mnemonic word is empty or contains characters outside lowercase ASCII.+ InvalidBip39Word+ -- | One-based word position; excludes the word itself.+ !Int+ | -- | At least one word is absent from the English BIP39 dictionary.+ UnknownBip39Word+ | -- | The mnemonic checksum does not agree with its entropy.+ InvalidBip39Checksum+ | -- | PBKDF2 requires a nonempty salt.+ EmptyPbkdf2Salt+ | -- | PBKDF2 iteration count is outside 1 through 4294967295 inclusive.+ InvalidPbkdf2Iterations+ -- | Requested iteration count.+ !Integer+ | -- | PBKDF2 output byte count is outside its documented bounds.+ InvalidPbkdf2OutputLength+ -- | Requested output byte count.+ !Integer+ | -- | EMIP3 plaintext exceeds its documented size bounds.+ InvalidEmip3PlaintextLength+ -- | Actual plaintext byte count.+ !Int+ | -- | EMIP3 envelope is outside its documented size bounds.+ InvalidEmip3EnvelopeLength+ -- | Actual encoded byte count.+ !Int+ | -- | An unencoded derivation component is outside 0 through 2147483647.+ InvalidDerivationIndex+ -- | Exact requested component number.+ !Integer+ | -- | Public derivation requires soft indices below 2^31.+ HardenedPublicDerivation+ -- | First hardened encoded index encountered.+ !Word32+ | -- | A CBOR integer is outside the supported primitive range, from+ -- @-2^64@ through @2^64 - 1@ inclusive. Tagged bignums are not encoded here.+ InvalidCborInteger+ -- | Requested integer value.+ !Integer+ | -- | A decoded CBOR text string contains invalid UTF-8.+ InvalidCborUtf8+ | -- | A native-asset name exceeds 32 bytes.+ InvalidAssetNameLength !Int+ | -- | Asset-name CBOR is malformed or does not contain a name of 0 through 32 bytes.+ InvalidAssetNameCbor !Text+ | -- | A native-asset identity encoding does not contain 28 through 60 bytes.+ InvalidAssetIdLength !Int+ | -- | A native-asset policy identifier does not contain exactly 28 bytes.+ InvalidPolicyIdLength !Int+ | -- | A credential hash does not contain exactly 28 bytes.+ InvalidCredentialHashLength !Int+ | -- | A credential CBOR item has invalid syntax, shape or kind.+ InvalidCredentialCbor !Text+ | -- | A digest CBOR item has invalid syntax or is not one byte string.+ InvalidHashCbor !Text+ | -- | A Shelley network tag is outside 0 through 15 inclusive.+ InvalidNetworkId !Integer+ | -- | The four-bit header selects an address form unsupported by the chosen+ -- payment-address or reward-account decoder.+ UnsupportedAddressType !Word8+ | -- | Address bytes are empty or have an incorrect exact length.+ InvalidShelleyAddress+ | -- | Address text is malformed, mixed-case, has an invalid checksum or+ -- bit padding, or has a prefix inconsistent with its network/address form.+ InvalidShelleyAddressText+ | -- | Plutus data CBOR is malformed or contains unsupported data forms.+ InvalidPlutusDataCbor !Text+ | -- | A metadata integer is outside -2^64 through 2^64 - 1 inclusive.+ InvalidMetadataInteger !Integer+ | -- | A metadata byte string exceeds 64 bytes.+ InvalidMetadataBytesLength !Int+ | -- | A metadata text string exceeds 64 UTF-8 bytes.+ InvalidMetadataTextLength !Int+ | -- | Metadata CBOR is malformed or violates metadata bounds.+ InvalidMetadataCbor !Text+ | -- | A transaction metadata label occurs more than once.+ DuplicateMetadataLabel !Word64+ | -- | Detailed metadata JSON is malformed or violates metadata bounds.+ InvalidMetadataJson !Text+ | -- | Script CBOR is malformed or has an unsupported script form.+ InvalidScriptCbor !Text+ | -- | Native script construction JSON is malformed or violates script bounds.+ InvalidScriptJson !Text+ | -- | Compiled Plutus script bytes are empty.+ EmptyPlutusScript+ | -- | A protocol fraction has a negative or oversized component, or a zero denominator.+ InvalidProtocolRational !Integer !Integer+ | -- | An integer text radix or uppercase rendering radix is unsupported.+ InvalidIntegerRadix !Int+ | -- | Integer text contains invalid digits or no digits; payload is diagnostic.+ InvalidIntegerText !Text+ | -- | A modular operation has a zero or otherwise unsupported modulus.+ InvalidModulus !Integer+ | -- | The given integer has no inverse for the given modulus.+ NoModularInverse !Integer !Integer+ | -- | A floating-point protocol fraction is nonfinite, negative or has an oversized whole part.+ InvalidProtocolDouble+ | -- | A floating-point unit interval is nonfinite or outside zero through one.+ InvalidUnitIntervalDouble+ | -- | A unit interval fraction lies outside zero through one inclusive.+ InvalidUnitInterval !Integer !Integer+ | -- | An execution budget component is outside the unsigned 64-bit range.+ InvalidExUnits !Integer !Integer+ | -- | A protocol version exceeds its unsigned major/minor bounds.+ InvalidProtocolVersion !Integer !Integer+ | -- | A protocol value has malformed CBOR or violates its field constraints.+ InvalidProtocolCbor !Text+ | -- | Transaction CBOR is malformed or violates its field constraints.+ InvalidTransactionCbor !Text+ | -- | A transaction output contains an unsupported quantity.+ InvalidTransactionOutputValue !Integer+ | -- | A standalone value has Ada outside 0..2^63-1 or a native quantity outside int64.+ InvalidValueQuantity !Integer+ | -- | Standalone value CBOR is malformed or violates its quantity constraints.+ InvalidValueCbor !Text+ | -- | Governance action identifier text is malformed or has an invalid prefix or payload.+ InvalidGovernanceActionText !Text+ | -- | An action index exceeds the one-byte CIP-129 text representation.+ InvalidGovernanceActionTextIndex !Word64+ | -- | A DRep identifier has an invalid checksum, prefix, header or payload.+ InvalidDRepText !Text+ | -- | A transaction digest does not contain exactly 32 bytes.+ InvalidTransactionHashLength !Int+ | -- | A transaction field violates its domain constraints.+ InvalidTransactionField !Text+ | -- | Witness CBOR is malformed or violates its field constraints.+ InvalidWitnessCbor !Text+ | -- | Redeemer CBOR is malformed or violates its field constraints.+ InvalidRedeemerCbor !Text+ | -- | Auxiliary data CBOR is malformed or violates its field constraints.+ InvalidAuxiliaryDataCbor !Text+ | -- | A bootstrap witness chain code does not contain 32 bytes.+ InvalidBootstrapChainCodeLength !Int+ | -- | Witnesses contain conflicting values for the same identity.+ WitnessConflict !Text+ | -- | Byron address bytes or attributes are malformed or have a bad checksum.+ InvalidByronAddress !Text+ | -- | Byron address text is not a valid Base58 address.+ InvalidByronAddressText+ | -- | A backend rejected an HTTP request. The payload contains the operation+ -- name and HTTP status, without response bodies or credentials.+ ProviderHttpError !Text !Int+ | -- | A backend request could not complete. The payload contains the operation+ -- name and a credential-free description of the transport failure.+ ProviderTransportError !Text !Text+ | -- | A backend response violates the named operation's data contract.+ InvalidProviderResponse !Text+ | -- | A backend configuration is invalid. The diagnostic excludes credentials.+ InvalidProviderConfiguration !Text+ | -- | The requested service capability is not supplied.+ UnsupportedOperation !Text+ | -- | An operation used a resource after its scope ended.+ RuntimeClosed+ | -- | An overlapping operation is already using the same resource.+ RuntimeBusy+ | -- | An injected callback returned a result outside its contract.+ InvalidCallbackResult !Text+ | -- | A parameter snapshot is incomplete or outside supported bounds.+ InvalidParameterSnapshot !Text+ | -- | Coin-selection inputs are inconsistent or outside supported bounds.+ InvalidSelectionRequest !Text+ | -- | A selection violates eligibility, balance or change requirements.+ InvalidSelection !Text+ | -- | An evaluation target or resolved input snapshot is inconsistent.+ InvalidEvaluationRequest !Text+ | -- | Evaluation budgets do not match the transaction's redeemer identities.+ InvalidEvaluationResult !Text+ | -- | Pool CBOR is malformed or violates a field constraint.+ InvalidPoolCbor !Text+ | -- | A pool VRF key hash does not contain 32 bytes.+ InvalidPoolHashLength !Int+ | -- | A pool metadata URL violates its byte-length or NUL constraint.+ InvalidPoolMetadataUrl !Text+ | -- | A pool metadata hash does not contain 32 bytes.+ InvalidPoolMetadataHashLength !Int+ | -- | A relay DNS name violates its byte-length or NUL constraint.+ InvalidPoolDnsName !Text+ | -- | An IP address has an incorrect byte count: expected, then actual.+ InvalidPoolIpLength !Int !Int+ | -- | An IP address text representation is malformed.+ InvalidPoolIpText !Text+ | -- | A BLS key or possession proof has an incorrect byte count.+ InvalidPoolBlsKeyLength+ -- | Actual public-key byte count; 96 is required.+ !Int+ -- | Actual possession-proof byte count; 48 is required.+ !Int+ | -- | A certificate has malformed CBOR or invalid fields.+ InvalidCertificateCbor !Text+ | -- | A governance proposal has malformed CBOR or invalid fields.+ InvalidProposalCbor !Text+ | -- | A reward account occurs more than once in treasury withdrawals.+ DuplicateTreasuryWithdrawal+ | -- | A committee credential occurs more than once.+ DuplicateCommitteeMember+ | -- | A genesis key occurs more than once in a proposed update map.+ DuplicateProtocolUpdate+ | -- | A cost model contains an unsupported number of coefficients.+ InvalidCostModelLength !Int+ | -- | A parameter update has malformed CBOR or invalid fields.+ InvalidProtocolParametersCbor !Text+ | -- | A reference script cost stride is outside 1 through 4294967295 bytes.+ InvalidReferenceScriptCostStride !Integer+ | -- | A nonneutral protocol nonce does not contain exactly 32 bytes.+ InvalidProtocolNonceLength !Int+ | -- | An anchor URL is outside 1 through 128 UTF-8 bytes.+ InvalidAnchorUrlLength !Int+ | -- | An anchor URL contains a NUL character.+ InvalidAnchorUrl+ | -- | An anchor data digest does not contain exactly 32 bytes.+ InvalidAnchorDataHashLength !Int+ | -- | A transaction identifier does not contain exactly 32 bytes.+ InvalidTransactionIdLength !Int+ | -- | Governance CBOR is malformed or violates the selected value's schema.+ InvalidGovernanceCbor !Text+ | -- | A voter/action pair is present more than once.+ DuplicateGovernanceVote+ | -- | An operation reported success but did not produce a valid result.+ NativeContractViolation+ -- | Operation name; excludes user input.+ !Text+ deriving (Eq, Show)
@@ -0,0 +1,385 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Named cardano-c status codes, including success. Unknown numeric codes are+-- preserved exactly for logging and interchange. A code can be named even when+-- this package does not expose operations from the corresponding domain.+--+-- @+-- import qualified Cometa.Error.Code as Code+--+-- main :: IO ()+-- main = print (Code.fromNumber (Code.toNumber Code.InvalidArgument) == Code.InvalidArgument)+-- @+module Cometa.Error.Code+ ( -- * Status codes+ ErrorCode+ ( Success,+ GenericFailure,+ InsufficientBufferSize,+ NullPointer,+ MemoryAllocationFailed,+ OutOfBoundsMemoryRead,+ OutOfBoundsMemoryWrite,+ InvalidArgument,+ InvalidUrl,+ ElementNotFound,+ EncodingFailure,+ DecodingFailure,+ ChecksumMismatch,+ InvalidJson,+ IntegerOverflow,+ IntegerUnderflow,+ ConversionFailed,+ IndexOutOfBounds,+ InvalidCertificateType,+ NotImplemented,+ InvalidPassphrase,+ IllegalState,+ DuplicateKey,+ JsonTypeMismatch,+ LossOfPrecision,+ InvalidMagic,+ InvalidChecksum,+ InvalidBlake2bHashSize,+ InvalidEd25519SignatureSize,+ InvalidEd25519PublicKeySize,+ InvalidEd25519PrivateKeySize,+ InvalidBip32PublicKeySize,+ InvalidBip32PrivateKeySize,+ InvalidBip32DerivationIndex,+ UnexpectedCborType,+ InvalidCborValue,+ InvalidCborArraySize,+ InvalidCborMapSize,+ DuplicateCborMapKey,+ InvalidCborMapKey,+ InvalidAddressType,+ InvalidAddressFormat,+ InvalidCredentialType,+ InvalidPlutusDataConversion,+ InvalidDatumType,+ InvalidScriptLanguage,+ InvalidNativeScriptType,+ InvalidPlutusCostModel,+ InvalidProposalProcedureType,+ InvalidMetadatumConversion,+ InvalidMetadatumTextStringSize,+ InvalidMetadatumBoundedBytesSize,+ InvalidHttpRequest,+ InsufficientBalance,+ UtxoNotFragmentedEnough,+ UtxoFullyDepleted,+ MaximumInputCountExceeded,+ UnbalancedSubTransactions,+ DisallowedSupplementalDatums,+ MissingRedeemer,+ ScriptEvaluationFailure+ ),++ -- * Numeric conversion+ fromNumber,+ toNumber,++ -- * Inspection+ isKnown,+ knownCodes,+ )+where++-- TYPES ----------------------------------------------------------------------++-- | A native status code. 'Success' represents a successful operation; all other+-- named constructors represent failures. Use 'fromNumber' to construct a code+-- from any integer, and 'isKnown' to distinguish named and unrecognized codes.+-- Equality distinguishes exact numeric codes. 'Show' is diagnostic only.+data ErrorCode+ = -- | Successful operation.+ Success+ | -- | Generic error.+ GenericFailure+ | -- | Insufficient buffer size.+ InsufficientBufferSize+ | -- | Operation over a null pointer.+ NullPointer+ | -- | Memory could not be allocated.+ MemoryAllocationFailed+ | -- | Out of bounds memory read.+ OutOfBoundsMemoryRead+ | -- | Out of bounds memory write.+ OutOfBoundsMemoryWrite+ | -- | Invalid argument.+ InvalidArgument+ | -- | Invalid URL.+ InvalidUrl+ | -- | Element not found.+ ElementNotFound+ | -- | Encoding failure.+ EncodingFailure+ | -- | Decoding failure.+ DecodingFailure+ | -- | Invalid checksum.+ ChecksumMismatch+ | -- | Invalid JSON.+ InvalidJson+ | -- | An integer exceeds its upper bound.+ IntegerOverflow+ | -- | An integer is below its lower bound.+ IntegerUnderflow+ | -- | Conversion error.+ ConversionFailed+ | -- | Index out of bounds.+ IndexOutOfBounds+ | -- | Invalid certificate type.+ InvalidCertificateType+ | -- | The operation is not implemented.+ NotImplemented+ | -- | The passphrase is invalid.+ InvalidPassphrase+ | -- | The state of the object is illegal.+ IllegalState+ | -- | The element is already present.+ DuplicateKey+ | -- | The JSON type is unexpected.+ JsonTypeMismatch+ | -- | The serialization or deserialization process resulted in a loss of precision.+ LossOfPrecision+ | -- | The magic number is invalid.+ InvalidMagic+ | -- | The checksum is invalid.+ InvalidChecksum+ | -- | The hash size is invalid.+ InvalidBlake2bHashSize+ | -- | The Ed25519 signature size is invalid.+ InvalidEd25519SignatureSize+ | -- | The Ed25519 public key size is invalid.+ InvalidEd25519PublicKeySize+ | -- | The Ed25519 private key size is invalid.+ InvalidEd25519PrivateKeySize+ | -- | The BIP32 public key size is invalid.+ InvalidBip32PublicKeySize+ | -- | The BIP32 private key size is invalid.+ InvalidBip32PrivateKeySize+ | -- | The BIP32 derivation index is invalid.+ InvalidBip32DerivationIndex+ | -- | The CBOR type is unexpected.+ UnexpectedCborType+ | -- | The CBOR type is expected, but its value is invalid or out of range.+ InvalidCborValue+ | -- | The CBOR array size is invalid.+ InvalidCborArraySize+ | -- | The CBOR map size is invalid.+ InvalidCborMapSize+ | -- | The CBOR map key is duplicated.+ DuplicateCborMapKey+ | -- | The CBOR map key is invalid.+ InvalidCborMapKey+ | -- | The address type is invalid.+ InvalidAddressType+ | -- | The address format is invalid.+ InvalidAddressFormat+ | -- | The credential type is invalid.+ InvalidCredentialType+ | -- | The Plutus data conversion is invalid.+ InvalidPlutusDataConversion+ | -- | The Plutus datum type is invalid.+ InvalidDatumType+ | -- | The script language is invalid.+ InvalidScriptLanguage+ | -- | The native script type is invalid.+ InvalidNativeScriptType+ | -- | The Plutus cost model is invalid.+ InvalidPlutusCostModel+ | -- | The governance action type is invalid.+ InvalidProposalProcedureType+ | -- | The metadatum conversion is invalid.+ InvalidMetadatumConversion+ | -- | The metadatum text string size is invalid.+ InvalidMetadatumTextStringSize+ | -- | The metadatum bounded byte string size is invalid.+ InvalidMetadatumBoundedBytesSize+ | -- | The HTTP request is invalid.+ InvalidHttpRequest+ | -- | Available UTxO value is less than the requested output value.+ InsufficientBalance+ | -- | The selection algorithm requires more UTxO entries to cover the outputs.+ UtxoNotFragmentedEnough+ | -- | Selection exhausted the available UTxO entries before covering all outputs.+ UtxoFullyDepleted+ | -- | Progress would exceed the selection algorithm's maximum input count.+ MaximumInputCountExceeded+ | -- | Subtransactions do not conserve value as required by the batch.+ UnbalancedSubTransactions+ | -- | The top-level transaction carries a witness datum disallowed for its batch.+ DisallowedSupplementalDatums+ | -- | A Plutus script purpose in the transaction or its subtransactions lacks a redeemer.+ MissingRedeemer+ | -- | The transaction script evaluation failed.+ ScriptEvaluationFailure+ | UnknownCode !Integer+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Interpret a numeric status code. Every integer is accepted, including+-- negative values and values outside machine integer ranges, without truncation.+-- A recognized number becomes its named constructor; all others remain unknown.+--+-- @toNumber (fromNumber number) == number@+fromNumber :: Integer -> ErrorCode+fromNumber number = case lookup number [(toNumber code, code) | code <- knownCodes] of+ Just code -> code+ Nothing -> UnknownCode number++-- | Return the exact numeric code. No conversion to a bounded machine integer+-- occurs. This is the inverse of 'fromNumber' on all 'ErrorCode' values.+toNumber :: ErrorCode -> Integer+toNumber code = case code of+ Success -> 0+ GenericFailure -> 1+ InsufficientBufferSize -> 2+ NullPointer -> 3+ MemoryAllocationFailed -> 4+ OutOfBoundsMemoryRead -> 5+ OutOfBoundsMemoryWrite -> 6+ InvalidArgument -> 7+ InvalidUrl -> 8+ ElementNotFound -> 9+ EncodingFailure -> 10+ DecodingFailure -> 11+ ChecksumMismatch -> 12+ InvalidJson -> 13+ IntegerOverflow -> 14+ IntegerUnderflow -> 15+ ConversionFailed -> 16+ IndexOutOfBounds -> 17+ InvalidCertificateType -> 18+ NotImplemented -> 19+ InvalidPassphrase -> 20+ IllegalState -> 21+ DuplicateKey -> 22+ JsonTypeMismatch -> 23+ LossOfPrecision -> 100+ InvalidMagic -> 101+ InvalidChecksum -> 102+ InvalidBlake2bHashSize -> 200+ InvalidEd25519SignatureSize -> 201+ InvalidEd25519PublicKeySize -> 202+ InvalidEd25519PrivateKeySize -> 203+ InvalidBip32PublicKeySize -> 204+ InvalidBip32PrivateKeySize -> 205+ InvalidBip32DerivationIndex -> 206+ UnexpectedCborType -> 300+ InvalidCborValue -> 301+ InvalidCborArraySize -> 302+ InvalidCborMapSize -> 303+ DuplicateCborMapKey -> 304+ InvalidCborMapKey -> 305+ InvalidAddressType -> 400+ InvalidAddressFormat -> 401+ InvalidCredentialType -> 500+ InvalidPlutusDataConversion -> 600+ InvalidDatumType -> 601+ InvalidScriptLanguage -> 700+ InvalidNativeScriptType -> 701+ InvalidPlutusCostModel -> 702+ InvalidProposalProcedureType -> 800+ InvalidMetadatumConversion -> 900+ InvalidMetadatumTextStringSize -> 901+ InvalidMetadatumBoundedBytesSize -> 902+ InvalidHttpRequest -> 1000+ InsufficientBalance -> 1100+ UtxoNotFragmentedEnough -> 1101+ UtxoFullyDepleted -> 1102+ MaximumInputCountExceeded -> 1103+ UnbalancedSubTransactions -> 1104+ DisallowedSupplementalDatums -> 1105+ MissingRedeemer -> 1106+ ScriptEvaluationFailure -> 1200+ UnknownCode number -> number++-- | Whether a code has a name in this build of the package.+-- This does not indicate success: use equality with 'Success' for that purpose.+isKnown :: ErrorCode -> Bool+isKnown (UnknownCode _) = False+isKnown _ = True++-- | Every named code, including 'Success', once each, in numeric order.+-- Unknown numeric codes are excluded. Values have gaps; do not infer a code+-- by adding to or subtracting from another code.+knownCodes :: [ErrorCode]+knownCodes =+ [ Success,+ GenericFailure,+ InsufficientBufferSize,+ NullPointer,+ MemoryAllocationFailed,+ OutOfBoundsMemoryRead,+ OutOfBoundsMemoryWrite,+ InvalidArgument,+ InvalidUrl,+ ElementNotFound,+ EncodingFailure,+ DecodingFailure,+ ChecksumMismatch,+ InvalidJson,+ IntegerOverflow,+ IntegerUnderflow,+ ConversionFailed,+ IndexOutOfBounds,+ InvalidCertificateType,+ NotImplemented,+ InvalidPassphrase,+ IllegalState,+ DuplicateKey,+ JsonTypeMismatch,+ LossOfPrecision,+ InvalidMagic,+ InvalidChecksum,+ InvalidBlake2bHashSize,+ InvalidEd25519SignatureSize,+ InvalidEd25519PublicKeySize,+ InvalidEd25519PrivateKeySize,+ InvalidBip32PublicKeySize,+ InvalidBip32PrivateKeySize,+ InvalidBip32DerivationIndex,+ UnexpectedCborType,+ InvalidCborValue,+ InvalidCborArraySize,+ InvalidCborMapSize,+ DuplicateCborMapKey,+ InvalidCborMapKey,+ InvalidAddressType,+ InvalidAddressFormat,+ InvalidCredentialType,+ InvalidPlutusDataConversion,+ InvalidDatumType,+ InvalidScriptLanguage,+ InvalidNativeScriptType,+ InvalidPlutusCostModel,+ InvalidProposalProcedureType,+ InvalidMetadatumConversion,+ InvalidMetadatumTextStringSize,+ InvalidMetadatumBoundedBytesSize,+ InvalidHttpRequest,+ InsufficientBalance,+ UtxoNotFragmentedEnough,+ UtxoFullyDepleted,+ MaximumInputCountExceeded,+ UnbalancedSubTransactions,+ DisallowedSupplementalDatums,+ MissingRedeemer,+ ScriptEvaluationFailure+ ]
@@ -0,0 +1,47 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Inject script evaluation independently from balancing and signing. Evaluators+-- return budgets keyed by existing redeemer identifiers; they cannot replace+-- script arguments through their result. Applying budgets and recomputing+-- commitments remain explicit transaction-building operations.+--+-- @+-- import qualified Cometa.Evaluation as Evaluation+--+-- noScripts = Evaluation.Evaluator (\_ _ _ -> pure (Evaluation.mkBudgets []))+-- @+module Cometa.Evaluation+ ( Target (..),+ RedeemerId (..),+ Budgets,+ mkBudgets,+ budgets,+ Evaluator (..),+ evaluate,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.Evaluation+ ( Budgets,+ Evaluator (..),+ RedeemerId (..),+ Target (..),+ budgets,+ evaluate,+ mkBudgets,+ )
@@ -0,0 +1,33 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Execute compiled Plutus V1–V4 scripts in process with explicit protocol+-- context. Evaluation returns budgets without installing them or changing the+-- enclosing transaction. Script availability depends on the protocol version.+--+-- @+-- import qualified Cometa.Evaluation as Evaluation+-- import qualified Cometa.Evaluation.Native as Native+-- import qualified Cometa.Protocol.CostModels as Models+-- import qualified Cometa.SlotConfig as Slots+--+-- localEvaluator = Native.evaluator (Native.Config Slots.preview 12 Models.empty)+-- -- Evaluation.evaluate localEvaluator Evaluation.TopLevel transaction resolved+-- @+module Cometa.Evaluation.Native (Config (..), evaluator) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.Evaluation.Native (Config (..), evaluator)
@@ -0,0 +1,276 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Seven governance action alternatives assembled from validated components.+-- For example, @NoConfidence Nothing@ starts a new committee confidence chain.+-- These values describe proposals; they do not establish ledger eligibility.+module Cometa.Governance.Action+ ( Action (..),+ Removals,+ removalsFromList,+ removalsToList,+ EncodedRemovals,+ encodeRemovals,+ encodeRemovalsWith,+ decodeRemovals,+ fromRemovals,+ toRemovals,+ removalsCbor,+ removalsSetEncoding,+ withRemovalsSetEncoding,+ Withdrawals,+ withdrawalsFromList,+ withdrawalsToList,+ EncodedAction,+ encodeCbor,+ decodeCbor,+ fromAction,+ toAction,+ toCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Address.Reward as Reward+import Cometa.Credential (CommitteeCold, Credential, ScriptHash)+import qualified Cometa.Credential as Credential+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import Cometa.Governance.ActionId (ActionId)+import qualified Cometa.Governance.ActionId as ActionId+import Cometa.Governance.Committee (Members)+import qualified Cometa.Governance.Committee as Committee+import Cometa.Governance.Constitution (Constitution)+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Internal.ProposalCbor as Cbor+import qualified Cometa.Internal.SetEncoding as SetEncoding+import Cometa.Protocol.Parameters.Update (Update)+import qualified Cometa.Protocol.Parameters.Update as Update+import Cometa.Protocol.Version (ProtocolVersion)+import qualified Cometa.Protocol.Version as Version+import Cometa.UnitInterval (UnitInterval)+import qualified Cometa.UnitInterval as Interval+import Control.Monad (unless)+import Data.ByteString (ByteString)+import Data.List (sort, sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Cold credentials to remove, sorted by kind and hash. Repeated credentials+-- are retained. Ledger acceptance is a separate check.+newtype Removals = Removals [Credential CommitteeCold] deriving (Eq, Ord, Show)++-- | A standalone removal collection retaining its exact CBOR representation.+-- Equality and ordering compare bytes; inspect credentials with 'toRemovals'.+data EncodedRemovals = EncodedRemovals !ByteString !Removals deriving (Show)++instance Eq EncodedRemovals where+ left == right = removalsCbor left == removalsCbor right++instance Ord EncodedRemovals where+ compare left right = compare (removalsCbor left) (removalsCbor right)++-- | Unique reward accounts and lovelace amounts, including zero amounts.+newtype Withdrawals = Withdrawals (Map RewardAddress Word64) deriving (Eq, Ord, Show)++-- | A governance action. Optional predecessors reference the preceding action+-- of the corresponding purpose; 'Nothing' starts a chain. Optional script hashes+-- identify guardrails policies. Amounts and expiry epochs use unsigned 64-bit units.+data Action+ = -- | Previous parameter action, sparse changes, optional guardrails policy.+ ParameterChange !(Maybe ActionId) !Update !(Maybe ScriptHash)+ | -- | Previous hard-fork action and proposed protocol version.+ HardForkInitiation !(Maybe ActionId) !ProtocolVersion+ | -- | Reward accounts receiving treasury lovelace and optional policy.+ TreasuryWithdrawals !Withdrawals !(Maybe ScriptHash)+ | -- | Previous committee-confidence action.+ NoConfidence !(Maybe ActionId)+ | -- | Previous committee action, removals, additions with expiry, and quorum.+ UpdateCommittee !(Maybe ActionId) !Removals !Members !UnitInterval+ | -- | Previous constitution action and replacement constitution.+ NewConstitution !(Maybe ActionId) !Constitution+ | -- | Informational action without additional fields.+ InfoAction+ deriving (Eq, Show)++-- | Exact original CBOR plus its semantic action. Equality and ordering compare+-- bytes. Use 'toAction' when comparing action meanings.+data EncodedAction = EncodedAction !ByteString !Action deriving (Show)++instance Eq EncodedAction where+ left == right = toCbor left == toCbor right++instance Ord EncodedAction where+ compare left right = compare (toCbor left) (toCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | Sort by credential kind then hash bytes, retaining duplicate credentials.+removalsFromList :: [Credential CommitteeCold] -> Removals+removalsFromList = Removals . sort++-- | Sorted removal credentials, including duplicates.+removalsToList :: Removals -> [Credential CommitteeCold]+removalsToList (Removals values) = values++-- | Fresh tagged definite array of sorted credentials, retaining duplicates.+encodeRemovals :: Removals -> ByteString+encodeRemovals = Cbor.encode . removalsEncoding++-- | Fresh definite array with the requested outer set tag.+encodeRemovalsWith :: SetEncoding -> Removals -> ByteString+encodeRemovalsWith requested = SetEncoding.withEncoding requested . encodeRemovals++-- | Decode a standalone credential collection, retaining all imported bytes.+-- Optional tag 258, definite and indefinite arrays, and duplicate credentials+-- are accepted; invalid fields or trailing bytes return 'InvalidProposalCbor'.+decodeRemovals :: ByteString -> Either Error EncodedRemovals+decodeRemovals bytes = EncodedRemovals bytes . removalsFromList <$> Cbor.decode (Cbor.setList Cbor.credentialDecoder) bytes++-- | Assign fresh tagged encoding to a removal collection.+fromRemovals :: Removals -> EncodedRemovals+fromRemovals value = EncodedRemovals (encodeRemovals value) value++-- | Inspect sorted removal credentials without changing retained bytes.+toRemovals :: EncodedRemovals -> Removals+toRemovals (EncodedRemovals _ value) = value++-- | Exact imported bytes or fresh bytes assigned by 'fromRemovals'.+removalsCbor :: EncodedRemovals -> ByteString+removalsCbor (EncodedRemovals bytes _) = bytes++-- | Observe the exact standalone removal collection's outer set tag.+removalsSetEncoding :: EncodedRemovals -> SetEncoding+removalsSetEncoding = SetEncoding.encoding . removalsCbor++-- | Change only the outer tag, retaining every array and credential byte.+-- Requesting the current representation preserves the entire encoding exactly.+withRemovalsSetEncoding :: SetEncoding -> EncodedRemovals -> EncodedRemovals+withRemovalsSetEncoding requested (EncodedRemovals bytes values) =+ EncodedRemovals (SetEncoding.withEncoding requested bytes) values++-- | Reject repeated reward accounts with 'DuplicateTreasuryWithdrawal', even+-- when amounts agree. Values are lovelace; no minimum or positivity is imposed.+withdrawalsFromList :: [(RewardAddress, Word64)] -> Either Error Withdrawals+withdrawalsFromList values = Withdrawals <$> Cbor.uniqueMap DuplicateTreasuryWithdrawal values++-- | Entries ordered by exact reward-address bytes, matching fresh serialization.+withdrawalsToList :: Withdrawals -> [(RewardAddress, Word64)]+withdrawalsToList (Withdrawals values) = sortOn (Reward.toBytes . fst) (Map.toList values)++-- | Fresh definite CBOR with shortest integers and sorted maps/removal credentials.+-- Reconstructing semantic data can change transaction identity; 'toCbor' preserves+-- imported bytes instead.+encodeCbor :: Action -> ByteString+encodeCbor = Cbor.encode . actionEncoding++-- | Decode exactly one action and retain its original bytes. Definite and+-- indefinite containers and nonminimal integers are accepted; unknown variants,+-- wrong arity, invalid components, duplicate map keys and trailing data return+-- 'Cometa.Error.InvalidProposalCbor'.+decodeCbor :: ByteString -> Either Error EncodedAction+decodeCbor bytes = EncodedAction bytes <$> Cbor.decode actionDecoder bytes++-- | Assign fresh encoding to semantic data.+fromAction :: Action -> EncodedAction+fromAction value = EncodedAction (encodeCbor value) value++-- | Inspect semantic data without changing retained bytes.+toAction :: EncodedAction -> Action+toAction (EncodedAction _ value) = value++-- | Exact imported encoding, or the encoding assigned by 'fromAction'.+toCbor :: EncodedAction -> ByteString+toCbor (EncodedAction bytes _) = bytes++actionEncoding :: Action -> E.Encoding+actionEncoding value = case value of+ ParameterChange previous changes policy ->+ header 4 0+ <> predecessor previous+ <> Cbor.raw (Update.encodeCbor changes)+ <> policyEncoding policy+ HardForkInitiation previous version -> header 3 1 <> predecessor previous <> Cbor.raw (Version.encodeCbor version)+ TreasuryWithdrawals withdrawals policy -> header 3 2 <> withdrawalsEncoding withdrawals <> policyEncoding policy+ NoConfidence previous -> header 2 3 <> predecessor previous+ UpdateCommittee previous removals members quorum ->+ header 5 4+ <> predecessor previous+ <> removalsEncoding removals+ <> Cbor.raw (Committee.encodeMembers members)+ <> Cbor.raw (Interval.encodeCbor quorum)+ NewConstitution previous constitution -> header 3 5 <> predecessor previous <> Cbor.raw (Constitution.encodeCbor constitution)+ InfoAction -> header 1 6+ where+ header size code = E.encodeListLen size <> E.encodeWord code+ predecessor = Cbor.maybeEncoding (Cbor.raw . ActionId.encodeCbor)++policyEncoding :: Maybe ScriptHash -> E.Encoding+policyEncoding = Cbor.maybeEncoding (E.encodeBytes . Credential.scriptHashBytes)++removalsEncoding :: Removals -> E.Encoding+removalsEncoding (Removals values) = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap Cbor.credentialEncoding values++withdrawalsEncoding :: Withdrawals -> E.Encoding+withdrawalsEncoding value =+ E.encodeMapLen (fromIntegral (length values))+ <> foldMap (\(account, amount) -> E.encodeBytes (Reward.toBytes account) <> E.encodeWord64 amount) values+ where+ values = withdrawalsToList value++actionDecoder :: D.Decoder s Action+actionDecoder = do+ size <- D.decodeListLenOrIndef+ kind <- D.decodeWord+ let expected = case kind of 0 -> 4; 1 -> 3; 2 -> 3; 3 -> 2; 4 -> 5; 5 -> 3; _ -> 1+ case size of+ Just actual -> unless (actual == expected) (fail "Incorrect action arity")+ Nothing -> pure ()+ value <- variantDecoder kind+ Cbor.finishArray size+ pure value++variantDecoder :: Word -> D.Decoder s Action+variantDecoder kind = case kind of+ 0 -> ParameterChange <$> previous <*> (Update.toUpdate <$> Cbor.nested Update.decodeCbor) <*> policy+ 1 -> HardForkInitiation <$> previous <*> Cbor.nested Version.decodeCbor+ 2 -> TreasuryWithdrawals <$> withdrawalsDecoder <*> policy+ 3 -> NoConfidence <$> previous+ 4 ->+ UpdateCommittee+ <$> previous+ <*> (removalsFromList <$> Cbor.setList Cbor.credentialDecoder)+ <*> Cbor.nested Committee.decodeMembers+ <*> Cbor.nested Interval.decodeCbor+ 5 -> NewConstitution <$> previous <*> Cbor.nested Constitution.decodeCbor+ 6 -> pure InfoAction+ _ -> fail "Unknown governance action"+ where+ previous = Cbor.optional (Cbor.nested ActionId.decodeCbor)+ policy = Cbor.optional (D.decodeBytes >>= either (fail . show) pure . Credential.scriptHashFromBytes)++withdrawalsDecoder :: D.Decoder s Withdrawals+withdrawalsDecoder = do+ entries <- Cbor.entries $ do+ account <- D.decodeBytes >>= either (fail . show) pure . Reward.fromBytes+ (,) account <$> D.decodeWord64+ either (fail . show) pure (withdrawalsFromList entries)
@@ -0,0 +1,92 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Identify a governance proposal by its containing transaction and index.+-- These are standalone protocol identities; construction does not establish+-- that a proposal exists or is currently eligible for voting.+--+-- @+-- import qualified Cometa.Governance.ActionId as ActionId+-- import qualified Cometa.TransactionId as TransactionId+--+-- firstProposal :: TransactionId.TransactionId -> ActionId.ActionId+-- firstProposal transaction = ActionId.ActionId transaction 0+-- @+module Cometa.Governance.ActionId+ ( ActionId (..),+ encodeCbor,+ decodeCbor,+ toText,+ fromText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import Cometa.Error (Error (..))+import Cometa.Internal.Governance (ActionId (..))+import qualified Cometa.Internal.Governance as Internal+import qualified Cometa.TransactionId as TransactionId+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR @[transaction hash bytes, unsigned index]@ with the+-- shortest integer encoding. The index retains the full unsigned 64-bit range.+encodeCbor :: ActionId -> ByteString+encodeCbor = Internal.encodeActionId++-- | Decode exactly one complete action identifier. Both definite and indefinite+-- arrays and nonminimal integer encodings are accepted. Wrong arity, hash length,+-- non-unsigned index or trailing bytes returns+-- 'Cometa.Error.InvalidGovernanceCbor'. The result is semantic data; this+-- function does not retain the original encoding.+decodeCbor :: ByteString -> Either Error ActionId+decodeCbor = Internal.decodeActionId++-- | Encode the CIP-129 @gov_action@ Bech32 identifier: 32 transaction hash+-- bytes followed by the one-byte proposal index. Indices above 255 return+-- 'InvalidGovernanceActionTextIndex' without truncation. CBOR retains the full+-- unsigned 64-bit index range independently of this narrower display format.+toText :: ActionId -> Either Error Text+toText (ActionId transaction actionIndex)+ | actionIndex > 255 = Left (InvalidGovernanceActionTextIndex actionIndex)+ | otherwise = do+ prefix <- either (const (Left (NativeContractViolation "Invalid built-in governance action prefix"))) Right (Bech32.humanReadablePartFromText "gov_action")+ pure (Bech32.encodeLenient prefix (Bech32.dataPartFromBytes (TransactionId.toBytes transaction <> B.singleton (fromIntegral actionIndex))))++-- | Decode a checksummed CIP-129 @gov_action@ identifier with exactly 33+-- payload bytes. Uniform upper or lower case is accepted; mixed case, other+-- prefixes, incorrect padding, checksum or length returns+-- 'InvalidGovernanceActionText'. The decoded index is always 0 through 255.+fromText :: Text -> Either Error ActionId+fromText text = do+ (prefix, part) <- either (const failure) Right (Bech32.decodeLenient text)+ unlessValid (Bech32.humanReadablePartToText prefix == "gov_action")+ payload <- maybe failure Right (Bech32.dataPartToBytes part)+ unlessValid (B.length payload == 33)+ transaction <- TransactionId.fromBytes (B.take 32 payload)+ case B.uncons (B.drop 32 payload) of+ Just (actionIndex, _) -> Right (ActionId transaction (fromIntegral actionIndex))+ Nothing -> failure+ where+ failure :: Either Error a+ failure = Left (InvalidGovernanceActionText "Expected a CIP-129 gov_action identifier with a 33-byte payload")+ unlessValid True = Right ()+ unlessValid False = failure
@@ -0,0 +1,71 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Off-chain governance metadata locations and hashes. Validate external text+-- and bytes once, then assemble 'Anchor' values with its total constructor.+-- Locations are not fetched or checked for URI syntax.+--+-- @+-- import qualified Cometa.Governance.Anchor as Anchor+--+-- attach :: Anchor.Url -> Anchor.DataHash -> Anchor.Anchor+-- attach = Anchor.Anchor+-- @+module Cometa.Governance.Anchor+ ( Url,+ mkUrl,+ urlText,+ DataHash,+ dataHashFromBytes,+ dataHashBytes,+ hashData,+ Anchor (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error)+import Cometa.Internal.Governance (Anchor (..), DataHash, Url, dataHashBytes, dataHashFromBytes, mkUrl, urlText)+import qualified Cometa.Internal.Governance as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Hash the exact off-chain payload with BLAKE2b-256. Empty input returns+-- 'Cometa.Error.NativeError' with the native out-of-bounds-memory-read code,+-- matching the BLAKE2b boundary. Native allocation or hashing failures also return+-- 'Cometa.Error.NativeError'. No JSON parsing or normalization occurs.+hashData :: ByteString -> IO (Either Error DataHash)+hashData bytes = do+ result <- Blake2b.compute 32 bytes+ pure (result >>= dataHashFromBytes . Blake2b.toBytes)++-- | Fresh definite CBOR @[URL text, hash bytes]@. Re-encoding imported semantic+-- data may change its containing transaction's encoding; preserve the original+-- enclosing CBOR when identity matters.+encodeCbor :: Anchor -> ByteString+encodeCbor = Internal.encodeAnchor++-- | Decode one complete anchor, accepting definite or indefinite arrays and+-- nonminimal lengths. URL validation, the exact 32-byte hash and array arity+-- are enforced; invalid input or trailing bytes returns+-- 'Cometa.Error.InvalidGovernanceCbor'. This returns semantic data, not an+-- encoding-preserving wrapper.+decodeCbor :: ByteString -> Either Error Anchor+decodeCbor = Internal.decodeAnchor
@@ -0,0 +1,109 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Constitutional committee cold authorities and their expiry epochs.+-- Use 'membersFromList' for runtime entries, then assemble @Committee members quorum@.+module Cometa.Governance.Committee+ ( Members,+ membersFromList,+ membersToList,+ emptyMembers,+ Committee (..),+ encodeCbor,+ decodeCbor,+ encodeMembers,+ decodeMembers,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Credential (CommitteeCold, Credential)+import Cometa.Error (Error (..))+import qualified Cometa.Internal.ProposalCbor as Cbor+import Cometa.UnitInterval (UnitInterval)+import qualified Cometa.UnitInterval as Interval+import Data.ByteString (ByteString)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Unique cold authorities, ordered by credential kind then exact hash bytes.+-- Expiry epochs retain the full unsigned 64-bit range; this is not era validation.+newtype Members = Members (Map (Credential CommitteeCold) Word64)+ deriving (Eq, Ord, Show)++-- | Membership and the exact validated fraction required for a successful vote.+data Committee = Committee+ { -- | Cold authorities and their expiry epochs.+ committeeMembers :: !Members,+ -- | Fraction of committee votes required for success, from zero through one.+ committeeQuorum :: !UnitInterval+ }+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate unique cold authorities. Duplicate keys return+-- 'DuplicateCommitteeMember', even when expiry epochs agree.+membersFromList :: [(Credential CommitteeCold, Word64)] -> Either Error Members+membersFromList values = Members <$> Cbor.uniqueMap DuplicateCommitteeMember values++-- | Entries in credential order, retaining expiry epochs exactly.+membersToList :: Members -> [(Credential CommitteeCold, Word64)]+membersToList (Members values) = Map.toAscList values++-- | No committee members.+emptyMembers :: Members+emptyMembers = Members Map.empty++-- | Fresh map encoding, sorted by credential kind and hash.+encodeMembers :: Members -> ByteString+encodeMembers members =+ Cbor.encode+ ( E.encodeMapLen (fromIntegral (length values))+ <> foldMap (\(key, epoch) -> Cbor.credentialEncoding key <> E.encodeWord64 epoch) values+ )+ where+ values = membersToList members++-- | Decode one complete members map, rejecting duplicate authorities.+decodeMembers :: ByteString -> Either Error Members+decodeMembers = Cbor.decode $ do+ pairs <- Cbor.entries ((,) <$> Cbor.credentialDecoder <*> D.decodeWord64)+ either (fail . show) pure (membersFromList pairs)++-- | Fresh definite array containing members and quorum.+encodeCbor :: Committee -> ByteString+encodeCbor (Committee members quorum) =+ Cbor.encode+ (E.encodeListLen 2 <> Cbor.raw (encodeMembers members) <> Cbor.raw (Interval.encodeCbor quorum))++-- | Decode one complete committee; malformed values, duplicate members and+-- trailing bytes return 'Cometa.Error.InvalidProposalCbor'.+decodeCbor :: ByteString -> Either Error Committee+decodeCbor =+ Cbor.decode+ ( Cbor.array+ 2+ ( Committee+ <$> Cbor.nested decodeMembers+ <*> Cbor.nested Interval.decodeCbor+ )+ )
@@ -0,0 +1,70 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | A constitution's off-chain anchor and optional guardrails script hash.+-- Assembly is total: @Constitution anchor Nothing@ has no guardrails script.+module Cometa.Governance.Constitution+ ( Constitution (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Credential (ScriptHash)+import qualified Cometa.Credential as C+import Cometa.Error (Error)+import Cometa.Governance.Anchor (Anchor)+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Internal.ProposalCbor as Cbor+import Data.ByteString (ByteString)++-- TYPES ----------------------------------------------------------------------++-- | Immutable metadata and an optional exact 28-byte guardrails hash.+data Constitution = Constitution+ { -- | Off-chain constitution location and expected payload hash.+ constitutionAnchor :: !Anchor,+ -- | Optional guardrails script hash; absence encodes as null.+ constitutionScript :: !(Maybe ScriptHash)+ }+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR; absence of a guardrails script encodes as null.+encodeCbor :: Constitution -> ByteString+encodeCbor (Constitution anchor script) =+ Cbor.encode+ ( E.encodeListLen 2+ <> Cbor.raw (Anchor.encodeCbor anchor)+ <> Cbor.maybeEncoding (E.encodeBytes . C.scriptHashBytes) script+ )++-- | Decode one complete constitution; invalid schema or trailing bytes returns+-- 'Cometa.Error.InvalidProposalCbor'. This returns semantic data.+decodeCbor :: ByteString -> Either Error Constitution+decodeCbor =+ Cbor.decode+ ( Cbor.array+ 2+ ( Constitution+ <$> Cbor.nested Anchor.decodeCbor+ <*> Cbor.optional (D.decodeBytes >>= either (fail . show) pure . C.scriptHashFromBytes)+ )+ )
@@ -0,0 +1,95 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Delegation targets distinguish a DRep credential from the predefined+-- always-abstain and always-no-confidence targets. Special targets cannot be+-- used as voting authorities.+--+-- @+-- import qualified Cometa.Governance.DRep as DRep+--+-- abstainingTarget :: DRep.DRep+-- abstainingTarget = DRep.AlwaysAbstain+-- @+module Cometa.Governance.DRep+ ( DRep (..),+ encodeCbor,+ decodeCbor,+ toText,+ fromText,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import Cometa.Internal.Governance (DRep (..))+import qualified Cometa.Internal.Governance as Internal+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode fresh definite CBOR: @[0, key hash]@, @[1, script hash]@, @[2]@+-- (always abstain), or @[3]@ (always no confidence).+encodeCbor :: DRep -> ByteString+encodeCbor = Internal.encodeDRep++-- | Decode one complete DRep. Definite or indefinite arrays and nonminimal+-- unsigned codes are accepted. Codes, arity and 28-byte credential lengths are+-- checked; invalid input or trailing bytes returns+-- 'Cometa.Error.InvalidGovernanceCbor'. Original encoding is not retained.+decodeCbor :: ByteString -> Either Error DRep+decodeCbor = Internal.decodeDRep++-- | Encode a credential DRep as CIP-129 @drep@ Bech32 text, using header+-- @0x22@ for a key or @0x23@ for a script and its 28-byte hash. The special+-- abstain and no-confidence delegation targets have no credential identifier;+-- they return 'UnsupportedOperation'.+toText :: DRep -> Either Error Text+toText (DRepCredential credential) = do+ prefix <- either (const (Left (NativeContractViolation "Invalid built-in DRep prefix"))) Right (Bech32.humanReadablePartFromText "drep")+ let payload = case credential of+ Credential.KeyCredential hash -> B.cons 0x22 (Credential.keyHashBytes hash)+ Credential.ScriptCredential hash -> B.cons 0x23 (Credential.scriptHashBytes hash)+ pure (Bech32.encodeLenient prefix (Bech32.dataPartFromBytes payload))+toText AlwaysAbstain = Left (UnsupportedOperation "DRep.toText: always-abstain has no credential identifier")+toText AlwaysNoConfidence = Left (UnsupportedOperation "DRep.toText: always-no-confidence has no credential identifier")++-- | Import either CIP-105 (28-byte @drep@ key or @drep_script@ script) or+-- CIP-129 (29-byte @drep@ header and hash) text. Uniform upper or lower case is+-- accepted. Mixed case, invalid checksum/padding, other prefixes or headers and+-- wrong lengths return 'InvalidDRepText'. Re-encoding always produces CIP-129.+fromText :: Text -> Either Error DRep+fromText text = do+ (prefix, part) <- either (const failure) Right (Bech32.decodeLenient text)+ payload <- maybe failure Right (Bech32.dataPartToBytes part)+ case (Bech32.humanReadablePartToText prefix, B.length payload) of+ ("drep", 28) -> key payload+ ("drep_script", 28) -> script payload+ ("drep", 29) -> case B.uncons payload of+ Just (0x22, hash) -> key hash+ Just (0x23, hash) -> script hash+ _ -> failure+ _ -> failure+ where+ failure :: Either Error a+ failure = Left (InvalidDRepText "Expected a CIP-105 or CIP-129 DRep credential identifier")+ key payload = DRepCredential . Credential.KeyCredential <$> Credential.keyHashFromBytes payload+ script payload = DRepCredential . Credential.ScriptCredential <$> Credential.scriptHashFromBytes payload
@@ -0,0 +1,195 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Governance proposals and their index-sensitive ordered collections.+-- Assemble @Proposal deposit rewardAccount action anchor@ from validated values.+-- Deposit amounts are lovelace; current protocol requirements must be queried+-- separately. This module does not submit or validate transactions.+module Cometa.Governance.Proposal+ ( Proposal (..),+ Proposals,+ fromList,+ toList,+ empty,+ append,+ EncodedProposal,+ encodeCbor,+ decodeCbor,+ fromProposal,+ toProposal,+ toCbor,+ EncodedProposals,+ encodeProposals,+ encodeProposalsWith,+ setEncoding,+ withSetEncoding,+ decodeProposals,+ fromProposals,+ toProposals,+ proposalsCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Address.Reward as Reward+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error)+import Cometa.Governance.Action (Action)+import qualified Cometa.Governance.Action as Action+import Cometa.Governance.Anchor (Anchor)+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Internal.ProposalCbor as Cbor+import qualified Cometa.Internal.SetEncoding as SetEncoding+import Data.ByteString (ByteString)+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Deposit, its return account, the proposed action and mandatory metadata.+data Proposal = Proposal+ { -- | Lovelace deposited for the proposal, from zero through 2^64 - 1.+ proposalDeposit :: !Word64,+ -- | Reward account to receive the returned deposit.+ proposalReturnAccount :: !RewardAddress,+ -- | Requested governance change.+ proposalAction :: !Action,+ -- | Mandatory off-chain proposal metadata.+ proposalAnchor :: !Anchor+ }+ deriving (Eq, Show)++-- | Ordered proposals. Position determines proposal identity; duplicates and+-- empty collections are retained.+newtype Proposals = Proposals [Proposal] deriving (Eq, Show)++-- | One proposal retaining its original CBOR. Equality and ordering compare bytes.+data EncodedProposal = EncodedProposal !ByteString !Proposal deriving (Show)++instance Eq EncodedProposal where+ left == right = toCbor left == toCbor right++instance Ord EncodedProposal where+ compare left right = compare (toCbor left) (toCbor right)++-- | An ordered collection retaining exact imported bytes, including tag presence.+-- Equality and ordering compare those bytes; semantic inspection uses 'toProposals'.+data EncodedProposals = EncodedProposals !ByteString !Proposals deriving (Show)++instance Eq EncodedProposals where+ left == right = proposalsCbor left == proposalsCbor right++instance Ord EncodedProposals where+ compare left right = compare (proposalsCbor left) (proposalsCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | Preserve all proposals in input order, including duplicates.+fromList :: [Proposal] -> Proposals+fromList = Proposals++-- | Proposals in their index order.+toList :: Proposals -> [Proposal]+toList (Proposals values) = values++-- | No proposals.+empty :: Proposals+empty = Proposals []++-- | Append without sorting or deduplication. Associative, with 'empty' as identity.+append :: Proposals -> Proposals -> Proposals+append (Proposals left) (Proposals right) = Proposals (left <> right)++-- | Fresh definite CBOR with shortest deposit encoding.+encodeCbor :: Proposal -> ByteString+encodeCbor (Proposal deposit account action anchor) =+ Cbor.encode+ ( E.encodeListLen 4+ <> E.encodeWord64 deposit+ <> E.encodeBytes (Reward.toBytes account)+ <> Cbor.raw (Action.encodeCbor action)+ <> Cbor.raw (Anchor.encodeCbor anchor)+ )++-- | Decode one complete proposal and retain exact original bytes. Malformed+-- fields, non-reward return addresses or trailing bytes return+-- 'Cometa.Error.InvalidProposalCbor'.+decodeCbor :: ByteString -> Either Error EncodedProposal+decodeCbor bytes = EncodedProposal bytes <$> Cbor.decode proposalDecoder bytes++-- | Assign fresh CBOR to a proposal.+fromProposal :: Proposal -> EncodedProposal+fromProposal value = EncodedProposal (encodeCbor value) value++-- | Inspect the proposal while retaining its encoded wrapper unchanged.+toProposal :: EncodedProposal -> Proposal+toProposal (EncodedProposal _ value) = value++-- | Exact imported bytes or fresh bytes assigned by 'fromProposal'.+toCbor :: EncodedProposal -> ByteString+toCbor (EncodedProposal bytes _) = bytes++-- | Fresh tag-258 definite array, preserving proposal order and duplicates.+encodeProposals :: Proposals -> ByteString+encodeProposals (Proposals values) =+ Cbor.encode+ (E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . encodeCbor) values)++-- | Decode a tagged or untagged collection with definite or indefinite array.+-- Order and duplicates are preserved; invalid schema returns+-- 'Cometa.Error.InvalidProposalCbor'. Exact original bytes are retained.+decodeProposals :: ByteString -> Either Error EncodedProposals+decodeProposals bytes = EncodedProposals bytes . Proposals <$> Cbor.decode (Cbor.setList proposalDecoder) bytes++-- | Assign fresh CBOR to an ordered proposal collection.+fromProposals :: Proposals -> EncodedProposals+fromProposals value = EncodedProposals (encodeProposals value) value++-- | Inspect proposals in index order without changing retained CBOR.+toProposals :: EncodedProposals -> Proposals+toProposals (EncodedProposals _ value) = value++-- | Exact imported collection CBOR, or fresh encoding from 'fromProposals'.+proposalsCbor :: EncodedProposals -> ByteString+proposalsCbor (EncodedProposals bytes _) = bytes++-- | Fresh definite collection with the requested outer tag. Nested proposals+-- keep their usual encoding; order and duplicates are retained.+encodeProposalsWith :: SetEncoding -> Proposals -> ByteString+encodeProposalsWith requested = SetEncoding.withEncoding requested . encodeProposals++-- | Observe the exact proposal collection's outer set tag.+setEncoding :: EncodedProposals -> SetEncoding+setEncoding = SetEncoding.encoding . proposalsCbor++-- | Change only the outer tag, retaining every array and proposal byte.+-- Requesting the current representation preserves the complete encoding exactly.+withSetEncoding :: SetEncoding -> EncodedProposals -> EncodedProposals+withSetEncoding requested (EncodedProposals bytes values) =+ EncodedProposals (SetEncoding.withEncoding requested bytes) values++proposalDecoder :: D.Decoder s Proposal+proposalDecoder =+ Cbor.array+ 4+ ( Proposal+ <$> D.decodeWord64+ <*> (D.decodeBytes >>= either (fail . show) pure . Reward.fromBytes)+ <*> (Action.toAction <$> Cbor.nested Action.decodeCbor)+ <*> Cbor.nested Anchor.decodeCbor+ )
@@ -0,0 +1,121 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Assemble role-aware votes on governance actions. Validate identities once,+-- create a 'VotingProcedure' with an optional explanation, and associate it with+-- a voter/action pair. Repeated pairs fail explicitly rather than lose votes.+--+-- @+-- import qualified Cometa.Governance.ActionId as ActionId+-- import qualified Cometa.Governance.Voting as Voting+--+-- support :: Voting.Voter -> ActionId.ActionId -> Voting.VotingProcedures+-- support voter action =+-- Voting.singleton voter action (Voting.VotingProcedure Voting.Yes Nothing)+-- @+module Cometa.Governance.Voting+ ( -- * Choices and authorities+ Vote (..),+ Voter (..),+ VotingProcedure (..),+ encodeVoter,+ decodeVoter,+ encodeProcedure,+ decodeProcedure,++ -- * Unique voter/action collections+ VotingProcedures,+ empty,+ singleton,+ fromList,+ toList,+ insert,+ lookup,+ merge,++ -- * Encoding identity+ EncodedVotingProcedures,+ encodeCbor,+ decodeCbor,+ fromVotingProcedures,+ toVotingProcedures,+ toCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.Governance+ ( EncodedVotingProcedures,+ Vote (..),+ Voter (..),+ VotingProcedure (..),+ VotingProcedures,+ empty,+ fromList,+ fromVotingProcedures,+ insert,+ lookup,+ merge,+ singleton,+ toCbor,+ toList,+ toVotingProcedures,+ )+import qualified Cometa.Internal.Governance as Internal+import Data.ByteString (ByteString)+import Prelude hiding (lookup)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a voter as definite CBOR @[kind, hash bytes]@. Kinds are 0 committee+-- key, 1 committee script, 2 DRep key, 3 DRep script, and 4 stake pool key.+encodeVoter :: Voter -> ByteString+encodeVoter = Internal.encodeVoter++-- | Decode exactly one voter, enforcing kind, arity, and 28-byte hash length.+-- Definite/indefinite arrays and nonminimal codes are accepted. Invalid input+-- or trailing bytes returns 'Cometa.Error.InvalidGovernanceCbor'. The original+-- encoding is not retained.+decodeVoter :: ByteString -> Either Error Voter+decodeVoter = Internal.decodeVoter++-- | Encode a procedure as definite CBOR @[choice, anchor or null]@, using+-- choice codes 0 (No), 1 (Yes) and 2 (Abstain).+encodeProcedure :: VotingProcedure -> ByteString+encodeProcedure = Internal.encodeProcedure++-- | Decode exactly one procedure with a validated optional anchor. Invalid+-- choice, arity, anchor, or trailing bytes returns+-- 'Cometa.Error.InvalidGovernanceCbor'. Definite/indefinite arrays and nonminimal+-- codes are accepted; original encoding is not retained.+decodeProcedure :: ByteString -> Either Error VotingProcedure+decodeProcedure = Internal.decodeProcedure++-- | Encode fresh nested maps ordered by voter kind/hash, then transaction+-- hash/index, using definite containers and shortest integers. Re-encoding+-- inspected external data can change its containing transaction identity;+-- 'toCbor' preserves the imported encoding instead.+encodeCbor :: VotingProcedures -> ByteString+encodeCbor = Internal.encodeVoting++-- | Decode exactly one nested voting map, preserving its exact input bytes.+-- Definite/indefinite containers and nonminimal encodings are accepted. Duplicate+-- voter keys, duplicate action keys within a voter, and empty inner maps are+-- rejected. Malformed CBOR, invalid schema, bounds, UTF-8, or trailing bytes+-- returns 'Cometa.Error.InvalidGovernanceCbor'.+decodeCbor :: ByteString -> Either Error EncodedVotingProcedures+decodeCbor = Internal.decodeVoting
@@ -0,0 +1,527 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Inspect Cardano domain values using the CIP-116 JSON representation.+-- Large ledger integers become decimal strings and binary fields use explicit+-- text encodings. Object key order is insignificant. Inspection does not change+-- input encodings, validate ledger acceptance, sign or submit transactions.+-- Results are descriptive JSON, not exact-CBOR interchange. Render with+-- 'Data.Aeson.encode'. Expected validation/native failures remain explicit.+--+-- @+-- inspected <- Inspection.output output+-- -- fmap Data.Aeson.encode inspected+-- @+module Cometa.Inspection+ ( transaction,+ subTransaction,+ body,+ subBody,+ value,+ script,+ nativeScript,+ plutusScript,+ credential,+ certificate,+ governanceAction,+ proposal,+ poolParameters,+ protocolUpdate,+ plutusData,+ output,+ witnesses,+ utxo,+ drep,+ actionId,+ anchor,+ votingProcedures,+ metadatum,+ metadata,+ auxiliaryData,+ input,+ datum,+ redeemer,+ exUnits,+ protocolVersion,+ unitInterval,+ relay,+ poolMetadata,+ constitution,+ voter,+ votingProcedure,+ verificationWitness,+ bootstrapWitness,+ costModel,+ costModels,+ exUnitPrices,+ poolVotingThresholds,+ drepVotingThresholds,+ proposedUpdates,+ updateProposal,+ balanceInterval,+ balanceIntervals,+ directDeposits,+ requiredGuards,+ assetName,+ blake2bHash,+ blsKey,+ committeeMembers,+ withdrawals,+ hashes,+ guards,+ subTransactions,+ assets,+ assetEntries,+ policyAssets,+ policyAssetEntries,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as Encoding+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetName as Name+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Hash+import qualified Cometa.Encoding.Collections as Collections+import Cometa.Error (Error (InvalidValueCbor, NativeContractViolation))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.Inspection as Internal+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Pool.BlsKey as Bls+import qualified Cometa.Pool.Metadata as PoolMetadata+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Pool.Relay as Relay+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.DRepVotingThresholds as DRepThresholds+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as ExUnits+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.PoolVotingThresholds as PoolThresholds+import qualified Cometa.Protocol.ProposedUpdates as Proposed+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import Cometa.Transaction.Inspection (body, subBody, subTransaction, transaction)+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Data.Aeson (Value (Object), toJSON)+import qualified Data.Aeson.KeyMap as KeyMap+import Data.ByteString (ByteString)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Text (Text)+import Data.Word (Word64)+import Foreign.C.Types (CUInt)++-- DEFINITIONS ----------------------------------------------------------------++-- | Inspect a standalone value, including signed native-asset quantities.+-- Ada must be nonnegative and all quantities must fit the native signed+-- 64-bit range. Invalid quantities return the errors from 'Value.encodeCbor'.+value :: Value.Value -> IO (Either Error Value)+value amount = case Value.encodeCbor amount of+ Left failure -> pure (Left failure)+ Right bytes -> Internal.inspect "inspection.value" 4 bytes++-- | Inspect a script with a @native_script@ or @plutus_script@ tag and payload.+script :: Script.Script -> IO (Either Error Value)+script = Internal.inspect "inspection.script" 5 . Script.encodeCbor++-- | Inspect only the native-script payload, including recursive signature,+-- threshold, time and guard conditions. Omits the outer 'script' tag wrapper;+-- this is the CIP-116 schema, distinct from native-script construction JSON.+nativeScript :: Native.NativeScript -> IO (Either Error Value)+nativeScript = scriptPayload . Script.Native++-- | Inspect the language name and compiled bytes of a Plutus script, without+-- the outer 'script' tag wrapper. Does not check program executability.+plutusScript :: Plutus.PlutusScript -> IO (Either Error Value)+plutusScript = scriptPayload . Script.Plutus++scriptPayload :: Script.Script -> IO (Either Error Value)+scriptPayload suppliedScript = do+ result <- script suppliedScript+ pure $ do+ json <- result+ case json of+ Object fields -> maybe failure Right (KeyMap.lookup "value" fields)+ _ -> failure+ where+ failure = Left (NativeContractViolation "inspection.script.payload")++-- | Inspect a role-indexed key or script credential as its tagged hash.+credential :: Credential.Credential purpose -> IO (Either Error Value)+credential = Internal.inspect "inspection.credential" 6 . Credential.encodeCbor++-- | Inspect one staking, pool, committee or DRep certificate. Deposits, refunds+-- and epochs describe the supplied certificate without checking chain state.+certificate :: Certificate.Certificate -> IO (Either Error Value)+certificate = Internal.inspect "inspection.certificate" 7 . Certificate.encodeCbor++-- | Inspect a governance action, including its concrete action tag and fields.+-- Does not establish eligibility or interpret protocol activation rules.+governanceAction :: Action.Action -> IO (Either Error Value)+governanceAction = Internal.inspect "inspection.governanceAction" 19 . Action.encodeCbor++-- | Inspect the deposit, return account, governance action and proposal anchor.+proposal :: Proposal.Proposal -> IO (Either Error Value)+proposal = Internal.inspect "inspection.proposal" 8 . Proposal.encodeCbor++-- | Inspect the complete supplied pool registration parameters, including BLS,+-- relay, owner and metadata fields when present.+poolParameters :: Pool.PoolParameters -> IO (Either Error Value)+poolParameters = Internal.inspect "inspection.poolParameters" 9 . Pool.encodeCbor++-- | Inspect supplied sparse protocol changes. Absent fields stay absent;+-- no current protocol snapshot or ledger-state query is performed.+protocolUpdate :: Update.Update -> IO (Either Error Value)+protocolUpdate = Internal.inspect "inspection.protocolUpdate" 10 . Update.encodeCbor++-- | Inspect exact encoded script data. Arbitrary integers use decimal strings;+-- map entry order and duplicate keys remain represented in the JSON arrays.+plutusData :: Data.EncodedPlutusData -> IO (Either Error Value)+plutusData = Internal.inspect "inspection.plutusData" 11 . Data.toCbor++-- | Inspect one output's address, value, datum and optional reference script.+output :: Output.Output -> IO (Either Error Value)+output = Internal.inspect "inspection.output" 12 . Output.encodeCbor++-- | Inspect exact witness fields, including key witnesses, scripts, data and+-- redeemers. Does not verify signatures, budgets or script execution.+witnesses :: Witnesses.EncodedWitnesses -> IO (Either Error Value)+witnesses = Internal.inspect "inspection.witnesses" 13 . Witnesses.toCbor++-- | Inspect an input reference paired with its resolved output. Does not check+-- whether the output exists or is currently unspent on a network.+utxo :: Utxo.Utxo -> IO (Either Error Value)+utxo = Internal.inspect "inspection.utxo" 14 . Utxo.encodeCbor++-- | Inspect a credential DRep or either predefined delegation target.+drep :: DRep.DRep -> IO (Either Error Value)+drep = Internal.inspect "inspection.drep" 15 . DRep.encodeCbor++-- | Inspect a transaction identifier and governance-action index.+actionId :: ActionId.ActionId -> IO (Either Error Value)+actionId = Internal.inspect "inspection.actionId" 16 . ActionId.encodeCbor++-- | Inspect the metadata URL and content hash without fetching the URL.+anchor :: Anchor.Anchor -> IO (Either Error Value)+anchor = Internal.inspect "inspection.anchor" 17 . Anchor.encodeCbor++-- | Inspect voter/action choices and optional explanation anchors. Collection+-- order follows the supplied validated representation; no vote is submitted.+votingProcedures :: Voting.VotingProcedures -> IO (Either Error Value)+votingProcedures = Internal.inspect "inspection.votingProcedures" 18 . Voting.encodeCbor++-- | Inspect one validated metadata value using the tagged CIP-116 schema.+-- Nested map order and duplicate keys remain represented in the result. This+-- differs from the detailed and plain JSON codecs in "Cometa.Metadata".+metadatum :: Metadata.Metadatum -> IO (Either Error Value)+metadatum = Internal.inspect "inspection.metadatum" 20 . Metadata.encodeMetadatumCbor++-- | Inspect transaction metadata as an ordered array of label/value entries.+-- Labels use decimal strings; each value uses the tagged CIP-116 schema.+metadata :: Metadata.Metadata -> IO (Either Error Value)+metadata = Internal.inspect "inspection.metadata" 21 . Metadata.encodeCbor++-- | Inspect exact auxiliary data, including metadata and native/Plutus scripts.+-- Retains source encodings and auxiliary-data hashes without recalculation.+auxiliaryData :: Auxiliary.EncodedAuxiliaryData -> IO (Either Error Value)+auxiliaryData = Internal.inspect "inspection.auxiliaryData" 22 . Auxiliary.toCbor++-- | Inspect the transaction identifier and output index of an input reference.+-- Does not resolve the referenced output or establish its availability.+input :: Input.Input -> IO (Either Error Value)+input = Internal.inspect "inspection.input" 23 . Input.encodeCbor++-- | Inspect a datum hash or inline datum. 'Datum.NoDatum' returns 'Nothing'+-- without allocating a native datum;+-- the other alternatives return the tagged native CIP-116 datum object.+-- Inline data retains its arbitrary integers, map order and duplicate keys.+datum :: Datum.Datum -> IO (Either Error (Maybe Value))+datum Datum.NoDatum = pure (Right Nothing)+datum (Datum.DatumHash hash) = inspectDatum (Encoding.encodeListLen 2 <> Encoding.encodeWord 0 <> Encoding.encodeBytes (Datum.hashBytes hash))+datum (Datum.InlineDatum payload) = inspectDatum (Encoding.encodeListLen 2 <> Encoding.encodeWord 1 <> Encoding.encodeTag 24 <> Encoding.encodeBytes (Data.toCbor payload))++inspectDatum :: Encoding.Encoding -> IO (Either Error (Maybe Value))+inspectDatum = fmap (fmap Just) . Internal.inspect "inspection.datum" 24 . Write.toStrictByteString++-- | Inspect a redeemer's purpose, index, script data and declared execution+-- units. Does not execute the script or check its budget against a transaction.+redeemer :: Redeemer.Redeemer -> IO (Either Error Value)+redeemer = Internal.inspect "inspection.redeemer" 25 . Redeemer.encodeCbor++-- | Inspect declared memory and CPU steps as decimal strings; no evaluation is performed.+exUnits :: ExUnits.ExUnits -> IO (Either Error Value)+exUnits = Internal.inspect "inspection.exUnits" 26 . ExUnits.encodeCbor++-- | Inspect protocol major and minor versions as JSON numbers.+protocolVersion :: Version.ProtocolVersion -> IO (Either Error Value)+protocolVersion = Internal.inspect "inspection.protocolVersion" 27 . Version.encodeCbor++-- | Inspect the exact rational numerator and denominator as decimal strings.+unitInterval :: Unit.UnitInterval -> IO (Either Error Value)+unitInterval = Internal.inspect "inspection.unitInterval" 28 . Unit.encodeCbor++-- | Inspect a pool relay, preserving absent ports and IP addresses as null.+relay :: Relay.Relay -> IO (Either Error Value)+relay = Internal.inspect "inspection.relay" 29 . Relay.encodeCbor++-- | Inspect a pool metadata URL and hash without fetching the URL.+poolMetadata :: PoolMetadata.Metadata -> IO (Either Error Value)+poolMetadata = Internal.inspect "inspection.poolMetadata" 30 . PoolMetadata.encodeCbor++-- | Inspect a constitution anchor and optional guardrails hash; absence omits the hash.+constitution :: Constitution.Constitution -> IO (Either Error Value)+constitution = Internal.inspect "inspection.constitution" 31 . Constitution.encodeCbor++-- | Inspect a committee, DRep or stake-pool voting identity with its role tag.+voter :: Voting.Voter -> IO (Either Error Value)+voter = Internal.inspect "inspection.voter" 32 . Voting.encodeVoter++-- | Inspect a vote choice and optional explanation anchor; absence omits the anchor.+votingProcedure :: Voting.VotingProcedure -> IO (Either Error Value)+votingProcedure = Internal.inspect "inspection.votingProcedure" 33 . Voting.encodeProcedure++-- | Inspect a verification key and signature without verifying the signature.+verificationWitness :: Witness.VerificationWitness -> IO (Either Error Value)+verificationWitness = Internal.inspect "inspection.verificationWitness" 34 . Witness.encodeCbor++-- | Inspect a Byron witness key, signature, chain code and attributes as hexadecimal.+bootstrapWitness :: Witness.BootstrapWitness -> IO (Either Error Value)+bootstrapWitness = Internal.inspect "inspection.bootstrapWitness" 35 . Witness.encodeBootstrapCbor++-- | Inspect ordered signed costs as decimal strings. The language belongs to the+-- enclosing map and is absent from this array.+costModel :: Models.CostModel -> IO (Either Error Value)+costModel = Internal.inspect "inspection.costModel" 36 . costModelBytes++-- | Inspect known Plutus V1–V4 cost arrays. Unknown language identifiers are+-- omitted by this schema; input values and encodings remain unchanged.+costModels :: Models.CostModels -> IO (Either Error Value)+costModels = Internal.inspect "inspection.costModels" 37 . Models.encodeCbor++-- | Inspect exact lovelace prices for memory and steps. Original+-- numerator/denominator components are retained, including prices greater than+-- one.+exUnitPrices :: Prices.ExUnitPrices -> IO (Either Error Value)+exUnitPrices = Internal.inspect "inspection.exUnitPrices" 38 . Prices.encodeCbor++-- | Inspect all five stake-pool approval thresholds as exact rational components.+poolVotingThresholds :: PoolThresholds.PoolVotingThresholds -> IO (Either Error Value)+poolVotingThresholds = Internal.inspect "inspection.poolVotingThresholds" 39 . PoolThresholds.encodeCbor++-- | Inspect all ten DRep approval thresholds as exact rational components.+drepVotingThresholds :: DRepThresholds.DRepVotingThresholds -> IO (Either Error Value)+drepVotingThresholds = Internal.inspect "inspection.drepVotingThresholds" 40 . DRepThresholds.encodeCbor++-- | Inspect legacy genesis-authorized sparse changes as an object keyed by+-- hexadecimal genesis hashes. No authorization or era eligibility is+-- established.+proposedUpdates :: Proposed.ProposedUpdates -> IO (Either Error Value)+proposedUpdates = Internal.inspect "inspection.proposedUpdates" 41 . Proposed.encodeCbor++-- | Inspect a legacy update proposal and activation epoch. Epoch is a JSON+-- number, unlike decimal-string ledger quantities.+updateProposal :: Proposed.UpdateProposal -> IO (Either Error Value)+updateProposal = Internal.inspect "inspection.updateProposal" 42 . Proposed.encodeProposal++-- | Inspect an exact lovelace balance or inclusive-lower/exclusive-upper range.+-- Absent bounds are null; contradictory bounds are described without ledger-+-- state validation. A range with both bounds absent returns a native invalid-+-- argument error.+balanceInterval :: Fields.BalanceInterval -> IO (Either Error Value)+balanceInterval = Internal.inspect "inspection.balanceInterval" 43 . balanceIntervalBytes++-- | Inspect account balance requirements as ordered key/value entries. Keys are+-- reward addresses; bounds use the balance-interval schema.+balanceIntervals :: Fields.Entries Reward.RewardAddress Fields.BalanceInterval -> IO (Either Error Value)+balanceIntervals = Internal.inspect "inspection.balanceIntervals" 44 . balanceIntervalsBytes++-- | Inspect reward-account deposits as ordered key/value entries, preserving+-- present zero amounts as decimal strings.+directDeposits :: Fields.Entries Reward.RewardAddress Word64 -> IO (Either Error Value)+directDeposits = Internal.inspect "inspection.directDeposits" 45 . directDepositsBytes++-- | Inspect required guard credentials and optional exact script data as ordered+-- key/value entries. Absent data is null; script-data map order and duplicate+-- keys are retained.+requiredGuards :: Fields.Entries (Credential.Credential Credential.Guard) (Maybe Data.EncodedPlutusData) -> IO (Either Error Value)+requiredGuards = Internal.inspect "inspection.requiredGuards" 46 . requiredGuardsBytes++costModelBytes :: Models.CostModel -> ByteString+costModelBytes model = Write.toStrictByteString (Encoding.encodeListLen 2 <> Encoding.encodeWord8 (Models.languageId model)) <> Models.encodeCostModelCbor model++balanceIntervalEncoding :: Fields.BalanceInterval -> Encoding.Encoding+balanceIntervalEncoding interval = case interval of+ Fields.ExactBalance amount -> Encoding.encodeWord64 amount+ Fields.BalanceRange lower upper -> Encoding.encodeListLen 2 <> maybe Encoding.encodeNull Encoding.encodeWord64 lower <> maybe Encoding.encodeNull Encoding.encodeWord64 upper++balanceIntervalBytes :: Fields.BalanceInterval -> ByteString+balanceIntervalBytes = Write.toStrictByteString . balanceIntervalEncoding++associationBytes :: (key -> Encoding.Encoding) -> (value -> Encoding.Encoding) -> Fields.Entries key value -> ByteString+associationBytes encodeKey encodeValue entries = Write.toStrictByteString (Encoding.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, payload) -> encodeKey key <> encodeValue payload) pairs)+ where+ pairs = Fields.entries entries++balanceIntervalsBytes :: Fields.Entries Reward.RewardAddress Fields.BalanceInterval -> ByteString+balanceIntervalsBytes = associationBytes (Encoding.encodeBytes . Reward.toBytes) balanceIntervalEncoding++directDepositsBytes :: Fields.Entries Reward.RewardAddress Word64 -> ByteString+directDepositsBytes = associationBytes (Encoding.encodeBytes . Reward.toBytes) Encoding.encodeWord64++requiredGuardsBytes :: Fields.Entries (Credential.Credential Credential.Guard) (Maybe Data.EncodedPlutusData) -> ByteString+requiredGuardsBytes entries = Write.toStrictByteString (Encoding.encodeMapLen (fromIntegral (length pairs))) <> foldMap encodePair pairs+ where+ pairs = Fields.entries entries+ encodePair (key, payload) = Credential.encodeCbor key <> maybe (Write.toStrictByteString Encoding.encodeNull) Data.toCbor payload++-- | Inspect an asset name as lowercase hexadecimal, including the empty name.+-- Text decoding is not attempted.+assetName :: Name.AssetName -> IO (Either Error Value)+assetName = Internal.inspect "inspection.assetName" 47 . Name.encodeCbor++-- | Inspect a validated nonempty digest as lowercase hexadecimal. No hashing or+-- role inference is performed.+blake2bHash :: Hash.Blake2bHash -> IO (Either Error Value)+blake2bHash = Internal.inspect "inspection.blake2bHash" 48 . Hash.encodeCbor++-- | Inspect a pool BLS public key (96 bytes) and possession proof (48 bytes) as+-- hexadecimal. No group-membership or proof verification is performed.+blsKey :: Bls.BlsKey -> IO (Either Error Value)+blsKey = Internal.inspect "inspection.blsKey" 49 . Bls.encodeCbor++-- | Inspect cold committee credentials and expiry epochs as ordered key/value+-- entries. Credential kind and hash determine order; epochs are decimal+-- strings.+committeeMembers :: Committee.Members -> IO (Either Error Value)+committeeMembers = Internal.inspect "inspection.committeeMembers" 50 . Committee.encodeMembers++-- | Inspect reward accounts and withdrawn lovelace as ordered key/value entries.+-- Empty input, zero and duplicate accounts are retained. Accounts sort stably+-- by encoded address bytes, distinct from ledger redeemer-index ordering.+withdrawals :: [(Reward.RewardAddress, Word64)] -> IO (Either Error Value)+withdrawals = Internal.inspect "inspection.withdrawals" 51 . Collections.encodeWithdrawalsCbor++-- | Inspect digests as a JSON array, sorted stably by byte length then bytes.+-- Duplicate digests remain; empty input produces an empty array.+hashes :: [Hash.Blake2bHash] -> IO (Either Error Value)+hashes = Internal.inspect "inspection.hashes" 52 . Collections.encodeHashesCbor++-- | Inspect guards in supplied order. Empty input returns an empty array.+-- Key and script credentials remain tagged;+-- repeated credentials return a native duplicate-key error.+guards :: [Credential.Credential Credential.Guard] -> IO (Either Error Value)+guards [] = pure (Right (toJSON ([] :: [Value])))+guards credentials = Internal.inspect "inspection.guards" 53 (credentialListBytes credentials)++-- | Inspect subtransactions in supplied order. Empty input returns an empty+-- array. Repeated body identifiers return+-- a native duplicate-key error, even if witnesses or outer framing differ.+-- Signed body encodings are unchanged.+subTransactions :: [Sub.SubTransaction] -> IO (Either Error Value)+subTransactions [] = pure (Right (toJSON ([] :: [Value])))+subTransactions transactions = Internal.inspect "inspection.subTransactions" 54 (subTransactionsBytes transactions)++-- | Inspect policy/name associations as a JSON object keyed by hexadecimal+-- policies and names. Empty policy groups and zero quantities remain present.+-- Quantities must fit signed 64 bits ('Cometa.Error.InvalidValueQuantity').+-- Repeated policies use their last supplied group. Repeated names in a retained+-- group return 'InvalidValueCbor': object keys cannot retain repeated entries.+-- Ordering of object properties is insignificant.+assets :: [(Policy.PolicyId, [(Name.AssetName, Integer)])] -> IO (Either Error Value)+assets = inspectAssetAssociations "inspection.assets" 55++-- | Inspect policy groups as ordered @{script_hash, assets}@ entries. The inner+-- @assets@ value is a name-keyed object, not an asset-entry array. Groups sort+-- stably by policy bytes; empty groups and zero remain. Repeated policies use+-- the last supplied group, matching native map decoding.+-- Duplicate names return 'InvalidValueCbor'; signed overflow returns+-- 'Cometa.Error.InvalidValueQuantity'. Use 'policyAssetEntries' for repeated names.+assetEntries :: [(Policy.PolicyId, [(Name.AssetName, Integer)])] -> IO (Either Error Value)+assetEntries = inspectAssetAssociations "inspection.assetEntries" 56++-- | Inspect one policy's name/quantity associations as a hexadecimal-name-keyed+-- object. Empty input and explicit zero are retained. Repeated names return+-- 'InvalidValueCbor'; quantities outside signed 64 bits return+-- 'Cometa.Error.InvalidValueQuantity'. No policy identity is required.+policyAssets :: [(Name.AssetName, Integer)] -> IO (Either Error Value)+policyAssets pairs = case encoded of+ Left failure -> pure (Left failure)+ Right bytes -> Internal.inspect "inspection.policyAssets" 57 bytes+ where+ encoded = do+ bytes <- Collections.encodeAssetNamesCbor pairs+ uniqueObjectKeys "Repeated asset names cannot be represented as JSON object keys" (map fst pairs)+ pure bytes++-- | Inspect one policy's assets as ordered @{asset_name, amount}@ entries.+-- Names sort stably by byte length then bytes; repeated names keep their relative+-- order. Empty input and explicit zeros remain. Quantities outside signed 64 bits+-- return 'Cometa.Error.InvalidValueQuantity'. No policy identity is required.+policyAssetEntries :: [(Name.AssetName, Integer)] -> IO (Either Error Value)+policyAssetEntries pairs = case Collections.encodeAssetNamesCbor pairs of+ Left failure -> pure (Left failure)+ Right bytes -> Internal.inspect "inspection.policyAssetEntries" 58 bytes++inspectAssetAssociations :: Text -> CUInt -> [(Policy.PolicyId, [(Name.AssetName, Integer)])] -> IO (Either Error Value)+inspectAssetAssociations operation kind pairs = case encoded of+ Left failure -> pure (Left failure)+ Right bytes -> Internal.inspect operation kind bytes+ where+ encoded = do+ groups <- traverse encodeGroup (sortOn (Policy.toBytes . fst) pairs)+ mapM_ (uniqueObjectKeys "Repeated asset names cannot be represented as JSON object keys" . map fst) (Map.elems (Map.fromList pairs))+ pure (Write.toStrictByteString (Encoding.encodeMapLen (fromIntegral (length groups))) <> mconcat groups)+ encodeGroup (policy, quantities) = do+ bytes <- Collections.encodeAssetNamesCbor quantities+ pure (Write.toStrictByteString (Encoding.encodeBytes (Policy.toBytes policy)) <> bytes)++uniqueObjectKeys :: (Ord key) => Text -> [key] -> Either Error ()+uniqueObjectKeys message keys = unless (Set.size (Set.fromList keys) == length keys) (Left (InvalidValueCbor message))++credentialListBytes :: [Credential.Credential purpose] -> ByteString+credentialListBytes credentials = Write.toStrictByteString (Encoding.encodeTag 258 <> Encoding.encodeListLen (fromIntegral (length credentials))) <> foldMap Credential.encodeCbor credentials++subTransactionsBytes :: [Sub.SubTransaction] -> ByteString+subTransactionsBytes transactions = Write.toStrictByteString (Encoding.encodeTag 258 <> Encoding.encodeListLen (fromIntegral (length transactions))) <> foldMap Sub.encodeCbor transactions
@@ -0,0 +1,76 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Pure Bech32 address encoding. The four fixed HRPs are validated by their+-- literal contents and tests. The sole invariant assertion checks four+-- source-controlled literals using the public package validator; it cannot be+-- reached from external input. No arbitrary HRP enters encoding.+module Cometa.Internal.AddressText (fromText, toText) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import Cometa.Error (Error (..))+import Data.ByteString (ByteString)+import Data.Text (Text)+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++data Prefix = PaymentMainnet | PaymentTestnet | RewardMainnet | RewardTestnet++-- DEFINITIONS ----------------------------------------------------------------++toText :: Bool -> Bool -> ByteString -> Text+toText reward mainnet = Bech32.encodeLenient prefix . Bech32.dataPartFromBytes+ where+ prefix = case (reward, mainnet) of+ (False, True) -> paymentMainnetPrefix+ (False, False) -> paymentTestnetPrefix+ (True, True) -> rewardMainnetPrefix+ (True, False) -> rewardTestnetPrefix++-- Only these four static literals reach the assertion. Tests validate all four+-- through the public package API and pinned native text vectors.++paymentMainnetPrefix, paymentTestnetPrefix, rewardMainnetPrefix, rewardTestnetPrefix :: Bech32.HumanReadablePart+paymentMainnetPrefix = builtInPrefix PaymentMainnet+paymentTestnetPrefix = builtInPrefix PaymentTestnet+rewardMainnetPrefix = builtInPrefix RewardMainnet+rewardTestnetPrefix = builtInPrefix RewardTestnet++builtInPrefix :: Prefix -> Bech32.HumanReadablePart+builtInPrefix prefix = case Bech32.humanReadablePartFromText literal of+ Right value -> value+ Left _ -> error "Cometa: invalid built-in Bech32 prefix"+ where+ literal = case prefix of+ PaymentMainnet -> "addr"+ PaymentTestnet -> "addr_test"+ RewardMainnet -> "stake"+ RewardTestnet -> "stake_test"++fromText :: (ByteString -> Either Error address) -> (address -> Text) -> Text -> Either Error address+fromText parse encode text+ | Text.null text || Text.length text > 120 || Text.any (\character -> character < '!' || character > '~') text || (Text.toLower text /= text && Text.toUpper text /= text) = Left InvalidShelleyAddressText+ | otherwise = do+ (_, payload) <- either (const (Left InvalidShelleyAddressText)) Right (Bech32.decodeLenient text)+ bytes <- maybe (Left InvalidShelleyAddressText) Right (Bech32.dataPartToBytes payload)+ address <- parse bytes+ if encode address == Text.toLower text+ then Right address+ else Left InvalidShelleyAddressText
@@ -0,0 +1,143 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Checked accounting before native signed arithmetic. Parsed native owners+-- remain scoped by the existing standalone building transport.+module Cometa.Internal.Balance (imbalance, subTransactionImbalance, batchImbalance, isBalanced) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Building as Building+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionValue as ValueCbor+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import Data.ByteString (ByteString)+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Word (Word64)+import Foreign.C.Types (CUInt)++-- DEFINITIONS ----------------------------------------------------------------++imbalance :: Parameters.Parameters -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error Value.Value)+imbalance parameters resolved transaction = runExceptT $ do+ except (validateResolved resolved)+ implicit <- ExceptT (Building.implicitCoin parameters transaction)+ let body = Body.toBody (Tx.body transaction)+ _ <- except (bodyBalance resolved (Body.fee body) (Body.bodyFields body) implicit)+ ExceptT (compute 6 parameters resolved (Tx.encodeCbor transaction))++subTransactionImbalance :: Parameters.Parameters -> [Utxo.Utxo] -> Sub.SubTransaction -> IO (Either Error Value.Value)+subTransactionImbalance parameters resolved transaction = runExceptT $ do+ except (validateResolved resolved)+ implicit <- ExceptT (Building.subTransactionImplicitCoin parameters transaction)+ _ <- except (bodyBalance resolved 0 (SubBody.fields (SubBody.toBody (Sub.body transaction))) implicit)+ ExceptT (compute 7 parameters resolved (Sub.encodeCbor transaction))++batchImbalance :: Parameters.Parameters -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error Value.Value)+batchImbalance parameters resolved transaction = runExceptT $ do+ except (validateResolved resolved)+ let body = Body.toBody (Tx.body transaction)+ subs = fromMaybe [] (Body.bodySubTransactions body)+ fields = Body.bodyFields body : map (SubBody.fields . SubBody.toBody . Sub.body) subs+ outer <- ExceptT (Building.implicitCoin parameters transaction)+ nested <- traverse (ExceptT . Building.subTransactionImplicitCoin parameters) subs+ values <- except (sequence (zipWith3 (bodyBalance resolved) (Body.fee body : repeat 0) fields (outer : nested)))+ -- Native set iteration order need not match imported envelopes. Bounding the+ -- positive and negative totals separately protects every possible prefix.+ let positives = Value.fromList [(asset, amount) | value <- values, (asset, amount) <- Value.toList value, amount > 0]+ negatives = Value.fromList [(asset, amount) | value <- values, (asset, amount) <- Value.toList value, amount < 0]+ refund = Value.lovelace (repeatedPoolRefund parameters fields)+ except (bounded (positives <> refund) >> bounded negatives)+ ExceptT (compute 8 parameters resolved (Tx.encodeCbor transaction))++isBalanced :: Parameters.Parameters -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error Bool)+isBalanced parameters resolved transaction = fmap (fmap (== mempty)) (batchImbalance parameters resolved transaction)++validateResolved :: [Utxo.Utxo] -> Either Error ()+validateResolved resolved =+ unless+ (Set.size (Set.fromList (map Utxo.input resolved)) == length resolved)+ (Left (InvalidBuildingRequest "Duplicate resolved spending input"))++bodyBalance :: [Utxo.Utxo] -> Word64 -> Fields.Fields -> Building.ImplicitCoin -> Either Error Value.Value+bodyBalance resolved fee fields implicit = do+ inputs <- traverse resolve (Fields.fieldInputs fields)+ let inputValue = foldMap (Output.value . Utxo.output) inputs+ outputValue = foldMap Output.value (Fields.fieldOutputs fields)+ mint = maybe mempty Fields.mintValue (Fields.fieldMint fields)+ consumedCoin = toInteger (Building.withdrawals implicit) + toInteger (Building.reclaimedDeposits implicit)+ producedCoin =+ toInteger fee+ + toInteger (Building.deposits implicit)+ + maybe 0 toInteger (Fields.fieldDonation fields)+ + sum [toInteger amount | (_, amount) <- maybe [] Fields.entries (Fields.fieldDirectDeposits fields)]+ consumed = inputValue <> Value.lovelace consumedCoin <> mint+ difference = consumed <> negateValue outputValue+ result = difference <> Value.lovelace (negate producedCoin)+ mapM_ bounded [inputValue, outputValue, Value.lovelace consumedCoin, Value.lovelace producedCoin, consumed, difference, result]+ pure result+ where+ table = Map.fromList [(Utxo.input value, value) | value <- resolved]+ resolve reference = maybe (Left (InvalidBuildingRequest "A spending input has no resolved UTxO")) Right (Map.lookup reference table)++bounded :: Value.Value -> Either Error ()+bounded value = unless (all fits (Value.toList value)) (Left (InvalidBuildingRequest "Balance intermediate exceeds signed 64-bit bounds"))+ where+ fits (_, amount) = amount >= toInteger (minBound :: Int64) && amount <= toInteger (maxBound :: Int64)++negateValue :: Value.Value -> Value.Value+negateValue = Value.fromList . map (fmap negate) . Value.toList++repeatedPoolRefund :: Parameters.Parameters -> [Fields.Fields] -> Integer+repeatedPoolRefund parameters fields =+ toInteger (sum (map Set.size pools) - Set.size (Set.unions pools)) * toInteger (Parameters.parameterPoolDeposit parameters)+ where+ pools = map (Set.fromList . map Pool.operator . registrations) fields+ registrations body = [pool | Certificate.PoolRegistration pool <- maybe [] Certificates.toList (Fields.fieldCertificates body)]++compute :: CUInt -> Parameters.Parameters -> [Utxo.Utxo] -> ByteString -> IO (Either Error Value.Value)+compute operation parameters resolved transaction = do+ result <- Building.runUnchecked operation (Cbor.encode request)+ pure (result >>= Cbor.decodeAs InvalidBuildingRequest decoder)+ where+ request =+ E.encodeListLen 3+ <> Cbor.raw transaction+ <> Cbor.raw (Snapshot.encodeSnapshot parameters)+ <> E.encodeListLen (fromIntegral (length resolved))+ <> foldMap (Cbor.raw . Utxo.encodeCbor) resolved+ decoder = Cbor.array 2 (((<>) . Value.lovelace <$> D.decodeInteger) <*> ValueCbor.decodeAssets)
@@ -0,0 +1,213 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Select the language views for the outer body's actual script purposes.+-- Mirrors the pinned native get_needed_scripts/get_plutus_languages_used domain+-- traversal, but fails explicitly when a required script or cost model is absent.+-- Script hashing remains in IO; all supplied values and encodings stay unchanged.+module Cometa.Internal.BalancingScripts (usedCostModels) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (InvalidBuildingRequest))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import Data.ByteString (ByteString)+import qualified Data.List as List+import qualified Data.Map.Strict as Map+import Data.Maybe (catMaybes, fromMaybe, mapMaybe)+import qualified Data.Set as Set+import Data.Word (Word8)++-- DEFINITIONS ----------------------------------------------------------------++-- | Select only languages used by required outer scripts. Nested scripts may+-- provide a needed outer script, but nested purposes do not add outer language+-- views. Relevant reference scripts come only from spending/reference inputs of+-- the outer body and nested bodies. From protocol 12, newly created outputs+-- and collateral return also provide scripts; arbitrary wallet snapshots do not.+-- Missing/conflicting resolutions, scripts and cost models fail explicitly.+usedCostModels :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Models.CostModels)+usedCostModels parameters resolved transaction = runExceptT $ do+ table <- except (snapshotTable resolved)+ let body = Body.toBody (Tx.body transaction)+ fields = Body.bodyFields body+ nested = fromMaybe [] (Body.bodySubTransactions body)+ allFields = fields : map (SubBody.fields . SubBody.toBody . Sub.body) nested+ relevant = Set.toList (Set.fromList (concatMap references allFields))+ witnessScripts =+ Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses transaction))+ <> concatMap (Witnesses.scripts . Witnesses.toWitnesses . Sub.witnesses) nested+ sources <- except (traverse (resolve table) relevant)+ spending <- except (traverse (resolve table) (Fields.fieldInputs fields))+ policies <- except (mintPolicies (Body.toCbor (Tx.body transaction)))+ let needed = Set.fromList (mapMaybe (paymentScript . Utxo.output) spending <> policies <> fieldScripts fields)+ created =+ if Version.major (Parameters.parameterProtocolVersion parameters) >= 12+ then concatMap Fields.fieldOutputs allFields <> maybe [] pure (Body.bodyCollateralReturn body)+ else []+ provided = witnessScripts <> mapMaybe (Output.referenceScript . Utxo.output) sources <> mapMaybe Output.referenceScript created+ hashed <- traverse hashScript provided+ languages <- except (traverse (languageFor (Map.fromList hashed)) (Set.toList needed))+ models <- except (traverse lookupModel (Set.toList (Set.fromList (catMaybes languages))))+ pure (Models.fromList models)+ where+ hashScript script = do+ digest <- ExceptT (Script.hash script)+ pure (digest, script)+ lookupModel language =+ maybe+ (Left (InvalidBuildingRequest "A required script language has no cost model"))+ Right+ (Parameters.parameterCostModels parameters >>= Models.lookup language)++snapshotTable :: [Utxo] -> Either Error (Map.Map Input.Input Utxo)+snapshotTable = List.foldl' add (Right Map.empty)+ where+ add result utxo = do+ table <- result+ case Map.lookup (Utxo.input utxo) table of+ Just previous -> do+ unless (previous == utxo) (Left (InvalidBuildingRequest "Conflicting script-resolution snapshots"))+ pure table+ Nothing -> Right (Map.insert (Utxo.input utxo) utxo table)++resolve :: Map.Map Input.Input Utxo -> Input.Input -> Either Error Utxo+resolve table reference = maybe (Left (InvalidBuildingRequest "A script-resolution input is missing")) Right (Map.lookup reference table)++references :: Fields.Fields -> [Input.Input]+references fields = Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields)++paymentScript :: Output.Output -> Maybe Credential.ScriptHash+paymentScript output = case Output.address output of+ Address.ShelleyAddress address -> credentialScript (Shelley.paymentCredential address)+ Address.ByronAddress _ -> Nothing+ Address.RewardAddress _ -> Nothing++credentialScript :: Credential.Credential purpose -> Maybe Credential.ScriptHash+credentialScript credential = case credential of+ Credential.KeyCredential _ -> Nothing+ Credential.ScriptCredential hash -> Just hash++-- Native walker visits only field14 guards, not the field24 account guard map.+fieldScripts :: Fields.Fields -> [Credential.ScriptHash]+fieldScripts fields =+ mapMaybe (credentialScript . Reward.credential . fst) (maybe [] Fields.entries (Fields.fieldWithdrawals fields))+ <> concatMap certificateScripts (maybe [] Certificates.toList (Fields.fieldCertificates fields))+ <> concatMap (\(voter, _, _) -> voterScripts voter) (maybe [] Voting.toList (Fields.fieldVotingProcedures fields))+ <> mapMaybe (proposalPolicy . Proposal.proposalAction) (maybe [] Proposal.toList (Fields.fieldProposalProcedures fields))+ <> mapMaybe credentialScript (fromMaybe [] (Fields.fieldGuards fields))++-- Registration0 carries no authorizing credential; registration7 does. Combined+-- certificates authorize the stake credential, not the delegated pool or DRep.+-- Committee hot authorization requires the cold credential. Do not use the hot+-- credential or constitution metadata/guardrails as additional cert purposes.+certificateScripts :: Certificate.Certificate -> [Credential.ScriptHash]+certificateScripts certificate = case certificate of+ Certificate.StakeRegistration _ -> []+ Certificate.StakeDeregistration stake -> script stake+ Certificate.StakeDelegation stake _ -> script stake+ Certificate.PoolRegistration _ -> []+ Certificate.PoolRetirement _ _ -> []+ Certificate.GenesisKeyDelegation {} -> []+ Certificate.MoveInstantaneousRewards _ -> []+ Certificate.Registration stake _ -> script stake+ Certificate.Unregistration stake _ -> script stake+ Certificate.VoteDelegation stake _ -> script stake+ Certificate.StakeVoteDelegation stake _ _ -> script stake+ Certificate.StakeRegistrationDelegation stake _ _ -> script stake+ Certificate.VoteRegistrationDelegation stake _ _ -> script stake+ Certificate.StakeVoteRegistrationDelegation stake _ _ _ -> script stake+ Certificate.AuthorizeCommitteeHot cold _ -> script cold+ Certificate.ResignCommitteeCold cold _ -> script cold+ Certificate.RegisterDRep drep _ _ -> script drep+ Certificate.UnregisterDRep drep _ -> script drep+ Certificate.UpdateDRep drep _ -> script drep+ where+ script credential = maybe [] pure (credentialScript credential)++voterScripts :: Voting.Voter -> [Credential.ScriptHash]+voterScripts voter = case voter of+ Voting.CommitteeVoter credential -> script credential+ Voting.DRepVoter credential -> script credential+ Voting.StakePoolVoter _ -> []+ where+ script credential = maybe [] pure (credentialScript credential)++proposalPolicy :: Action.Action -> Maybe Credential.ScriptHash+proposalPolicy action = case action of+ Action.ParameterChange _ _ policy -> policy+ Action.TreasuryWithdrawals _ policy -> policy+ Action.HardForkInitiation _ _ -> Nothing+ Action.NoConfidence _ -> Nothing+ Action.UpdateCommittee {} -> Nothing+ Action.NewConstitution _ _ -> Nothing+ Action.InfoAction -> Nothing++languageFor :: Map.Map Credential.ScriptHash Script.Script -> Credential.ScriptHash -> Either Error (Maybe Word8)+languageFor provided hash = case Map.lookup hash provided of+ Nothing -> Left (InvalidBuildingRequest "A required body script is missing")+ Just (Script.Native _) -> Right Nothing+ Just (Script.Plutus script) -> Right (Just (languageId (Plutus.version script)))++languageId :: Plutus.Version -> Word8+languageId version = case version of+ Plutus.V1 -> 0+ Plutus.V2 -> 1+ Plutus.V3 -> 2+ Plutus.V4 -> 3++-- The semantic Mint observer intentionally normalizes zero/empty policy maps.+-- Native needed-script traversal still counts their original keys, so read only+-- these keys from the exact body encoding while the validated asset maps are+-- skipped. No source bytes or ledger values are reconstructed or normalized.+mintPolicies :: ByteString -> Either Error [Credential.ScriptHash]+mintPolicies bodyBytes = do+ fields <- Cbor.decodeAs InvalidBuildingRequest (Cbor.mapFields bodyBytes) bodyBytes+ case Map.lookup 9 fields of+ Nothing -> Right []+ Just bytes -> Cbor.decodeAs InvalidBuildingRequest (mapM decodePolicy =<< Cbor.entries ((,) <$> D.decodeBytes <*> Cbor.slice bytes)) bytes+ where+ decodePolicy (bytes, _) = either (fail . show) pure (Credential.scriptHashFromBytes bytes)
@@ -0,0 +1,57 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Verify declared intent budgets in the completed enclosing context without+-- mutating signed bodies. Each evaluator request remains operation-scoped.+module Cometa.Internal.BatchValidation (validateSubBudgets) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)++-- DEFINITIONS ----------------------------------------------------------------++validateSubBudgets :: Evaluation.Evaluator -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error ())+validateSubBudgets evaluator resolved transaction =+ runExceptT $+ mapM_ check (zip [0 ..] subs)+ where+ subs = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ check (index, intent) = do+ let redeemers = Witnesses.redeemers (Witnesses.toWitnesses (Sub.witnesses intent))+ declared = Map.fromList [(Evaluation.RedeemerId (Redeemer.purpose value) (Redeemer.index value), Redeemer.executionUnits value) | value <- redeemers]+ unless (null redeemers) $ do+ actual <- ExceptT (Evaluation.evaluate evaluator (Evaluation.SubTransaction index) transaction resolved)+ except (mapM_ (within declared) (Evaluation.budgets actual))+ within declared (identifier, actual) = case Map.lookup identifier declared of+ Nothing -> Left (InvalidEvaluationResult "Subtransaction evaluation returned an unknown redeemer")+ Just limit ->+ unless+ (Ex.memory actual <= Ex.memory limit && Ex.steps actual <= Ex.steps limit)+ (Left (InvalidBuildingRequest "Attached subtransaction execution exceeds its declared budget"))
@@ -0,0 +1,125 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Narrow purity exception for the audited pinned BIP39 conversion path.+-- No owner, callback, logger, RNG, allocator configuration or mutable error+-- state is reached. See docs/development/BIP39_PURITY.md for the build audit+-- and re-audit requirements. These concrete monomorphic NOINLINE boundaries+-- follow base's unsafePerformIO optimizer safeguards; never generalize them to+-- an arbitrary IO runner. Re-evaluation or sharing is semantically harmless.+-- Safe foreign calls unwind before finally wipes scratch on cancellation.+-- Results (including errors) are forced before leaving the private IO action.+module Cometa.Internal.Bip39Pure (Mnemonic, fromEntropy, fromText, fromWords, wordCount, exportText, exportEntropy) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Bip39 as Internal+import Cometa.Internal.Error (fromNativeFailure)+import Cometa.Internal.Failure (NativeFailure (..))+import Control.Exception (evaluate)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Char (isAsciiLower)+import Data.Text (Text)+import qualified Data.Text as Text+import System.IO.Unsafe (unsafePerformIO)++-- TYPES ----------------------------------------------------------------------++-- | A checksum-validated sequence of 12, 15, 18, 21 or 24 lowercase English+-- BIP39 words. Constructors are hidden; secret export is explicit.+newtype Mnemonic = Mnemonic [Text]++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate the bound before entering the audited conversion; force owned words.+{-# NOINLINE fromEntropy #-}+fromEntropy :: ByteString -> Either Error Mnemonic+fromEntropy entropy+ | size `notElem` [16, 20, 24, 28, 32] = Left (InvalidBip39EntropyLength size)+ | otherwise = unsafePerformIO $ do+ result <- fmap (either (Left . fromNativeFailure) (Right . Mnemonic)) (Internal.fromEntropy entropy)+ evaluate (forceMnemonic result)+ pure result+ where+ size = ByteString.length entropy++-- | Unicode splitting is pure and delegates to the concrete word boundary.+fromText :: Text -> Either Error Mnemonic+fromText = fromWords . Text.words++-- | Preserve domain/native errors; force the retained input words before return.+{-# NOINLINE fromWords #-}+fromWords :: [Text] -> Either Error Mnemonic+fromWords words' = case validateWords words' of+ Left err -> Left err+ Right () -> unsafePerformIO $ do+ result <- fmap (either (Left . mnemonicError) (const (Right (Mnemonic words')))) (Internal.validate words')+ evaluate (forceMnemonic result)+ pure result++-- | Inspect the materialized list.+wordCount :: Mnemonic -> Int+wordCount (Mnemonic words') = length words'++-- | Explicitly materialize a caller-requested secret phrase.+exportText :: Mnemonic -> Text+exportText (Mnemonic words') = Text.unwords words'++-- | Preserve all native/contract errors; force the owned copy before return.+{-# NOINLINE exportEntropy #-}+exportEntropy :: Mnemonic -> Either Error ByteString+exportEntropy (Mnemonic words') = unsafePerformIO $ do+ result <- fmap (either (Left . fromNativeFailure) Right) (Internal.exportEntropy words')+ evaluate (case result of Left err -> forceError err; Right bytes -> ByteString.length bytes `seq` ())+ pure result++validateWords :: [Text] -> Either Error ()+validateWords words'+ | count `notElem` [12, 15, 18, 21, 24] = Left (InvalidBip39WordCount count)+ | otherwise = mapM_ validate (zip [1 ..] words')+ where+ count = length words'+ validate (position, word)+ | Text.null word || not (Text.all isAsciiLower word) = Left (InvalidBip39Word position)+ | otherwise = Right ()++mnemonicError :: NativeFailure -> Error+mnemonicError failure = case failure of+ NativeFailure _ status _+ | Code.fromNumber status == Code.InvalidChecksum -> InvalidBip39Checksum+ | Code.fromNumber status == Code.InvalidArgument -> UnknownBip39Word+ _ -> fromNativeFailure failure++-- Force the actual word list, without constructing another secret phrase.+-- Strict Text/ByteString values own their contents; forcing their lengths and+-- every list cell leaves no deferred decoding or borrowed foreign reads.+forceMnemonic :: Either Error Mnemonic -> ()+forceMnemonic (Left err) = forceError err+forceMnemonic (Right (Mnemonic words')) = forceWords words'+ where+ forceWords [] = ()+ forceWords (word : rest) = Text.length word `seq` forceWords rest++forceError :: Error -> ()+forceError (NativeError operation code diagnostic) =+ Text.length operation `seq` Code.toNumber code `seq` Text.length diagnostic `seq` ()+forceError (NativeContractViolation operation) = Text.length operation `seq` ()+-- Remaining constructors are nullary or contain strict scalar fields.+forceError err = err `seq` ()
@@ -0,0 +1,167 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Checked domain requests and operation-scoped native utility marshaling.+-- Each request decodes fresh independent owners in C. Runtime.withOwnedBuffer+-- releases even partial output on failure and copies before releasing success.+module Cometa.Internal.Building+ ( ImplicitCoin (..),+ minimumAda,+ baseFee,+ minimumFee,+ referenceScriptFee,+ scriptDataHash,+ implicitCoin,+ subTransactionImplicitCoin,+ runUnchecked,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error (..))+import qualified Cometa.Internal.FFI.Building as FFI+import qualified Cometa.Internal.FFI.CoinSelection as Selection+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionFields as Fields+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import Cometa.Transaction.Datum (Hash32)+import qualified Cometa.Transaction.Datum as Datum+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import qualified Data.Text+import Data.Word (Word64)+import Foreign.C.Types (CUInt)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (castPtr)+import Foreign.Storable (peek)++-- TYPES ----------------------------------------------------------------------++-- | Top-level reward withdrawals, deposits charged and deposits reclaimed,+-- all in lovelace. The three totals are separate unsigned 64-bit quantities.+data ImplicitCoin = ImplicitCoin+ { -- | Reward withdrawals included in this body.+ withdrawals :: !Word64,+ -- | Certificate and governance proposal deposits paid.+ deposits :: !Word64,+ -- | Stake credential and DRep deposits returned by certificates.+ reclaimedDeposits :: !Word64+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++minimumAda :: Word64 -> Output.Output -> IO (Either Error Word64)+minimumAda cost output = Runtime.withBytes (Output.encodeCbor output) $ \bytes size -> alloca $ \result -> do+ code <- Selection.cMinimumAda bytes size cost result+ status <- Runtime.checkStatus "building.minimumAda" code+ case status of+ Left failure -> pure (Left failure)+ Right () -> Right <$> peek result++baseFee :: Word64 -> Word64 -> Tx.Transaction -> IO (Either Error Word64)+baseFee constant coefficient transaction = compute 4 D.decodeWord64 [Cbor.raw (Tx.encodeCbor transaction), E.encodeWord64 constant, E.encodeWord64 coefficient]++minimumFee :: Parameters.Parameters -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error Word64)+minimumFee parameters resolved transaction = case validate of+ Left failure -> pure (Left failure)+ Right () -> compute 0 D.decodeWord64 [Cbor.raw (Tx.encodeCbor transaction), Cbor.raw (Snapshot.encodeSnapshot parameters), encodeUtxos (pricedInputs transaction resolved)]+ where+ validate = do+ validateParameters parameters+ validateReferences resolved+ unless (Set.fromList (map Utxo.input resolved) == Set.unions (pricedInputSets transaction)) (Left (InvalidBuildingRequest "Resolved inputs must exactly cover top-level and subtransaction spending and reference inputs"))+ require (Parameters.parameterExecutionCosts parameters) "Execution prices are required"+ require (Parameters.parameterRefScriptCostPerByte parameters) "Reference script byte price is required"++referenceScriptFee :: Parameters.Parameters -> [Utxo.Utxo] -> IO (Either Error Word64)+referenceScriptFee parameters resolved = case validate of+ Left failure -> pure (Left failure)+ Right () -> compute 1 D.decodeWord64 [Cbor.raw (Snapshot.encodeSnapshot parameters), encodeUtxos resolved]+ where+ validate = do+ validateParameters parameters+ validateReferences resolved+ require (Parameters.parameterRefScriptCostPerByte parameters) "Reference script byte price is required"++scriptDataHash :: Models.CostModels -> Witnesses.EncodedWitnesses -> IO (Either Error (Maybe Hash32))+scriptDataHash models witnesses = do+ result <- compute 3 (Cbor.optional D.decodeBytes) [Cbor.raw (Models.encodeCbor models), Cbor.raw (Witnesses.toCbor witnesses)]+ pure (result >>= traverse Datum.hashFromBytes)++implicitCoin :: Parameters.Parameters -> Tx.Transaction -> IO (Either Error ImplicitCoin)+implicitCoin parameters transaction = case validateParameters parameters of+ Left failure -> pure (Left failure)+ Right () -> compute 2 (Cbor.array 3 (ImplicitCoin <$> D.decodeWord64 <*> D.decodeWord64 <*> D.decodeWord64)) [Cbor.raw (Tx.encodeCbor transaction), Cbor.raw (Snapshot.encodeSnapshot parameters)]++subTransactionImplicitCoin :: Parameters.Parameters -> Sub.SubTransaction -> IO (Either Error ImplicitCoin)+subTransactionImplicitCoin parameters transaction = case validateParameters parameters of+ Left failure -> pure (Left failure)+ Right () -> compute 5 (Cbor.array 3 (ImplicitCoin <$> D.decodeWord64 <*> D.decodeWord64 <*> D.decodeWord64)) [Cbor.raw (Sub.encodeCbor transaction), Cbor.raw (Snapshot.encodeSnapshot parameters)]++validateParameters :: Parameters.Parameters -> Either Error ()+validateParameters = Snapshot.validateNative++require :: Maybe a -> Data.Text.Text -> Either Error ()+require value message = case value of+ Nothing -> Left (InvalidBuildingRequest message)+ Just _ -> Right ()++validateReferences :: [Utxo.Utxo] -> Either Error ()+validateReferences resolved = unless (Set.size (Set.fromList (map Utxo.input resolved)) == length resolved) (Left (InvalidBuildingRequest "Duplicate resolved reference input"))++-- Each body's spending/reference union is priced once; the native balancer+-- concatenates those per-body lists rather than deduplicating across a batch.+pricedInputSets :: Tx.Transaction -> [Set.Set Input]+pricedInputSets transaction = map inputs (Body.bodyFields body : subFields)+ where+ body = Body.toBody (Tx.body transaction)+ subFields = maybe [] (map (SubBody.fields . SubBody.toBody . Sub.body)) (Body.bodySubTransactions body)+ inputs fields = Set.fromList (Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields))++pricedInputs :: Tx.Transaction -> [Utxo.Utxo] -> [Utxo.Utxo]+pricedInputs transaction resolved = concatMap (\refs -> filter (\utxo -> Set.member (Utxo.input utxo) refs) resolved) (pricedInputSets transaction)++encodeUtxos :: [Utxo.Utxo] -> E.Encoding+encodeUtxos values = E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Utxo.encodeCbor) values++compute :: CUInt -> (forall s. D.Decoder s a) -> [E.Encoding] -> IO (Either Error a)+compute operation decoder fields = do+ result <- runUnchecked operation (Cbor.encode (E.encodeListLen (fromIntegral (length fields)) <> mconcat fields))+ pure (result >>= Cbor.decodeAs InvalidBuildingRequest decoder)++-- | Private malformed-request hook. Fresh native owners are released before return.+runUnchecked :: CUInt -> ByteString -> IO (Either Error ByteString)+runUnchecked operation request = B.useAsCStringLen request $ \(bytes, size) -> Runtime.withOwnedBuffer "building.compute" (FFI.cCompute operation (castPtr bytes) (fromIntegral size))
@@ -0,0 +1,353 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Immutable certificates, exact envelopes and private CBOR schema workers.+-- No native resources or effects are used by these codecs.+module Cometa.Internal.Certificate+ ( Certificate (..),+ Mir (..),+ Pot (..),+ EncodedCertificate,+ encodeCertificate,+ decodeCertificate,+ fromCertificate,+ toCertificate,+ certificateCbor,+ Certificates (..),+ EncodedCertificates,+ encodeCertificates,+ decodeCertificates,+ fromCertificates,+ toCertificates,+ certificatesCbor,+ certificatesSetEncoding,+ withCertificatesSetEncoding,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Term as Term+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Credential as Credential+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Internal.Pool as Pool+import qualified Cometa.Internal.SetEncoding as SetEncoding+import Control.Monad (foldM, replicateM, unless, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as Lazy+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Text as Text+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Source accounting pot for instantaneous rewards. Ordering follows CBOR codes.+data Pot+ = -- | The reserve accounting pot.+ Reserves+ | -- | The treasury accounting pot.+ Treasury+ deriving (Eq, Ord, Show, Bounded, Enum)++-- | Instantaneous reward transfers. All quantities are+-- lovelace from 0 through 2^64-1; signed reward adjustments are rejected.+data Mir+ = -- | Transfer from the source pot to the other accounting pot.+ ToOtherPot !Pot !Word64+ | -- | Assign rewards from the source pot to unique stake credentials.+ ToStakeCredentials !Pot !(Map (Credential.Credential Credential.Stake) Word64)+ deriving (Eq, Ord, Show)++-- | Certificate semantic data. Deposits, refunds and reward amounts are unsigned+-- 64-bit lovelace. Constructors do not check protocol parameters, era eligibility,+-- registration state, witnesses, or ledger acceptance. Equality and ordering+-- compare constructor then fields; 'Show' is diagnostic.+data Certificate+ = -- | Register a stake credential without an explicit deposit (legacy form).+ StakeRegistration !(Credential.Credential Credential.Stake)+ | -- | Deregister a stake credential without an explicit refund (legacy form).+ StakeDeregistration !(Credential.Credential Credential.Stake)+ | -- | Delegate stake to the pool identified by its operator key hash.+ StakeDelegation !(Credential.Credential Credential.Stake) !(Credential.KeyHash Credential.StakePool)+ | -- | Register or update all pool parameters.+ PoolRegistration !Pool.PoolParameters+ | -- | Retire a pool at the given epoch (unsigned 64-bit epoch number).+ PoolRetirement !(Credential.KeyHash Credential.StakePool) !Word64+ | -- | Delegate a genesis key to a delegate key and VRF key hash (legacy form).+ GenesisKeyDelegation !(Credential.KeyHash Credential.Genesis) !(Credential.KeyHash Credential.GenesisDelegate) !Pool.VrfKeyHash+ | -- | Transfer instantaneous rewards (legacy form).+ MoveInstantaneousRewards !Mir+ | -- | Register a stake credential with its explicit deposit in lovelace.+ Registration !(Credential.Credential Credential.Stake) !Word64+ | -- | Deregister a stake credential with its explicit refund in lovelace.+ Unregistration !(Credential.Credential Credential.Stake) !Word64+ | -- | Delegate voting power to a DRep or a predefined target.+ VoteDelegation !(Credential.Credential Credential.Stake) !DRep.DRep+ | -- | Delegate stake and voting power together.+ StakeVoteDelegation !(Credential.Credential Credential.Stake) !(Credential.KeyHash Credential.StakePool) !DRep.DRep+ | -- | Register and delegate stake; the last argument is the deposit in lovelace.+ StakeRegistrationDelegation !(Credential.Credential Credential.Stake) !(Credential.KeyHash Credential.StakePool) !Word64+ | -- | Register and delegate voting power; the last argument is the deposit in lovelace.+ VoteRegistrationDelegation !(Credential.Credential Credential.Stake) !DRep.DRep !Word64+ | -- | Register and delegate both powers; the last argument is the deposit in lovelace.+ StakeVoteRegistrationDelegation !(Credential.Credential Credential.Stake) !(Credential.KeyHash Credential.StakePool) !DRep.DRep !Word64+ | -- | Authorize a committee hot credential using its cold credential.+ AuthorizeCommitteeHot !(Credential.Credential Credential.CommitteeCold) !(Credential.Credential Credential.CommitteeHot)+ | -- | Resign a committee cold credential with an optional explanation.+ ResignCommitteeCold !(Credential.Credential Credential.CommitteeCold) !(Maybe Anchor.Anchor)+ | -- | Register a DRep with its deposit in lovelace and optional metadata.+ RegisterDRep !(Credential.Credential Credential.DRep) !Word64 !(Maybe Anchor.Anchor)+ | -- | Unregister a DRep with its refund in lovelace.+ UnregisterDRep !(Credential.Credential Credential.DRep) !Word64+ | -- | Update or remove a DRep metadata anchor.+ UpdateDRep !(Credential.Credential Credential.DRep) !(Maybe Anchor.Anchor)+ deriving (Eq, Ord, Show)++-- | Certificate with its exact original CBOR. Equality and ordering include bytes.+data EncodedCertificate = EncodedCertificate !ByteString !Certificate deriving (Eq, Ord, Show)++-- | Ordered certificates. Order and repeated certificates are preserved, matching+-- the native certificate collection despite its historical set name.+newtype Certificates = Certificates [Certificate] deriving (Eq, Ord, Show)++-- | Ordered certificates retaining their complete imported CBOR envelope.+data EncodedCertificates = EncodedCertificates !ByteString !Certificates deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite certificate encoding, with canonical unsigned integers.+encodeCertificate :: Certificate -> ByteString+encodeCertificate = Write.toStrictByteString . certificateEncoding++-- | Validate a complete certificate and retain exact bytes; schema failures return InvalidCertificateCbor.+decodeCertificate :: ByteString -> Either Error EncodedCertificate+decodeCertificate bytes = EncodedCertificate bytes <$> decodeComplete certificateDecoder bytes++-- | Create an exact envelope using fresh certificate encoding.+fromCertificate :: Certificate -> EncodedCertificate+fromCertificate value = EncodedCertificate (encodeCertificate value) value++-- | Inspect semantic certificate fields without changing the exact envelope.+toCertificate :: EncodedCertificate -> Certificate+toCertificate (EncodedCertificate _ value) = value++-- | Return original bytes for an imported certificate envelope.+certificateCbor :: EncodedCertificate -> ByteString+certificateCbor (EncodedCertificate bytes _) = bytes++-- | Encode ordered entries with set tag 258, retaining repeated certificates.+encodeCertificates :: Certificates -> ByteString+encodeCertificates (Certificates values) = Write.toStrictByteString (Encode.encodeTag 258 <> Encode.encodeListLen (fromIntegral (length values)) <> foldMap certificateEncoding values)++-- | Validate an optionally tagged collection and retain its complete bytes.+decodeCertificates :: ByteString -> Either Error EncodedCertificates+decodeCertificates bytes = EncodedCertificates bytes <$> decodeComplete certificatesDecoder bytes++-- | Wrap an ordered collection using its fresh definite encoding.+fromCertificates :: Certificates -> EncodedCertificates+fromCertificates value = EncodedCertificates (encodeCertificates value) value++-- | Inspect the ordered semantic collection.+toCertificates :: EncodedCertificates -> Certificates+toCertificates (EncodedCertificates _ value) = value++-- | Return the exact imported collection bytes.+certificatesCbor :: EncodedCertificates -> ByteString+certificatesCbor (EncodedCertificates bytes _) = bytes++-- | Observe the outer collection tag without changing its exact envelope.+certificatesSetEncoding :: EncodedCertificates -> SetEncoding+certificatesSetEncoding = SetEncoding.encoding . certificatesCbor++-- | Change only the outer tag; retain every array and certificate byte.+withCertificatesSetEncoding :: SetEncoding -> EncodedCertificates -> EncodedCertificates+withCertificatesSetEncoding requested (EncodedCertificates bytes values) =+ EncodedCertificates (SetEncoding.withEncoding requested bytes) values++certificateEncoding :: Certificate -> Encode.Encoding+certificateEncoding certificate = case certificate of+ StakeRegistration stake -> Encode.encodeListLen 2 <> Encode.encodeWord 0 <> credentialEncoding stake+ StakeDeregistration stake -> Encode.encodeListLen 2 <> Encode.encodeWord 1 <> credentialEncoding stake+ StakeDelegation stake pool -> Encode.encodeListLen 3 <> Encode.encodeWord 2 <> credentialEncoding stake <> keyEncoding pool+ PoolRegistration parameters -> Encode.encodeListLen (1 + Pool.parametersFieldCount parameters) <> Encode.encodeWord 3 <> Pool.parametersEncoding parameters+ PoolRetirement pool epoch -> Encode.encodeListLen 3 <> Encode.encodeWord 4 <> keyEncoding pool <> Encode.encodeWord64 epoch+ GenesisKeyDelegation genesis delegate vrf -> Encode.encodeListLen 4 <> Encode.encodeWord 5 <> keyEncoding genesis <> keyEncoding delegate <> (Encode.encodeBytes . Pool.vrfKeyHashBytes) vrf+ MoveInstantaneousRewards rewards -> Encode.encodeListLen 2 <> Encode.encodeWord 6 <> mirEncoding rewards+ Registration stake deposit -> Encode.encodeListLen 3 <> Encode.encodeWord 7 <> credentialEncoding stake <> Encode.encodeWord64 deposit+ Unregistration stake refund -> Encode.encodeListLen 3 <> Encode.encodeWord 8 <> credentialEncoding stake <> Encode.encodeWord64 refund+ VoteDelegation stake drep -> Encode.encodeListLen 3 <> Encode.encodeWord 9 <> credentialEncoding stake <> (Encode.encodePreEncoded . DRep.encodeCbor) drep+ StakeVoteDelegation stake pool drep -> Encode.encodeListLen 4 <> Encode.encodeWord 10 <> credentialEncoding stake <> keyEncoding pool <> (Encode.encodePreEncoded . DRep.encodeCbor) drep+ StakeRegistrationDelegation stake pool deposit -> Encode.encodeListLen 4 <> Encode.encodeWord 11 <> credentialEncoding stake <> keyEncoding pool <> Encode.encodeWord64 deposit+ VoteRegistrationDelegation stake drep deposit -> Encode.encodeListLen 4 <> Encode.encodeWord 12 <> credentialEncoding stake <> (Encode.encodePreEncoded . DRep.encodeCbor) drep <> Encode.encodeWord64 deposit+ StakeVoteRegistrationDelegation stake pool drep deposit -> Encode.encodeListLen 5 <> Encode.encodeWord 13 <> credentialEncoding stake <> keyEncoding pool <> (Encode.encodePreEncoded . DRep.encodeCbor) drep <> Encode.encodeWord64 deposit+ AuthorizeCommitteeHot cold hot -> Encode.encodeListLen 3 <> Encode.encodeWord 14 <> credentialEncoding cold <> credentialEncoding hot+ ResignCommitteeCold cold anchor -> Encode.encodeListLen 3 <> Encode.encodeWord 15 <> credentialEncoding cold <> anchorEncoding anchor+ RegisterDRep drep deposit anchor -> Encode.encodeListLen 4 <> Encode.encodeWord 16 <> credentialEncoding drep <> Encode.encodeWord64 deposit <> anchorEncoding anchor+ UnregisterDRep drep refund -> Encode.encodeListLen 3 <> Encode.encodeWord 17 <> credentialEncoding drep <> Encode.encodeWord64 refund+ UpdateDRep drep anchor -> Encode.encodeListLen 3 <> Encode.encodeWord 18 <> credentialEncoding drep <> anchorEncoding anchor++credentialEncoding :: Credential.Credential purpose -> Encode.Encoding+credentialEncoding credential =+ Encode.encodeListLen 2 <> case credential of+ Credential.KeyCredential hash -> Encode.encodeWord 0 <> keyEncoding hash+ Credential.ScriptCredential hash -> Encode.encodeWord 1 <> Encode.encodeBytes (Credential.scriptHashBytes hash)++keyEncoding :: Credential.KeyHash purpose -> Encode.Encoding+keyEncoding = Encode.encodeBytes . Credential.keyHashBytes++anchorEncoding :: Maybe Anchor.Anchor -> Encode.Encoding+anchorEncoding = maybe Encode.encodeNull (Encode.encodePreEncoded . Anchor.encodeCbor)++mirEncoding :: Mir -> Encode.Encoding+mirEncoding rewards =+ Encode.encodeListLen 2 <> case rewards of+ ToOtherPot source amount -> potEncoding source <> Encode.encodeWord64 amount+ ToStakeCredentials source amounts -> potEncoding source <> Encode.encodeMapLen (fromIntegral (Map.size amounts)) <> foldMap (\(credential, amount) -> credentialEncoding credential <> Encode.encodeWord64 amount) (Map.toAscList amounts)++potEncoding :: Pot -> Encode.Encoding+potEncoding Reserves = Encode.encodeWord 0+potEncoding Treasury = Encode.encodeWord 1++certificateDecoder :: Decode.Decoder s Certificate+certificateDecoder = do+ size <- Decode.decodeListLenOrIndef+ kind <- Decode.decodeWord+ value <- case kind of+ 0 -> checkSize 2 size >> (StakeRegistration <$> credentialDecoder)+ 1 -> checkSize 2 size >> (StakeDeregistration <$> credentialDecoder)+ 2 -> checkSize 3 size >> (StakeDelegation <$> credentialDecoder <*> keyDecoder)+ 3 -> do+ (fields, parameters) <- Pool.parametersDecoderWithFieldCount+ checkSize (1 + fromIntegral fields) size+ pure (PoolRegistration parameters)+ 4 -> checkSize 3 size >> (PoolRetirement <$> keyDecoder <*> Decode.decodeWord64)+ 5 -> checkSize 4 size >> (GenesisKeyDelegation <$> keyDecoder <*> keyDecoder <*> (validated Pool.vrfKeyHashFromBytes =<< Decode.decodeBytes))+ 6 -> checkSize 2 size >> (MoveInstantaneousRewards <$> mirDecoder)+ 7 -> checkSize 3 size >> (Registration <$> credentialDecoder <*> Decode.decodeWord64)+ 8 -> checkSize 3 size >> (Unregistration <$> credentialDecoder <*> Decode.decodeWord64)+ 9 -> checkSize 3 size >> (VoteDelegation <$> credentialDecoder <*> embedded DRep.decodeCbor)+ 10 -> checkSize 4 size >> (StakeVoteDelegation <$> credentialDecoder <*> keyDecoder <*> embedded DRep.decodeCbor)+ 11 -> checkSize 4 size >> (StakeRegistrationDelegation <$> credentialDecoder <*> keyDecoder <*> Decode.decodeWord64)+ 12 -> checkSize 4 size >> (VoteRegistrationDelegation <$> credentialDecoder <*> embedded DRep.decodeCbor <*> Decode.decodeWord64)+ 13 -> checkSize 5 size >> (StakeVoteRegistrationDelegation <$> credentialDecoder <*> keyDecoder <*> embedded DRep.decodeCbor <*> Decode.decodeWord64)+ 14 -> checkSize 3 size >> (AuthorizeCommitteeHot <$> credentialDecoder <*> credentialDecoder)+ 15 -> checkSize 3 size >> (ResignCommitteeCold <$> credentialDecoder <*> anchorDecoder)+ 16 -> checkSize 4 size >> (RegisterDRep <$> credentialDecoder <*> Decode.decodeWord64 <*> anchorDecoder)+ 17 -> checkSize 3 size >> (UnregisterDRep <$> credentialDecoder <*> Decode.decodeWord64)+ 18 -> checkSize 3 size >> (UpdateDRep <$> credentialDecoder <*> anchorDecoder)+ _ -> fail "Unknown certificate kind"+ endArray size+ pure value++credentialDecoder :: Decode.Decoder s (Credential.Credential purpose)+credentialDecoder = arrayOf 2 $ do+ kind <- Decode.decodeWord+ case kind of+ 0 -> Credential.KeyCredential <$> keyDecoder+ 1 -> Credential.ScriptCredential <$> (validated Credential.scriptHashFromBytes =<< Decode.decodeBytes)+ _ -> fail "Unknown credential kind"++keyDecoder :: Decode.Decoder s (Credential.KeyHash purpose)+keyDecoder = validated Credential.keyHashFromBytes =<< Decode.decodeBytes++anchorDecoder :: Decode.Decoder s (Maybe Anchor.Anchor)+anchorDecoder = do+ token <- Decode.peekTokenType+ if token == Decode.TypeNull then Decode.decodeNull >> pure Nothing else Just <$> embedded Anchor.decodeCbor++mirDecoder :: Decode.Decoder s Mir+mirDecoder = arrayOf 2 $ do+ code <- Decode.decodeWord+ source <- case code of+ 0 -> pure Reserves+ 1 -> pure Treasury+ _ -> fail "Unknown rewards pot"+ token <- Decode.peekTokenType+ if token == Decode.TypeMapLen || token == Decode.TypeMapLenIndef+ then ToStakeCredentials source <$> rewardsDecoder+ else ToOtherPot source <$> Decode.decodeWord64++rewardsDecoder :: Decode.Decoder s (Map (Credential.Credential Credential.Stake) Word64)+rewardsDecoder = do+ size <- Decode.decodeMapLenOrIndef+ entries <- sequenceEntries size ((,) <$> credentialDecoder <*> Decode.decodeWord64)+ foldM insertReward Map.empty entries+ where+ insertReward amounts (credential, amount)+ | Map.member credential amounts = fail "Duplicate rewards credential"+ | otherwise = pure (Map.insert credential amount amounts)++certificatesDecoder :: Decode.Decoder s Certificates+certificatesDecoder = do+ token <- Decode.peekTokenType+ when (token == Decode.TypeTag || token == Decode.TypeTag64) $ do+ tag <- Decode.decodeTag64+ unless (tag == 258) (fail "Expected certificate set tag 258")+ size <- Decode.decodeListLenOrIndef+ Certificates <$> sequenceEntries size certificateDecoder++sequenceEntries :: Maybe Int -> Decode.Decoder s a -> Decode.Decoder s [a]+sequenceEntries size entry = case size of+ Just count -> replicateM count entry+ Nothing -> go+ where+ go = do+ ended <- Decode.decodeBreakOr+ if ended then pure [] else (:) <$> entry <*> go++embedded :: (ByteString -> Either Error a) -> Decode.Decoder s a+embedded decode = do+ term <- Term.decodeTerm+ validated decode (Write.toStrictByteString (Term.encodeTerm term))++arrayOf :: Int -> Decode.Decoder s a -> Decode.Decoder s a+arrayOf expected entry = do+ size <- Decode.decodeListLenOrIndef+ checkSize expected size+ value <- entry+ endArray size+ pure value++checkSize :: Int -> Maybe Int -> Decode.Decoder s ()+checkSize expected size = case size of+ Just actual -> unless (actual == expected) (fail "Incorrect certificate array length")+ Nothing -> pure ()++endArray :: Maybe Int -> Decode.Decoder s ()+endArray size = case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- Decode.decodeBreakOr+ unless ended (fail "Extra certificate array elements")++validated :: (a -> Either Error b) -> a -> Decode.Decoder s b+validated validate value = either (fail . show) pure (validate value)++decodeComplete :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a+decodeComplete decoder bytes = case Read.deserialiseFromBytes decoder (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidCertificateCbor (Text.pack (show failure)))+ Right (remaining, value)+ | Lazy.null remaining -> Right value+ | otherwise -> Left (InvalidCertificateCbor "Trailing bytes after certificate value")
@@ -0,0 +1,348 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Owned selection domains, contextual invariants and private wire encoding.+module Cometa.Internal.CoinSelection+ ( Selector (..),+ Strategy (..),+ largestFirst,+ randomImprove,+ randomImproveWithSeed,+ randomImproveWithOptions,+ SelectionOptions (..),+ SelectionRequest,+ Selection (..),+ mkSelectionRequest,+ preselected,+ available,+ target,+ outputHints,+ changeAddress,+ parameters,+ validateSelection,+ encodeRequest,+ decodeRequest,+ encodeSelection,+ decodeSelection,+ select,+ checkChange,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address (Address)+import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (Ada))+import Cometa.Error (Error (..))+import qualified Cometa.Internal.FFI.CoinSelection as Native+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionValue as V+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.Protocol.Parameters as Parameters+import Cometa.Transaction.Datum (Datum (NoDatum))+import Cometa.Transaction.Input (Input)+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import Cometa.Value (Value)+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (castPtr)+import Foreign.Storable (peek)++-- TYPES ----------------------------------------------------------------------++-- | Application-supplied coin selection. The function receives an immutable,+-- validated request and returns the complete selection, remaining candidates and+-- change. Use 'select' to check contextual laws and change minimum Ada. Exceptions+-- propagate normally; 'Left' represents an expected selection failure.+newtype Selector = Selector+ { -- | Select all spending inputs, including mandatory preselected inputs.+ selectCoins :: SelectionRequest -> IO (Either Error Selection)+ }++-- | Random-improve input selection policy. Both policies may acquire more Ada+-- to fund change. Neither policy changes the authoritative target.+data Strategy+ = -- | Select enough of each asset to meet its required quantity.+ Minimal+ | -- | Attempt approximately twice the required quantity to improve change.+ Optimal+ deriving (Eq, Ord, Show, Bounded, Enum)++-- | Select the largest available quantities of required assets, with Ada last.+-- Aggregate eligible and hinted quantities must fit signed 64-bit arithmetic;+-- excessive minimum-Ada multiplication bounds return 'InvalidSelectionRequest'.+-- Output hints are ignored. A successful selection always spends an input,+-- including when the target is zero. Insufficient funding or change Ada returns+-- the native balance failure. Change respects a supplied maximum value size;+-- absent or zero maximum value size disables splitting.+largestFirst :: Selector+largestFirst = nativeSelector 0 0 Optimal++-- | Round-robin random-improve with the 'Optimal' policy, seeded from the native+-- secure entropy source separately on every invocation. Aggregate bounds are+-- checked as for 'largestFirst'. Output hints influence+-- change shape, never the authoritative funding requirement.+randomImprove :: Selector+randomImprove = nativeSelector 1 0 Optimal++-- | Deterministic random-improve using 'Optimal'. The same seed and request+-- replay the same selection on each call; this is not a persistent random stream.+randomImproveWithSeed :: Word64 -> Selector+randomImproveWithSeed seed = randomImproveWithOptions seed Optimal++-- | Deterministic random-improve with an explicit seed and policy. Output hints+-- shape change; additional Ada inputs may be selected to satisfy minimum Ada.+-- Selection replays from the seed on each call. Deterministic replay applies to+-- the same library version; ordering can change between versions.+randomImproveWithOptions :: Word64 -> Strategy -> Selector+randomImproveWithOptions = nativeSelector 2++-- Native selectors use independent operation-local owners; no mutable handle or+-- RNG state escapes. Validate aggregate arithmetic before native signed sums.+nativeSelector :: Word64 -> Word64 -> Strategy -> Selector+nativeSelector algorithm seed strategy = Selector $ \request -> case validateNativeSelection request of+ Left failure -> pure (Left failure)+ Right () -> Runtime.withBytes (encodeRequest (disjointRequest request)) $ \bytes size -> do+ response <- Runtime.withOwnedBuffer "coinSelection.native" (Native.cNativeSelect (fromIntegral algorithm) seed (if strategy == Minimal then 0 else 1) bytes size)+ pure (response >>= decodeSelection)++-- Native random-improve concatenates mandatory and available pools without+-- deduplicating. P09 permits identical overlap, so marshal only optional+-- candidates; returned remaining is unchanged because mandatory is selected.+disjointRequest :: SelectionRequest -> SelectionRequest+disjointRequest request@(SelectionRequest options) = SelectionRequest options {selectionAvailable = filter (\item -> Map.notMember (Utxo.input item) mandatory) (available request)}+ where+ mandatory = Map.fromList [(Utxo.input item, ()) | item <- preselected request]++validateNativeSelection :: SelectionRequest -> Either Error ()+validateNativeSelection request = do+ let eligible = Map.elems (Map.fromList [(Utxo.input item, item) | item <- preselected request ++ available request])+ total = sumUtxos eligible+ capacity = total <> Value.fromList [(asset, negate amount) | (asset, amount) <- Value.toList (target request), amount < 0]+ hints = maybe mempty (foldMap Output.value) (outputHints request)+ maps = max 1 (maybe 0 length (outputHints request))+ assets = max 1 (length (filter ((/= Ada) . fst) (Value.toList capacity)))+ outputCount = toInteger maps * toInteger assets+ validate value = case V.validateOutput value of+ Left _ -> Left (InvalidSelectionRequest "Native selection aggregate quantities exceed int64")+ Right () -> Right ()+ validate total+ validate capacity+ validate hints+ -- The aggregate output bounds every possible split change output's encoded+ -- size. Bound all possible split maps as native largest-first accumulates their+ -- unsigned minimum Ada and casts that sum to int64. Include fixed overhead+ -- and worst coin-width growth, including shape-hinted empty maps.+ output <- Output.mkOutput (changeAddress request) capacity NoDatum Nothing+ case Parameters.parameterAdaPerUtxoByte (parameters request) of+ Just cost -> unless (toInteger cost * (toInteger (B.length (Output.encodeCbor output)) + 168) * outputCount <= toInteger (maxBound :: Int64)) (Left (InvalidSelectionRequest "Native change minimum Ada arithmetic exceeds int64"))+ Nothing -> Left (InvalidSelectionRequest "Ada per UTxO byte is required")++-- | Named input to request validation. Candidate lists must have unique+-- references. Identical references may occur once in both lists; conflicting+-- resolved outputs are rejected. Preselected inputs may be outside available.+data SelectionOptions = SelectionOptions+ { -- | Mandatory selected inputs. Each must survive in a successful selection.+ selectionPreselected :: ![Utxo],+ -- | Eligible candidate inputs, including any optional overlap with preselected.+ selectionAvailable :: ![Utxo],+ -- | Authoritative signed value to fund, including externally assessed fees,+ -- deposits, withdrawals and mint. Negative components are implicit surplus+ -- that must return as change. Ada counts lovelace; quantities fit Int64.+ selectionTarget :: !Value,+ -- | Optional output-shape hints, independent of authoritative target arithmetic.+ selectionOutputHints :: !(Maybe [Output]),+ -- | Required destination for every generated change output.+ selectionChangeAddress :: !Address,+ -- | Current protocol snapshot. Ada-per-UTxO-byte must be present for change+ -- minimum-Ada validation. This does not promise consistent chain observations.+ selectionParameters :: !Parameters+ }+ deriving (Eq, Show)++-- | Validated request. Equality compares all owned fields and preserves list+-- order; validation does not select coins or access chain state.+newtype SelectionRequest = SelectionRequest SelectionOptions deriving (Eq, Show)++-- | Full selection result. Assembly is total; 'select' checks contextual+-- eligibility, balance, remaining candidates, change destination and minimum Ada.+-- Equality compares list order and semantic fields; no random-choice equivalence+-- is implied. Empty change means an exact target match.+data Selection = Selection+ { -- | Complete selected inputs, including the preselected inputs, with unique refs.+ selected :: ![Utxo],+ -- | Exactly the available candidates not selected, with unique references.+ remaining :: ![Utxo],+ -- | Locally balanced outputs returning all excess value to the change address.+ change :: ![Output]+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate unique references and nonconflicting overlapping snapshots, a+-- signed native-range target, an available Ada-per-UTxO-byte parameter,+-- and supported parameter bounds. Failure returns 'InvalidSelectionRequest' or+-- 'InvalidParameterSnapshot'. This does not query input eligibility on chain.+mkSelectionRequest :: SelectionOptions -> Either Error SelectionRequest+mkSelectionRequest options = do+ mandatory <- indexUtxos (InvalidSelectionRequest "Duplicate preselected reference") (selectionPreselected options)+ candidates <- indexUtxos (InvalidSelectionRequest "Duplicate available reference") (selectionAvailable options)+ unless (and (Map.elems (Map.intersectionWith (==) mandatory candidates))) (Left (InvalidSelectionRequest "Conflicting overlapping UTxO snapshots"))+ unless+ (all (\(_, quantity) -> quantity >= toInteger (minBound :: Int64) && quantity <= toInteger (maxBound :: Int64)) (Value.toList (selectionTarget options)))+ (Left (InvalidSelectionRequest "Target quantities must fit int64"))+ case Parameters.parameterAdaPerUtxoByte (selectionParameters options) of+ Nothing -> Left (InvalidSelectionRequest "Ada per UTxO byte is required")+ Just _ -> pure ()+ Snapshot.validateNative (selectionParameters options)+ pure (SelectionRequest options)++-- | Mandatory input snapshots in caller order.+preselected :: SelectionRequest -> [Utxo]+preselected (SelectionRequest options) = selectionPreselected options++-- | Eligible candidate snapshots in caller order.+available :: SelectionRequest -> [Utxo]+available (SelectionRequest options) = selectionAvailable options++-- | Authoritative funding requirement; output hints do not change it.+target :: SelectionRequest -> Value+target (SelectionRequest options) = selectionTarget options++-- | Optional output-shape hints, retaining absence versus an empty hint list.+outputHints :: SelectionRequest -> Maybe [Output]+outputHints (SelectionRequest options) = selectionOutputHints options++-- | Destination required for each change output.+changeAddress :: SelectionRequest -> Address+changeAddress (SelectionRequest options) = selectionChangeAddress options++-- | Protocol snapshot supplied with the request.+parameters :: SelectionRequest -> Parameters+parameters (SelectionRequest options) = selectionParameters options++-- | Check unique references, unaltered eligible snapshots, mandatory inclusion,+-- exact remaining accounting and componentwise selected = target + change.+-- Change destinations must match. Ordering does not affect these laws. This+-- pure check does not assess minimum Ada; 'select' performs that additional check.+validateSelection :: SelectionRequest -> Selection -> Either Error ()+validateSelection request result = do+ chosen <- indexUtxos (InvalidSelection "Repeated selected reference") (selected result)+ rest <- indexUtxos (InvalidSelection "Repeated remaining reference") (remaining result)+ let mandatory = Map.fromList [(Utxo.input value, value) | value <- preselected request]+ candidates = Map.fromList [(Utxo.input value, value) | value <- available request]+ eligible = Map.union mandatory candidates+ unless (Map.isSubmapOfBy (==) chosen eligible) (Left (InvalidSelection "Selection contains an ineligible or changed snapshot"))+ unless (Map.isSubmapOfBy (==) mandatory chosen) (Left (InvalidSelection "Preselected input was dropped or changed"))+ unless (rest == Map.difference candidates chosen) (Left (InvalidSelection "Remaining candidates do not account exactly for the available set"))+ unless (all ((== changeAddress request) . Output.address) (change result)) (Left (InvalidSelection "Change destination differs from request"))+ unless (sumUtxos (selected result) == target request <> foldMap Output.value (change result)) (Left (InvalidSelection "Selected value differs from target plus change"))++indexUtxos :: Error -> [Utxo] -> Either Error (Map Input Utxo)+indexUtxos failure values = do+ let result = Map.fromList [(Utxo.input value, value) | value <- values]+ unless (Map.size result == length values) (Left failure)+ pure result++sumUtxos :: [Utxo] -> Value+sumUtxos = foldMap (Output.value . Utxo.output)++-- | Invoke an application selector once, validate its complete result and check+-- minimum Ada for every change output. No fees, additional inputs, witnesses or+-- output amounts are changed implicitly. Expected failures retain their error;+-- callback exceptions and asynchronous cancellation propagate normally.+select :: Selector -> SelectionRequest -> IO (Either Error Selection)+select selector request = do+ result <- selectCoins selector request+ case result >>= (\selection -> validateSelection request selection >> pure selection) of+ Left failure -> pure (Left failure)+ Right selection -> do+ checked <- checkChange request (change selection)+ pure (selection <$ checked)++checkChange :: SelectionRequest -> [Output] -> IO (Either Error ())+checkChange request outputs = case Parameters.parameterAdaPerUtxoByte (parameters request) of+ Nothing -> pure (Left (InvalidSelectionRequest "Ada per UTxO byte is required"))+ Just cost -> go cost outputs+ where+ go _ [] = pure (Right ())+ go cost (output : rest) = do+ required <- minimumAda cost output+ case required of+ Left failure -> pure (Left failure)+ Right amount+ | Value.quantity Ada (Output.value output) < toInteger amount -> pure (Left (InvalidSelection "Change output is below minimum Ada"))+ | otherwise -> go cost rest++minimumAda :: Word64 -> Output -> IO (Either Error Word64)+minimumAda cost output = B.useAsCStringLen (Output.encodeCbor output) $ \(bytes, size) -> alloca $ \result -> do+ code <- Native.cMinimumAda (castPtr bytes) (fromIntegral size) cost result+ status <- Runtime.checkStatus "coinSelection.minimumAda" code+ case status of+ Left failure -> pure (Left failure)+ Right () -> Right <$> peek result++encodeList :: (a -> ByteString) -> [a] -> E.Encoding+encodeList encode values = E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . encode) values++-- Internal requests use signed coin plus signed native-asset quantities.+-- Ledger Value CBOR cannot represent negative coin, despite native value_t+-- supporting signed arithmetic for implicit sources during balancing.+encodeValue :: Value -> E.Encoding+encodeValue value = E.encodeListLen 2 <> E.encodeInteger (Value.quantity Ada value) <> V.encodeAssets value++decodeValue :: D.Decoder s Value+decodeValue = Cbor.array 2 (((<>) . Value.lovelace <$> D.decodeInteger) <*> V.decodeAssets)++encodeRequest :: SelectionRequest -> ByteString+encodeRequest request = Cbor.encode (E.encodeListLen 6 <> encodeList Utxo.encodeCbor (preselected request) <> encodeList Utxo.encodeCbor (available request) <> encodeValue (target request) <> maybe E.encodeNull (encodeList Output.encodeCbor) (outputHints request) <> E.encodeBytes (Address.toBytes (changeAddress request)) <> Cbor.raw (Snapshot.encodeSnapshot (parameters request)))++decodeRequest :: ByteString -> Either Error SelectionRequest+decodeRequest bytes = Cbor.decode parser bytes >>= mkSelectionRequest+ where+ parser =+ Cbor.array+ 6+ ( SelectionOptions+ <$> Cbor.list (Cbor.nested bytes Utxo.decodeCbor)+ <*> Cbor.list (Cbor.nested bytes Utxo.decodeCbor)+ <*> decodeValue+ <*> Cbor.optional (Cbor.list (Output.toOutput <$> Cbor.nested bytes Output.decodeCbor))+ <*> (D.decodeBytes >>= either (fail . show) pure . Address.fromBytes)+ <*> Cbor.nested bytes Snapshot.decodeSnapshot+ )++encodeSelection :: Selection -> ByteString+encodeSelection result = Cbor.encode (E.encodeListLen 3 <> encodeList Utxo.encodeCbor (selected result) <> encodeList Utxo.encodeCbor (remaining result) <> encodeList Output.encodeCbor (change result))++decodeSelection :: ByteString -> Either Error Selection+decodeSelection bytes = Cbor.decode (Cbor.array 3 (Selection <$> Cbor.list (Cbor.nested bytes Utxo.decodeCbor) <*> Cbor.list (Cbor.nested bytes Utxo.decodeCbor) <*> Cbor.list (Output.toOutput <$> Cbor.nested bytes Output.decodeCbor))) bytes
@@ -0,0 +1,55 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private adapter scopes used by native builder integration and dispatch tests.+-- Public direct selection does not acquire a callback registration. Factories and+-- native invokes run inside the shared operation gate, which contains callback+-- exceptions and joins cancellation before releasing native or Haskell owners.+module Cometa.Internal.CoinSelection.Native (withSelector, invoke, invokeWith, dispatch) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.CoinSelection (Selection, SelectionRequest, Selector)+import qualified Cometa.Internal.CoinSelection as Selection+import qualified Cometa.Internal.FFI.CoinSelection as Native+import Cometa.Internal.Runtime (Dispatch, Runtime)+import qualified Cometa.Internal.Runtime as Runtime++-- DEFINITIONS ----------------------------------------------------------------++withSelector :: Selector -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)+withSelector selector = Runtime.withRuntime (dispatch selector)++dispatch :: Selector -> Dispatch+dispatch selector operation bytes+ | operation /= 200 = pure (Left (InvalidSelectionRequest "Unknown selector operation"))+ | otherwise = case Selection.decodeRequest bytes of+ Left failure -> pure (Left failure)+ Right request -> fmap Selection.encodeSelection <$> Selection.select selector request++invoke :: Selector -> SelectionRequest -> IO (Either Error Selection)+invoke selector request = withSelector selector (`invokeWith` request)++invokeWith :: Runtime -> SelectionRequest -> IO (Either Error Selection)+invokeWith runtime request = do+ response <- Runtime.withOperation runtime $ \context ->+ Runtime.withBytes (Selection.encodeRequest request) $ \bytes size ->+ Runtime.withOwnedBuffer "coinSelection.nativeDispatch" (Native.cSelect context bytes size)+ pure (response >>= Selection.decodeSelection >>= checked)+ where+ checked value = Selection.validateSelection request value >> pure value
@@ -0,0 +1,92 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Owned native contextual utilities with complete buffer cleanup.+module Cometa.Internal.ContextualTransaction (findCertificate, requiredKeyHashes, runRequiredKeys) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.FFI.ContextualTransaction as FFI+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Utxo as Utxo+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Maybe (fromMaybe)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Storable (peek)++-- DEFINITIONS ----------------------------------------------------------------++findCertificate :: Certificate.EncodedCertificate -> Maybe ByteString -> IO (Either Error (Maybe Word64))+findCertificate _ Nothing = pure (Right Nothing)+findCertificate certificate (Just collection) =+ Runtime.withBytes collection $ \bytes size ->+ Runtime.withBytes (Certificate.toCbor certificate) $ \target targetSize ->+ alloca $ \index -> do+ status <- FFI.cCertificateIndex bytes size target targetSize index+ if toInteger status == Code.toNumber Code.ElementNotFound+ then pure (Right Nothing)+ else do+ checked <- Runtime.checkStatus "transaction.indices.certificate" status+ case checked of+ Left failure -> pure (Left failure)+ Right () -> Right . Just <$> peek index++requiredKeyHashes :: Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error (Set Blake2b.Blake2bHash))+requiredKeyHashes transaction resolved = case validateResolution transaction resolved of+ Left failure -> pure (Left failure)+ Right () -> do+ result <- runRequiredKeys (Tx.encodeCbor transaction) (encodeUtxos resolved)+ pure $ do+ bytes <- result+ hashes <- Cbor.decode (Cbor.setList D.decodeBytes) bytes+ unless (all ((== 28) . B.length) hashes) (Left (NativeContractViolation "transaction.authority.hashSize"))+ Set.fromList <$> traverse Blake2b.fromBytes hashes++validateResolution :: Tx.Transaction -> [Utxo.Utxo] -> Either Error ()+validateResolution transaction resolved = do+ unless (Set.size available == length references) (Left (InvalidTransactionField "Duplicate resolved UTxO references"))+ unless (all (`Set.member` available) required) (Left (InvalidTransactionField "All spending and collateral inputs must resolve"))+ where+ body = Body.toBody (Tx.body transaction)+ required = Fields.fieldInputs (Body.bodyFields body) ++ fromMaybe [] (Body.bodyCollateral body)+ references = map Utxo.input resolved+ available = Set.fromList references++encodeUtxos :: [Utxo.Utxo] -> ByteString+encodeUtxos values = Cbor.encode (E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Utxo.encodeCbor) values)++-- | Internal malformed-transport boundary for deterministic cleanup tests.+runRequiredKeys :: ByteString -> ByteString -> IO (Either Error ByteString)+runRequiredKeys transaction resolved =+ Runtime.withBytes transaction $ \bytes size ->+ Runtime.withBytes resolved $ \utxos utxosSize ->+ Runtime.withOwnedBuffer "transaction.authority.requiredKeyHashes" (FFI.cRequiredKeys bytes size utxos utxosSize)
@@ -0,0 +1,133 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Ordered cost parameter vectors, independent of evaluator validation.+module Cometa.Internal.CostModels+ ( CostModel (..),+ CostModels (..),+ mkCostModel,+ encodeCostArray,+ decodeCostArray,+ encodeCostModels,+ encodeLanguageViews,+ decodeCostModels,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Write as Write+import Cometa.Error (Error (InvalidCostModelLength))+import Control.Monad (replicateM)+import qualified Data.ByteString as ByteString+import Data.Int (Int64)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word8)++-- TYPES ----------------------------------------------------------------------++-- | Raw ledger language id and ordered signed 64-bit costs. At most 2048 costs+-- are supported. Construction does not establish evaluator validity.+data CostModel = CostModel+ { -- | Raw ledger language identifier from 0 through 255.+ languageId :: !Word8,+ -- | Ordered signed 64-bit parameters, with at most 2048 entries.+ costs :: ![Int64]+ }+ deriving (Eq, Ord, Show)++-- | One model per language id. Equality and ordering compare ascending entries.+newtype CostModels = CostModels (Map Word8 CostModel) deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate the native vector length bound. Unknown language ids are retained.+mkCostModel :: Word8 -> [Int64] -> Either Error CostModel+mkCostModel language values+ | count > 2048 = Left (InvalidCostModelLength count)+ | otherwise = Right (CostModel language values)+ where+ count = length values++encodeCostArray :: CostModel -> Encode.Encoding+encodeCostArray (CostModel _ values) = Encode.encodeListLen (fromIntegral (length values)) <> foldMap Encode.encodeInt64 values++decodeCostArray :: Word8 -> Decode.Decoder s CostModel+decodeCostArray language = do+ count <- Decode.decodeListLenOrIndef+ values <- case count of+ Just size | size > 2048 -> fail "cost model exceeds 2048 parameters"+ Just size -> replicateM size Decode.decodeInt64+ Nothing -> indefiniteCosts 0 []+ pure (CostModel language values)+ where+ indefiniteCosts count values = do+ end <- Decode.decodeBreakOr+ if end+ then pure (reverse values)+ else+ if count >= (2048 :: Int)+ then fail "cost model exceeds 2048 parameters"+ else do+ value <- Decode.decodeInt64+ indefiniteCosts (count + 1) (value : values)++encodeCostModels :: CostModels -> Encode.Encoding+encodeCostModels (CostModels models) = Encode.encodeMapLen (fromIntegral (Map.size models)) <> foldMap encodeEntry (Map.toAscList models)+ where+ encodeEntry (language, model) = Encode.encodeWord8 language <> encodeCostArray model++decodeCostModels :: Decode.Decoder s CostModels+decodeCostModels = do+ count <- Decode.decodeMapLenOrIndef+ case count of+ Just size -> replicateM size decodeEntry >>= uniqueModels+ Nothing -> indefiniteEntries [] >>= uniqueModels+ where+ uniqueModels entries =+ let models = Map.fromList entries+ in if Map.size models == length entries then pure (CostModels models) else fail "duplicate cost model language"+ decodeEntry = do+ language <- Decode.decodeWord8+ model <- decodeCostArray language+ pure (language, model)+ indefiniteEntries entries = do+ end <- Decode.decodeBreakOr+ if end+ then pure entries+ else do+ entry <- decodeEntry+ indefiniteEntries (entry : entries)++-- | Ledger language views preserve the historical Plutus V1 encoding defect.+-- Only known native language ids contribute to the commitment.+encodeLanguageViews :: CostModels -> Encode.Encoding+encodeLanguageViews (CostModels models) =+ Encode.encodeMapLen (fromIntegral (Map.size known))+ <> foldMap encodeEntry (Map.toAscList (Map.delete 0 known))+ <> maybe mempty encodeV1 (Map.lookup 0 known)+ where+ known = Map.filterWithKey (\language _ -> language <= 3) models+ encodeEntry (language, model) = Encode.encodeWord8 language <> encodeCostArray model+ encodeV1 model =+ Encode.encodeBytes (ByteString.singleton 0)+ <> Encode.encodeBytes+ ( Write.toStrictByteString+ (Encode.encodeListLenIndef <> foldMap Encode.encodeInt64 (costs model) <> Encode.encodeBreak)+ )
@@ -0,0 +1,28 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Private representation shared by scoped Ed25519 and BIP32 acquisition.+module Cometa.Internal.Ed25519SigningKey (SigningKey (..)) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.SigningKey as Internal++-- TYPES ----------------------------------------------------------------------++-- | An opaque scoped secret. Escaping a scope does not extend its usable lifetime.+-- Keys of both supported formats use the same operations.+newtype SigningKey = SigningKey Internal.Key
@@ -0,0 +1,33 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Translate private native failures into the public error vocabulary.+module Cometa.Internal.Error (fromNativeFailure) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import Cometa.Internal.Failure (NativeFailure (..))++-- DEFINITIONS ----------------------------------------------------------------++-- | Preserve the operation, exact status and copied diagnostic. Contract+-- failures remain distinct from statuses reported by the native library.+fromNativeFailure :: NativeFailure -> Error+fromNativeFailure failure = case failure of+ NativeFailure operation code message -> NativeError operation (Code.fromNumber code) message+ NativeContractFailure operation -> NativeContractViolation operation
@@ -0,0 +1,153 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Evaluation result validation shared by public injection and native adapters.+-- No native resources are acquired here. Exact redeemer arguments never come+-- from an evaluator result; they are copied from the selected transaction level.+module Cometa.Internal.Evaluation+ ( Target (..),+ RedeemerId (..),+ Budgets,+ mkBudgets,+ budgets,+ Evaluator (..),+ evaluate,+ targetRedeemers,+ validateRequest,+ checkedRedeemers,+ budgetsFromRedeemers,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Protocol.ExUnits (ExUnits)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (foldM_, unless)+import qualified Data.List as List+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Word (Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | Transaction level whose execution budgets are requested. A sub-transaction+-- evaluator still receives the complete enclosing transaction and resolved UTxOs.+data Target+ = -- | Redeemers in the outer transaction witness set.+ TopLevel+ | -- | Zero-based serialized position in the body's sub-transaction list.+ SubTransaction !Word64+ deriving (Eq, Ord, Show)++-- | A redeemer's purpose and zero-based index in its corresponding body field.+-- The index is bounded by 2^32-1, matching serializable redeemer identifiers.+data RedeemerId = RedeemerId !Redeemer.Purpose !Word32 deriving (Eq, Ord, Show)++-- | Unique sorted execution budgets. Equality compares identifiers and both+-- budget components. No script argument or transaction bytes occur in a result.+newtype Budgets = Budgets [(RedeemerId, ExUnits)] deriving (Eq, Show)++-- | An application-supplied evaluator. Expected failures use 'Either'; thrown+-- exceptions retain ordinary IO behavior. It receives the complete immutable+-- transaction and caller-supplied resolved UTxO snapshot. Implementations must+-- return exactly one budget for each redeemer at the requested level.+newtype Evaluator = Evaluator+ { -- | Perform evaluation without installing budgets or changing the input.+ -- Use 'evaluate' to check target, resolution and result correspondence.+ evaluateTransaction :: Target -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Budgets)+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Reject duplicate identifiers, then sort by purpose and index. Budgets contain+-- unsigned 64-bit memory units and CPU steps; this does not run a script.+mkBudgets :: [(RedeemerId, ExUnits)] -> Either Error Budgets+mkBudgets values = do+ let sorted = List.sortOn fst values+ unless (length sorted == Map.size (Map.fromList sorted)) (Left (InvalidEvaluationResult "Duplicate redeemer budget identifier"))+ pure (Budgets sorted)++-- | Budgets in ascending purpose/index order.+budgets :: Budgets -> [(RedeemerId, ExUnits)]+budgets (Budgets values) = values++-- | Validate the target and resolved-input uniqueness, call the injected+-- evaluator, and require complete identifier correspondence. Missing or unknown+-- identifiers return 'InvalidEvaluationResult'. Duplicate resolved references+-- return 'InvalidEvaluationRequest'. This neither checks chain freshness nor+-- requires all spending/reference inputs to resolve; that is evaluator-specific.+-- No body, script argument, witness or commitment is modified.+evaluate :: Evaluator -> Target -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Budgets)+evaluate evaluator target transaction resolved = case validateRequest target transaction resolved of+ Left failure -> pure (Left failure)+ Right () -> do+ result <- evaluateTransaction evaluator target transaction resolved+ pure $ do+ value <- result+ _ <- checkedRedeemers target transaction value+ pure value++validateRequest :: Target -> Tx.Transaction -> [Utxo.Utxo] -> Either Error ()+validateRequest target transaction resolved = do+ _ <- targetRedeemers target transaction+ foldM_ insert Map.empty resolved+ where+ insert values value+ | Map.member (Utxo.input value) values = Left (InvalidEvaluationRequest "Duplicate resolved input reference")+ | otherwise = Right (Map.insert (Utxo.input value) value values)++targetRedeemers :: Target -> Tx.Transaction -> Either Error [Redeemer.Redeemer]+targetRedeemers target transaction = case target of+ TopLevel -> Right (Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction)))+ SubTransaction index -> case dropInteger (toInteger index) subs of+ [] -> Left (InvalidEvaluationRequest "Sub-transaction target is out of range")+ selected : _ -> Right (Witnesses.redeemers (Witnesses.toWitnesses (Sub.witnesses selected)))+ where+ subs = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ dropInteger 0 values = values+ dropInteger _ [] = []+ dropInteger count (_ : rest) = dropInteger (count - 1) rest++identifier :: Redeemer.Redeemer -> RedeemerId+identifier value = RedeemerId (Redeemer.purpose value) (Redeemer.index value)++checkedRedeemers :: Target -> Tx.Transaction -> Budgets -> Either Error [Redeemer.Redeemer]+checkedRedeemers target transaction computed = do+ expected <- targetRedeemers target transaction+ let requested = Map.fromList [(identifier r, r) | r <- expected]+ returned = Map.fromList (budgets computed)+ unless (Map.keys requested == Map.keys returned) (Left (InvalidEvaluationResult "Missing or unknown redeemer budget identifiers"))+ traverse (replace returned) expected+ where+ replace values original = case Map.lookup (identifier original) values of+ Nothing -> Left (InvalidEvaluationResult "Missing redeemer budget identifier")+ Just units -> Right original {Redeemer.executionUnits = units}++budgetsFromRedeemers :: Target -> Tx.Transaction -> [Redeemer.Redeemer] -> Either Error Budgets+budgetsFromRedeemers target transaction returned = do+ computed <- mkBudgets [(identifier r, Redeemer.executionUnits r) | r <- returned]+ expected <- checkedRedeemers target transaction computed+ let ordered = List.sortOn identifier returned+ unless (ordered == List.sortOn identifier expected) (Left (InvalidEvaluationResult "Evaluator changed exact redeemer arguments"))+ pure computed
@@ -0,0 +1,140 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Each invocation owns a distinct evaluator and parsed transaction snapshot.+-- Safe synchronous C return encloses every native owner, including cancellation.+module Cometa.Internal.Evaluation.Native (Config (..), evaluator, runUnchecked) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Evaluation as Evaluation+import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.FFI.NativeEvaluation as FFI+import qualified Cometa.Internal.FFI.Runtime as Raw+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.SlotConfig as Slots+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import Control.Exception (bracket)+import Control.Monad (unless)+import Data.ByteString (ByteString)+import Data.Foldable (traverse_)+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Native evaluator context. The schedule applies to every validity interval;+-- the protocol major selects language and builtin availability. Missing cost+-- models use the built-in per-version defaults. This is phase-2 execution,+-- not a check that the complete transaction is admissible on chain.+data Config = Config+ { -- | Constant-duration schedule, in Unix milliseconds.+ slotConfig :: !Slots.SlotConfig,+ -- | Ledger protocol major version (minor versions do not affect this VM).+ protocolMajor :: !Word64,+ -- | Ledger coefficients keyed by language id; empty selects VM defaults.+ costModels :: !Models.CostModels+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Construct an injectable evaluator. Every target evaluates all levels: a+-- failure in any level fails the request, and execution consumes a shared limit+-- of 100,000,000 memory units and 100,000,000,000 CPU steps. The target selects+-- only which level's budgets are returned. No transaction bytes are changed.+--+-- All spending and reference inputs at every level must resolve exactly once;+-- extra resolved UTxOs are allowed. Validity bounds must fit the supplied slot+-- schedule. No scripts returns empty budgets after these checks.+evaluator :: Config -> Evaluation.Evaluator+evaluator config = Evaluation.Evaluator $ \target transaction resolved -> case validate config target transaction resolved of+ Left failure -> pure (Left failure)+ Right () -> do+ result <- runUnchecked config target (Tx.encodeCbor transaction) (encodeUtxos resolved)+ pure $ do+ bytes <- result+ returned <- Redeemer.decodeCollectionCbor bytes+ Evaluation.budgetsFromRedeemers target transaction returned++validate :: Config -> Evaluation.Target -> Tx.Transaction -> [Utxo.Utxo] -> Either Error ()+validate config target transaction resolved = do+ Evaluation.validateRequest target transaction resolved+ traverse_ checkLevel levels+ where+ body = Body.toBody (Tx.body transaction)+ levels = Body.bodyFields body : maybe [] (map (SubBody.fields . SubBody.toBody . Sub.body)) (Body.bodySubTransactions body)+ available = Set.fromList (map Utxo.input resolved)+ checkLevel fields = do+ let required = Fields.fieldInputs fields ++ fromMaybe [] (Fields.fieldReferenceInputs fields)+ unless (all (`Set.member` available) required) (Left (InvalidEvaluationRequest "All spending and reference inputs must resolve"))+ traverse_ (Slots.slotToTime (slotConfig config)) (Fields.fieldInvalidBefore fields)+ traverse_ (Slots.slotToTime (slotConfig config)) (Fields.fieldInvalidAfter fields)++encodeUtxos :: [Utxo.Utxo] -> ByteString+encodeUtxos values = Cbor.encode (E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Utxo.encodeCbor) values)++-- | Internal malformed transport boundary for partial-cleanup tests.+runUnchecked :: Config -> Evaluation.Target -> ByteString -> ByteString -> IO (Either Error ByteString)+runUnchecked config target transaction resolved =+ Runtime.withBytes (Models.encodeCbor (costModels config)) $ \models modelsSize ->+ Runtime.withBytes transaction $ \tx txSize ->+ Runtime.withBytes resolved $ \utxos utxosSize ->+ withResult (FFI.cRun (Slots.zeroTime slots) (Slots.zeroSlot slots) (Slots.slotLength slots) (protocolMajor config) isSub index models modelsSize tx txSize utxos utxosSize)+ where+ slots = slotConfig config+ (isSub, index) = case target of+ Evaluation.TopLevel -> (0, 0)+ Evaluation.SubTransaction position -> (1, position)++-- Both slots initialize under mask and release after copying on every path.+withResult :: (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)+withResult call = alloca $ \output -> alloca $ \diagnostic ->+ bracket+ (poke output nullPtr >> poke diagnostic nullPtr)+ (\() -> Raw.cBufferRelease output >> Raw.cBufferRelease diagnostic)+ $ \() -> do+ status <- call output diagnostic+ if status == Status.success+ then peek output >>= Runtime.copyBuffer "evaluation.native"+ else do+ pointer <- peek diagnostic+ if pointer == nullPtr+ then do+ checked <- Runtime.checkStatus "evaluation.native" status+ pure (checked >> Left (NativeContractViolation "evaluation.native.status"))+ else do+ copied <- Runtime.copyBuffer "evaluation.native.diagnostic" pointer+ pure $ case copied of+ Left failure -> Left failure+ Right bytes -> Left (NativeError "evaluation.native" (Code.fromNumber (toInteger status)) (Text.decodeUtf8With (\_ _ -> Just '\xfffd') bytes))
@@ -0,0 +1,116 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private native evaluator injection. Public direct Haskell evaluation avoids+-- a C roundtrip. Runtime scopes root registrations through final callback unwind;+-- no native context handle appears in the public evaluator record.+module Cometa.Internal.EvaluationNative+ ( NativeEvaluator,+ withEvaluator,+ withProviderEvaluator,+ withDispatch,+ withRetained,+ close,+ evaluate,+ evaluateRepeated,+ dispatch,+ runUnchecked,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Evaluation as Evaluation+import qualified Cometa.Internal.FFI.Evaluation as FFI+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import Data.ByteString (ByteString)+import Data.Word (Word32)++-- TYPES ----------------------------------------------------------------------++data NativeEvaluator = NativeEvaluator !Runtime.Runtime !Evaluation.Target !Bool++-- DEFINITIONS ----------------------------------------------------------------++withEvaluator :: Evaluation.Evaluator -> Evaluation.Target -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)+withEvaluator evaluator target = withDispatch target (dispatch evaluator target)++-- | Real provider-backed native factory, bound to the provider's top-level ABI.+withProviderEvaluator :: Evaluation.Evaluator -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)+withProviderEvaluator evaluator action = Runtime.withRuntime route $ \runtime -> action (NativeEvaluator runtime Evaluation.TopLevel True)+ where+ route operation = dispatch evaluator Evaluation.TopLevel (if operation == 9 then 100 else operation)++-- | Private malformed-transport injection for ownership tests.+withDispatch :: Evaluation.Target -> Runtime.Dispatch -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)+withDispatch target handler action = Runtime.withRuntime handler $ \runtime -> action (NativeEvaluator runtime target False)++withRetained :: NativeEvaluator -> (NativeEvaluator -> IO (Either Error a)) -> IO (Either Error a)+withRetained (NativeEvaluator runtime target provider) action = Runtime.withRetained runtime $ \alias -> action (NativeEvaluator alias target provider)++close :: NativeEvaluator -> IO (Either Error ())+close (NativeEvaluator runtime _ _) = Runtime.close runtime++evaluate :: NativeEvaluator -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Evaluation.Budgets)+evaluate = evaluateRepeated 1++evaluateRepeated :: Word32 -> NativeEvaluator -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Evaluation.Budgets)+evaluateRepeated count handle@(NativeEvaluator _ target _) transaction resolved = case Evaluation.validateRequest target transaction resolved of+ Left failure -> pure (Left failure)+ Right () -> do+ result <- runUnchecked count handle (Tx.encodeCbor transaction) (encodeUtxos resolved)+ pure $ do+ bytes <- result+ redeemers <- Redeemer.decodeCollectionCbor bytes+ Evaluation.budgetsFromRedeemers target transaction redeemers++-- | Test-only malformed/reply and partial-cleanup injection boundary. Runtime+-- activation still encloses all native work and callbacks.+runUnchecked :: Word32 -> NativeEvaluator -> ByteString -> ByteString -> IO (Either Error ByteString)+runUnchecked count (NativeEvaluator runtime _ provider) transaction resolved = Runtime.withOperation runtime $ \context ->+ Runtime.withBytes transaction $ \txBytes txSize ->+ Runtime.withBytes resolved $ \utxoBytes utxoSize ->+ Runtime.withOwnedBuffer "evaluation.evaluate" ((if provider then FFI.cRunProvider else FFI.cRun) context txBytes txSize utxoBytes utxoSize count)++-- | Native serialization snapshots the complete native transaction. Its outer+-- frame may be definite even when the original input used an indefinite array;+-- existing exact body, script, argument and witness child encodings are retained.+dispatch :: Evaluation.Evaluator -> Evaluation.Target -> Runtime.Dispatch+dispatch evaluator target operation input+ | operation /= 100 = pure (Left (UnsupportedOperation "Unknown evaluator callback operation"))+ | otherwise = case decodeRequest input of+ Left failure -> pure (Left failure)+ Right (transaction, resolved) -> do+ result <- Evaluation.evaluate evaluator target transaction resolved+ pure $ do+ computed <- result+ values <- Evaluation.checkedRedeemers target transaction computed+ Redeemer.encodeCollectionCbor values++encodeUtxos :: [Utxo.Utxo] -> ByteString+encodeUtxos values = Cbor.encode (E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Utxo.encodeCbor) values)++decodeRequest :: ByteString -> Either Error (Tx.Transaction, [Utxo.Utxo])+decodeRequest bytes = Cbor.decodeAs InvalidEvaluationRequest parser bytes+ where+ parser = Cbor.array 2 ((,) <$> Cbor.nested bytes Tx.decodeCbor <*> Cbor.list (Cbor.nested bytes Utxo.decodeCbor))
@@ -0,0 +1,451 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Private immutable governance representations and CBOR schemas.+-- No native object is retained. Public modules select the domain operations;+-- parser workers remain private to this module.+module Cometa.Internal.Governance+ ( Url,+ mkUrl,+ urlText,+ DataHash,+ dataHashFromBytes,+ dataHashBytes,+ Anchor (..),+ encodeAnchor,+ decodeAnchor,+ ActionId (..),+ encodeActionId,+ decodeActionId,+ DRep (..),+ encodeDRep,+ decodeDRep,+ Vote (..),+ Voter (..),+ VotingProcedure (..),+ VotingProcedures,+ empty,+ singleton,+ fromList,+ toList,+ insert,+ lookup,+ merge,+ EncodedVotingProcedures,+ encodeVoting,+ decodeVoting,+ fromVotingProcedures,+ toVotingProcedures,+ toCbor,+ encodeVoter,+ decodeVoter,+ encodeProcedure,+ decodeProcedure,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import Cometa.TransactionId (TransactionId)+import qualified Cometa.TransactionId as TransactionId+import Control.Monad (foldM, replicateM, unless, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Prelude hiding (lookup)++-- TYPES ----------------------------------------------------------------------++-- | Metadata location containing 1 through 128 UTF-8 bytes and no NUL.+-- No URI syntax, network reachability, or payload validation is implied.+-- Equality and ordering compare text. 'Show' is diagnostic.+newtype Url = Url Text deriving (Eq, Ord, Show)++-- | An exact 32-byte BLAKE2b-256 digest of off-chain metadata bytes.+-- Importing bytes does not verify metadata. Equality and ordering compare bytes.+newtype DataHash = DataHash ByteString deriving (Eq, Ord, Show)++-- | A metadata location and the expected hash of its payload. Assembly is total+-- because both components are validated. A location does not authenticate data+-- unless the retrieved bytes are checked against the hash.+data Anchor = Anchor+ { -- | Off-chain metadata location.+ url :: !Url,+ -- | Expected digest of the exact off-chain payload bytes.+ dataHash :: !DataHash+ }+ deriving (Eq, Ord, Show)++-- | A proposal's identity: the transaction containing it and its zero-based+-- index within that transaction. The standalone native schema permits the full+-- unsigned 64-bit index range. This does not establish ledger acceptance of an+-- index in a particular era. Ordering compares transaction bytes, then index.+data ActionId = ActionId+ { -- | Transaction-body hash of the transaction containing the proposal.+ transactionId :: !TransactionId,+ -- | Zero-based proposal index, from 0 through 2^64 - 1.+ index :: !Word64+ }+ deriving (Eq, Ord, Show)++-- | A delegation target. The two special targets are not voting authorities;+-- only a credential can identify a DRep voter.+data DRep+ = -- | A key or script DRep credential.+ DRepCredential !(Credential.Credential Credential.DRep)+ | -- | Delegate to the predefined always-abstain target.+ AlwaysAbstain+ | -- | Delegate to the predefined always-no-confidence target.+ AlwaysNoConfidence+ deriving (Eq, Ord, Show)++-- | A governance voting choice. Ordering follows CBOR codes: No=0, Yes=1,+-- Abstain=2. Abstention is an explicit choice, distinct from an absent vote.+data Vote = No | Yes | Abstain deriving (Eq, Ord, Show, Bounded, Enum)++-- | Authority casting a vote. Committee votes use the hot credential;+-- stake pools have key authorities only. Ordering follows native voter codes+-- (committee key/script, DRep key/script, pool key), then exact hash bytes.+data Voter+ = -- | Constitutional committee hot key or script.+ CommitteeVoter !(Credential.Credential Credential.CommitteeHot)+ | -- | DRep key or script; special delegation targets cannot vote.+ DRepVoter !(Credential.Credential Credential.DRep)+ | -- | Stake pool verification-key hash.+ StakePoolVoter !(Credential.KeyHash Credential.StakePool)+ deriving (Eq, Ord, Show)++-- | A voting choice and optional explanation. 'Nothing' encodes as CBOR null;+-- a present anchor carries a validated metadata location and payload hash.+data VotingProcedure = VotingProcedure+ { -- | Explicit choice on the proposal.+ vote :: !Vote,+ -- | Optional off-chain explanation.+ anchor :: !(Maybe Anchor)+ }+ deriving (Eq, Ord, Show)++-- | At most one procedure for each voter/action pair. Empty is valid; stored+-- voters always have at least one procedure. Equality is semantic; ordering+-- compares sorted voter/action entries and their procedures. 'Show' is diagnostic.+newtype VotingProcedures = VotingProcedures (Map Voter (Map ActionId VotingProcedure))+ deriving (Eq, Ord, Show)++-- | Voting data with its exact original CBOR encoding. Equality and ordering+-- compare encoded bytes; 'toVotingProcedures' permits semantic comparison.+-- Imported map order and nonminimal encodings remain observable through 'toCbor'.+data EncodedVotingProcedures = EncodedVotingProcedures !ByteString !VotingProcedures+ deriving (Show)++instance Eq EncodedVotingProcedures where+ left == right = toCbor left == toCbor right++instance Ord EncodedVotingProcedures where+ compare left right = compare (toCbor left) (toCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate 1 through 128 UTF-8 bytes and absence of NUL. Bad length returns+-- 'InvalidAnchorUrlLength'; NUL returns 'InvalidAnchorUrl'. No URI parsing or+-- network request occurs.+mkUrl :: Text -> Either Error Url+mkUrl value+ | size < 1 || size > 128 = Left (InvalidAnchorUrlLength size)+ | Text.any (== '\0') value = Left InvalidAnchorUrl+ | otherwise = Right (Url value)+ where+ size = ByteString.length (Text.encodeUtf8 value)++-- | Exact validated location text.+urlText :: Url -> Text+urlText (Url value) = value++-- | Import exactly 32 bytes without hashing. Another length returns+-- 'InvalidAnchorDataHashLength' with the actual byte count.+dataHashFromBytes :: ByteString -> Either Error DataHash+dataHashFromBytes bytes+ | ByteString.length bytes == 32 = Right (DataHash bytes)+ | otherwise = Left (InvalidAnchorDataHashLength (ByteString.length bytes))++-- | Exact expected payload hash bytes.+dataHashBytes :: DataHash -> ByteString+dataHashBytes (DataHash bytes) = bytes++-- | No votes.+empty :: VotingProcedures+empty = VotingProcedures Map.empty++-- | One voter casting one procedure on one action. All arguments are validated+-- domain values, so assembly cannot fail.+singleton :: Voter -> ActionId -> VotingProcedure -> VotingProcedures+singleton voter action procedure = VotingProcedures (Map.singleton voter (Map.singleton action procedure))++-- | Assemble triples in any order. Repeating a voter/action pair returns+-- 'DuplicateGovernanceVote', even when the procedures agree. No vote is discarded.+fromList :: [(Voter, ActionId, VotingProcedure)] -> Either Error VotingProcedures+fromList = foldM (\votes (voter, action, procedure) -> insert voter action procedure votes) empty++-- | Entries sorted by voter kind/hash, then transaction hash/index. Input+-- insertion order is not retained by this semantic collection.+toList :: VotingProcedures -> [(Voter, ActionId, VotingProcedure)]+toList (VotingProcedures voters) =+ [(voter, action, procedure) | (voter, actions) <- Map.toAscList voters, (action, procedure) <- Map.toAscList actions]++-- | Add a vote, rejecting an existing voter/action pair with+-- 'DuplicateGovernanceVote'. Other votes remain unchanged.+insert :: Voter -> ActionId -> VotingProcedure -> VotingProcedures -> Either Error VotingProcedures+insert voter action procedure (VotingProcedures voters)+ | Map.member action actions = Left DuplicateGovernanceVote+ | otherwise = Right (VotingProcedures (Map.insert voter (Map.insert action procedure actions) voters))+ where+ actions = Map.findWithDefault Map.empty voter voters++-- | Find the procedure for a voter/action pair; absence is legitimate.+lookup :: Voter -> ActionId -> VotingProcedures -> Maybe VotingProcedure+lookup voter action (VotingProcedures voters) = Map.lookup voter voters >>= Map.lookup action++-- | Combine disjoint voter/action pairs. Any overlap returns+-- 'DuplicateGovernanceVote', even when both votes agree. Successful merge is+-- associative and commutative, with 'empty' as its identity.+merge :: VotingProcedures -> VotingProcedures -> Either Error VotingProcedures+merge left right = foldM (\votes (voter, action, procedure) -> insert voter action procedure votes) left (toList right)++encodeAnchor :: Anchor -> ByteString+encodeAnchor = Write.toStrictByteString . anchorEncoding++decodeAnchor :: ByteString -> Either Error Anchor+decodeAnchor = decodeComplete anchorDecoder++encodeActionId :: ActionId -> ByteString+encodeActionId = Write.toStrictByteString . actionEncoding++decodeActionId :: ByteString -> Either Error ActionId+decodeActionId = decodeComplete actionDecoder++encodeDRep :: DRep -> ByteString+encodeDRep = Write.toStrictByteString . drepEncoding++decodeDRep :: ByteString -> Either Error DRep+decodeDRep = decodeComplete drepDecoder++encodeVoter :: Voter -> ByteString+encodeVoter = Write.toStrictByteString . voterEncoding++decodeVoter :: ByteString -> Either Error Voter+decodeVoter = decodeComplete voterDecoder++encodeProcedure :: VotingProcedure -> ByteString+encodeProcedure = Write.toStrictByteString . procedureEncoding++decodeProcedure :: ByteString -> Either Error VotingProcedure+decodeProcedure = decodeComplete procedureDecoder++-- | Serialize fresh data in native voter/hash/index order with definite maps,+-- definite arrays and shortest integer encodings. Re-encoding semantic data+-- inspected from external CBOR can change transaction identity; use 'toCbor'+-- on the encoded wrapper to retain imported bytes.+encodeVoting :: VotingProcedures -> ByteString+encodeVoting = Write.toStrictByteString . votingEncoding++-- | Decode exactly one complete nested voting map. Definite and indefinite+-- containers and nonminimal unsigned integers are accepted. Duplicate voter+-- keys, duplicate voter/action pairs and empty inner maps are rejected rather+-- than merged or discarded. Invalid schema, bounds, UTF-8, or trailing bytes+-- returns 'InvalidGovernanceCbor'. Original bytes are preserved unchanged.+decodeVoting :: ByteString -> Either Error EncodedVotingProcedures+decodeVoting bytes = EncodedVotingProcedures bytes <$> decodeComplete votingDecoder bytes++-- | Assign fresh minimal, sorted CBOR to a semantic collection.+fromVotingProcedures :: VotingProcedures -> EncodedVotingProcedures+fromVotingProcedures value = EncodedVotingProcedures (encodeVoting value) value++-- | Inspect votes without changing their preserved encoding.+toVotingProcedures :: EncodedVotingProcedures -> VotingProcedures+toVotingProcedures (EncodedVotingProcedures _ value) = value++-- | The exact imported encoding, or the fresh encoding assigned by+-- 'fromVotingProcedures'.+toCbor :: EncodedVotingProcedures -> ByteString+toCbor (EncodedVotingProcedures bytes _) = bytes++anchorEncoding :: Anchor -> Encode.Encoding+anchorEncoding (Anchor location digest) = Encode.encodeListLen 2 <> Encode.encodeString (urlText location) <> Encode.encodeBytes (dataHashBytes digest)++actionEncoding :: ActionId -> Encode.Encoding+actionEncoding (ActionId hash actionIndex) = Encode.encodeListLen 2 <> Encode.encodeBytes (TransactionId.toBytes hash) <> Encode.encodeWord64 actionIndex++credentialEncoding :: Credential.Credential purpose -> Encode.Encoding+credentialEncoding credential = case credential of+ Credential.KeyCredential hash -> Encode.encodeWord 0 <> Encode.encodeBytes (Credential.keyHashBytes hash)+ Credential.ScriptCredential hash -> Encode.encodeWord 1 <> Encode.encodeBytes (Credential.scriptHashBytes hash)++drepEncoding :: DRep -> Encode.Encoding+drepEncoding drep = case drep of+ DRepCredential credential -> Encode.encodeListLen 2 <> credentialEncoding credential+ AlwaysAbstain -> Encode.encodeListLen 1 <> Encode.encodeWord 2+ AlwaysNoConfidence -> Encode.encodeListLen 1 <> Encode.encodeWord 3++voterEncoding :: Voter -> Encode.Encoding+voterEncoding voter =+ Encode.encodeListLen 2 <> case voter of+ CommitteeVoter credential -> credentialEncoding credential+ DRepVoter credential -> case credential of+ Credential.KeyCredential hash -> Encode.encodeWord 2 <> Encode.encodeBytes (Credential.keyHashBytes hash)+ Credential.ScriptCredential hash -> Encode.encodeWord 3 <> Encode.encodeBytes (Credential.scriptHashBytes hash)+ StakePoolVoter hash -> Encode.encodeWord 4 <> Encode.encodeBytes (Credential.keyHashBytes hash)++procedureEncoding :: VotingProcedure -> Encode.Encoding+procedureEncoding (VotingProcedure choice explanation) = Encode.encodeListLen 2 <> Encode.encodeWord (voteCode choice) <> maybe Encode.encodeNull anchorEncoding explanation++votingEncoding :: VotingProcedures -> Encode.Encoding+votingEncoding (VotingProcedures voters) = Encode.encodeMapLen (fromIntegral (Map.size voters)) <> foldMap encodeVoterVotes (Map.toAscList voters)+ where+ encodeVoterVotes (voter, actions) = voterEncoding voter <> Encode.encodeMapLen (fromIntegral (Map.size actions)) <> foldMap (\(action, procedure) -> actionEncoding action <> procedureEncoding procedure) (Map.toAscList actions)++voteCode :: Vote -> Word+voteCode No = 0+voteCode Yes = 1+voteCode Abstain = 2++anchorDecoder :: Decode.Decoder s Anchor+anchorDecoder = arrayOf 2 $ do+ location <- validated mkUrl =<< Decode.decodeString+ digest <- validated dataHashFromBytes =<< Decode.decodeBytes+ pure (Anchor location digest)++actionDecoder :: Decode.Decoder s ActionId+actionDecoder = arrayOf 2 $ do+ hash <- validated TransactionId.fromBytes =<< Decode.decodeBytes+ ActionId hash <$> Decode.decodeWord64++credentialDecoder :: Word -> Decode.Decoder s (Credential.Credential purpose)+credentialDecoder kind = do+ bytes <- Decode.decodeBytes+ case kind of+ 0 -> Credential.KeyCredential <$> validated Credential.keyHashFromBytes bytes+ 1 -> Credential.ScriptCredential <$> validated Credential.scriptHashFromBytes bytes+ _ -> fail "Invalid credential kind"++drepDecoder :: Decode.Decoder s DRep+drepDecoder = do+ size <- Decode.decodeListLenOrIndef+ kind <- Decode.decodeWord+ let expected = if kind < 2 then 2 else 1+ checkSize expected size+ value <- case kind of+ 0 -> DRepCredential <$> credentialDecoder 0+ 1 -> DRepCredential <$> credentialDecoder 1+ 2 -> pure AlwaysAbstain+ 3 -> pure AlwaysNoConfidence+ _ -> fail "Invalid DRep kind"+ endArray size+ pure value++voterDecoder :: Decode.Decoder s Voter+voterDecoder = arrayOf 2 $ do+ kind <- Decode.decodeWord+ case kind of+ 0 -> CommitteeVoter <$> credentialDecoder 0+ 1 -> CommitteeVoter <$> credentialDecoder 1+ 2 -> DRepVoter <$> credentialDecoder 0+ 3 -> DRepVoter <$> credentialDecoder 1+ 4 -> StakePoolVoter <$> (validated Credential.keyHashFromBytes =<< Decode.decodeBytes)+ _ -> fail "Invalid voter kind"++procedureDecoder :: Decode.Decoder s VotingProcedure+procedureDecoder = arrayOf 2 $ do+ code <- Decode.decodeWord+ choice <- case code of+ 0 -> pure No+ 1 -> pure Yes+ 2 -> pure Abstain+ _ -> fail "Invalid vote code"+ token <- Decode.peekTokenType+ explanation <- if token == Decode.TypeNull then Decode.decodeNull >> pure Nothing else Just <$> anchorDecoder+ pure (VotingProcedure choice explanation)++votingDecoder :: Decode.Decoder s VotingProcedures+votingDecoder = do+ pairs <- mapEntries $ do+ voter <- voterDecoder+ actions <- mapEntries ((,) <$> actionDecoder <*> procedureDecoder)+ when (null actions) (fail "Empty inner voting map")+ pure (voter, actions)+ voters <- foldM addVoter Map.empty pairs+ pure (VotingProcedures voters)+ where+ addVoter voters (voter, actions)+ | Map.member voter voters = fail "Duplicate voter key"+ | otherwise = do+ unique <- foldM addAction Map.empty actions+ pure (Map.insert voter unique voters)+ addAction actions (action, procedure)+ | Map.member action actions = fail "Duplicate governance action key"+ | otherwise = pure (Map.insert action procedure actions)++mapEntries :: Decode.Decoder s a -> Decode.Decoder s [a]+mapEntries entry = do+ size <- Decode.decodeMapLenOrIndef+ case size of+ Just count -> replicateM count entry+ Nothing -> go+ where+ go = do+ ended <- Decode.decodeBreakOr+ if ended then pure [] else (:) <$> entry <*> go++arrayOf :: Int -> Decode.Decoder s a -> Decode.Decoder s a+arrayOf expected entry = do+ size <- Decode.decodeListLenOrIndef+ checkSize expected size+ value <- entry+ endArray size+ pure value++checkSize :: Int -> Maybe Int -> Decode.Decoder s ()+checkSize expected size = case size of+ Just actual -> unless (actual == expected) (fail "Incorrect governance array length")+ Nothing -> pure ()++endArray :: Maybe Int -> Decode.Decoder s ()+endArray size = case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- Decode.decodeBreakOr+ unless ended (fail "Extra governance array elements")++validated :: (a -> Either Error b) -> a -> Decode.Decoder s b+validated validate value = either (fail . show) pure (validate value)++decodeComplete :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a+decodeComplete decoder bytes = case Read.deserialiseFromBytes decoder (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidGovernanceCbor (Text.pack (show failure)))+ Right (remaining, value)+ | Lazy.null remaining -> Right value+ | otherwise -> Left (InvalidGovernanceCbor "Trailing bytes after governance value")
@@ -0,0 +1,46 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Fresh native inspection results copied before releasing their buffer. The+-- existing owned-buffer runner preserves native status and cleans partial output+-- on normal return, native failure and asynchronous unwind.+module Cometa.Internal.Inspection (inspect, runUnchecked) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.FFI.Inspection as FFI+import qualified Cometa.Internal.Runtime as Runtime+import Data.Aeson (Value, eitherDecodeStrict')+import Data.ByteString (ByteString)+import Data.Text (Text)+import Foreign.C.Types (CUInt)++-- DEFINITIONS ----------------------------------------------------------------++inspect :: Text -> CUInt -> ByteString -> IO (Either Error Value)+inspect operation kind bytes = do+ result <- runUnchecked kind bytes+ pure $ do+ json <- result+ either (const (Left (NativeContractViolation operation))) Right (eitherDecodeStrict' json)++-- | Private malformed-CBOR/operation transport for error and cleanup tests. All+-- native owners still remain scoped through safe foreign return before copying.+runUnchecked :: CUInt -> ByteString -> IO (Either Error ByteString)+runUnchecked kind bytes = Runtime.withBytes bytes $ \input size ->+ Runtime.withOwnedBuffer "inspection.compute" (FFI.cCompute kind input size)
@@ -0,0 +1,120 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Borrowed inputs and scoped key access; both native output slots are released+-- on success, native error, copying exception and cancellation.+module Cometa.Internal.Message.Cip8+ ( Binding,+ addressBinding,+ keyHashBinding,+ SignedMessage (..),+ sign,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Credential as Credential+import Cometa.Crypto.Ed25519.SigningKey (SigningKey)+import Cometa.Error (Error (..))+import Cometa.Internal.Ed25519SigningKey (SigningKey (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Cip8 as Native+import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.FFI.PasswordCrypto as Buffer+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyStaticText)+import qualified Cometa.Internal.SigningKey as Key+import Control.Exception (bracket)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Word (Word8)+import Foreign.C.Types (CSize, CUInt)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | A validated address or 28-byte key hash to include in the protected headers.+-- This value does not establish a relationship with a signing key.+data Binding = Binding !CUInt !ByteString deriving (Eq, Show)++-- | Two independently owned CBOR encodings, without hexadecimal conversion.+-- The signature includes the payload and the COSE key includes its public key.+data SignedMessage = SignedMessage+ { -- | CBOR-encoded COSE_Sign1 containing the payload and signature.+ coseSign1 :: !ByteString,+ -- | CBOR-encoded COSE_Key containing the Ed25519 public key.+ coseKey :: !ByteString+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Bind the signed headers to the complete validated address bytes.+addressBinding :: Address.Address -> Binding+addressBinding = Binding 0 . Address.toBytes++-- | Bind the signed headers to a validated key hash of any credential role.+keyHashBinding :: Credential.KeyHash purpose -> Binding+keyHashBinding = Binding 1 . Credential.keyHashBytes++-- | Sign a nonempty binary payload using a live normal or extended key.+-- Empty input returns native @InvalidArgument@; a closed key returns+-- 'SigningKeyClosed'. The result can outlive the key's scope.+sign :: SigningKey -> Binding -> ByteString -> IO (Either Error SignedMessage)+sign (SigningKey key) (Binding kind binding) message =+ withBytes binding $ \bindingPointer bindingSize ->+ withBytes message $ \messagePointer messageSize -> do+ result <- Key.withKey key $ \pointer ->+ withOutput $ \signSlot -> withOutput $ \keySlot -> do+ code <- Native.cSign pointer kind bindingPointer bindingSize messagePointer messageSize signSlot keySlot+ if code /= Status.success+ then do+ diagnostic <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (Key.NativeFailure (NativeFailure "cip8.sign" (toInteger code) diagnostic)))+ else do+ encodedSign <- copyBuffer signSlot+ encodedKey <- copyBuffer keySlot+ pure $ case (encodedSign, encodedKey) of+ (Just signBytes, Just keyBytes) -> Right (SignedMessage signBytes keyBytes)+ _ -> Left (Key.NativeFailure (NativeContractFailure "cip8.sign"))+ pure $ case result of+ Right value -> Right value+ Left Key.Closed -> Left SigningKeyClosed+ Left (Key.NativeFailure failure) -> Left (fromNativeFailure failure)+ Left _ -> Left (NativeContractViolation "cip8.sign")++withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)++withOutput :: (Ptr (Ptr Buffer.Buffer) -> IO value) -> IO value+withOutput action = alloca $ \slot -> bracket (poke slot nullPtr >> pure slot) Buffer.cRelease action++copyBuffer :: Ptr (Ptr Buffer.Buffer) -> IO (Maybe ByteString)+copyBuffer slot = do+ pointer <- peek slot+ if pointer == nullPtr+ then pure Nothing+ else do+ size <- Buffer.cSize pointer+ bytes <- Buffer.cData pointer+ if size == 0 || toInteger size > toInteger (maxBound :: Int) || bytes == nullPtr+ then pure Nothing+ else Just <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)
@@ -0,0 +1,104 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Private complete parameter snapshots and native-representability checks.+-- Wire maps reuse protocol-update keys while requiring every nonoptional snapshot+-- field. A sparse update is never completed with invented defaults.+module Cometa.Internal.ParameterSnapshot (encodeSnapshot, decodeSnapshot, validateNative) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Protocol.Parameters (Parameters (..))+import qualified Cometa.Protocol.Parameters.Update as Update+import Data.ByteString (ByteString)+import Data.Int (Int64)++-- DEFINITIONS ----------------------------------------------------------------++encodeSnapshot :: Parameters -> ByteString+encodeSnapshot = Update.encodeCbor . Update.fromParameters++decodeSnapshot :: ByteString -> Either Error Parameters+decodeSnapshot bytes = do+ change <- Update.toUpdate <$> Update.decodeCbor bytes+ Parameters+ <$> required (Update.updateMinFeeA change)+ <*> required (Update.updateMinFeeB change)+ <*> required (Update.updateMaxBlockBodySize change)+ <*> required (Update.updateMaxTxSize change)+ <*> required (Update.updateMaxBlockHeaderSize change)+ <*> required (Update.updateKeyDeposit change)+ <*> required (Update.updatePoolDeposit change)+ <*> required (Update.updateMaxEpoch change)+ <*> required (Update.updateDesiredPoolCount change)+ <*> required (Update.updatePoolPledgeInfluence change)+ <*> required (Update.updateExpansionRate change)+ <*> required (Update.updateTreasuryGrowthRate change)+ <*> pure (Update.updateDecentralization change)+ <*> pure (Update.updateExtraEntropy change)+ <*> required (Update.updateProtocolVersion change)+ <*> required (Update.updateMinPoolCost change)+ <*> pure (Update.updateAdaPerUtxoByte change)+ <*> pure (Update.updateCostModels change)+ <*> pure (Update.updateExecutionCosts change)+ <*> pure (Update.updateMaxTxExUnits change)+ <*> pure (Update.updateMaxBlockExUnits change)+ <*> pure (Update.updateMaxValueSize change)+ <*> pure (Update.updateCollateralPercentage change)+ <*> pure (Update.updateMaxCollateralInputs change)+ <*> pure (Update.updatePoolVotingThresholds change)+ <*> pure (Update.updateDrepVotingThresholds change)+ <*> pure (Update.updateMinCommitteeSize change)+ <*> pure (Update.updateCommitteeTermLimit change)+ <*> pure (Update.updateGovernanceActionValidityPeriod change)+ <*> pure (Update.updateGovernanceActionDeposit change)+ <*> pure (Update.updateDrepDeposit change)+ <*> pure (Update.updateDrepInactivityPeriod change)+ <*> pure (Update.updateRefScriptCostPerByte change)+ <*> pure (Update.updateMaxRefScriptSizePerBlock change)+ <*> pure (Update.updateMaxRefScriptSizePerTx change)+ <*> pure (Update.updateRefScriptCostStride change)+ <*> pure (Update.updateRefScriptCostMultiplier change)+ <*> pure (Update.updateMaxPledgeLeverage change)+ <*> pure (Update.updateMinPoolMargin change)+ <*> pure (Update.updateLeiosAnnouncementPeriodLength change)+ <*> pure (Update.updateLeiosVotePeriodLength change)+ <*> pure (Update.updateLeiosDiffusionPeriodLength change)+ <*> pure (Update.updateLeiosCommitteeSize change)+ <*> pure (Update.updateLeiosQuorumStakeThreshold change)+ <*> pure (Update.updateMaxEndorserBlockReferencesSize change)+ <*> pure (Update.updateMaxEndorserBlockTxsSize change)+ <*> pure (Update.updateMaxEndorserBlockExecutionUnits change)+ <*> pure (Update.updateMaxRefScriptSizePerEndorserBlock change)+ <*> pure (Update.updatePerasMinCandidateBlockAge change)+ <*> pure (Update.updatePerasHealingFactor change)+ <*> pure (Update.updatePerasCertBoost change)+ <*> pure (Update.updatePerasTargetCommitteeSize change)+ <*> pure (Update.updatePerasBootstrapRound change)+ <*> pure (Update.updatePerasQuorumThresholdSafetyMargin change)+ <*> pure (Update.updateRefInputsCostPerMultiAssetByte change)+ <*> pure (Update.updateRefInputsCostPerDatumByte change)+ where+ required = maybe (Left (InvalidParameterSnapshot "Missing required protocol snapshot field")) Right++-- | The pinned native full-parameter setter accepts a signed max-value size.+-- Reject unsupported narrowing before entering C; the pure snapshot domain+-- remains capable of representing the complete protocol uint64 field.+validateNative :: Parameters -> Either Error ()+validateNative parameters = case parameterMaxValueSize parameters of+ Just value | value > fromIntegral (maxBound :: Int64) -> Left (InvalidParameterSnapshot "Maximum value size exceeds native signed setter range")+ _ -> Right ()
@@ -0,0 +1,35 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Convert one complete update using operation-scoped native owners. The+-- result is copied before release, including on cancellation and decode failure.+module Cometa.Internal.ParameterUpdate (toPlutusData) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import qualified Cometa.Internal.FFI.ParameterUpdate as FFI+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.PlutusData as Data+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++toPlutusData :: ByteString -> IO (Either Error Data.PlutusData)+toPlutusData encoded = Runtime.withBytes encoded $ \bytes size -> do+ result <- Runtime.withOwnedBuffer "parameters.toPlutusData" (FFI.cToPlutusData bytes size)+ pure (result >>= fmap Data.toData . Data.decodeCbor)
@@ -0,0 +1,53 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Concrete purity exception for the separately audited pinned PBKDF2 path.+-- Caller-owned scratch is the only mutable output. Neither native configured+-- allocation, RNG, global state, callbacks nor logging is reached. See+-- docs/development/PBKDF2_PURITY.md. Never generalize to an arbitrary IO runner.+module Cometa.Internal.Pbkdf2Pure (deriveBytes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.PasswordCrypto as Internal+import Control.Exception (evaluate)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import Data.Word (Word32)+import System.IO.Unsafe (unsafePerformIO)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validated inputs only. Force the strict owned result and any diagnostic+-- before returning from this boundary; repeated evaluation is equivalent.+{-# NOINLINE deriveBytes #-}+deriveBytes :: ByteString -> ByteString -> Word32 -> Int -> Either Error ByteString+deriveBytes password salt iterations size = unsafePerformIO $ do+ result <- either (Left . fromNativeFailure) Right <$> Internal.deriveBytes password salt iterations size+ evaluate (forceResult result)+ pure result++forceResult :: Either Error ByteString -> ()+forceResult (Right bytes) = ByteString.length bytes `seq` ()+forceResult (Left (NativeError operation code diagnostic)) =+ Text.length operation `seq` Code.toNumber code `seq` Text.length diagnostic `seq` ()+forceResult (Left (NativeContractViolation operation)) = Text.length operation `seq` ()+forceResult (Left err) = err `seq` ()
@@ -0,0 +1,491 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Immutable pool values and schema workers. No native effects occur here.+module Cometa.Internal.Pool+ ( Ipv4,+ ipv4FromBytes,+ ipv4Bytes,+ ipv4FromText,+ ipv4Text,+ Ipv6,+ ipv6FromBytes,+ ipv6Bytes,+ ipv6FromText,+ ipv6Text,+ DnsName,+ mkDnsName,+ dnsNameText,+ Relay (..),+ Url,+ mkUrl,+ urlText,+ MetadataHash,+ metadataHashFromBytes,+ metadataHashBytes,+ Metadata (..),+ VrfKeyHash,+ vrfKeyHashFromBytes,+ vrfKeyHashBytes,+ BlsKey,+ mkBlsKey,+ publicKeyBytes,+ possessionProofBytes,+ PoolParameters (..),+ parametersFieldCount,+ relayEncoding,+ relayDecoder,+ metadataEncoding,+ metadataDecoder,+ blsEncoding,+ blsDecoder,+ parametersEncoding,+ parametersDecoder,+ parametersDecoderWithFieldCount,+ parametersValueEncoding,+ parametersValueEncodingWith,+ parametersValueDecoder,+ encode,+ decodeComplete,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Credential as Credential+import Cometa.Encoding.Set (SetEncoding (..))+import Cometa.Error (Error (..))+import qualified Cometa.Internal.ProtocolValues as Protocol+import Control.Monad (replicateM, unless, when)+import Data.Bits (shiftR, (.&.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Char (isDigit, isHexDigit)+import Data.List (intercalate)+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word16, Word64)+import Numeric (readHex, showHex)+import Text.Read (readMaybe)++-- TYPES ----------------------------------------------------------------------++-- | IPv4 address in network byte order. Equality and ordering compare bytes.+newtype Ipv4 = Ipv4 ByteString deriving (Eq, Ord, Show)++-- | IPv6 address in network byte order. Equality and ordering compare bytes.+newtype Ipv6 = Ipv6 ByteString deriving (Eq, Ord, Show)++-- | Relay DNS label, containing 1 through 64 UTF-8 bytes and no NUL.+-- DNS syntax and reachability are not checked. Comparison uses text.+newtype DnsName = DnsName Text deriving (Eq, Ord, Show)++-- | Relay alternatives. Ordering follows CBOR codes, then constructor fields.+-- Ports are unsigned 16-bit port numbers; absent fields encode as null.+data Relay+ = -- | IP relay: optional port, IPv4 and IPv6. All may be absent.+ SingleHostAddress !(Maybe Word16) !(Maybe Ipv4) !(Maybe Ipv6)+ | -- | A or AAAA DNS record, with optional port.+ SingleHostName !(Maybe Word16) !DnsName+ | -- | SRV DNS record; its port is supplied by DNS.+ MultiHostName !DnsName+ deriving (Eq, Ord, Show)++-- | Pool metadata location of 0 through 128 UTF-8 bytes with no NUL.+-- No URI syntax or reachability check is implied. Comparison uses text.+newtype Url = Url Text deriving (Eq, Ord, Show)++-- | Exact 32-byte BLAKE2b-256 metadata digest. Comparison uses bytes.+newtype MetadataHash = MetadataHash ByteString deriving (Eq, Ord, Show)++-- | Metadata reference. Fetching and checking the payload is a caller operation.+data Metadata = Metadata+ { -- | Off-chain location, including the native schema's empty location.+ url :: !Url,+ -- | Expected digest of exact payload bytes.+ metadataHash :: !MetadataHash+ }+ deriving (Eq, Ord, Show)++-- | Exact 32-byte VRF verification-key hash. Importing does not verify a key.+newtype VrfKeyHash = VrfKeyHash ByteString deriving (Eq, Ord, Show)++-- | BLS public key (96 bytes) and possession proof (48 bytes). Only lengths+-- are checked; construction does not verify group membership or proof validity.+-- Equality and ordering compare public-key bytes, then proof bytes.+data BlsKey = BlsKey !ByteString !ByteString deriving (Eq, Ord, Show)++-- | Registration parameters. Assembly and record updates are total because+-- constrained fields are validated values. Equality is semantic (numeric margin,+-- unordered owners, ordered relays); Show is diagnostic. No ledger-era admission,+-- minimum cost, pledge funding, or BLS proof verification is implied.+data PoolParameters = PoolParameters+ { -- | Pool operator verification-key hash, exactly 28 bytes.+ operator :: !(Credential.KeyHash Credential.StakePool),+ -- | VRF verification-key hash, exactly 32 bytes.+ vrfKeyHash :: !VrfKeyHash,+ -- | Optional Dijkstra BLS key and proof; absent in earlier registrations.+ blsKey :: !(Maybe BlsKey),+ -- | Pledged lovelace, from zero through 2^64 - 1.+ pledge :: !Word64,+ -- | Fixed pool cost in lovelace, from zero through 2^64 - 1.+ cost :: !Word64,+ -- | Exact share of remaining rewards, zero through one inclusive.+ margin :: !Protocol.UnitInterval,+ -- | Account receiving operator rewards, with its network tag preserved.+ rewardAccount :: !Reward.RewardAddress,+ -- | Staking key hashes. Set semantics remove repeated owners.+ owners :: !(Set (Credential.KeyHash Credential.Stake)),+ -- | Relay sequence; order and duplicates are preserved.+ relays :: ![Relay],+ -- | Optional off-chain metadata reference.+ metadata :: !(Maybe Metadata)+ }+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate an exact four-byte network-order IPv4 address.+-- Wrong lengths return 'InvalidPoolIpLength' with expected and actual lengths.+ipv4FromBytes :: ByteString -> Either Error Ipv4+ipv4FromBytes bytes = Ipv4 <$> exactIp 4 bytes++-- | Exact four-byte address.+ipv4Bytes :: Ipv4 -> ByteString+ipv4Bytes (Ipv4 bytes) = bytes++-- | Parse four decimal octets, each 0 through 255, separated by dots.+-- Leading zeros are accepted; signs, whitespace and empty octets are rejected.+-- Malformed input returns 'InvalidPoolIpText' with a diagnostic.+ipv4FromText :: Text -> Either Error Ipv4+ipv4FromText text = case traverse octet (Text.splitOn "." text) of+ Just values | length values == 4 -> ipv4FromBytes (ByteString.pack values)+ _ -> Left (InvalidPoolIpText "Invalid dotted IPv4 address")+ where+ octet part+ | Text.null part || Text.length part > 3 || not (Text.all isDigit part) = Nothing+ | otherwise = do+ value <- readMaybe (Text.unpack part) :: Maybe Int+ if value <= 255 then Just (fromIntegral value) else Nothing++-- | Canonical dotted decimal, without leading zeros.+ipv4Text :: Ipv4 -> Text+ipv4Text = Text.pack . intercalate "." . map show . ByteString.unpack . ipv4Bytes++-- | Validate an exact sixteen-byte network-order IPv6 address.+ipv6FromBytes :: ByteString -> Either Error Ipv6+ipv6FromBytes bytes = Ipv6 <$> exactIp 16 bytes++-- | Exact sixteen-byte address.+ipv6Bytes :: Ipv6 -> ByteString+ipv6Bytes (Ipv6 bytes) = bytes++-- | Parse IPv6 hexadecimal groups, accepting a single @::@ compression and+-- an optional final dotted IPv4 address. Hexadecimal letter case is ignored;+-- signs, whitespace, repeated compression and incorrect group counts return+-- 'InvalidPoolIpText'.+ipv6FromText :: Text -> Either Error Ipv6+ipv6FromText text = case expandIpv4Suffix text >>= ipv6Groups of+ Just groups -> ipv6FromBytes (ByteString.pack (concatMap networkBytes groups))+ Nothing -> Left (InvalidPoolIpText "Invalid IPv6 address")+ where+ networkBytes value = [fromIntegral (value `shiftR` 8), fromIntegral (value .&. 255)]++ipv6Groups :: Text -> Maybe [Word16]+ipv6Groups text = case Text.splitOn "::" text of+ [whole] -> do+ groups <- side whole+ if length groups == 8 then Just groups else Nothing+ [before, after] -> do+ left <- side before+ right <- side after+ let missing = 8 - length left - length right+ if missing > 0 then Just (left ++ replicate missing 0 ++ right) else Nothing+ _ -> Nothing+ where+ side part+ | Text.null part = Just []+ | otherwise = traverse group (Text.splitOn ":" part)+ group part+ | Text.null part || Text.length part > 4 || not (Text.all isHexDigit part) = Nothing+ | otherwise = case readHex (Text.unpack part) of+ [(value, "")] -> Just value+ _ -> Nothing++-- Convert a final dotted address into two hexadecimal groups before parsing+-- compression. Dotted input anywhere else remains invalid hexadecimal text.+expandIpv4Suffix :: Text -> Maybe Text+expandIpv4Suffix text+ | not (Text.any (== '.') text) = Just text+ | otherwise = do+ let (prefix, suffix) = Text.breakOnEnd ":" text+ when (Text.null prefix) Nothing+ address <- either (const Nothing) Just (ipv4FromText suffix)+ case ByteString.unpack (ipv4Bytes address) of+ [a, b, c, d] -> Just (prefix <> pair a b <> ":" <> pair c d)+ _ -> Nothing+ where+ pair a b = Text.pack (showHex (fromIntegral a * 256 + fromIntegral b :: Word16) "")++-- | Lowercase, fully expanded IPv6 text with eight four-digit groups.+ipv6Text :: Ipv6 -> Text+ipv6Text = Text.intercalate ":" . pairs . ByteString.unpack . ipv6Bytes+ where+ pairs (a : b : rest) = Text.pack (pad a ++ pad b) : pairs rest+ pairs _ = []+ pad value = let digits = showHex value "" in replicate (2 - length digits) '0' ++ digits++exactIp :: Int -> ByteString -> Either Error ByteString+exactIp size bytes+ | ByteString.length bytes == size = Right bytes+ | otherwise = Left (InvalidPoolIpLength size (ByteString.length bytes))++-- | Validate 1 through 64 UTF-8 bytes and reject NUL, returning+-- 'InvalidPoolDnsName' on either violation. DNS syntax is not checked.+mkDnsName :: Text -> Either Error DnsName+mkDnsName text+ | size < 1 || size > 64 || Text.any (== '\0') text = Left (InvalidPoolDnsName "Expected 1 through 64 UTF-8 bytes without NUL")+ | otherwise = Right (DnsName text)+ where+ size = ByteString.length (Text.encodeUtf8 text)++-- | Original DNS text.+dnsNameText :: DnsName -> Text+dnsNameText (DnsName text) = text++-- | Validate at most 128 UTF-8 bytes without NUL. Empty is valid in this+-- pool schema. Violations return 'InvalidPoolMetadataUrl'.+mkUrl :: Text -> Either Error Url+mkUrl text+ | ByteString.length (Text.encodeUtf8 text) > 128 || Text.any (== '\0') text = Left (InvalidPoolMetadataUrl "Expected at most 128 UTF-8 bytes without NUL")+ | otherwise = Right (Url text)++-- | Exact original location text.+urlText :: Url -> Text+urlText (Url text) = text++-- | Import exactly 32 metadata digest bytes without hashing; other lengths+-- return 'InvalidPoolMetadataHashLength' with the actual byte count.+metadataHashFromBytes :: ByteString -> Either Error MetadataHash+metadataHashFromBytes bytes+ | ByteString.length bytes == 32 = Right (MetadataHash bytes)+ | otherwise = Left (InvalidPoolMetadataHashLength (ByteString.length bytes))++-- | Exact metadata digest bytes.+metadataHashBytes :: MetadataHash -> ByteString+metadataHashBytes (MetadataHash bytes) = bytes++-- | Import exactly 32 VRF digest bytes without hashing; other lengths return+-- 'InvalidPoolHashLength' with the actual byte count.+vrfKeyHashFromBytes :: ByteString -> Either Error VrfKeyHash+vrfKeyHashFromBytes bytes+ | ByteString.length bytes == 32 = Right (VrfKeyHash bytes)+ | otherwise = Left (InvalidPoolHashLength (ByteString.length bytes))++-- | Exact VRF digest bytes.+vrfKeyHashBytes :: VrfKeyHash -> ByteString+vrfKeyHashBytes (VrfKeyHash bytes) = bytes++-- | Validate public-key bytes (first argument, 96 bytes) and possession-proof+-- bytes (second argument, 48 bytes). 'InvalidPoolBlsKeyLength' reports both+-- actual lengths. No cryptographic validation occurs.+mkBlsKey :: ByteString -> ByteString -> Either Error BlsKey+mkBlsKey key proof+ | ByteString.length key == 96 && ByteString.length proof == 48 = Right (BlsKey key proof)+ | otherwise = Left (InvalidPoolBlsKeyLength (ByteString.length key) (ByteString.length proof))++-- | Exact 96 public-key bytes.+publicKeyBytes :: BlsKey -> ByteString+publicKeyBytes (BlsKey key _) = key++-- | Exact 48 possession-proof bytes.+possessionProofBytes :: BlsKey -> ByteString+possessionProofBytes (BlsKey _ proof) = proof++encode :: (a -> Encode.Encoding) -> a -> ByteString+encode encoder = Write.toStrictByteString . encoder++decodeComplete :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a+decodeComplete decoder bytes = case Read.deserialiseFromBytes decoder (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidPoolCbor (Text.pack (show failure)))+ Right (remaining, value)+ | Lazy.null remaining -> Right value+ | otherwise -> Left (InvalidPoolCbor "Trailing pool CBOR bytes")++metadataEncoding :: Metadata -> Encode.Encoding+metadataEncoding (Metadata location digest) = Encode.encodeListLen 2 <> Encode.encodeString (urlText location) <> Encode.encodeBytes (metadataHashBytes digest)++metadataDecoder :: Decode.Decoder s Metadata+metadataDecoder = arrayOf 2 $ Metadata <$> (validated mkUrl =<< Decode.decodeString) <*> (validated metadataHashFromBytes =<< Decode.decodeBytes)++blsEncoding :: BlsKey -> Encode.Encoding+blsEncoding (BlsKey key proof) = Encode.encodeListLen 2 <> Encode.encodeBytes key <> Encode.encodeBytes proof++blsDecoder :: Decode.Decoder s BlsKey+blsDecoder = arrayOf 2 $ do+ key <- Decode.decodeBytes+ proof <- Decode.decodeBytes+ validated (uncurry mkBlsKey) (key, proof)++relayEncoding :: Relay -> Encode.Encoding+relayEncoding relay = case relay of+ SingleHostAddress port ipv4 ipv6 -> Encode.encodeListLen 4 <> Encode.encodeWord 0 <> optional Encode.encodeWord16 port <> optional (Encode.encodeBytes . ipv4Bytes) ipv4 <> optional (Encode.encodeBytes . ipv6Bytes) ipv6+ SingleHostName port dns -> Encode.encodeListLen 3 <> Encode.encodeWord 1 <> optional Encode.encodeWord16 port <> Encode.encodeString (dnsNameText dns)+ MultiHostName dns -> Encode.encodeListLen 2 <> Encode.encodeWord 2 <> Encode.encodeString (dnsNameText dns)++relayDecoder :: Decode.Decoder s Relay+relayDecoder = do+ size <- Decode.decodeListLenOrIndef+ kind <- Decode.decodeWord+ expected <- case kind of+ 0 -> pure 4+ 1 -> pure 3+ 2 -> pure 2+ _ -> fail "Unknown relay kind"+ checkSize expected size+ value <- case kind of+ 0 -> SingleHostAddress <$> nullable Decode.decodeWord16 <*> nullable (validated ipv4FromBytes =<< Decode.decodeBytes) <*> nullable (validated ipv6FromBytes =<< Decode.decodeBytes)+ 1 -> SingleHostName <$> nullable Decode.decodeWord16 <*> (validated mkDnsName =<< Decode.decodeString)+ _ -> MultiHostName <$> (validated mkDnsName =<< Decode.decodeString)+ endArray size+ pure value++parametersFieldCount :: PoolParameters -> Word+parametersFieldCount value = maybe 9 (const 10) (blsKey value)++parametersEncoding :: PoolParameters -> Encode.Encoding+parametersEncoding = parametersEncodingWith TaggedSet++parametersEncodingWith :: SetEncoding -> PoolParameters -> Encode.Encoding+parametersEncodingWith requested value =+ Encode.encodeBytes (Credential.keyHashBytes (operator value))+ <> Encode.encodeBytes (vrfKeyHashBytes (vrfKeyHash value))+ <> foldMap blsEncoding (blsKey value)+ <> Encode.encodeWord64 (pledge value)+ <> Encode.encodeWord64 (cost value)+ <> Protocol.encodeUnitInterval (margin value)+ <> Encode.encodeBytes (Reward.toBytes (rewardAccount value))+ <> (case requested of TaggedSet -> Encode.encodeTag 258; UntaggedSet -> mempty)+ <> Encode.encodeListLen (fromIntegral (Set.size (owners value)))+ <> foldMap (Encode.encodeBytes . Credential.keyHashBytes) (Set.toAscList (owners value))+ <> Encode.encodeListLen (fromIntegral (length (relays value)))+ <> foldMap relayEncoding (relays value)+ <> optional metadataEncoding (metadata value)++parametersDecoder :: Decode.Decoder s PoolParameters+parametersDecoder = snd <$> parametersDecoderWithFieldCount++parametersDecoderWithFieldCount :: Decode.Decoder s (Word, PoolParameters)+parametersDecoderWithFieldCount = do+ poolOperator <- validated Credential.keyHashFromBytes =<< Decode.decodeBytes+ vrf <- validated vrfKeyHashFromBytes =<< Decode.decodeBytes+ token <- Decode.peekTokenType+ bls <- case token of+ Decode.TypeListLen -> Just <$> blsDecoder+ Decode.TypeListLenIndef -> Just <$> blsDecoder+ Decode.TypeNull -> Decode.decodeNull >> pure Nothing+ _ -> pure Nothing+ poolPledge <- Decode.decodeWord64+ poolCost <- Decode.decodeWord64+ poolMargin <- Protocol.decodeUnitInterval+ account <- validated Reward.fromBytes =<< Decode.decodeBytes+ ownerSet <- ownersDecoder+ relayList <- listOf relayDecoder+ reference <- nullable metadataDecoder+ let count = case token of+ Decode.TypeListLen -> 10+ Decode.TypeListLenIndef -> 10+ Decode.TypeNull -> 10+ _ -> 9+ pure (count, PoolParameters poolOperator vrf bls poolPledge poolCost poolMargin account ownerSet relayList reference)++parametersValueEncoding :: PoolParameters -> Encode.Encoding+parametersValueEncoding = parametersValueEncodingWith TaggedSet++-- | The explicit tag choice applies only to the pool owner set.+parametersValueEncodingWith :: SetEncoding -> PoolParameters -> Encode.Encoding+parametersValueEncodingWith requested value = Encode.encodeListLen (fromIntegral (parametersFieldCount value)) <> parametersEncodingWith requested value++parametersValueDecoder :: Decode.Decoder s PoolParameters+parametersValueDecoder = do+ size <- Decode.decodeListLenOrIndef+ (count, value) <- parametersDecoderWithFieldCount+ checkSize (fromIntegral count) size+ endArray size+ pure value++ownersDecoder :: Decode.Decoder s (Set (Credential.KeyHash Credential.Stake))+ownersDecoder = do+ token <- Decode.peekTokenType+ when (token == Decode.TypeTag || token == Decode.TypeTag64) $ do+ tag <- Decode.decodeTag64+ unless (tag == 258) (fail "Incorrect pool-owner set tag")+ values <- listOf (validated Credential.keyHashFromBytes =<< Decode.decodeBytes)+ let unique = Set.fromList values+ unless (Set.size unique == length values) (fail "Duplicate pool owner")+ pure unique++optional :: (a -> Encode.Encoding) -> Maybe a -> Encode.Encoding+optional = maybe Encode.encodeNull++nullable :: Decode.Decoder s a -> Decode.Decoder s (Maybe a)+nullable decoder = do+ token <- Decode.peekTokenType+ if token == Decode.TypeNull then Decode.decodeNull >> pure Nothing else Just <$> decoder++listOf :: Decode.Decoder s a -> Decode.Decoder s [a]+listOf decoder = do+ size <- Decode.decodeListLenOrIndef+ case size of+ Just count -> replicateM count decoder+ Nothing -> go+ where+ go = do+ ended <- Decode.decodeBreakOr+ if ended then pure [] else (:) <$> decoder <*> go++arrayOf :: Int -> Decode.Decoder s a -> Decode.Decoder s a+arrayOf expected decoder = do+ size <- Decode.decodeListLenOrIndef+ checkSize expected size+ value <- decoder+ endArray size+ pure value++checkSize :: Int -> Maybe Int -> Decode.Decoder s ()+checkSize expected size = case size of+ Just actual -> unless (actual == expected) (fail "Incorrect pool array length")+ Nothing -> pure ()++endArray :: Maybe Int -> Decode.Decoder s ()+endArray size = case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- Decode.decodeBreakOr+ unless ended (fail "Extra pool array elements")++validated :: (a -> Either Error b) -> a -> Decode.Decoder s b+validated validate value = either (fail . show) pure (validate value)
@@ -0,0 +1,147 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Private complete CBOR decoding and nested semantic-codec composition.+-- No native objects or arbitrary effect boundaries are involved.+module Cometa.Internal.ProposalCbor+ ( encode,+ decode,+ raw,+ nested,+ array,+ finishArray,+ list,+ entries,+ optional,+ maybeEncoding,+ credentialEncoding,+ credentialDecoder,+ uniqueMap,+ setList,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import qualified Codec.CBOR.Write as W+import qualified Cometa.Credential as C+import Cometa.Error (Error (..))+import Control.Monad (foldM, replicateM, unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as L+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Text as Text++-- DEFINITIONS ----------------------------------------------------------------++encode :: E.Encoding -> ByteString+encode = W.toStrictByteString++decode :: (forall s. D.Decoder s a) -> ByteString -> Either Error a+decode parser bytes = case R.deserialiseFromBytes parser (L.fromStrict bytes) of+ Left failure -> Left (InvalidProposalCbor (Text.pack (show failure)))+ Right (rest, value)+ | L.null rest -> Right value+ | otherwise -> Left (InvalidProposalCbor "Trailing proposal CBOR")++raw :: ByteString -> E.Encoding+raw = E.encodePreEncoded++nested :: (ByteString -> Either Error a) -> D.Decoder s a+nested parser = do+ term <- T.decodeTerm+ either (fail . show) pure (parser (encode (T.encodeTerm term)))++array :: Int -> D.Decoder s a -> D.Decoder s a+array count parser = do+ size <- D.decodeListLenOrIndef+ case size of+ Just actual -> unless (actual == count) (fail "Incorrect proposal array arity")+ Nothing -> pure ()+ value <- parser+ finishArray size+ pure value++finishArray :: Maybe Int -> D.Decoder s ()+finishArray size = case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- D.decodeBreakOr+ unless ended (fail "Extra proposal array elements")++list :: D.Decoder s a -> D.Decoder s [a]+list parser = D.decodeListLenOrIndef >>= sequenceLength parser++entries :: D.Decoder s a -> D.Decoder s [a]+entries parser = D.decodeMapLenOrIndef >>= sequenceLength parser++sequenceLength :: D.Decoder s a -> Maybe Int -> D.Decoder s [a]+sequenceLength parser size = case size of+ Just count -> replicateM count parser+ Nothing -> go+ where+ go = do+ ended <- D.decodeBreakOr+ if ended then pure [] else (:) <$> parser <*> go++optional :: D.Decoder s a -> D.Decoder s (Maybe a)+optional parser = do+ token <- D.peekTokenType+ if token == D.TypeNull then D.decodeNull >> pure Nothing else Just <$> parser++maybeEncoding :: (a -> E.Encoding) -> Maybe a -> E.Encoding+maybeEncoding = maybe E.encodeNull++credentialEncoding :: C.Credential purpose -> E.Encoding+credentialEncoding credential =+ E.encodeListLen 2 <> case credential of+ C.KeyCredential hash -> E.encodeWord 0 <> E.encodeBytes (C.keyHashBytes hash)+ C.ScriptCredential hash -> E.encodeWord 1 <> E.encodeBytes (C.scriptHashBytes hash)++credentialDecoder :: D.Decoder s (C.Credential purpose)+credentialDecoder = array 2 $ do+ kind <- D.decodeWord+ bytes <- D.decodeBytes+ case kind of+ 0 -> either (fail . show) (pure . C.KeyCredential) (C.keyHashFromBytes bytes)+ 1 -> either (fail . show) (pure . C.ScriptCredential) (C.scriptHashFromBytes bytes)+ _ -> fail "Invalid credential kind"++uniqueMap :: (Ord key) => Error -> [(key, value)] -> Either Error (Map key value)+uniqueMap duplicate = foldM insert Map.empty+ where+ insert values (key, value)+ | Map.member key values = Left duplicate+ | otherwise = Right (Map.insert key value values)++setList :: D.Decoder s a -> D.Decoder s [a]+setList parser = do+ token <- D.peekTokenType+ case token of+ D.TypeTag -> checkTag+ D.TypeTag64 -> checkTag+ _ -> pure ()+ list parser+ where+ checkTag = do+ tag <- D.decodeTag64+ unless (tag == 258) (fail "Invalid set tag")
@@ -0,0 +1,278 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Owned protocol values and schema codecs. No native calls occur here.+module Cometa.Internal.ProtocolValues+ ( NonNegativeRational (..),+ UnitInterval (..),+ ExUnits (..),+ ProtocolVersion (..),+ ExUnitPrices (..),+ PoolVotingThresholds (..),+ DRepVotingThresholds (..),+ mkNonNegativeRational,+ mkUnitInterval,+ rationalNumerator,+ rationalDenominator,+ rationalValue,+ unitIntervalRational,+ mkExUnits,+ mkProtocolVersion,+ encodeBytes,+ decodeBytes,+ decodeTuple,+ encodeRational,+ decodeRational,+ encodeUnitInterval,+ decodeUnitInterval,+ encodeExUnits,+ decodeExUnits,+ encodeProtocolVersion,+ decodeProtocolVersion,+ encodeExUnitPrices,+ decodeExUnitPrices,+ encodePoolVotingThresholds,+ decodePoolVotingThresholds,+ encodeDRepVotingThresholds,+ decodeDRepVotingThresholds,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Error (Error (..))+import Control.Monad (when)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as Lazy+import Data.Ratio ((%))+import qualified Data.Text as Text+import Data.Word (Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | Exact nonnegative fraction with an unsigned 64-bit numerator and positive+-- unsigned 64-bit denominator. The original pair is retained for encoding;+-- equality and ordering compare numeric values. Show is diagnostic.+data NonNegativeRational = NonNegativeRational !Word64 !Word64 deriving (Show)++instance Eq NonNegativeRational where+ a == b = compare a b == EQ++instance Ord NonNegativeRational where+ compare (NonNegativeRational n d) (NonNegativeRational m e) = compare (toInteger n * toInteger e) (toInteger m * toInteger d)++-- | Exact proportion between zero and one, inclusive. Equality and ordering+-- compare numeric values; the original pair is retained for encoding.+newtype UnitInterval = UnitInterval NonNegativeRational deriving (Eq, Ord, Show)++-- | Memory and CPU execution budget. Each unsigned component is bounded by 2^64-1.+data ExUnits+ = -- | Assemble validated components.+ ExUnits+ { -- | Memory execution units.+ memory :: !Word64,+ -- | CPU execution steps.+ steps :: !Word64+ }+ deriving (Eq, Show)++-- | Protocol major/minor version; ordering compares major then minor.+data ProtocolVersion+ = -- | Assemble validated components.+ ProtocolVersion+ { -- | Unsigned 64-bit major version.+ major :: !Word64,+ -- | Unsigned 32-bit minor version.+ minor :: !Word32+ }+ deriving (Eq, Ord, Show)++-- | Exact nonnegative lovelace costs per memory unit and CPU step.+data ExUnitPrices+ = -- | Assemble validated components.+ ExUnitPrices+ { -- | Lovelace per memory unit.+ memoryPrice :: !NonNegativeRational,+ -- | Lovelace per CPU step.+ stepPrice :: !NonNegativeRational+ }+ deriving (Eq, Show)++-- | Stake-pool approval thresholds, each from zero through one inclusive.+data PoolVotingThresholds+ = -- | Assemble validated components.+ PoolVotingThresholds+ { -- | Approval threshold for a motion of no confidence in the committee.+ poolMotionNoConfidence :: !UnitInterval,+ -- | Approval threshold for committee changes while the committee has confidence.+ poolCommitteeNormal :: !UnitInterval,+ -- | Approval threshold for committee changes after a loss of confidence.+ poolCommitteeNoConfidence :: !UnitInterval,+ -- | Approval threshold for initiating a protocol hard fork.+ poolHardForkInitiation :: !UnitInterval,+ -- | Approval threshold for security-relevant protocol parameter changes.+ poolSecurityRelevantParameter :: !UnitInterval+ }+ deriving (Eq, Show)++-- | DRep approval thresholds, each from zero through one inclusive.+data DRepVotingThresholds+ = -- | Assemble validated components.+ DRepVotingThresholds+ { -- | Approval threshold for a motion of no confidence in the committee.+ drepMotionNoConfidence :: !UnitInterval,+ -- | Approval threshold for committee changes while the committee has confidence.+ drepCommitteeNormal :: !UnitInterval,+ -- | Approval threshold for committee changes after a loss of confidence.+ drepCommitteeNoConfidence :: !UnitInterval,+ -- | Approval threshold for adopting a new constitution.+ drepUpdateConstitution :: !UnitInterval,+ -- | Approval threshold for initiating a protocol hard fork.+ drepHardForkInitiation :: !UnitInterval,+ -- | Approval threshold for network protocol parameter changes.+ drepNetworkParameterGroup :: !UnitInterval,+ -- | Approval threshold for economic protocol parameter changes.+ drepEconomicParameterGroup :: !UnitInterval,+ -- | Approval threshold for technical protocol parameter changes.+ drepTechnicalParameterGroup :: !UnitInterval,+ -- | Approval threshold for governance protocol parameter changes.+ drepGovernanceParameterGroup :: !UnitInterval,+ -- | Approval threshold for treasury withdrawal proposals.+ drepTreasuryWithdrawal :: !UnitInterval+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate an unsigned 64-bit numerator and positive unsigned 64-bit+-- denominator. Retain the exact pair. Invalid values return+-- 'InvalidProtocolRational'.+mkNonNegativeRational :: Integer -> Integer -> Either Error NonNegativeRational+mkNonNegativeRational n d+ | n < 0 || n > toInteger (maxBound :: Word64) || d <= 0 || d > toInteger (maxBound :: Word64) = Left (InvalidProtocolRational n d)+ | otherwise = Right (NonNegativeRational (fromInteger n) (fromInteger d))++-- | Validate a proportion numerator and denominator. Invalid unsigned bounds+-- or a zero denominator return 'InvalidProtocolRational'; a numerator larger+-- than its denominator returns 'InvalidUnitInterval'.+mkUnitInterval :: Integer -> Integer -> Either Error UnitInterval+mkUnitInterval n d = do+ value <- mkNonNegativeRational n d+ if n > d then Left (InvalidUnitInterval n d) else Right (UnitInterval value)++rationalNumerator :: NonNegativeRational -> Word64+rationalNumerator (NonNegativeRational n _) = n++rationalDenominator :: NonNegativeRational -> Word64+rationalDenominator (NonNegativeRational _ d) = d++rationalValue :: NonNegativeRational -> Rational+rationalValue (NonNegativeRational n d) = toInteger n % toInteger d++unitIntervalRational :: UnitInterval -> NonNegativeRational+unitIntervalRational (UnitInterval r) = r++-- | Validate external memory and step counts in 0..2^64-1. Invalid input+-- returns 'InvalidExUnits'.+mkExUnits :: Integer -> Integer -> Either Error ExUnits+mkExUnits m s+ | m < 0 || m > toInteger (maxBound :: Word64) || s < 0 || s > toInteger (maxBound :: Word64) = Left (InvalidExUnits m s)+ | otherwise = Right (ExUnits (fromInteger m) (fromInteger s))++-- | Validate an external major in 0..2^64-1 and minor in 0..2^32-1.+-- Invalid input returns 'InvalidProtocolVersion'.+mkProtocolVersion :: Integer -> Integer -> Either Error ProtocolVersion+mkProtocolVersion a b+ | a < 0 || a > toInteger (maxBound :: Word64) || b < 0 || b > toInteger (maxBound :: Word32) = Left (InvalidProtocolVersion a b)+ | otherwise = Right (ProtocolVersion (fromInteger a) (fromInteger b))++encodeRational :: NonNegativeRational -> Encode.Encoding+encodeRational (NonNegativeRational n d) = Encode.encodeTag 30 <> Encode.encodeListLen 2 <> Encode.encodeWord64 n <> Encode.encodeWord64 d++decodeRational :: Decode.Decoder s NonNegativeRational+decodeRational = do+ tag <- Decode.decodeTag+ when (tag /= 30) (fail "expected rational tag 30")+ decodeTuple 2 $ do+ n <- Decode.decodeWord64+ d <- Decode.decodeWord64+ either (fail . show) pure (mkNonNegativeRational (toInteger n) (toInteger d))++encodeUnitInterval :: UnitInterval -> Encode.Encoding+encodeUnitInterval = encodeRational . unitIntervalRational++decodeUnitInterval :: Decode.Decoder s UnitInterval+decodeUnitInterval = do+ r@(NonNegativeRational n d) <- decodeRational+ if n > d then fail "unit interval exceeds one" else pure (UnitInterval r)++encodeExUnits :: ExUnits -> Encode.Encoding+encodeExUnits (ExUnits m s) = Encode.encodeListLen 2 <> Encode.encodeWord64 m <> Encode.encodeWord64 s++decodeExUnits :: Decode.Decoder s ExUnits+decodeExUnits = decodeTuple 2 (ExUnits <$> Decode.decodeWord64 <*> Decode.decodeWord64)++encodeProtocolVersion :: ProtocolVersion -> Encode.Encoding+encodeProtocolVersion (ProtocolVersion a b) = Encode.encodeListLen 2 <> Encode.encodeWord64 a <> Encode.encodeWord32 b++decodeProtocolVersion :: Decode.Decoder s ProtocolVersion+decodeProtocolVersion = decodeTuple 2 (ProtocolVersion <$> Decode.decodeWord64 <*> Decode.decodeWord32)++encodeExUnitPrices :: ExUnitPrices -> Encode.Encoding+encodeExUnitPrices (ExUnitPrices m s) = Encode.encodeListLen 2 <> encodeRational m <> encodeRational s++decodeExUnitPrices :: Decode.Decoder s ExUnitPrices+decodeExUnitPrices = decodeTuple 2 (ExUnitPrices <$> decodeRational <*> decodeRational)++-- | Fixed tuples accept definite and indefinite arrays and check exact arity.+decodeTuple :: Int -> Decode.Decoder s a -> Decode.Decoder s a+decodeTuple expected fields = do+ count <- Decode.decodeListLenOrIndef+ case count of+ Just actual | actual /= expected -> fail "wrong protocol tuple length"+ _ -> pure ()+ result <- fields+ case count of+ Nothing -> Decode.decodeBreakOr >>= \end -> if end then pure () else fail "extra protocol tuple field"+ Just _ -> pure ()+ pure result++encodeBytes :: (a -> Encode.Encoding) -> a -> ByteString+encodeBytes encode = Write.toStrictByteString . encode++decodeBytes :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a+decodeBytes decode bytes = case Read.deserialiseFromBytes decode (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidProtocolCbor (Text.pack (show failure)))+ Right (remaining, value)+ | Lazy.null remaining -> Right value+ | otherwise -> Left (InvalidProtocolCbor "trailing CBOR data")++encodePoolVotingThresholds :: PoolVotingThresholds -> Encode.Encoding+encodePoolVotingThresholds (PoolVotingThresholds noConfidence normalCommittee noConfidenceCommittee hardFork securityParameters) = Encode.encodeListLen 5 <> encodeUnitInterval noConfidence <> encodeUnitInterval normalCommittee <> encodeUnitInterval noConfidenceCommittee <> encodeUnitInterval hardFork <> encodeUnitInterval securityParameters++decodePoolVotingThresholds :: Decode.Decoder s PoolVotingThresholds+decodePoolVotingThresholds = decodeTuple 5 (PoolVotingThresholds <$> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval)++encodeDRepVotingThresholds :: DRepVotingThresholds -> Encode.Encoding+encodeDRepVotingThresholds (DRepVotingThresholds noConfidence normalCommittee noConfidenceCommittee constitution hardFork networkParameters economicParameters technicalParameters governanceParameters treasury) = Encode.encodeListLen 10 <> encodeUnitInterval noConfidence <> encodeUnitInterval normalCommittee <> encodeUnitInterval noConfidenceCommittee <> encodeUnitInterval constitution <> encodeUnitInterval hardFork <> encodeUnitInterval networkParameters <> encodeUnitInterval economicParameters <> encodeUnitInterval technicalParameters <> encodeUnitInterval governanceParameters <> encodeUnitInterval treasury++decodeDRepVotingThresholds :: Decode.Decoder s DRepVotingThresholds+decodeDRepVotingThresholds = decodeTuple 10 (DRepVotingThresholds <$> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval <*> decodeUnitInterval)
@@ -0,0 +1,198 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Typed provider/native callback translation. Scoped adapters own their runtime;+-- direct public records have no native lifetime. Private round-trip operations+-- exercise actual cardano_provider_* dispatch, not a Haskell-only echo.+module Cometa.Internal.ProviderRuntime (Adapter, withProvider, runtime, nativeProvider, dispatch, withNative) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as AssetName+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Evaluation as Eval+import qualified Cometa.Internal.FFI.ProviderRuntime as FFI+import qualified Cometa.Internal.ParameterSnapshot as Parameters+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import Cometa.Provider (Provider (..))+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import Control.Exception (bracket)+import Control.Monad ((>=>))+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word32)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++data Adapter = Adapter Runtime.Runtime !Text !ByteString !Word32++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate metadata before adopting any Haskell callback registration.+withProvider :: Provider -> (Adapter -> IO (Either Error a)) -> IO (Either Error a)+withProvider provider action+ | B.length bytes > 255 || Text.any (== '\0') (name provider) = pure (Left (InvalidCallbackResult "Provider name must be at most 255 UTF-8 bytes without NUL"))+ | otherwise = Runtime.withRuntime (dispatch provider) $ \owner -> action (Adapter owner (name provider) bytes (networkMagic provider))+ where+ bytes = Text.encodeUtf8 (name provider)++-- | The runtime is available only for internal grouped operation activation.+runtime :: Adapter -> Runtime.Runtime+runtime (Adapter owner _ _ _) = owner++-- | Scope one actual native provider under this adapter's operation state.+-- The continuation borrows it; no returned native reference may escape the scope.+withNative :: Adapter -> (Ptr FFI.NativeProvider -> IO (Either Error a)) -> IO (Either Error a)+withNative (Adapter owner _ backendName magic) action = Runtime.withOperation owner $ \context ->+ Runtime.withBytes backendName $ \nameBytes nameSize -> alloca $ \slot ->+ bracket (poke slot nullPtr >> pure slot) FFI.cRelease $ \output -> do+ result <- FFI.cNew context nameBytes nameSize magic output >>= Runtime.checkStatus "provider.acquire"+ case result of+ Left failure -> pure (Left failure)+ Right () -> do+ pointer <- peek output+ if pointer == nullPtr then pure (Left (NativeContractViolation "provider.acquire")) else action pointer++call :: Adapter -> Word32 -> ByteString -> IO (Either Error ByteString)+call (Adapter owner _ backendName magic) operation bytes = Runtime.withOperation owner $ \context ->+ Runtime.withBytes backendName $ \nameBytes nameSize -> Runtime.withBytes bytes $ \input size ->+ Runtime.withOwnedBuffer "provider.nativeDispatch" (FFI.cCall context nameBytes nameSize magic operation input size)++-- | Re-express every callback through actual typed native provider methods.+-- Pure request decoders reject trailing bytes. Native serialization can normalize+-- outer framing; exact transaction-body bytes remain untouched.+nativeProvider :: Adapter -> Provider+nativeProvider adapter@(Adapter _ backendName _ magic) =+ Provider+ { name = backendName,+ networkMagic = magic,+ protocolParameters = do+ result <- call adapter 0 (C.encode (E.encodeListLen 0))+ pure (result >>= Parameters.decodeSnapshot),+ utxosAt = \address -> decodedCall 1 (bytesEncoding (Address.toBytes address)) utxosDecoder,+ rewardBalance = \address -> decodedCall 2 (bytesEncoding (Reward.toBytes address)) (decode D.decodeWord64),+ utxosWithAsset = \address asset -> decodedCall 3 (array [bytesEncoding (Address.toBytes address), assetEncoding asset]) utxosDecoder,+ utxoWithAsset = \asset -> decodedCall 4 (assetEncoding asset) (optionalDecoder Utxo.decodeCbor),+ resolveInputs = \inputs -> decodedCall 5 (list Input.encodeCbor inputs) utxosDecoder,+ resolveDatum = \hash -> decodedCall 6 (bytesEncoding (Datum.hashBytes hash)) (optionalDecoder Data.decodeCbor),+ awaitTransaction = \hash timeout -> decodedCall 7 (array [bytesEncoding (TxId.toBytes hash), C.encode (E.encodeWord64 timeout)]) (decode D.decodeBool),+ submitTransaction = \transaction -> decodedCall 8 (Tx.encodeCbor transaction) (decode D.decodeBytes >=> TxId.fromBytes),+ evaluateTransaction = \transaction utxos -> do+ reply <- call adapter 9 (array [Tx.encodeCbor transaction, list Utxo.encodeCbor utxos])+ pure (reply >>= Redeemer.decodeCollectionCbor >>= Eval.budgetsFromRedeemers Evaluation.TopLevel transaction)+ }+ where+ decodedCall operation request parser = do+ result <- call adapter operation request+ pure (result >>= parser)++-- | One complete typed handler action and encoding remains inside Runtime's user+-- worker. Errors preserve their exact constructors; there are no hidden defaults.+dispatch :: Provider -> Runtime.Dispatch+dispatch provider operation input = runExceptT $ case operation of+ 0 -> do+ _ <- except (decode (C.array 0 (pure ())) input)+ value <- ExceptT (protocolParameters provider)+ except (Parameters.validateNative value)+ pure (Parameters.encodeSnapshot value)+ 1 -> do+ address <- except (decode D.decodeBytes input >>= Address.fromBytes)+ list Utxo.encodeCbor <$> ExceptT (utxosAt provider address)+ 2 -> do+ address <- except (decode D.decodeBytes input >>= Reward.fromBytes)+ C.encode . E.encodeWord64 <$> ExceptT (rewardBalance provider address)+ 3 -> do+ (address, asset) <- except (decode (C.array 2 ((,) <$> addressDecoder <*> assetDecoder)) input)+ list Utxo.encodeCbor <$> ExceptT (utxosWithAsset provider address asset)+ 4 -> do+ asset <- except (decode assetDecoder input)+ optional Utxo.encodeCbor <$> ExceptT (utxoWithAsset provider asset)+ 5 -> do+ references <- except (decode (C.setList (C.nested input Input.decodeCbor)) input)+ list Utxo.encodeCbor <$> ExceptT (resolveInputs provider references)+ 6 -> do+ hash <- except (decode D.decodeBytes input >>= Datum.hashFromBytes)+ optional Data.toCbor <$> ExceptT (resolveDatum provider hash)+ 7 -> do+ (hash, timeout) <- except (decode (C.array 2 ((,) <$> hashDecoder <*> D.decodeWord64)) input)+ C.encode . E.encodeBool <$> ExceptT (awaitTransaction provider hash timeout)+ 8 -> do+ transaction <- except (Tx.decodeCbor input)+ bytesEncoding . TxId.toBytes <$> ExceptT (submitTransaction provider transaction)+ 9 -> do+ (transaction, utxos) <- except (decode (C.array 2 ((,) <$> C.nested input Tx.decodeCbor <*> C.list (C.nested input Utxo.decodeCbor))) input)+ budgets <- ExceptT (evaluateTransaction provider transaction utxos)+ values <- except (Eval.checkedRedeemers Evaluation.TopLevel transaction budgets)+ except (Redeemer.encodeCollectionCbor values)+ _ -> throwE (UnsupportedOperation "provider.callback")+ where+ addressDecoder = D.decodeBytes >>= either (fail . show) pure . Address.fromBytes+ assetDecoder = D.decodeBytes >>= either (fail . show) pure . assetFromBytes+ hashDecoder = D.decodeBytes >>= either (fail . show) pure . TxId.fromBytes++-- Internal wire helpers preserve each child's exact bytes.+decode :: (forall s. D.Decoder s a) -> ByteString -> Either Error a+decode = C.decodeAs InvalidCallbackResult++utxosDecoder :: ByteString -> Either Error [Utxo.Utxo]+utxosDecoder bytes = decode (C.list (C.nested bytes Utxo.decodeCbor)) bytes++optionalDecoder :: (ByteString -> Either Error a) -> ByteString -> Either Error (Maybe a)+optionalDecoder parser bytes = decode (C.optional (C.nested bytes parser)) bytes++bytesEncoding :: ByteString -> ByteString+bytesEncoding = C.encode . E.encodeBytes++assetEncoding :: AssetId -> ByteString+assetEncoding Ada = bytesEncoding B.empty+assetEncoding (Native policy assetName) = bytesEncoding (Policy.toBytes policy <> AssetName.toBytes assetName)++assetFromBytes :: ByteString -> Either Error AssetId+assetFromBytes bytes+ | B.null bytes = Right Ada+ | otherwise = Native <$> Policy.fromBytes (B.take 28 bytes) <*> AssetName.fromBytes (B.drop 28 bytes)++array :: [ByteString] -> ByteString+array values = C.encode (E.encodeListLen (fromIntegral (length values)) <> foldMap C.raw values)++list :: (a -> ByteString) -> [a] -> ByteString+list encoder = array . map encoder++optional :: (a -> ByteString) -> Maybe a -> ByteString+optional = maybe (C.encode E.encodeNull)
@@ -0,0 +1,30 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Operation-scoped native re-encoding. The input span is borrowed through+-- safe foreign return; every parsed owner/writer is released by C. Runtime's+-- owned-buffer scope copies results and releases partial outputs on all exits.+module Cometa.Internal.Reencode (reencode) where++import Cometa.Error (Error)+import qualified Cometa.Internal.FFI.Reencode as FFI+import qualified Cometa.Internal.Runtime as Runtime+import Data.ByteString (ByteString)+import Data.Text (Text)+import Foreign.C.Types (CUInt)++reencode :: Text -> CUInt -> ByteString -> IO (Either Error ByteString)+reencode operation kind bytes = Runtime.withBytes bytes $ \input size -> Runtime.withOwnedBuffer operation (FFI.cReencode kind input size)
@@ -0,0 +1,281 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Scoped adopted callback registrations. All contexts participating in one C+-- operation share one native worker; group cancellation signals every callback+-- control and joins that worker before releasing any reference or buffer.+module Cometa.Internal.Runtime+ ( Runtime,+ Context,+ Buffer,+ Dispatch,+ withRuntime,+ withRetained,+ close,+ withOperation,+ withOperations,+ withBytes,+ copyBuffer,+ withOwnedBuffer,+ checkStatus,+ liveContexts,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.Callback as Callback+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Native as Status+import Cometa.Internal.FFI.Runtime (Buffer, Context)+import qualified Cometa.Internal.FFI.Runtime as FFI+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyStaticText)+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, readMVar)+import Control.Concurrent.MVar (MVar, newMVar, takeMVar, tryTakeMVar)+import Control.Exception (SomeException, bracket, catch, evaluate, finally, getMaskingState, mask, mask_, onException, throwIO, uninterruptibleMask_)+import Control.Monad (forM, forM_, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Maybe (catMaybes, listToMaybe)+import Data.Text (Text)+import Data.Word (Word32, Word8)+import Foreign.C.Types (CSize)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, freeHaskellFunPtr, nullPtr)+import Foreign.StablePtr (deRefStablePtr, freeStablePtr, newStablePtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Families own operation identifiers and the complete request/reply schema.+type Dispatch = Word32 -> ByteString -> IO (Either Error ByteString)++data Shared = Shared (MVar ()) Callback.CallbackControl (IORef (Maybe Error))++data Runtime = Runtime (IORef (Maybe (Ptr Context))) Shared++data State = State Dispatch Callback.CallbackControl (IORef (Maybe Error))++-- DEFINITIONS ----------------------------------------------------------------++-- | Success adopts callback handles in C; failure leaves cleanup with Haskell.+-- Continuation cleanup waits until every operation using this handle has joined.+withRuntime :: Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)+withRuntime dispatch action = mask $ \restore -> do+ acquired <- acquire dispatch+ case acquired of+ Left failure -> pure (Left failure)+ Right runtime -> restore (action runtime) `finally` closeWaiting runtime++-- | An alias owns an independent reference but shares callback operation state.+-- Acquisition during an active operation fails fast instead of racing refcounts.+withRetained :: Runtime -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)+withRetained original action = mask $ \restore -> do+ acquired <- retain original+ case acquired of+ Left failure -> pure (Left failure)+ Right alias -> restore (action alias) `finally` closeWaiting alias++acquire :: Dispatch -> IO (Either Error Runtime)+acquire dispatch = do+ control <- Callback.newCallbackControl+ expected <- newIORef Nothing+ gate <- newMVar ()+ stable <- newStablePtr (State dispatch control expected)+ fun <- FFI.wrapCallback callback `onException` freeStablePtr stable+ let freeRegistration = freeHaskellFunPtr fun >> freeStablePtr stable+ alloca $ \slot -> do+ poke slot nullPtr+ result <- checkStatus "runtime.acquire" =<< (FFI.cNew stable fun slot `onException` freeRegistration)+ case result of+ Left failure -> freeRegistration >> pure (Left failure)+ Right () -> do+ pointer <- peek slot+ if pointer == nullPtr+ then freeRegistration >> pure (Left (NativeContractViolation "runtime.acquire"))+ else (do handle <- newIORef (Just pointer); pure (Right (Runtime handle (Shared gate control expected)))) `onException` FFI.cRelease pointer++retain :: Runtime -> IO (Either Error Runtime)+retain (Runtime handle shared@(Shared gate _ _)) = do+ entered <- tryTakeMVar gate+ case entered of+ Nothing -> pure (Left RuntimeBusy)+ Just () ->+ ( do+ current <- readIORef handle+ case current of+ Nothing -> pure (Left RuntimeClosed)+ Just pointer -> do+ FFI.cRef pointer+ (Right . (`Runtime` shared) <$> newIORef (Just pointer)) `onException` FFI.cRelease pointer+ )+ `finally` putMVar gate ()++-- | Closing while active returns busy. Scope cleanup waits instead. This rule+-- serializes native non-atomic reference transitions, including factory adoption.+close :: Runtime -> IO (Either Error ())+close runtime@(Runtime _ (Shared gate _ _)) = mask_ $ do+ entered <- tryTakeMVar gate+ case entered of+ Nothing -> pure (Left RuntimeBusy)+ Just () -> (releaseHandle runtime >> pure (Right ())) `finally` putMVar gate ()++closeWaiting :: Runtime -> IO ()+closeWaiting runtime@(Runtime _ (Shared gate _ _)) = uninterruptibleMask_ $ do+ takeMVar gate+ releaseHandle runtime `finally` putMVar gate ()++releaseHandle :: Runtime -> IO ()+releaseHandle (Runtime handle _) = do+ current <- readIORef handle+ writeIORef handle Nothing+ maybe (pure ()) FFI.cRelease current++-- | One context is the one-element grouped operation, never a nested worker.+withOperation :: Runtime -> (Ptr Context -> IO (Either Error a)) -> IO (Either Error a)+withOperation runtime action = withOperations [runtime] $ \case+ [pointer] -> action pointer+ _ -> pure (Left (NativeContractViolation "runtime.withOperation"))++-- | Acquire unique gates without blocking, then retain all input handles.+-- Repeated aliases share one callback control. A busy/closed member runs no C.+-- Factories and native owner cleanup must stay inside the supplied operation.+withOperations :: [Runtime] -> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)+withOperations runtimes action = do+ -- Force the supplied list and abstract handle constructors before acquiring+ -- any gates; a lazy group argument must not strand an ownership obligation.+ mapM_ evaluate runtimes+ masking <- getMaskingState+ mask $ \restore -> do+ acquired <- acquireGroup runtimes+ case acquired of+ Left failure -> pure (Left failure)+ Right (pointers, shared) ->+ ( do+ forM_ shared $ \(Shared _ control expected) -> writeIORef expected Nothing >> Callback.beginCallbackOperation control masking+ finished <- newEmptyMVar+ let native = do+ result <- action pointers+ mapM_ (\(Shared _ control _) -> Callback.rethrowCallbackException control) shared+ errors <- mapM (\(Shared _ _ slot) -> readIORef slot) shared+ pure $ case result of+ Right _ -> result+ Left _ -> maybe result Left (listToMaybe (catMaybes errors))+ _ <- forkFinally native (putMVar finished)+ outcome <- restore (readMVar finished) `catch` cancelGroup shared finished+ either throwIO pure outcome+ )+ `finally` (mapM_ (\(Shared _ control _) -> Callback.finishCallbackOperation control) shared >> releaseGroup pointers shared)++acquireGroup :: [Runtime] -> IO (Either Error ([Ptr Context], [Shared]))+acquireGroup = go [] []+ where+ go pointers shared [] = pure (Right (reverse pointers, reverse shared))+ go pointers shared (Runtime handle item@(Shared gate _ _) : rest) = do+ entered <- if any (sameGate gate) shared then pure (Just ()) else tryTakeMVar gate+ case entered of+ Nothing -> releaseGroup pointers shared >> pure (Left RuntimeBusy)+ Just () -> do+ let owners = if any (sameGate gate) shared then shared else item : shared+ current <- readIORef handle+ case current of+ Nothing -> releaseGroup pointers owners >> pure (Left RuntimeClosed)+ Just pointer -> FFI.cRef pointer >> go (pointer : pointers) owners rest+ sameGate gate (Shared candidate _ _) = gate == candidate++releaseGroup :: [Ptr Context] -> [Shared] -> IO ()+releaseGroup pointers shared = do+ mapM_ FFI.cRelease pointers+ forM_ shared $ \(Shared gate _ _) -> putMVar gate ()++cancelGroup :: [Shared] -> MVar (Either SomeException a) -> SomeException -> IO b+cancelGroup shared finished cause = uninterruptibleMask_ $ do+ -- throwTo is synchronous: independent senders ensure a masked worker cannot+ -- delay cancellation of another context whose finalizer lets it unwind.+ senders <- forM shared $ \(Shared _ control _) -> do+ completed <- newEmptyMVar+ _ <- forkFinally (Callback.cancelCallbackOperation control cause) (putMVar completed)+ pure completed+ _ <- readMVar finished+ mapM_ readMVar senders+ throwIO cause++-- | The complete callback decode/action/encode/copy runs inside the protected+-- user worker. Only an owned native buffer crosses back to C on success.+callback :: FFI.Callback State+callback stable operation input size output diagnostic capacity = mask_ $ do+ poke output nullPtr+ State dispatch control expected <- deRefStablePtr stable+ let failed (cause :: SomeException) = uninterruptibleMask_ $ do+ Callback.rememberCallbackException control cause+ when (diagnostic /= nullPtr && capacity > 0) (poke diagnostic 0)+ pure 1+ Callback.runCallbackWorker+ control+ ( do+ writeIORef expected Nothing+ bytes <- if size == 0 then pure B.empty else B.packCStringLen (castPtr input, fromIntegral size)+ result <- dispatch operation bytes+ case result of+ Left failure -> do+ _ <- evaluate (length (show failure))+ writeIORef expected (Just failure)+ when (diagnostic /= nullPtr && capacity > 0) (poke diagnostic 0)+ pure 1+ Right reply -> withBytes reply $ \pointer count -> FFI.cBufferNew pointer count output+ )+ `catch` failed++-- | Byte storage stays alive for the entire synchronous call.+withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a+withBytes bytes action = B.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)++-- | Copy borrowed public bytes while the native owner is still live.+copyBuffer :: Text -> Ptr Buffer -> IO (Either Error ByteString)+copyBuffer operation buffer+ | buffer == nullPtr = pure (Left (NativeContractViolation operation))+ | otherwise = do+ size <- FFI.cBufferSize buffer+ bytes <- FFI.cBufferData buffer+ if toInteger size > toInteger (maxBound :: Int) || (bytes == nullPtr && size /= 0)+ then pure (Left (NativeContractViolation operation))+ else if size == 0 then pure (Right B.empty) else Right <$> B.packCStringLen (castPtr bytes, fromIntegral size)++-- | Initialize, adopt, copy and release an owned public buffer on every exit.+withOwnedBuffer :: Text -> (Ptr (Ptr Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)+withOwnedBuffer operation call = alloca $ \slot -> bracket (poke slot nullPtr >> pure slot) FFI.cBufferRelease $ \output -> do+ result <- call output >>= checkStatus operation+ case result of+ Left failure -> pure (Left failure)+ Right () -> peek output >>= copyBuffer operation++-- | Preserve native status and copy its static diagnostic before returning.+checkStatus :: Text -> Status.NativeCode -> IO (Either Error ())+checkStatus operation code+ | code == Status.success = pure (Right ())+ | otherwise = do+ message <- Status.cErrorMessage code >>= copyStaticText+ pure (Left (fromNativeFailure (NativeFailure operation (toInteger code) message)))++-- | Test-only count of contexts rooting runtime handles.+liveContexts :: IO Int+liveContexts = fromIntegral <$> FFI.cLiveContexts
@@ -0,0 +1,51 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Tag edits on already validated ledger set encodings.+module Cometa.Internal.SetEncoding (encoding, withEncoding) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Encoding.Set (SetEncoding (..))+import Data.Bits ((.&.))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B++-- FUNCTIONS ------------------------------------------------------------------++-- | Observe the outer tag of a validated set array.+encoding :: ByteString -> SetEncoding+encoding bytes = case B.uncons bytes of+ Just (header, _) | header .&. 224 == 192 -> TaggedSet+ _ -> UntaggedSet++-- | Preserve an unchanged representation exactly. Changed tags retain every byte+-- of the array, including indefinite lengths and nonminimal element encodings.+-- The input must already be validated as an array optionally prefixed by tag 258.+withEncoding :: SetEncoding -> ByteString -> ByteString+withEncoding requested bytes+ | requested == encoding bytes = bytes+ | requested == TaggedSet = B.pack [217, 1, 2] <> bytes+ | otherwise = B.drop (tagWidth bytes) bytes++-- | Header width of a validated tag 258, including nonminimal integer widths.+tagWidth :: ByteString -> Int+tagWidth bytes = case B.uncons bytes of+ Just (header, _) -> case header .&. 31 of+ 25 -> 3+ 26 -> 5+ 27 -> 9+ _ -> 0+ Nothing -> 0
@@ -0,0 +1,220 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Operation-owned native sub-builder. Runtime roots callback plans through+-- native builder destruction and joins callback cancellation before scope exit.+module Cometa.Internal.SubTransactionBuilder (Config (..), build, runUnchecked, runWithDispatch, dispatch) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.AssetId (AssetId (Ada))+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.FFI.Native as Status+import qualified Cometa.Internal.FFI.Runtime as Raw+import qualified Cometa.Internal.FFI.SubTransactionBuilder as FFI+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.Internal.Runtime as Runtime+import Cometa.Internal.SubTransactionPlan (Plan)+import qualified Cometa.Internal.SubTransactionPlan as Plan+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionPlan as Common+import qualified Cometa.Internal.TransactionValue as ValueCbor+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.ExUnits as Ex+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.Protocol.Parameters as Parameters+import Cometa.SlotConfig (SlotConfig)+import qualified Cometa.SlotConfig as Slots+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import Cometa.Transaction.Fields (BodyNetwork (..))+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.Value as Value+import Control.Exception (bracket)+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sort, sortOn)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Sequence as Seq+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Context for building an intent. Protocol parameters supply deposits, cost+-- models and language availability; the schedule converts explicit validity+-- slots, and the network is written into the local body.+data Config = Config+ { -- | Complete protocol parameter snapshot.+ parameters :: !Parameters,+ -- | Constant-duration schedule in Unix milliseconds.+ slotConfig :: !SlotConfig,+ -- | Ledger body network, distinct from network magic.+ networkId :: !BodyNetwork+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Build exactly the requested inputs and outputs with no fee, collateral,+-- balancing or change. Deferred arguments run once on the local zero-fee draft+-- before native V4 evaluation and script-data commitment. An unused or cancelled+-- mint group does not invoke its callback. Native expected errors return 'Left';+-- callback exceptions propagate after native cleanup. Aggregate quantities and+-- deposits must fit signed 64-bit. The result must fit the configured transaction+-- size and execution limits, and output values must fit their configured limit.+-- Later signatures and enclosing fields consume additional transaction space.+--+-- Scripts are evaluated at position zero in an otherwise empty enclosing batch.+-- A script that depends on the actual batch position or surrounding transaction+-- can need different budgets or fail when later assembled. Building does not+-- establish complete ledger admission, balance or the freshness of inputs.+build :: Config -> Plan -> IO (Either Error SubTransaction)+build config plan = case validate config plan of+ Left failure -> pure (Left failure)+ Right () -> do+ result <- runUnchecked config plan (Common.encodePlan (fromMaybe 0 (Parameters.parameterGovernanceActionDeposit (parameters config))) (Plan.toPlan plan))+ pure $ do+ bytes <- result+ transaction <- Sub.decodeCbor bytes+ validateBuilt config transaction+ pure transaction++validate :: Config -> Plan -> Either Error ()+validate config plan = do+ Snapshot.validateNative params+ Common.validatePlan common+ mapM_ (Slots.slotToTime (slotConfig config)) (Common.validitySlots common)+ let funding = Map.elems (Map.fromList [(Utxo.input input, input) | input <- Common.spendingInputs common])+ boundedValue (foldMap (Output.value . Utxo.output) funding <> Common.sourceExtras params common)+ boundedValue (foldMap Output.value (Common.planOutputs common) <> Common.sinkExtras params common)+ mapM_+ bounded+ [ toInteger (Parameters.parameterKeyDeposit params),+ toInteger (Parameters.parameterPoolDeposit params),+ toInteger (fromMaybe 0 (Parameters.parameterGovernanceActionDeposit params)),+ toInteger (fromMaybe 0 (Parameters.parameterDrepDeposit params))+ ]+ where+ common = Plan.toPlan plan+ params = parameters config+ bounded amount = unless (amount >= 0 && amount <= toInteger (maxBound :: Int64)) (Left (InvalidBuildingRequest "Sub-transaction aggregate exceeds signed native bounds"))+ boundedValue value = mapM_ (bounded . snd) (Value.toList value)++validateBuilt :: Config -> SubTransaction -> Either Error ()+validateBuilt config transaction = do+ let params = parameters config+ fields = SubBody.fields (SubBody.toBody (Sub.body transaction))+ units = map Redeemer.executionUnits (Witnesses.redeemers (Witnesses.toWitnesses (Sub.witnesses transaction)))+ unless (toInteger (B.length (Sub.encodeCbor transaction)) <= toInteger (Parameters.parameterMaxTxSize params)) (Left (InvalidBuildingRequest "Sub-transaction exceeds maximum transaction size"))+ mapM_ (checkOutputSize (Parameters.parameterMaxValueSize params)) (Fields.fieldOutputs fields)+ case (units, Parameters.parameterMaxTxExUnits params) of+ ([], _) -> pure ()+ (_, Nothing) -> Left (InvalidBuildingRequest "Maximum transaction execution units are required")+ (_, Just cap) ->+ unless+ (sum (map (toInteger . Ex.memory) units) <= toInteger (Ex.memory cap) && sum (map (toInteger . Ex.steps) units) <= toInteger (Ex.steps cap))+ (Left (InvalidEvaluationResult "Sub-transaction exceeds maximum transaction execution units"))++checkOutputSize :: Maybe Word64 -> Output.Output -> Either Error ()+checkOutputSize Nothing _ = pure ()+checkOutputSize (Just limit) output =+ unless (toInteger (B.length (Cbor.encode encoding)) <= toInteger limit) (Left (InvalidBuildingRequest "Sub-transaction output exceeds maximum value size"))+ where+ value = Output.value output+ coin = E.encodeInteger (Value.quantity Ada value)+ assets = Value.toList (Value.difference value (Value.lovelace (Value.quantity Ada value)))+ encoding = if null assets then coin else E.encodeListLen 2 <> coin <> ValueCbor.encodeAssets value++-- | Test-only malformed instruction boundary. The runtime still encloses every+-- native owner and callback, including expected errors and asynchronous unwind.+runUnchecked :: Config -> Plan -> ByteString -> IO (Either Error ByteString)+runUnchecked config plan = runWithDispatch config (dispatch plan)++-- | Private dispatch injection for native callback-count and cleanup tests.+runWithDispatch :: Config -> Runtime.Dispatch -> ByteString -> IO (Either Error ByteString)+runWithDispatch config handler instructions = Runtime.withRuntime handler $ \runtime ->+ Runtime.withOperation runtime $ \context ->+ Runtime.withBytes (encodeConfig config) $ \configBytes configSize ->+ Runtime.withBytes instructions $ \planBytes planSize ->+ withResult (FFI.cBuild context configBytes configSize planBytes planSize)++encodeConfig :: Config -> ByteString+encodeConfig config =+ Cbor.encode+ ( E.encodeListLen 5+ <> E.encodeBytes (Snapshot.encodeSnapshot (parameters config))+ <> E.encodeWord (case networkId config of Testnet -> 0; Mainnet -> 1)+ <> E.encodeWord64 (Slots.zeroTime slots)+ <> E.encodeWord64 (Slots.zeroSlot slots)+ <> E.encodeWord64 (Slots.slotLength slots)+ )+ where+ slots = slotConfig config++-- Complete decoding, callback evaluation, payload encoding and native copying+-- happen inside the shared protected callback worker, forcing lazy failures.+dispatch :: Plan -> Runtime.Dispatch+dispatch plan operation bytes+ | operation /= 110 = pure (Left (UnsupportedOperation "Unknown sub-transaction deferred operation"))+ | otherwise = pure $ do+ (index, transaction, inputs) <- Cbor.decodeAs InvalidTransactionPlan parser bytes+ callback <- maybe (Left (NativeContractViolation "subTransaction.deferredIndex")) Right (Seq.lookup index (Common.deferredRedeemers (Plan.toPlan plan)))+ let canonical = sortOn Utxo.input inputs+ references = sort (Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body transaction))))+ unless (map Utxo.input canonical == references && Body.fee (Body.toBody (Tx.body transaction)) == 0) (Left (NativeContractViolation "subTransaction.deferredInputs"))+ Data.toCbor <$> callback transaction canonical+ where+ parser = Cbor.array 3 ((,,) <$> D.decodeInt <*> Cbor.nested bytes Tx.decodeCbor <*> Cbor.list (Cbor.nested bytes Utxo.decodeCbor))++-- Initialize and bracket both transferred buffer obligations before calling C.+withResult :: (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)+withResult call = alloca $ \output -> alloca $ \diagnostic ->+ bracket+ (poke output nullPtr >> poke diagnostic nullPtr)+ (\() -> Raw.cBufferRelease output >> Raw.cBufferRelease diagnostic)+ $ \() -> do+ status <- call output diagnostic+ if status == Status.success+ then peek output >>= Runtime.copyBuffer "subTransaction.build"+ else do+ pointer <- peek diagnostic+ if pointer == nullPtr+ then do+ checked <- Runtime.checkStatus "subTransaction.build" status+ pure (checked >> Left (NativeContractViolation "subTransaction.status"))+ else do+ copied <- Runtime.copyBuffer "subTransaction.diagnostic" pointer+ pure $ case copied of+ Left failure -> Left failure+ Right bytes -> Left (NativeError "subTransaction.build" (Code.fromNumber (toInteger status)) (Text.decodeUtf8With (\_ _ -> Just '\xfffd') bytes))
@@ -0,0 +1,258 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Sub-transaction plans share validated instructions and callback indexing+-- with ordinary plans while exposing only the sub-transaction schema.+module Cometa.Internal.SubTransactionPlan+ ( Plan,+ DeferredRedeemer,+ payTo,+ spend,+ spendWith,+ spendWithDeferredRedeemer,+ referenceInput,+ attachScript,+ mint,+ mintWithRedeemer,+ mintWithDeferredRedeemer,+ metadata,+ attachDatum,+ certificate,+ certificateWithRedeemer,+ certificateWithDeferredRedeemer,+ withdraw,+ withdrawWithRedeemer,+ withdrawWithDeferredRedeemer,+ requireSigner,+ validFrom,+ validUntil,+ requireTopLevelGuard,+ requireGuard,+ guardWithRedeemer,+ directDeposit,+ accountBalance,+ donate,+ propose,+ proposeWithRedeemer,+ proposeWithDeferredRedeemer,+ vote,+ voteWithRedeemer,+ voteWithDeferredRedeemer,+ resolvedInputs,+ toPlan,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address.Reward (RewardAddress)+import Cometa.AssetId (AssetId)+import Cometa.AssetName (AssetName)+import Cometa.Certificate (Certificate)+import Cometa.Credential (Credential, Guard, KeyHash, Payment, ScriptHash)+import Cometa.Error (Error)+import Cometa.Governance.Action (Action)+import Cometa.Governance.ActionId (ActionId)+import Cometa.Governance.Anchor (Anchor)+import Cometa.Governance.Voting (Voter, VotingProcedure)+import qualified Cometa.Internal.TransactionPlan as Top+import Cometa.Metadata (Metadatum)+import Cometa.PlutusData (EncodedPlutusData)+import Cometa.PolicyId (PolicyId)+import Cometa.Script (Script)+import Cometa.Transaction (Transaction)+import Cometa.Transaction.Fields (BalanceInterval)+import Cometa.Transaction.Output (Output)+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Ordered intent instructions. Composition combines mint quantities and+-- validity requirements, preserving outputs and certificate order. Conflicting+-- arguments or snapshots fail when building. Plans contain functions, so their+-- monoid laws concern behavior rather than structural equality.+newtype Plan = Plan Top.Plan++instance Semigroup Plan where+ Plan left <> Plan right = Plan (left <> right)++instance Monoid Plan where+ mempty = Plan mempty++-- | Compute an argument once from the local draft: its fee is zero, inputs and+-- redeemer indices are local to the sub-transaction, and resolved spending+-- inputs are in canonical order. Reference inputs are available in the draft+-- body but absent from the supplied spending snapshot. Return an error to abort.+-- The callback must be pure and deterministic. Snapshots are ordinary owned+-- values; no pointer or resource scope escapes the build.+type DeferredRedeemer = Transaction -> [Utxo] -> Either Error EncodedPlutusData++-- DEFINITIONS ----------------------------------------------------------------++-- | Append an output in creation order. Building preserves its exact value.+payTo :: Output -> Plan+payTo a = Plan (Top.payTo a)++-- | Spend exactly this resolved key-controlled output.+spend :: Utxo -> Plan+spend a = Plan (Top.spend a)++-- | Spend a script output with optional argument and datum witness.+spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan+spendWith a b c = Plan (Top.spendWith a b c)++-- | Spend a script output with a local deferred argument and optional datum witness. Register each input once.+spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan+spendWithDeferredRedeemer a b c = Plan (Top.spendWithDeferredRedeemer a b c)++-- | Make a resolved reference output available without spending it.+referenceInput :: Utxo -> Plan+referenceInput a = Plan (Top.referenceInput a)++-- | Attach a native or compiled Plutus script. Executed sub-level scripts require V4.+-- Repeated attachments with the same language and script bytes contribute one+-- witness, ordered by the first attachment.+attachScript :: Script -> Plan+attachScript a = Plan (Top.attachScript a)++-- | Mint or burn a native asset. Ada and combined quantity overflow fail at build.+mint :: AssetId -> Int64 -> Plan+mint a b = Plan (Top.mint a b)++-- | Mint or burn a Plutus-policy asset with an immediate argument.+mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan+mintWithRedeemer a b c = Plan (Top.mintWithRedeemer a b c)++-- | Mint or burn a group of names under one policy with one local deferred argument. Repeated names combine and zero totals disappear. Register each policy once.+mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan+mintWithDeferredRedeemer a b c = Plan (Top.mintWithDeferredRedeemer a b c)++-- | Attach a metadata label; conflicting values fail at build.+metadata :: Word64 -> Metadatum -> Plan+metadata a b = Plan (Top.metadata a b)++-- | Attach an exact datum witness. Repeated exact CBOR encodings contribute one+-- witness, including data supplied to spending inputs, in first occurrence order.+-- Different encodings remain distinct because their hashes differ.+attachDatum :: EncodedPlutusData -> Plan+attachDatum a = Plan (Top.attachDatum a)++-- | Append a typed certificate without a script argument.+certificate :: Certificate -> Plan+certificate a = Plan (Top.certificate a)++-- | Append a typed certificate authorized by an immediate argument.+certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan+certificateWithRedeemer a b = Plan (Top.certificateWithRedeemer a b)++-- | Append a typed certificate authorized by a local deferred argument.+certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan+certificateWithDeferredRedeemer a b = Plan (Top.certificateWithDeferredRedeemer a b)++-- | Withdraw rewards from a key-controlled account. Amounts must fit signed 64-bit.+withdraw :: RewardAddress -> Word64 -> Plan+withdraw a b = Plan (Top.withdraw a b)++-- | Withdraw rewards with an immediate Plutus argument.+withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan+withdrawWithRedeemer a b c = Plan (Top.withdrawWithRedeemer a b c)++-- | Withdraw rewards with a local deferred argument. Register each account once.+withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan+withdrawWithDeferredRedeemer a b c = Plan (Top.withdrawWithDeferredRedeemer a b c)++-- | Require a payment key hash as a local guard.+requireSigner :: KeyHash Payment -> Plan+requireSigner a = Plan (Top.requireSigner a)++-- | Inclusive lower validity slot; composition takes the greatest lower bound.+validFrom :: Word64 -> Plan+validFrom a = Plan (Top.validFrom a)++-- | Exclusive upper validity slot; composition takes the least upper bound.+validUntil :: Word64 -> Plan+validUntil a = Plan (Top.validUntil a)++-- | Unique spending and reference snapshots in ascending input-reference order.+-- Conflicting original snapshots are rejected when building.+-- Supply this result alongside a successfully built intent when attaching it+-- to an outer plan.+resolvedInputs :: Plan -> [Utxo]+resolvedInputs (Plan plan) = Map.elems (Map.fromList [(Utxo.input input, input) | input <- Top.resolvedInputs plan])++-- | Internal reuse of common validation, serialization and rooted callbacks.+toPlan :: Plan -> Top.Plan+toPlan (Plan plan) = plan++-- | Require a key or native-script guard. Use guardWithRedeemer for Plutus guards.+requireGuard :: Credential Guard -> Plan+requireGuard credential = Plan (Top.requireGuard credential)++-- | Require a local Plutus guard with its immediate argument.+guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan+guardWithRedeemer hash argument = Plan (Top.guardWithRedeemer hash argument)++-- | Deposit lovelace directly into a reward account. Repeated amounts combine.+directDeposit :: RewardAddress -> Word64 -> Plan+directDeposit account amount = Plan (Top.directDeposit account amount)++-- | Require a reward-account balance interval for this intent.+accountBalance :: RewardAddress -> BalanceInterval -> Plan+accountBalance account interval = Plan (Top.accountBalance account interval)++-- | Donate lovelace to the treasury; repeated donations combine.+donate :: Word64 -> Plan+donate amount = Plan (Top.donate amount)++-- | Append a governance proposal, using the configured governance deposit.+-- Parameter changes and treasury withdrawals naming a guardrails policy use+-- the unit argument @Constr 0 []@ and require a supplied Plutus V4 script.+-- Actions without a policy do not create a proposing redeemer.+propose :: RewardAddress -> Action -> Anchor -> Plan+propose account action anchor = Plan (Top.propose account action anchor)++-- | Append a proposal with a guardrails argument. The action must name a policy;+-- the configured protocol snapshot supplies its deposit. Attach the script or+-- resolve its reference input separately. Duplicate proposals fail at build.+proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan+proposeWithRedeemer account action anchor argument = Plan (Top.proposeWithRedeemer account action anchor argument)++-- | Compute a proposal's guardrails argument from the local draft. Proposal+-- indices and resolved inputs belong to this subtransaction. The action must+-- name a policy; duplicate proposals fail at build.+proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan+proposeWithDeferredRedeemer account action anchor callback = Plan (Top.proposeWithDeferredRedeemer account action anchor callback)++-- | Cast a key-authorized governance vote.+vote :: Voter -> ActionId -> VotingProcedure -> Plan+vote voter action procedure = Plan (Top.vote voter action procedure)++-- | Cast several votes under one voter with one immediate argument.+voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan+voteWithRedeemer voter votes argument = Plan (Top.voteWithRedeemer voter votes argument)++-- | Cast several votes under one voter with one local deferred argument. Register each voter once; empty groups do not invoke the callback.+voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan+voteWithDeferredRedeemer voter votes callback = Plan (Top.voteWithDeferredRedeemer voter votes callback)++-- | Require an outer guard and optional datum for this intent. This records a+-- requirement; the enclosing transaction must satisfy it when assembled.+requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan+requireTopLevelGuard credential datum = Plan (Top.requireTopLevelGuard credential datum)
@@ -0,0 +1,358 @@+{-# LANGUAGE LambdaCase #-}+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Scoped standalone balancing, including stable spending-redeemer identity.+module Cometa.Internal.TransactionBalancing (balance, balanceWithRedeemers) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Term as Term+import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (Ada))+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Eval+import qualified Cometa.Internal.Balance as Balance+import qualified Cometa.Internal.BalancingScripts as Scripts+import qualified Cometa.Internal.BatchValidation as Batch+import qualified Cometa.Internal.Building as Building+import qualified Cometa.Internal.CoinSelection.Native as Selection+import qualified Cometa.Internal.Evaluation.Native as NativeEvaluation+import qualified Cometa.Internal.EvaluationNative as Evaluation+import qualified Cometa.Internal.FFI.TransactionBuilder as FFI+import qualified Cometa.Internal.ParameterSnapshot as Parameters+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionBuilder as Builder+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Plan (DeferredRedeemer)+import qualified Cometa.Transaction.Redeemer as Redeemer+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sort, sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, isJust)+import qualified Data.Set as Set+import Data.Text (Text)+import Foreign.Ptr (nullPtr)++-- DEFINITIONS ----------------------------------------------------------------++-- | Balance an existing transaction with the same configuration used by+-- 'Cometa.Transaction.Builder.build'. Supply resolved spending, reference and+-- collateral inputs for every level; wallet candidates in the configuration may+-- also provide these snapshots. Every existing outer output is treated as a+-- payment, including previous change. The existing fee and configured minimum+-- fee are lower bounds. The imported network id is retained.+--+-- The result drops outer key/bootstrap signatures and retains signed nested+-- intent bodies and witnesses. Native serialization may normalize enclosing CBOR+-- array framing; it does not promise byte-for-byte transaction interchange.+-- Spending redeemers follow their original inputs when selection changes+-- input order. Script budgets, commitments, collateral and fees are recalculated.+-- Missing/conflicting inputs or invalid redeemer positions fail explicitly.+-- Callback exceptions and cancellation release scoped resources before propagating.+-- No provider queries, signing or submission occur; ledger acceptance is separate.+balance :: Builder.Config -> [Utxo] -> Transaction -> IO (Either Error Transaction)+balance config resolved = balanceWithRedeemers config resolved Map.empty++-- | Like 'balance', replacing selected outer redeemer payloads on every balancing+-- iteration. Keys identify purpose/index pairs in the ORIGINAL transaction; every+-- key must already have a witness redeemer. Spending associations follow their+-- original inputs even when their indices change. Other purposes retain their+-- existing body order. Callbacks receive the current draft and canonically ordered+-- resolved outer spending inputs. They may run repeatedly and must be deterministic.+-- Use "Cometa.Transaction.Deferred" to compose pure queries. Nested redeemers are+-- signed intent content and cannot be replaced by this operation.+balanceWithRedeemers :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> IO (Either Error Transaction)+balanceWithRedeemers config resolved callbacks original = runExceptT $ do+ snapshots <- except (validate config resolved callbacks original)+ ExceptT (preflight config snapshots original)+ prepared <- except (reserveScriptHash original)+ balancedDraft <- ExceptT (runBalance config snapshots callbacks prepared)+ models <- ExceptT (Scripts.usedCostModels (Builder.parameters config) snapshots balancedDraft)+ commitment <- ExceptT (Building.scriptDataHash models (Tx.witnesses balancedDraft))+ result <- except (setScriptHash commitment balancedDraft)+ except (validateResult config result)+ let evaluator = evaluatorFor config+ ExceptT (Batch.validateSubBudgets evaluator snapshots result)+ balanced <- ExceptT (Balance.isBalanced (Builder.parameters config) snapshots result)+ unless balanced (throwE (NativeContractViolation "balancing.conservation"))+ pure result++-- | Resolve identities once; duplicates within a supplied snapshot are rejected.+validate :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> Either Error [Utxo]+validate config resolved callbacks transaction = do+ Parameters.validateNative (Builder.parameters config)+ mapM_ unique [resolved, Builder.availableUtxos config, Builder.collateralUtxos config]+ let allInputs = resolved <> Builder.availableUtxos config <> Builder.collateralUtxos config+ grouped = Map.fromListWith (<>) [(Utxo.input u, [u]) | u <- allInputs]+ unless (all agrees (Map.elems grouped)) (Left (InvalidBuildingRequest "Conflicting resolved input snapshots"))+ let snapshots = Map.fromList [(Utxo.input u, u) | u <- allInputs]+ body = Body.toBody (Tx.body transaction)+ fields = Body.bodyFields body+ subFields = maybe [] (map (SubBody.fields . SubBody.toBody . Sub.body)) (Body.bodySubTransactions body)+ required = concatMap references (fields : subFields) <> fromMaybe [] (Body.bodyCollateral body)+ redeemers = outerRedeemers transaction+ identifiers = map identifier redeemers+ unless (all (`Map.member` snapshots) required) (Left (InvalidBuildingRequest "A transaction input has no resolved UTxO"))+ unless (all uniqueReferences (fields : subFields)) (Left (InvalidBuildingRequest "Duplicate transaction input reference"))+ unless (Set.size (Set.fromList identifiers) == length identifiers) (Left (InvalidBuildingRequest "Duplicate redeemer purpose and index"))+ unless (all (`elem` identifiers) (Map.keys callbacks)) (Left (InvalidBuildingRequest "Deferred redeemer has no existing witness"))+ mapM_ (spendingInput fields) redeemers+ mapM_ (validatePurpose transaction) redeemers+ mapM_ (Slot.slotToTime (Builder.slotConfig config)) (maybe [] pure (Fields.fieldInvalidBefore fields) <> maybe [] pure (Fields.fieldInvalidAfter fields))+ pure (Map.elems snapshots)+ where+ unique values = unless (Set.size (Set.fromList (map Utxo.input values)) == length values) (Left (InvalidBuildingRequest "Duplicate resolved input snapshot"))+ agrees [] = True+ agrees (x : xs) = all (== x) xs+ uniqueReferences fields = let refs = Fields.fieldInputs fields in Set.size (Set.fromList refs) == length refs++-- | Spending indices refer to sorted original input identities, not list storage.+spendingInput :: Fields.Fields -> Redeemer.Redeemer -> Either Error (Maybe Input.Input)+spendingInput fields redeemer+ | Redeemer.purpose redeemer /= Redeemer.Spending = Right Nothing+ | otherwise = case dropInteger (Redeemer.index redeemer) (sort (Fields.fieldInputs fields)) of+ value : _ -> Right (Just value)+ [] -> Left (InvalidBuildingRequest "Spending redeemer index has no original input")+ where+ dropInteger index values+ | toInteger index >= toInteger (length values) = []+ | otherwise = drop (fromIntegral index) values++-- | Conservative bounds protect intermediate native fee and value arithmetic.+preflight :: Builder.Config -> [Utxo] -> Transaction -> IO (Either Error ())+preflight config snapshots transaction = runExceptT $ do+ let params = Builder.parameters config+ body = Body.toBody (Tx.body transaction)+ intents = fromMaybe [] (Body.bodySubTransactions body)+ allFields = Body.bodyFields body : map (SubBody.fields . SubBody.toBody . Sub.body) intents+ outputs = concatMap Fields.fieldOutputs allFields+ redeemers = outerRedeemers transaction <> concatMap (Witnesses.redeemers . Witnesses.toWitnesses . Sub.witnesses) intents+ outer <- ExceptT (Building.implicitCoin params transaction)+ nested <- traverse (ExceptT . Building.subTransactionImplicitCoin params) intents+ let implicit = outer : nested+ coin = sum [toInteger (Building.deposits x) + toInteger (Building.reclaimedDeposits x) + toInteger (Building.withdrawals x) | x <- implicit]+ spending = Set.fromList (concatMap Fields.fieldInputs allFields)+ referenced = Set.fromList (concatMap (fromMaybe [] . Fields.fieldReferenceInputs) allFields)+ authorized = Set.fromList (map Utxo.input (Builder.availableUtxos config))+ potential = filter (\u -> Utxo.input u `Set.member` spending || (Utxo.input u `Set.member` authorized && Utxo.input u `Set.notMember` referenced)) snapshots+ mint = concatMap (maybe [] (Value.toList . Fields.mintValue) . Fields.fieldMint) allFields+ consumed = Map.fromListWith (+) (concatMap (Value.toList . Output.value . Utxo.output) potential <> [(asset, amount) | (asset, amount) <- mint, amount > 0])+ produced = Map.fromListWith (+) (concatMap (Value.toList . Output.value) outputs <> [(asset, negate amount) | (asset, amount) <- mint, amount < 0])+ totals = Map.unionWith max consumed produced+ collateral = Map.fromListWith (+) (concatMap (Value.toList . Output.value . Utxo.output) (Builder.collateralUtxos config))+ except (mapM_ (bounded "Aggregate balance exceeds signed native bounds") (coin : Map.elems totals <> Map.elems collateral))+ except (bounded "Deposit exceeds signed native bounds" (toInteger (P.parameterKeyDeposit params) + toInteger (P.parameterPoolDeposit params)))+ let maximumSize = toInteger (P.parameterMaxTxSize params)+ extraKeys = toInteger (Builder.extraSigners config)+ snapshotSize = toInteger (B.length (Tx.encodeCbor transaction)) + sum [toInteger (B.length (Utxo.encodeCbor u)) | u <- snapshots]+ changeSize = (toInteger (length outputs) + 1) * (snapshotSize + 1) * (snapshotSize + toInteger (B.length (Address.toBytes (Builder.changeAddress config))) + 256)+ sizeBound = snapshotSize + changeSize + 1024 + 101 * (extraKeys + toInteger (length snapshots))+ except (unless (extraKeys <= maximumSize `div` 101) (Left (InvalidBuildingRequest "Additional signer witnesses exceed maximum transaction size")))+ except (bounded "Minimum Ada multiplication exceeds signed bounds" (toInteger (fromMaybe 0 (P.parameterAdaPerUtxoByte params)) * (maximumSize + 160)))+ except (unless (all ((<= maximumSize) . toInteger . B.length . Output.encodeCbor) outputs) (Left (InvalidBuildingRequest "Output exceeds maximum transaction size")))+ referenceFee <- if any (isJust . Output.referenceScript . Utxo.output) snapshots then ExceptT (Builder.pricedReferenceFee params (snapshots <> concatMap (const snapshots) intents)) else pure 0+ executionFee <-+ except $+ if null redeemers+ then Right 0+ else do+ prices <- maybe (Left (InvalidBuildingRequest "Script execution prices are required")) Right (P.parameterExecutionCosts params)+ cap <- maybe (Left (InvalidBuildingRequest "Maximum transaction execution units are required")) Right (P.parameterMaxTxExUnits params)+ pure (ceiling (fromIntegral (Ex.memory cap) * Rational.toRational (Prices.memoryPrice prices) + fromIntegral (Ex.steps cap) * Rational.toRational (Prices.stepPrice prices)))+ let feeBound = max (toInteger (max (Body.fee body) (Builder.minimumFee config))) (toInteger (P.parameterMinFeeB params) + toInteger (P.parameterMinFeeA params) * sizeBound + executionFee + toInteger referenceFee)+ except (bounded "Priced transaction exceeds signed balance bounds" (feeBound + coin + Map.findWithDefault 0 Ada totals))++bounded :: Text -> Integer -> Either Error ()+bounded message value = unless (value >= 0 && value <= toInteger (maxBound :: Int64)) (Left (InvalidBuildingRequest message))++-- | Run all callback owners under the same protected native operation.+runBalance :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> IO (Either Error Transaction)+runBalance config snapshots callbacks original =+ Runtime.withRuntime selection $ \selector ->+ Runtime.withRuntime (Evaluation.dispatch (Builder.checkedEvaluator config (evaluatorFor config)) Eval.TopLevel) $ \evaluator ->+ Runtime.withRuntime (deferredDispatch original callbacks) $ \deferred -> do+ result <- Runtime.withOperations [selector, evaluator, deferred] $ \case+ [selectionContext, evaluationContext, deferredContext] ->+ Runtime.withBytes (Builder.encodeConfig mempty configured) $ \configBytes configSize ->+ Runtime.withBytes (encodeRequest snapshots callbacks unsigned) $ \requestBytes requestSize ->+ Builder.withResultNamed "transaction.balance" (FFI.cBalance (if isJust (Builder.selector config) then selectionContext else nullPtr) evaluationContext deferredContext configBytes configSize requestBytes requestSize)+ _ -> pure (Left (NativeContractViolation "balancing.contexts"))+ pure $ do+ (bytes, keys) <- result+ transaction <- Tx.decodeCbor bytes+ let reserve = sum [180 + toInteger (B.length address) | address <- Set.toList (byronAddresses snapshots transaction)]+ size = toInteger (B.length bytes) + 101 * toInteger keys + reserve + 32+ unless (size <= toInteger (P.parameterMaxTxSize (Builder.parameters config))) (Left (InvalidBuildingRequest "Balanced transaction and witnesses exceed maximum size"))+ pure transaction+ where+ unsigned = Tx.setWitnesses (Witnesses.removeKeyWitnesses (Tx.witnesses original)) original+ body = Body.toBody (Tx.body original)+ fields = Body.bodyFields body+ reserved = references fields+ nestedReferences = maybe [] (concatMap (references . SubBody.fields . SubBody.toBody . Sub.body)) (Body.bodySubTransactions body)+ originalCollateral = fromMaybe [] (Body.bodyCollateral body)+ configured =+ config+ { Builder.availableUtxos = Map.elems (Map.fromList [(Utxo.input u, u) | u <- Builder.availableUtxos config <> filter (\u -> Utxo.input u `elem` nestedReferences) snapshots, Utxo.input u `notElem` reserved]),+ Builder.collateralUtxos = Map.elems (Map.fromList [(Utxo.input u, u) | u <- Builder.collateralUtxos config <> filter (\u -> Utxo.input u `elem` originalCollateral) snapshots])+ }+ selection = maybe (\_ _ -> pure (Left (NativeContractViolation "balancing.selector"))) Selection.dispatch (Builder.selector config)++-- | Native evaluator remains explicit IO, including inside native callback dispatch.+evaluatorFor :: Builder.Config -> Eval.Evaluator+evaluatorFor config = fromMaybe native (Builder.evaluator config)+ where+ Version.ProtocolVersion major _ = P.parameterProtocolVersion (Builder.parameters config)+ native = NativeEvaluation.evaluator (NativeEvaluation.Config (Builder.slotConfig config) major (fromMaybe Models.empty (P.parameterCostModels (Builder.parameters config))))++validateResult :: Builder.Config -> Transaction -> Either Error ()+validateResult config transaction = Builder.validateBudget config (map Redeemer.executionUnits redeemers)+ where+ redeemers = outerRedeemers transaction <> maybe [] (concatMap (Witnesses.redeemers . Witnesses.toWitnesses . Sub.witnesses)) (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))++references :: Fields.Fields -> [Input.Input]+references fields = Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields)++outerRedeemers :: Transaction -> [Redeemer.Redeemer]+outerRedeemers = Witnesses.redeemers . Witnesses.toWitnesses . Tx.witnesses++identifier :: Redeemer.Redeemer -> Eval.RedeemerId+identifier r = Eval.RedeemerId (Redeemer.purpose r) (Redeemer.index r)++encodeRequest :: [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> ByteString+encodeRequest snapshots callbacks transaction =+ C.encode $+ E.encodeListLen 4+ <> E.encodeBytes (Tx.encodeCbor transaction)+ <> utxos refs+ <> utxos spending+ <> E.encodeListLen (fromIntegral (length redeemers))+ <> foldMap entry redeemers+ where+ fields = Body.bodyFields (Body.toBody (Tx.body transaction))+ redeemers = outerRedeemers transaction+ refs = filter (\u -> Utxo.input u `elem` fromMaybe [] (Fields.fieldReferenceInputs fields)) snapshots+ spending = filter (\u -> Utxo.input u `elem` Fields.fieldInputs fields) snapshots+ utxos values = E.encodeListLen (fromIntegral (length values)) <> foldMap (C.raw . Utxo.encodeCbor) values+ entry r =+ E.encodeListLen 4+ <> E.encodeWord (fromIntegral (fromEnum (Redeemer.purpose r)))+ <> E.encodeWord32 (Redeemer.index r)+ <> E.encodeBytes (either (const mempty) (maybe mempty Input.encodeCbor) (spendingInput fields r))+ <> E.encodeBool (Map.member (identifier r) callbacks)++-- | Decode and fully force callback replies inside Runtime's exception boundary.+deferredDispatch :: Transaction -> Map Eval.RedeemerId DeferredRedeemer -> Runtime.Dispatch+deferredDispatch original callbacks operation bytes+ | operation /= 110 = pure (Left (UnsupportedOperation "Unknown balancing callback operation"))+ | otherwise = pure $ do+ (index, transaction, inputs) <- C.decodeAs InvalidBuildingRequest parser bytes+ ident <- maybe (Left (NativeContractViolation "balancing.callbackIndex")) Right (Map.lookup index identifiers)+ callback <- maybe (Left (NativeContractViolation "balancing.callback")) Right (Map.lookup ident callbacks)+ let selected = sortOn Utxo.input inputs+ unless (map Utxo.input selected == sort (Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body transaction))))) (Left (NativeContractViolation "balancing.callbackInputs"))+ Data.toCbor <$> callback transaction selected+ where+ identifiers = Map.fromList (zip [0 :: Int ..] (map identifier (outerRedeemers original)))+ parser = C.array 3 ((,,) <$> D.decodeInt <*> C.nested bytes Tx.decodeCbor <*> C.list (C.nested bytes Utxo.decodeCbor))++-- | Inspect exact body collection lengths so imported zero mint groups still count.+validatePurpose :: Transaction -> Redeemer.Redeemer -> Either Error ()+validatePurpose transaction redeemer = do+ let bytes = Body.toCbor (Tx.body transaction)+ key = case Redeemer.purpose redeemer of+ Redeemer.Spending -> 0+ Redeemer.Minting -> 9+ Redeemer.Certifying -> 4+ Redeemer.Rewarding -> 5+ Redeemer.Voting -> 19+ Redeemer.Proposing -> 20+ Redeemer.Guarding -> 14+ fields <- C.decodeAs InvalidBuildingRequest (C.mapFields bytes) bytes+ count <- case Map.lookup key fields of+ Nothing -> Right 0+ Just encoded -> collectionLength <$> C.decodeAs InvalidBuildingRequest Term.decodeTerm encoded+ unless (toInteger (Redeemer.index redeemer) < toInteger count) (Left (InvalidBuildingRequest "Redeemer index has no body operation"))+ where+ collectionLength term = case term of+ Term.TTagged _ value -> collectionLength value+ Term.TList values -> length values+ Term.TListI values -> length values+ Term.TMap values -> length values+ Term.TMapI values -> length values+ _ -> 0++-- | Reserve exactly the final commitment's byte length before fee calculation.+reserveScriptHash :: Transaction -> Either Error Transaction+reserveScriptHash transaction+ | null (outerRedeemers transaction) && null (Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses transaction))) = setScriptHash Nothing transaction+ | otherwise = Datum.hashFromBytes (B.replicate 32 0) >>= \hash -> setScriptHash (Just hash) transaction++-- | Replace only the unsigned outer body's commitment; preserve other field bytes.+setScriptHash :: Maybe Datum.Hash32 -> Transaction -> Either Error Transaction+setScriptHash commitment transaction = do+ let bytes = Body.toCbor (Tx.body transaction)+ fields <- C.decodeAs InvalidBuildingRequest (C.mapFields bytes) bytes+ let updated = case commitment of+ Nothing -> Map.delete 11 fields+ Just hash -> Map.insert 11 (C.encode (E.encodeBytes (Datum.hashBytes hash))) fields+ encoded = C.encode (E.encodeMapLen (fromIntegral (Map.size updated)) <> foldMap (\(key, value) -> E.encodeWord64 key <> C.raw value) (Map.toAscList updated))+ replacement <- Body.decodeCbor encoded+ pure (Tx.setBody replacement transaction)++-- | Only actual spending/collateral Byron addresses need bootstrap reserves.+byronAddresses :: [Utxo] -> Transaction -> Set.Set ByteString+byronAddresses snapshots transaction =+ Set.fromList+ [ Address.toBytes address+ | u <- snapshots,+ Utxo.input u `elem` used,+ let address = Output.address (Utxo.output u),+ case address of Address.ByronAddress _ -> True; _ -> False+ ]+ where+ body = Body.toBody (Tx.body transaction)+ used = Fields.fieldInputs (Body.bodyFields body) <> fromMaybe [] (Body.bodyCollateral body)
@@ -0,0 +1,466 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TupleSections #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Balance a complete pure transaction plan using explicit protocol and wallet+-- snapshots. Build returns a fresh unsigned transaction; signing and submission+-- are separate operations. Inject selection or evaluation with ordinary records.+--+-- @+-- buildPayment params slots change funds output =+-- build (defaultConfig params slots change) {availableUtxos = funds}+-- (Plan.payTo output)+-- @+module Cometa.Internal.TransactionBuilder (Config (..), defaultConfig, build, encodeConfig, withResult, withResultNamed, checkedEvaluator, validateBudget, pricedReferenceFee) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address (Address)+import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (Ada))+import Cometa.CoinSelection (Selector)+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import Cometa.Evaluation (Evaluator, Target (TopLevel))+import qualified Cometa.Evaluation as Eval+import qualified Cometa.Internal.BatchValidation as Batch+import qualified Cometa.Internal.Building as Building+import qualified Cometa.Internal.CoinSelection.Native as Selection+import qualified Cometa.Internal.Evaluation.Native as NativeEvaluation+import qualified Cometa.Internal.EvaluationNative as Evaluation+import qualified Cometa.Internal.FFI.Native as Native+import qualified Cometa.Internal.FFI.Runtime as Raw+import qualified Cometa.Internal.FFI.TransactionBuilder as FFI+import qualified Cometa.Internal.ParameterSnapshot as Parameters+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.Internal.TransactionPlan as Plan+import qualified Cometa.Internal.TransactionValue as ValueCbor+import qualified Cometa.PlutusData as Data+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import Cometa.SlotConfig (SlotConfig)+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Transaction+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Plan (Plan)+import qualified Cometa.Transaction.Redeemer as Redeemer+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.Value as Value+import Control.Exception (bracket)+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sort, sortOn)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, isJust)+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (peek, poke)++-- TYPES ----------------------------------------------------------------------++-- | Explicit context for one build. Snapshots must describe the same ledger+-- state. Callback records can be invoked repeatedly as balancing converges.+data Config = Config+ { -- | Complete protocol snapshot used for fees, limits and script costs.+ parameters :: Parameters,+ -- | Network slot/time conversion used by script evaluation.+ slotConfig :: SlotConfig,+ -- | Address receiving change; its network also sets the body network id.+ changeAddress :: Address,+ -- | Wallet outputs eligible for additional spending selection.+ availableUtxos :: [Utxo],+ -- | Outputs eligible for Plutus collateral selection.+ collateralUtxos :: [Utxo],+ -- | Optional collateral return destination; defaults to the change address.+ collateralChangeAddress :: Maybe Address,+ -- | Optional selector; absence uses the native random-improve selector.+ selector :: Maybe Selector,+ -- | Optional evaluator; absence uses the built-in evaluator. For batches,+ -- the evaluator must also support subtransaction targets to verify that+ -- signed execution budgets cover the final batch context.+ evaluator :: Maybe Evaluator,+ -- | Lower bound on the fee in lovelace; zero permits ordinary calculation.+ minimumFee :: Word64,+ -- | Additional key witnesses included in fee size estimation.+ extraSigners :: Word64,+ -- | Latest registered pools for owner-witness estimation from protocol 12.+ -- Prefer pending parameters over active ones and include each pool once.+ -- Unknown pools retain conservative estimates. Pool deposits are unaffected.+ poolState :: [Pool.PoolParameters]+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | No eligible wallet/collateral outputs, no injected callbacks, and zero fee+-- floor or additional witnesses. Supply wallet snapshots before building.+defaultConfig :: Parameters -> SlotConfig -> Address -> Config+defaultConfig params slots change = Config params slots change [] [] Nothing Nothing Nothing 0 0 []++-- | Validate requirements, run balancing and copy the completed unsigned+-- transaction. Expected failures return once here, including original callback+-- errors. Callback exceptions and asynchronous cancellation unwind all native+-- work before propagating. No chain queries, signing or submission occur.+build :: Config -> Plan -> IO (Either Error Transaction)+build config plan = case validate config plan of+ Left failure -> pure (Left failure)+ Right () -> do+ fees <- validateFees config plan+ case fees of+ Left failure -> pure (Left failure)+ Right () -> buildNative config plan++buildNative :: Config -> Plan -> IO (Either Error Transaction)+buildNative config plan =+ Runtime.withRuntime selectDispatch $ \selection ->+ Runtime.withRuntime evaluateDispatch $ \evaluation ->+ Runtime.withRuntime (deferredDispatch plan) $ \deferred -> do+ result <- Runtime.withOperations [selection, evaluation, deferred] $ \case+ [selectContext, evaluateContext, deferredContext] ->+ Runtime.withBytes (encodeConfig plan config) $ \configBytes configSize ->+ Runtime.withBytes (Plan.encodePlan (fromMaybe 0 (P.parameterGovernanceActionDeposit (parameters config))) plan) $ \planBytes planSize ->+ withResult+ ( FFI.cBuild+ (if isJust (selector config) then selectContext else nullPtr)+ (if isJust (evaluator config) then evaluateContext else nullPtr)+ deferredContext+ configBytes+ configSize+ planBytes+ planSize+ )+ _ -> pure (Left (NativeContractViolation "builder.contexts"))+ case result >>= decodeBuilt of+ Left failure -> pure (Left failure)+ Right transaction -> do+ checked <- Batch.validateSubBudgets (fromMaybe nativeEvaluator (evaluator config)) resolved transaction+ pure (transaction <$ checked)+ where+ decodeBuilt (bytes, keyCount) = do+ transaction <- Transaction.decodeCbor bytes+ validateBuilt config plan keyCount transaction+ pure transaction+ resolved = Map.elems (Map.fromList [(Utxo.input input, input) | input <- availableUtxos config <> collateralUtxos config <> Plan.resolvedInputs plan])+ nativeEvaluator =+ let Version.ProtocolVersion major _ = P.parameterProtocolVersion (parameters config)+ in NativeEvaluation.evaluator (NativeEvaluation.Config (slotConfig config) major (fromMaybe Models.empty (P.parameterCostModels (parameters config))))+ selectDispatch = maybe unavailable Selection.dispatch (selector config)+ evaluateDispatch = maybe unavailable (\backend -> Evaluation.dispatch (checkedEvaluator config backend) TopLevel) (evaluator config)+ unavailable _ _ = pure (Left (NativeContractViolation "builder.unconfiguredCallback"))++validate :: Config -> Plan -> Either Error ()+validate config plan = do+ let poolIds = map Pool.operator (poolState config)+ unless (length poolIds == Set.size (Set.fromList poolIds)) $+ Left (InvalidBuildingRequest "Pool state contains duplicate pool operators")+ Plan.validatePlan plan+ Plan.validateTopLevel plan+ mapM_+ (checkSubOutputSize (P.parameterMaxValueSize (parameters config)))+ [output | (transaction, _) <- Plan.subTransactions plan, output <- Fields.fieldOutputs (SubBody.fields (SubBody.toBody (Sub.body transaction)))]+ mapM_ (Slot.slotToTime (slotConfig config)) (Plan.validitySlots plan)+ Parameters.validateNative (parameters config)+ consistent (availableUtxos config <> collateralUtxos config <> Plan.resolvedInputs plan)+ unique (availableUtxos config)+ unique (collateralUtxos config)+ bounded "Fee exceeds signed native balance bounds" (toInteger (minimumFee config))+ let funds = Map.elems (Map.fromList [(Utxo.input u, u) | u <- eligible plan (availableUtxos config) <> Plan.spendingInputs plan])+ inputValue = foldMap (Output.value . Utxo.output) funds+ outputValue = foldMap Output.value (Plan.planOutputs plan)+ collateralValue = foldMap (Output.value . Utxo.output) (eligible plan (collateralUtxos config))+ witnessBytes values =+ sum+ [ case Output.address (Utxo.output u) of+ Address.ByronAddress _ -> 180 + toInteger (B.length (Address.toBytes (Output.address (Utxo.output u))))+ _ -> 101+ | u <- values+ ]+ potentialWitnessBytes = witnessBytes (funds <> collateralUtxos config) + 101 * (toInteger (extraSigners config) + Plan.witnessCount plan) + 32+ maximumFee =+ max+ (toInteger (minimumFee config))+ (toInteger (P.parameterMinFeeA (parameters config)) * toInteger (P.parameterMaxTxSize (parameters config)) + toInteger (P.parameterMinFeeB (parameters config)))+ bounded+ "Potential native witness fee exceeds signed balance bounds"+ (maximumFee + potentialWitnessBytes * toInteger (P.parameterMinFeeA (parameters config)))+ bounded "Maximum linear transaction fee exceeds signed native balance bounds" maximumFee+ case P.parameterAdaPerUtxoByte (parameters config) of+ Nothing -> pure ()+ Just price ->+ bounded+ "Minimum Ada multiplication exceeds signed bounds"+ (toInteger price * (160 + toInteger (P.parameterMaxTxSize (parameters config))))+ boundedValue (inputValue <> Plan.sourceExtras (parameters config) plan)+ boundedValue (outputValue <> Plan.sinkExtras (parameters config) plan <> Value.lovelace maximumFee)+ boundedValue collateralValue+ bounded "Stake key deposit exceeds signed native bounds" (toInteger (P.parameterKeyDeposit (parameters config)))+ bounded "Governance proposal deposit exceeds signed native bounds" (toInteger (fromMaybe 0 (P.parameterGovernanceActionDeposit (parameters config))))+ bounded "Pool deposit exceeds signed native bounds" (toInteger (P.parameterPoolDeposit (parameters config)))+ unless+ (toInteger (extraSigners config) <= toInteger (P.parameterMaxTxSize (parameters config)) `div` 101)+ (Left (InvalidBuildingRequest "Additional signer witnesses exceed maximum transaction size"))+ where+ bounded message n = unless (n >= 0 && n <= toInteger (maxBound :: Int64)) (Left (InvalidBuildingRequest message))+ boundedValue value = mapM_ (bounded "Aggregate native balance exceeds signed bounds" . snd) (Value.toList value)+ unique values =+ unless+ (Set.size (Set.fromList (map Utxo.input values)) == length values)+ (Left (InvalidBuildingRequest "Duplicate input reference in wallet snapshot"))+ consistent values =+ unless+ (all (\a -> all (\b -> Utxo.input a /= Utxo.input b || a == b) values) values)+ (Left (InvalidBuildingRequest "Conflicting snapshots for one wallet input"))++-- Fee preflight includes every potentially selected reference script. The native+-- VM uses one shared fixed100m/100b memory/CPU ceiling (pinned native evaluator+-- lines128/134 and2249); injected budgets are capped by the supplied protocol.+validateFees :: Config -> Plan -> IO (Either Error ())+validateFees config plan = do+ let possible = Map.elems (Map.fromList [(Utxo.input u, u) | u <- eligible plan (availableUtxos config) <> Plan.outerResolvedInputs plan])+ subPriced = concatMap pricedSub (Plan.subTransactions plan)+ allPriced = possible <> subPriced+ hasReferenceScript = any (isJust . Output.referenceScript . Utxo.output) allPriced+ reference <- if hasReferenceScript then pricedReferenceFee (parameters config) allPriced else pure (Right 0)+ pure $ do+ referenceFee <- reference+ executionFee <- executionLimitFee config plan+ let params = parameters config+ witnessBytes =+ 101 * (toInteger (extraSigners config) + Plan.witnessCount plan)+ + sum+ [ case Output.address (Utxo.output u) of+ Address.ByronAddress _ -> 180 + toInteger (B.length (Address.toBytes (Output.address (Utxo.output u))))+ _ -> 101+ | u <- possible <> collateralUtxos config+ ]+ + 32+ -- A source/plan byte bounds the count of distinct assets it can+ -- encode. Native change may repeat all incidental assets for every+ -- output hint, then split oversized values. Bound those two counts by+ -- (hints+1)*(snapshotBytes+1), and each resulting output by the full+ -- asset snapshot plus address and map/coin/script framing allowance.+ snapshotBytes =+ toInteger (B.length (Plan.encodePlan (fromMaybe 0 (P.parameterGovernanceActionDeposit (parameters config))) plan))+ + sum [toInteger (B.length (Utxo.encodeCbor u)) | u <- possible <> collateralUtxos config]+ changeCount = (toInteger (length (Plan.planOutputs plan)) + 1) * (snapshotBytes + 1)+ changeBytes = changeCount * (snapshotBytes + toInteger (B.length (Address.toBytes (changeAddress config))) + 256)+ sizeBound = snapshotBytes + changeBytes + 1024 + witnessBytes+ linearFee = toInteger (P.parameterMinFeeB params) + toInteger (P.parameterMinFeeA params) * sizeBound+ fee = max (toInteger (minimumFee config)) (linearFee + executionFee + toInteger referenceFee)+ sink = foldMap Output.value (Plan.planOutputs plan) <> Plan.sinkExtras params plan <> Value.lovelace fee+ unless+ (fee <= toInteger (maxBound :: Int64) && all ((<= toInteger (maxBound :: Int64)) . snd) (Value.toList sink))+ (Left (InvalidBuildingRequest "Complete priced fee or target exceeds signed native bounds"))++executionLimitFee :: Config -> Plan -> Either Error Integer+executionLimitFee config plan+ | not (Plan.requiresEvaluation plan) = Right 0+ | otherwise = do+ prices <- maybe (Left (InvalidBuildingRequest "Script execution prices are required")) Right (P.parameterExecutionCosts (parameters config))+ cap <- case evaluator config of+ Nothing -> Right (Ex.ExUnits 100000000 100000000000)+ Just _ -> maybe (Left (InvalidBuildingRequest "Maximum transaction execution units are required")) Right (P.parameterMaxTxExUnits (parameters config))+ pure+ ( ceiling+ ( fromIntegral (Ex.memory cap) * Rational.toRational (Prices.memoryPrice prices)+ + fromIntegral (Ex.steps cap) * Rational.toRational (Prices.stepPrice prices)+ )+ )++checkedEvaluator :: Config -> Evaluator -> Evaluator+checkedEvaluator config backend = Eval.Evaluator $ \target transaction inputs -> do+ result <- Eval.evaluate backend target transaction inputs+ pure $ do+ computed <- result+ validateBudget config (map snd (Eval.budgets computed))+ pure computed++validateBudget :: Config -> [Ex.ExUnits] -> Either Error ()+validateBudget config units = case (units, P.parameterMaxTxExUnits (parameters config)) of+ ([], _) -> pure ()+ (_, Nothing) -> Left (InvalidBuildingRequest "Maximum transaction execution units are required")+ (_, Just cap) ->+ unless+ ( sum (map (toInteger . Ex.memory) units) <= toInteger (Ex.memory cap)+ && sum (map (toInteger . Ex.steps) units) <= toInteger (Ex.steps cap)+ )+ (Left (InvalidEvaluationResult "Evaluation exceeds maximum transaction execution units"))++validateBuilt :: Config -> Plan -> Word64 -> Transaction -> Either Error ()+validateBuilt config plan keyCount transaction = do+ let body = Body.toBody (Transaction.body transaction)+ fields = Body.bodyFields body+ used = Fields.fieldInputs fields <> fromMaybe [] (Body.bodyCollateral body)+ sourceMap = Map.fromList [(Utxo.input u, u) | u <- availableUtxos config <> collateralUtxos config <> Plan.resolvedInputs plan]+ selectedInputs = [u | reference <- used, Just u <- [Map.lookup reference sourceMap]]+ byronAddresses =+ Set.fromList+ [ Address.toBytes destination+ | u <- selectedInputs,+ let destination = Output.address (Utxo.output u),+ case destination of Address.ByronAddress _ -> True; _ -> False+ ]+ reserve = 101 * toInteger keyCount + sum [180 + toInteger (B.length bytes) | bytes <- Set.toList byronAddresses] + 32+ size = toInteger (B.length (Transaction.encodeCbor transaction)) + reserve+ validateBudget+ config+ ( map Redeemer.executionUnits (Witnesses.redeemers (Witnesses.toWitnesses (Transaction.witnesses transaction)))+ <> concatMap (map Redeemer.executionUnits . Witnesses.redeemers . Witnesses.toWitnesses . Sub.witnesses . fst) (Plan.subTransactions plan)+ )+ unless+ (size <= toInteger (P.parameterMaxTxSize (parameters config)))+ (Left (InvalidBuildingRequest "Transaction and required witness reserve exceed maximum transaction size"))++encodeConfig :: Plan -> Config -> ByteString+encodeConfig plan config =+ C.encode+ ( E.encodeListLen 11+ <> mconcat+ [ E.encodeBytes (Parameters.encodeSnapshot (parameters config)),+ E.encodeBytes (Address.toBytes (changeAddress config)),+ utxos (filter (\u -> Utxo.input u `notElem` map Utxo.input (Plan.spendingInputs plan)) (eligible plan (availableUtxos config))),+ utxos (eligible plan (collateralUtxos config)),+ E.encodeBytes (maybe mempty Address.toBytes (collateralChangeAddress config)),+ E.encodeWord64 (minimumFee config),+ E.encodeWord64 (extraSigners config),+ E.encodeWord64 (Slot.zeroTime (slotConfig config)),+ E.encodeWord64 (Slot.zeroSlot (slotConfig config)),+ E.encodeWord64 (Slot.slotLength (slotConfig config)),+ E.encodeListLen (fromIntegral (length (poolState config)))+ <> foldMap (E.encodeBytes . Pool.encodeCbor) (poolState config)+ ]+ )+ where+ utxos values = E.encodeListLen (fromIntegral (length values)) <> foldMap (C.raw . Utxo.encodeCbor) values++-- | Initialize both owner slots before C; diagnostics are copied before release,+-- including failures. Runtime preserves original typed callback errors on unwind.+withResult :: (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> Ptr Word64 -> IO Native.NativeCode) -> IO (Either Error (ByteString, Word64))+withResult = withResultNamed "builder.build"++-- | Preserve operation-specific diagnostic names while sharing buffer ownership.+withResultNamed :: Text -> (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> Ptr Word64 -> IO Native.NativeCode) -> IO (Either Error (ByteString, Word64))+withResultNamed operation call = alloca $ \output -> alloca $ \diagnostic -> alloca $ \keyCount ->+ bracket+ (poke output nullPtr >> poke diagnostic nullPtr >> poke keyCount 0)+ (\() -> Raw.cBufferRelease output >> Raw.cBufferRelease diagnostic)+ $ \() -> do+ status <- call output diagnostic keyCount+ if status == Native.success+ then do+ bytes <- peek output >>= Runtime.copyBuffer operation+ count <- peek keyCount+ pure ((,count) <$> bytes)+ else do+ pointer <- peek diagnostic+ if pointer == nullPtr+ then do+ checked <- Runtime.checkStatus operation status+ pure (checked >> Left (NativeContractViolation "builder.status"))+ else do+ copied <- Runtime.copyBuffer "builder.diagnostic" pointer+ pure $ case copied of+ Left failure -> Left failure+ Right bytes -> Left (NativeError operation (Code.fromNumber (toInteger status)) (Text.decodeUtf8With (\_ _ -> Just '\xfffd') bytes))++-- The runtime protects decoding, pure callback evaluation, complete reply+-- encoding and native copying together. Lazy failures therefore unwind through+-- the ordinary callback exception/cancellation boundary before C sees success.+deferredDispatch :: Plan -> Runtime.Dispatch+deferredDispatch plan operation bytes+ | operation /= 110 = pure (Left (UnsupportedOperation "Unknown deferred redeemer callback operation"))+ | otherwise = pure $ do+ (index, transaction, inputs) <- C.decodeAs InvalidTransactionPlan parser bytes+ callback <- maybe (Left (NativeContractViolation "builder.deferredIndex")) Right (Seq.lookup index (Plan.deferredRedeemers plan))+ -- The pinned native balancer supplies selection order despite its header+ -- promising canonical order. Normalize the owned snapshot and verify that+ -- every spending input resolves exactly once before invoking user code.+ let canonical = sortOn Utxo.input inputs+ references = sort (Fields.fieldInputs (Body.bodyFields (Body.toBody (Transaction.body transaction))))+ unless (map Utxo.input canonical == references) (Left (NativeContractViolation "builder.deferredInputs"))+ Data.toCbor <$> callback transaction canonical+ where+ parser = C.array 3 ((,,) <$> D.decodeInt <*> C.nested bytes Transaction.decodeCbor <*> C.list (C.nested bytes Utxo.decodeCbor))++-- A subtransaction reserves both its spending and reference inputs against+-- parent spending/collateral selection. Explicit parent reference inputs remain+-- independently priced; each level counts its own referenced scripts once.+eligible :: Plan -> [Utxo] -> [Utxo]+eligible plan = filter (\input -> Utxo.input input `notElem` Plan.reservedInputs plan)++pricedSub :: (Sub.SubTransaction, [Utxo]) -> [Utxo]+pricedSub (transaction, resolved) =+ let fields = SubBody.fields (SubBody.toBody (Sub.body transaction))+ references = Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields)+ in filter (\input -> Utxo.input input `elem` references) resolved++-- The public standalone reference-fee helper rejects duplicate identities, but+-- batch pricing deliberately counts a shared script once for each level using+-- it. The private native transport accepts that multiplicity and applies the+-- pricing tiers to the complete byte total, avoiding a sum of underpriced tiers.+pricedReferenceFee :: Parameters -> [Utxo] -> IO (Either Error Word64)+pricedReferenceFee params inputs = case P.parameterRefScriptCostPerByte params of+ Nothing -> pure (Left (InvalidBuildingRequest "Reference script byte price is required"))+ Just _ -> do+ result <-+ Building.runUnchecked+ 1+ ( C.encode+ ( E.encodeListLen 2+ <> C.raw (Parameters.encodeSnapshot params)+ <> E.encodeListLen (fromIntegral (length inputs))+ <> foldMap (C.raw . Utxo.encodeCbor) inputs+ )+ )+ pure (result >>= C.decodeAs InvalidBuildingRequest D.decodeWord64)++-- Imported/signed subtransactions bypass local building, so validate their+-- immutable output values against the same configured limit before attachment.+checkSubOutputSize :: Maybe Word64 -> Output.Output -> Either Error ()+checkSubOutputSize Nothing _ = pure ()+checkSubOutputSize (Just limit) output =+ unless+ (toInteger (B.length (C.encode encoding)) <= toInteger limit)+ (Left (InvalidBuildingRequest "Attached subtransaction output exceeds maximum value size"))+ where+ value = Output.value output+ coin = E.encodeInteger (Value.quantity Ada value)+ assets = Value.toList (Value.difference value (Value.lovelace (Value.quantity Ada value)))+ encoding = if null assets then coin else E.encodeListLen 2 <> coin <> ValueCbor.encodeAssets value
@@ -0,0 +1,84 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Exact nested transaction CBOR slices and schema combinators.+module Cometa.Internal.TransactionCbor (decode, decodeAs, encode, raw, nested, array, list, entries, setList, optional, slice, mapFields) where++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import qualified Codec.CBOR.Write as W+import Cometa.Error (Error (..))+import qualified Cometa.Internal.ProposalCbor as P+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)++encode :: E.Encoding -> ByteString+encode = W.toStrictByteString++decode :: (forall s. D.Decoder s a) -> ByteString -> Either Error a+decode = decodeAs InvalidTransactionCbor++-- | Preserve the caller's domain error at complete-CBOR boundaries.+decodeAs :: (Text -> Error) -> (forall s. D.Decoder s a) -> ByteString -> Either Error a+decodeAs failure parser bytes = case R.deserialiseFromBytes parser (L.fromStrict bytes) of+ Left problem -> Left (failure (Text.pack (show problem)))+ Right (rest, value)+ | L.null rest -> Right value+ | otherwise -> Left (failure "Trailing transaction CBOR")++raw :: ByteString -> E.Encoding+raw = E.encodePreEncoded++-- | Extract bytes by original offsets; Term is used only to advance the decoder.+slice :: ByteString -> D.Decoder s ByteString+slice bytes = do+ (_, start, end) <- D.decodeWithByteSpan T.decodeTerm+ pure (B.take (fromIntegral (end - start)) (B.drop (fromIntegral start) bytes))++nested :: ByteString -> (ByteString -> Either Error a) -> D.Decoder s a+nested bytes parser = slice bytes >>= either (fail . show) pure . parser++array :: Int -> D.Decoder s a -> D.Decoder s a+array = P.array++list :: D.Decoder s a -> D.Decoder s [a]+list = P.list++entries :: D.Decoder s a -> D.Decoder s [a]+entries = P.entries++setList :: D.Decoder s a -> D.Decoder s [a]+setList = P.setList++optional :: D.Decoder s a -> D.Decoder s (Maybe a)+optional = P.optional++mapFields :: ByteString -> D.Decoder s (Map Word64 ByteString)+mapFields bytes = do+ pairs <- entries ((,) <$> D.decodeWord64 <*> slice bytes)+ let result = Map.fromList pairs+ unless (Map.size result == length pairs) (fail "Duplicate transaction map key")+ pure result
@@ -0,0 +1,317 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Fields shared by ordinary transaction bodies and Dijkstra subtransaction+-- bodies. Construct defaults with 'fields', then update typed optional fields.+-- Absence and a present empty collection are distinct where represented.+--+-- @+-- noOptionalFields = fields [] []+-- @+module Cometa.Internal.TransactionFields+ ( Fields (..),+ fields,+ Mint,+ mkMint,+ mintValue,+ Entries,+ mkEntries,+ entries,+ BalanceInterval (..),+ BodyNetwork (..),+ encodeFields,+ decodeFields,+ validateFields,+ encodeIntervals,+ decodeIntervals,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Address.Reward as Reward+import Cometa.Certificate.Collection (Certificates)+import qualified Cometa.Certificate.Collection as Certificates+import Cometa.Credential (Credential, Guard)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import Cometa.Governance.Proposal (Proposals)+import qualified Cometa.Governance.Proposal as Proposal+import Cometa.Governance.Voting (VotingProcedures)+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.ProposalCbor as P+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionValue as V+import Cometa.PlutusData (EncodedPlutusData)+import qualified Cometa.PlutusData as Data+import Cometa.Transaction.Datum (Hash32)+import qualified Cometa.Transaction.Datum as Datum+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Input as Input+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import Cometa.Value (Value)+import qualified Cometa.Value as Value+import Control.Monad (unless, when)+import Data.ByteString (ByteString)+import Data.List (sort, sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Nonempty unique-key association. Equality compares keys and values, ignoring+-- insertion order. Construction rejects duplicate keys even when values agree.+newtype Entries key value = Entries (Map key value) deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate a nonempty collection of unique keys. Empty or duplicate-key input+-- returns 'InvalidTransactionField'. No entry is silently overwritten.+mkEntries :: (Ord key) => [(key, value)] -> Either Error (Entries key value)+mkEntries pairs+ | null pairs = Left (InvalidTransactionField "Empty transaction association")+ | Map.size result /= length pairs = Left (InvalidTransactionField "Duplicate transaction association key")+ | otherwise = Right (Entries result)+ where+ result = Map.fromList pairs++-- | Entries in ascending key order, independent of insertion order.+entries :: Entries key value -> [(key, value)]+entries (Entries result) = Map.toAscList result++-- | Signed native-asset mint/burn quantities, each within int64. Ada is excluded.+-- Equality compares normalized quantities; zero entries disappear.+newtype Mint = Mint Value deriving (Eq, Show)++-- | Validate signed native-asset quantities and exclude Ada. Quantity overflow+-- returns 'InvalidTransactionOutputValue'; Ada returns 'InvalidTransactionField'.+mkMint :: Value -> Either Error Mint+mkMint value = V.validateMint value >> pure (Mint value)++-- | Signed asset quantities; positive creates units and negative burns them.+mintValue :: Mint -> Value+mintValue (Mint result) = result++-- | Dijkstra account-balance condition, measured in lovelace. Range lower bound+-- is inclusive and upper bound is exclusive; Nothing leaves that side unbounded.+-- Representability does not establish satisfiability against ledger account state.+data BalanceInterval+ = -- | Require exactly this unsigned 64-bit balance.+ ExactBalance !Word64+ | -- | Inclusive lower bound and exclusive upper bound, respectively.+ BalanceRange !(Maybe Word64) !(Maybe Word64)+ deriving (Eq, Show)++-- | Shared body data. Collections preserve order and duplicates except unique-key+-- 'Entries'. Optional values distinguish field absence from present zero/empty.+-- No fee, collateral or nested subtransactions occur in this shared record.+data Fields = Fields+ { -- | Spending references. Fresh encoding and decoding sort by hash/index,+ -- retaining duplicate references as the native input collection does.+ -- A reference need not exist on chain.+ fieldInputs :: ![Input],+ -- | Outputs in creation order; the index in this list identifies an output.+ fieldOutputs :: ![Output],+ -- | Exclusive upper validity slot, from zero through 2^64 - 1.+ fieldInvalidAfter :: !(Maybe Word64),+ -- | Ordered certificates, retaining duplicate instructions.+ fieldCertificates :: !(Maybe Certificates),+ -- | Nonempty reward-account to withdrawn-lovelace association.+ fieldWithdrawals :: !(Maybe (Entries RewardAddress Word64)),+ -- | Expected 32-byte auxiliary-data digest, without verifying auxiliary data.+ fieldAuxiliaryDataHash :: !(Maybe Hash32),+ -- | Inclusive lower validity slot, from zero through 2^64 - 1.+ fieldInvalidBefore :: !(Maybe Word64),+ -- | Optional signed mint/burn instructions, excluding Ada.+ fieldMint :: !(Maybe Mint),+ -- | Expected 32-byte script-integrity digest, without computing it.+ fieldScriptDataHash :: !(Maybe Hash32),+ -- | Required signing/guard credentials. Key and script guards are distinct.+ fieldGuards :: !(Maybe [Credential Guard]),+ -- | Optional network tag. Body CBOR permits mainnet 1 or testnet 0 only.+ fieldNetworkId :: !(Maybe BodyNetwork),+ -- | References made available to scripts without spending them. Fresh+ -- encoding and decoding sort by hash/index and retain duplicates.+ fieldReferenceInputs :: !(Maybe [Input]),+ -- | Unique voter/action voting instructions.+ fieldVotingProcedures :: !(Maybe VotingProcedures),+ -- | Ordered governance proposals; order determines proposal indices.+ fieldProposalProcedures :: !(Maybe Proposals),+ -- | Current treasury value claimed by the transaction, in lovelace.+ fieldTreasuryValue :: !(Maybe Word64),+ -- | Treasury donation in lovelace; a present zero differs from absence.+ fieldDonation :: !(Maybe Word64),+ -- | Dijkstra top-level required guard credential and optional exact datum.+ fieldRequiredTopLevelGuards :: !(Maybe (Entries (Credential Guard) (Maybe EncodedPlutusData))),+ -- | Dijkstra direct deposits to reward accounts, measured in lovelace.+ fieldDirectDeposits :: !(Maybe (Entries RewardAddress Word64)),+ -- | Dijkstra account-balance requirements for this body.+ fieldAccountBalanceIntervals :: !(Maybe (Entries RewardAddress BalanceInterval))+ }+ deriving (Eq, Show)++-- | Transaction bodies carry one of the two ledger network alternatives.+data BodyNetwork = Testnet | Mainnet deriving (Eq, Ord, Show, Enum, Bounded)++-- | Required inputs and outputs, with every optional field absent. Lists may be+-- empty: this is structural assembly and does not establish ledger admission.+fields :: [Input] -> [Output] -> Fields+fields inputs outputs = Fields (sort inputs) outputs Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing++-- | Internal field serializer shared by the two body schemas.+encodeFields :: Fields -> [(Word64, E.Encoding)]+encodeFields value =+ [(0, inputSet (fieldInputs value)), (1, outputList (fieldOutputs value))]+ ++ optional 3 E.encodeWord64 (fieldInvalidAfter value)+ ++ optional 4 (Cbor.raw . Certificates.encodeCbor) (fieldCertificates value)+ ++ optional 5 (association (E.encodeBytes . Reward.toBytes) E.encodeWord64) (fieldWithdrawals value)+ ++ optional 7 hashEncoding (fieldAuxiliaryDataHash value)+ ++ optional 8 E.encodeWord64 (fieldInvalidBefore value)+ ++ optional 9 (V.encodeAssets . mintValue) (fieldMint value)+ ++ optional 11 hashEncoding (fieldScriptDataHash value)+ ++ optional 14 guardSet (fieldGuards value)+ ++ optional 15 (E.encodeWord . fromIntegral . fromEnum) (fieldNetworkId value)+ ++ optional 18 inputSet (fieldReferenceInputs value)+ ++ optional 19 (Cbor.raw . Voting.encodeCbor) (fieldVotingProcedures value)+ ++ optional 20 (Cbor.raw . Proposal.encodeProposals) (fieldProposalProcedures value)+ ++ optional 21 E.encodeWord64 (fieldTreasuryValue value)+ ++ optional 22 E.encodeWord64 (fieldDonation value)+ ++ optional 24 (association P.credentialEncoding (maybe E.encodeNull (Cbor.raw . Data.toCbor))) (fieldRequiredTopLevelGuards value)+ ++ optional 25 (association (E.encodeBytes . Reward.toBytes) E.encodeWord64) (fieldDirectDeposits value)+ ++ optional 26 (association (E.encodeBytes . Reward.toBytes) intervalEncoding) (fieldAccountBalanceIntervals value)+ where+ optional key enc = maybe [] (\payload -> [(key, enc payload)])+ hashEncoding = E.encodeBytes . Datum.hashBytes++inputSet :: [Input] -> E.Encoding+inputSet values = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Input.encodeCbor) (sort values)++outputList :: [Output] -> E.Encoding+outputList values = E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Output.encodeCbor) values++association :: (key -> E.Encoding) -> (value -> E.Encoding) -> Entries key value -> E.Encoding+association encodeKey encodeValue values = E.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, value) -> encodeKey key <> encodeValue value) pairs+ where+ pairs = sortOn (Cbor.encode . encodeKey . fst) (entries values)++guardSet :: [Credential Guard] -> E.Encoding+guardSet values = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap encodeGuard values+ where+ credentialForm = any isScript values+ isScript (Credential.ScriptCredential _) = True+ isScript _ = False+ encodeGuard credential =+ if credentialForm+ then P.credentialEncoding credential+ else case credential of+ Credential.KeyCredential hash -> E.encodeBytes (Credential.keyHashBytes hash)+ Credential.ScriptCredential hash -> E.encodeBytes (Credential.scriptHashBytes hash)++intervalEncoding :: BalanceInterval -> E.Encoding+intervalEncoding interval = case interval of+ ExactBalance coin -> E.encodeWord64 coin+ BalanceRange lower upper -> E.encodeListLen 2 <> maybe E.encodeNull E.encodeWord64 lower <> maybe E.encodeNull E.encodeWord64 upper++-- | Internal shared-schema decoder. Each nested payload is decoded against its+-- exact original slice; containing-body identity never depends on re-encoding.+decodeFields :: Map Word64 ByteString -> Either Error Fields+decodeFields values =+ Fields+ <$> required 0 inputDecoder+ <*> required 1 outputDecoder+ <*> optional 3 word+ <*> optional 4 (fmap Certificates.toCertificates . Certificates.decodeCbor)+ <*> optional 5 (associationDecoder rewardDecoder D.decodeWord64)+ <*> optional 7 hashDecoder+ <*> optional 8 word+ <*> optional 9 mintDecoder+ <*> optional 11 hashDecoder+ <*> optional 14 guardsDecoder+ <*> optional 15 networkDecoder+ <*> optional 18 inputDecoder+ <*> optional 19 (fmap Voting.toVotingProcedures . Voting.decodeCbor)+ <*> optional 20 (fmap Proposal.toProposals . Proposal.decodeProposals)+ <*> optional 21 word+ <*> optional 22 word+ <*> optional 24 requiredGuardsDecoder+ <*> optional 25 (associationDecoder rewardDecoder D.decodeWord64)+ <*> optional 26 (associationDecoder rewardDecoder intervalDecoder)+ where+ required key parser = maybe (Left (InvalidTransactionField "Missing required transaction body field")) parser (Map.lookup key values)+ optional key parser = traverse parser (Map.lookup key values)+ word = Cbor.decode D.decodeWord64+ inputDecoder bytes = sort <$> Cbor.decode (Cbor.setList (Cbor.nested bytes Input.decodeCbor)) bytes+ outputDecoder bytes = Cbor.decode (Cbor.list (Output.toOutput <$> Cbor.nested bytes Output.decodeCbor)) bytes+ hashDecoder = Cbor.decode (D.decodeBytes >>= either (fail . show) pure . Datum.hashFromBytes)+ mintDecoder bytes = Cbor.decode V.decodeAssets bytes >>= mkMint+ networkDecoder bytes = do+ value <- Cbor.decode D.decodeWord bytes+ case value of+ 0 -> Right Testnet+ 1 -> Right Mainnet+ _ -> Left (InvalidTransactionField "Body network id must be 0 or 1")+ guardsDecoder bytes = do+ guards <- Cbor.decode (Cbor.setList guardDecoder) bytes+ unless (Set.size (Set.fromList guards) == length guards) (Left (InvalidTransactionField "Duplicate guard credential"))+ pure guards+ guardDecoder = do+ token <- D.peekTokenType+ if token == D.TypeBytes then Credential.KeyCredential <$> (D.decodeBytes >>= either (fail . show) pure . Credential.keyHashFromBytes) else P.credentialDecoder+ requiredGuardsDecoder bytes = associationDecoder P.credentialDecoder (Cbor.optional (Cbor.nested bytes Data.decodeCbor)) bytes++rewardDecoder :: D.Decoder s RewardAddress+rewardDecoder = D.decodeBytes >>= either (fail . show) pure . Reward.fromBytes++associationDecoder :: (Ord key) => (forall s. D.Decoder s key) -> (forall s. D.Decoder s value) -> ByteString -> Either Error (Entries key value)+associationDecoder keyParser valueParser bytes = Cbor.decode (Cbor.entries ((,) <$> keyParser <*> valueParser)) bytes >>= mkEntries++intervalDecoder :: D.Decoder s BalanceInterval+intervalDecoder = do+ token <- D.peekTokenType+ if token == D.TypeUInt || token == D.TypeUInt64+ then ExactBalance <$> D.decodeWord64+ else Cbor.array 2 (BalanceRange <$> Cbor.optional D.decodeWord64 <*> Cbor.optional D.decodeWord64)++-- | Context checks follow native sub-body restrictions. Imported historical+-- top-level empty guard fields remain inspectable but fresh assembly rejects them.+validateFields :: Bool -> Fields -> Either Error ()+validateFields isSub value = do+ case fieldGuards value of+ Nothing -> pure ()+ Just guards -> do+ when (null guards) (Left (InvalidTransactionField "Present guard set must be nonempty"))+ unless (Set.size (Set.fromList guards) == length guards) (Left (InvalidTransactionField "Duplicate guard credential"))+ when isSub $ do+ case fieldCertificates value of+ Just certs -> when (null (Certificates.toList certs)) (Left (InvalidTransactionField "Present subtransaction certificates must be nonempty"))+ Nothing -> pure ()+ case fieldMint value of+ Just mint -> when (Value.isZero (mintValue mint)) (Left (InvalidTransactionField "Present subtransaction mint must be nonempty"))+ Nothing -> pure ()++-- | Native typed reward-account/interval association codec shared by keys 26/27.+encodeIntervals :: Entries RewardAddress BalanceInterval -> E.Encoding+encodeIntervals = association (E.encodeBytes . Reward.toBytes) intervalEncoding++decodeIntervals :: ByteString -> Either Error (Entries RewardAddress BalanceInterval)+decodeIntervals = associationDecoder rewardDecoder intervalDecoder
@@ -0,0 +1,128 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# OPTIONS_HADDOCK hide #-}++-- | Level-local index inspection shared by top-level and nested transactions.+module Cometa.Internal.TransactionIndices+ ( findInput,+ findReferenceInput,+ findOutput,+ findMintPolicy,+ findWithdrawal,+ findVote,+ findProposal,+ findRedeemer,+ certificateBytes,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Term as T+import Cometa.Address (Address)+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (Ada))+import qualified Cometa.Credential as Credential+import Cometa.Evaluation (RedeemerId (..))+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.NetworkId as Network+import Cometa.PolicyId (PolicyId)+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Transaction.Fields as Fields+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Value as Value+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.List (sort)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++findInput :: Input -> Fields.Fields -> Maybe Word64+findInput reference = position (== reference) . sort . Fields.fieldInputs++findReferenceInput :: Input -> Fields.Fields -> Maybe Word64+findReferenceInput reference = position (== reference) . sort . fromMaybe [] . Fields.fieldReferenceInputs++findOutput :: Address -> Word64 -> Fields.Fields -> Maybe Word64+findOutput destination minimumLovelace = position matches . Fields.fieldOutputs+ where+ matches output =+ Address.toBytes (Output.address output) == Address.toBytes destination+ && Value.quantity Ada (Output.value output) >= toInteger minimumLovelace++findMintPolicy :: PolicyId -> ByteString -> Maybe Word64+findMintPolicy policy bytes = do+ mint <- fieldBytes 9 bytes+ policies <- either (const Nothing) Just (Cbor.decode (Cbor.entries (D.decodeBytes <* T.decodeTerm)) mint)+ position (== Policy.toBytes policy) (sort policies)++-- Ledger ordering groups non-mainnet tags together and puts scripts first.+findWithdrawal :: Reward.RewardAddress -> Fields.Fields -> Maybe Word64+findWithdrawal reward = rank (rewardKey reward) . map (rewardKey . fst) . maybe [] Fields.entries . Fields.fieldWithdrawals++rewardKey :: Reward.RewardAddress -> ByteString+rewardKey reward = B.cons (if Reward.networkId reward == Network.mainnet then 1 else 0) (credentialKey (Reward.credential reward))++credentialKey :: Credential.Credential purpose -> ByteString+credentialKey authority = case authority of+ Credential.ScriptCredential hash -> B.cons 0 (Credential.scriptHashBytes hash)+ Credential.KeyCredential hash -> B.cons 1 (Credential.keyHashBytes hash)++findVote :: Voting.Voter -> Fields.Fields -> Maybe Word64+findVote voter = rank (voterKey voter) . map voterKey . Set.toList . Set.fromList . map (\(authority, _, _) -> authority) . maybe [] Voting.toList . Fields.fieldVotingProcedures++findProposal :: Proposal.Proposal -> Fields.Fields -> Maybe Word64+findProposal proposal = position ((== Proposal.encodeCbor proposal) . Proposal.encodeCbor) . maybe [] Proposal.toList . Fields.fieldProposalProcedures++voterKey :: Voting.Voter -> ByteString+voterKey voter = case voter of+ Voting.CommitteeVoter authority -> B.cons 0 (credentialKey authority)+ Voting.DRepVoter authority -> B.cons 1 (credentialKey authority)+ Voting.StakePoolVoter hash -> B.cons 2 (B.cons 1 (Credential.keyHashBytes hash))++findRedeemer :: RedeemerId -> [Redeemer.Redeemer] -> Maybe Word64+findRedeemer identifier = rank identifier . map (\value -> RedeemerId (Redeemer.purpose value) (Redeemer.index value))++certificateBytes :: ByteString -> Maybe ByteString+certificateBytes = fieldBytes 4++fieldBytes :: Word64 -> ByteString -> Maybe ByteString+fieldBytes key bytes = do+ fields <- either (const Nothing) Just (Cbor.decode (Cbor.mapFields bytes) bytes)+ Map.lookup key fields++-- Native lookups count items strictly below the requested ledger key.+rank :: (Ord a) => a -> [a] -> Maybe Word64+rank target values+ | target `elem` values = Just (fromIntegral (length (filter (< target) values)))+ | otherwise = Nothing++position :: (a -> Bool) -> [a] -> Maybe Word64+position matches = go 0+ where+ go _ [] = Nothing+ go index (value : rest)+ | matches value = Just index+ | otherwise = go (index + 1) rest
@@ -0,0 +1,691 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Owned composable builder instructions and preflight conflict checks.+module Cometa.Internal.TransactionPlan+ ( Plan,+ payTo,+ spend,+ spendWith,+ DeferredRedeemer,+ spendWithDeferredRedeemer,+ mintWithDeferredRedeemer,+ certificateWithDeferredRedeemer,+ withdrawWithDeferredRedeemer,+ deferredRedeemers,+ referenceInput,+ attachScript,+ mint,+ mintWithRedeemer,+ metadata,+ attachDatum,+ certificate,+ certificateWithRedeemer,+ withdraw,+ withdrawWithRedeemer,+ requireSigner,+ validFrom,+ validUntil,+ requireGuard,+ guardWithRedeemer,+ directDeposit,+ accountBalance,+ startingAccountBalance,+ donate,+ currentTreasuryValue,+ propose,+ proposeWithRedeemer,+ proposeWithDeferredRedeemer,+ vote,+ voteWithRedeemer,+ voteWithDeferredRedeemer,+ attachSubTransaction,+ subTransactions,+ requireTopLevelGuard,+ validateTopLevel,+ reservedInputs,+ outerResolvedInputs,+ encodePlan,+ validatePlan,+ resolvedInputs,+ spendingInputs,+ planOutputs,+ sourceExtras,+ sinkExtras,+ validitySlots,+ witnessCount,+ requiresEvaluation,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (..))+import Cometa.AssetName (AssetName)+import qualified Cometa.AssetName as AssetName+import Cometa.Certificate (Certificate)+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import Cometa.Credential (Credential, Guard, KeyHash, Payment, ScriptHash)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import Cometa.Governance.Action (Action)+import qualified Cometa.Governance.Action as Action+import Cometa.Governance.ActionId (ActionId)+import qualified Cometa.Governance.ActionId as ActionId+import Cometa.Governance.Anchor (Anchor)+import qualified Cometa.Governance.Proposal as Proposal+import Cometa.Governance.Voting (Voter, VotingProcedure)+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.TransactionCbor as C+import Cometa.Metadata (Metadatum)+import qualified Cometa.Metadata as Metadata+import Cometa.PlutusData (EncodedPlutusData)+import qualified Cometa.PlutusData as Data+import Cometa.PolicyId (PolicyId)+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.Parameters as Parameters+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.Script.Plutus as Plutus+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import Cometa.Transaction (Transaction)+import Cometa.Transaction.Fields (BalanceInterval (..))+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.Value as Value+import Control.Monad (unless, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Foldable (toList)+import Data.Int (Int64)+import Data.Maybe (catMaybes, fromMaybe, isJust)+import qualified Data.Sequence as Seq+import qualified Data.Set as Set+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Compute an argument from the balanced draft and its selected spending inputs+-- in canonical order. The callback may run on every balancing iteration. It must+-- be pure and deterministic; return an explicit error to abort the build. Values+-- are ordinary owned snapshots and may be inspected without resource scopes.+type DeferredRedeemer = Transaction -> [Utxo] -> Either Error EncodedPlutusData++data Argument = Immediate EncodedPlutusData | Deferred Int deriving (Eq, Show)++data Operation+ = Pay Output+ | Spend Utxo (Maybe Argument) (Maybe EncodedPlutusData)+ | Reference Utxo+ | Script Script+ | Mint AssetId Int64 (Maybe Argument)+ | Metadata Word64 Metadatum+ | Datum EncodedPlutusData+ | Certificate Certificate (Maybe Argument)+ | Withdraw RewardAddress Word64 (Maybe Argument)+ | Signer (KeyHash Payment)+ | From Word64+ | Until Word64+ | Guard (Credential Guard) (Maybe EncodedPlutusData)+ | DirectDeposit RewardAddress Word64+ | AccountBalance RewardAddress BalanceInterval+ | StartingBalance RewardAddress BalanceInterval+ | Donation Word64+ | TreasuryValue Word64+ | Propose RewardAddress Action Anchor (Maybe Argument)+ | Vote Voter ActionId VotingProcedure (Maybe Argument)+ | Sub SubTransaction [Utxo]+ | TopLevelGuard (Credential Guard) (Maybe EncodedPlutusData)+ deriving (Eq, Show)++-- | Ordered immutable instructions. Composition preserves output order and+-- combines requirements; conflicts are reported by the single build boundary.+-- Function values have no structural equality or printable representation.+-- Plan intentionally has neither Eq nor Show; its monoid laws concern behavior.+data Plan = Plan (Seq.Seq Operation) (Seq.Seq DeferredRedeemer)++instance Semigroup Plan where+ Plan a callbacksA <> Plan b callbacksB =+ Plan (a <> fmap (shiftCallbacks (Seq.length callbacksA)) b) (callbacksA <> callbacksB)++instance Monoid Plan where+ mempty = Plan Seq.empty Seq.empty++-- DEFINITIONS ----------------------------------------------------------------++one :: Operation -> Plan+one op = Plan (Seq.singleton op) Seq.empty++-- | Append a payment output; minimum Ada is checked when building.+payTo :: Output -> Plan+payTo = one . Pay++-- | Spend a key-controlled resolved output without script arguments.+spend :: Utxo -> Plan+spend u = spendWith u Nothing Nothing++-- | Spend a resolved output with optional redeemer argument followed by optional+-- datum witness. Inline datums do not need a separate datum witness.+spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan+spendWith u r = one . Spend u (Immediate <$> r)++-- | Resolve a reference input without consuming its value.+referenceInput :: Utxo -> Plan+referenceInput = one . Reference++-- | Attach a native or Plutus script witness. Repeated attachments of the same+-- language and script bytes contribute one witness, ordered by the first+-- attachment. Different Plutus versions remain distinct.+attachScript :: Script -> Plan+attachScript = one . Script++-- | Mint positive or burn negative token units under a native policy. Ada and+-- overflowing combined quantities are rejected when building.+mint :: AssetId -> Int64 -> Plan+mint a n = one (Mint a n Nothing)++-- | Mint or burn units under a Plutus policy using its redeemer argument.+mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan+mintWithRedeemer a n = one . Mint a n . Just . Immediate++-- | Require metadata under a label. Conflicting values fail when building.+metadata :: Word64 -> Metadatum -> Plan+metadata label = one . Metadata label++-- | Attach a datum witness. Repeated exact CBOR encodings contribute one+-- witness, including data supplied to spending inputs. First occurrence order+-- is retained; different encodings remain distinct because their hashes differ.+attachDatum :: EncodedPlutusData -> Plan+attachDatum = one . Datum++-- | Append a certificate without a script argument.+certificate :: Certificate -> Plan+certificate c = one (Certificate c Nothing)++-- | Append a certificate authorized by the supplied Plutus argument.+certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan+certificateWithRedeemer c = one . Certificate c . Just . Immediate++-- | Withdraw lovelace from a key-controlled reward account. Amounts above Int64+-- are rejected when building.+withdraw :: RewardAddress -> Word64 -> Plan+withdraw a n = one (Withdraw a n Nothing)++-- | Withdraw lovelace from a script reward account using its Plutus argument.+withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan+withdrawWithRedeemer a n = one . Withdraw a n . Just . Immediate++-- | Require a payment key hash to sign the completed transaction.+requireSigner :: KeyHash Payment -> Plan+requireSigner = one . Signer++-- | Inclusive lower validity slot. Composition takes the greatest lower bound.+validFrom :: Word64 -> Plan+validFrom = one . From++-- | Exclusive upper validity slot. Composition takes the least upper bound.+validUntil :: Word64 -> Plan+validUntil = one . Until++validatePlan :: Plan -> Either Error ()+validatePlan (Plan instructions callbacks) = do+ let ops = toList instructions+ inputs = [(Utxo.input u, (u, r, d)) | Spend u r d <- ops]+ refs = [(Utxo.input u, u) | Reference u <- ops]+ metas = [(k, v) | Metadata k v <- ops]+ withdrawals = [(a, (n, r)) | Withdraw a n r <- ops]+ certificates = [(c, r) | Certificate c r <- ops]+ mints = [(p, r) | Mint (Native p _) _ r <- ops]+ lows = [n | From n <- ops]+ highs = [n | Until n <- ops]+ consistent "Conflicting requirements for one spending input" inputs+ consistent "Conflicting reference input snapshots" refs+ consistent "Conflicting resolved input snapshots" [(Utxo.input u, u) | u <- resolvedInputs (Plan instructions callbacks)]+ consistent "Conflicting metadata label" metas+ consistent "Conflicting reward withdrawal" withdrawals+ consistent "Conflicting minting policy redeemers" mints+ consistent "Conflicting certificate redeemers" certificates+ consistent "Conflicting required top-level guard arguments" [(g, r) | TopLevelGuard g r <- ops]+ consistent "Conflicting guard redeemers" [(g, r) | Guard g r <- ops]+ consistent "Conflicting account balance intervals" [(a, i) | AccountBalance a i <- ops]+ consistent "Conflicting starting account balance intervals" [(a, i) | StartingBalance a i <- ops]+ consistent "Conflicting votes for one action" [((v, a), p) | Vote v a p _ <- ops]+ consistent "Conflicting voter redeemers" [(v, r) | Vote v _ _ r <- ops]+ consistent "Conflicting current treasury values" [((), amount) | TreasuryValue amount <- ops]+ let proposals = [Proposal.encodeCbor (Proposal.Proposal 0 account action anchor) | Propose account action anchor _ <- ops]+ unless (distinct proposals) (Left (InvalidTransactionPlan "Duplicate governance proposal"))+ mapM_ validateProposal ops+ let donation = sum [toInteger n | Donation n <- ops]+ deposits = [(a, sum [toInteger n | DirectDeposit a' n <- ops, a == a']) | DirectDeposit a _ <- ops]+ subSpent = concatMap (Fields.fieldInputs . subFields . fst) (subTransactions (Plan instructions callbacks))+ outerSpent = [Utxo.input u | Spend u _ _ <- ops]+ unless (donation <= toInteger (maxBound :: Int64)) (Left (InvalidTransactionPlan "Combined donation exceeds signed native bounds"))+ when+ (any (\(_, n) -> n > toInteger (maxBound :: Int64)) deposits || any (\case DirectDeposit _ 0 -> True; _ -> False) ops)+ (Left (InvalidTransactionPlan "Direct deposits must be positive and fit signed native bounds"))+ unless+ (Set.size (Set.fromList subSpent) == length subSpent && all (`notElem` subSpent) outerSpent)+ (Left (InvalidTransactionPlan "Spending inputs overlap between transaction levels"))+ mapM_ validateSub (subTransactions (Plan instructions callbacks))+ let totals = [(asset, sum [toInteger amount | Mint asset' amount _ <- ops, asset == asset']) | Mint asset _ _ <- ops]+ when+ (any (\(_, amount) -> amount < toInteger (minBound :: Int64) || amount > toInteger (maxBound :: Int64)) totals)+ (Left (InvalidTransactionPlan "Combined mint quantity exceeds signed native bounds"))+ when (any isAdaMint ops) (Left (InvalidTransactionPlan "Ada cannot be minted"))+ when (any excessiveWithdrawal ops) (Left (InvalidTransactionPlan "Withdrawal exceeds signed native amount"))+ unless (null lows || null highs || maximum lows < minimum highs) (Left (InvalidTransactionPlan "Empty validity interval"))+ where+ distinct [] = True+ distinct (value : rest) = value `notElem` rest && distinct rest+ validateProposal (Propose _ action _ (Just _)) =+ unless (hasPolicy action) (Left (InvalidTransactionPlan "A proposing redeemer requires a guardrails policy"))+ validateProposal _ = pure ()+ consistent message pairs = unless (all (\(k, v) -> all (\(k', v') -> k /= k' || v == v') pairs) pairs) (Left (InvalidTransactionPlan message))+ isAdaMint (Mint Ada _ _) = True+ isAdaMint _ = False+ excessiveWithdrawal (Withdraw _ n _) = toInteger n > toInteger (maxBound :: Int64)+ excessiveWithdrawal _ = False++encodePlan :: Word64 -> Plan -> ByteString+encodePlan deposit plan = C.encode (E.encodeListLen (fromIntegral (length ops)) <> foldMap (encodeOperation deposit) ops)+ where+ ops = normalizedOperations plan++normalizedOperations :: Plan -> [Operation]+normalizedOperations (Plan instructions _) = ops+ where+ original = toList instructions+ ops = uniqueDatums Set.empty requirements+ requirements =+ normalizeMints (deduplicate [op | op <- original, case op of From _ -> False; Until _ -> False; Donation _ -> False; _ -> True])+ <> [Donation (fromInteger (sum ns)) | let ns = [toInteger n | Donation n <- original], not (null ns)]+ <> [From (maximum ns) | let ns = [n | From n <- original], not (null ns)]+ <> [Until (minimum ns) | let ns = [n | Until n <- original], not (null ns)]++ -- Both native add_datum and add_input append to the same witness set.+ -- Keep datum hash preimages exactly; stripping a repeated input argument+ -- only avoids its second global insertion, not any input or callback.+ uniqueDatums _ [] = []+ uniqueDatums seen (Datum datum : rest)+ | datum `Set.member` seen = uniqueDatums seen rest+ | otherwise = Datum datum : uniqueDatums (Set.insert datum seen) rest+ uniqueDatums seen (Spend input argument (Just datum) : rest)+ | datum `Set.member` seen = Spend input argument Nothing : uniqueDatums seen rest+ | otherwise = Spend input argument (Just datum) : uniqueDatums (Set.insert datum seen) rest+ uniqueDatums seen (operation : rest) = operation : uniqueDatums seen rest++ deduplicate [] = []+ deduplicate (op : rest) = op : deduplicate (if idempotent op then filter (not . sameAttachment op) rest else rest)+ -- Native builder_witnesses.c (eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1)+ -- appends scripts without enforcing witness-set uniqueness. Match the exact+ -- hash preimage here; Plutus outer bytestring framing is not script identity.+ sameAttachment (Script left) (Script right) = scriptIdentity left == scriptIdentity right+ sameAttachment left right = left == right+ scriptIdentity (Script.Native script) = (0, NativeScript.encodeCbor script)+ scriptIdentity (Script.Plutus script) = (fromEnum (Plutus.version script) + 1, Plutus.toBytes script)+ idempotent op = case op of+ Script {} -> True+ Spend {} -> True+ Reference {} -> True+ Metadata {} -> True+ Withdraw {} -> True+ Signer {} -> True+ Guard {} -> True+ TopLevelGuard {} -> True+ AccountBalance {} -> True+ StartingBalance {} -> True+ TreasuryValue {} -> True+ Vote {} -> True+ _ -> False++ normalizeMints [] = []+ normalizeMints (Mint asset _ redeemer : rest) =+ let amount = sum [toInteger n | Mint a n _ <- original, a == asset]+ remaining = filter (\case Mint a _ _ -> a /= asset; _ -> True) rest+ in [Mint asset (fromInteger amount) redeemer | amount /= 0] <> normalizeMints remaining+ normalizeMints (op : rest) = op : normalizeMints rest++requiresEvaluation :: Plan -> Bool+requiresEvaluation = any needs . normalizedOperations+ where+ needs (Spend _ (Just _) _) = True+ needs (Guard _ (Just _)) = True+ needs (Vote _ _ _ (Just _)) = True+ needs (Propose _ action _ _) = hasPolicy action+ needs (Sub transaction _) = not (null (Witnesses.redeemers (Witnesses.toWitnesses (Sub.witnesses transaction))))+ needs (Mint _ _ (Just _)) = True+ needs (Certificate _ (Just _)) = True+ needs (Withdraw _ _ (Just _)) = True+ needs _ = False++validitySlots :: Plan -> [Word64]+validitySlots (Plan instructions _) = concatMap slots (toList instructions)+ where+ slots (From n) = [n]+ slots (Until n) = [n]+ slots (Sub transaction _) =+ let fields = subFields transaction+ in catMaybes [Fields.fieldInvalidBefore fields, Fields.fieldInvalidAfter fields]+ slots _ = []++-- Native unique_signers does not inspect keys embedded in native scripts;+-- applications provide those additional witnesses through extraSigners.+witnessCount :: Plan -> Integer+witnessCount = sum . map count . normalizedOperations+ where+ count (Signer _) = 1+ count (Guard (Credential.KeyCredential _) _) = 1+ count Vote {} = 1+ count Withdraw {} = 1+ count (Certificate c _) = 1 + toInteger (B.length (Certificate.encodeCbor c)) `div` 28+ count _ = 0++spendingInputs :: Plan -> [Utxo]+spendingInputs (Plan instructions _) = [u | Spend u _ _ <- toList instructions]++planOutputs :: Plan -> [Output]+planOutputs (Plan instructions _) = [o | Pay o <- toList instructions]++sourceExtras :: Parameters.Parameters -> Plan -> Value.Value+sourceExtras params = foldMap source . normalizedOperations+ where+ source (Mint a n _) | n > 0 = Value.singleton a (toInteger n)+ source (Withdraw _ n _) = Value.lovelace (toInteger n)+ source (Certificate cert _) =+ Value.lovelace+ ( case cert of+ Certificate.StakeDeregistration _ -> toInteger (Parameters.parameterKeyDeposit params)+ Certificate.Unregistration _ amount -> toInteger amount+ Certificate.UnregisterDRep _ amount -> toInteger amount+ _ -> 0+ )+ source (Sub transaction resolved) =+ let fields = subFields transaction+ spent = Fields.fieldInputs fields+ funding = foldMap (Output.value . Utxo.output) [u | u <- resolved, Utxo.input u `elem` spent]+ in funding <> foldMap source (operationsFromFields fields)+ source _ = mempty++sinkExtras :: Parameters.Parameters -> Plan -> Value.Value+sinkExtras params = foldMap sink . normalizedOperations+ where+ sink (Mint a n _) | n < 0 = Value.singleton a (negate (toInteger n))+ sink (Certificate cert _) =+ Value.lovelace+ ( case cert of+ Certificate.StakeRegistration _ -> toInteger (Parameters.parameterKeyDeposit params)+ Certificate.PoolRegistration _ -> toInteger (Parameters.parameterPoolDeposit params)+ Certificate.Registration _ amount -> toInteger amount+ Certificate.StakeRegistrationDelegation _ _ amount -> toInteger amount+ Certificate.VoteRegistrationDelegation _ _ amount -> toInteger amount+ Certificate.StakeVoteRegistrationDelegation _ _ _ amount -> toInteger amount+ Certificate.RegisterDRep _ amount _ -> toInteger amount+ _ -> 0+ )+ sink (DirectDeposit _ n) = Value.lovelace (toInteger n)+ sink (Donation n) = Value.lovelace (toInteger n)+ sink Propose {} = Value.lovelace (toInteger (fromMaybe 0 (Parameters.parameterGovernanceActionDeposit params)))+ sink (Sub transaction _) =+ let fields = subFields transaction+ deposits = sum [toInteger (Proposal.proposalDeposit proposal) | Just proposals <- [Fields.fieldProposalProcedures fields], proposal <- Proposal.toList proposals]+ in foldMap Output.value (Fields.fieldOutputs fields) <> Value.lovelace deposits <> foldMap sink (operationsFromFields fields)+ sink _ = mempty++resolvedInputs :: Plan -> [Utxo]+resolvedInputs (Plan instructions _) = concatMap resolved (toList instructions)+ where+ resolved (Spend u _ _) = [u]+ resolved (Reference u) = [u]+ resolved (Sub _ values) = values+ resolved _ = []++encodeOperation :: Word64 -> Operation -> E.Encoding+encodeOperation deposit operation = case operation of+ Pay o -> fields 0 [bytes (Output.encodeCbor o)]+ Spend u (Just (Deferred index)) d -> fields 12 [bytes (Utxo.encodeCbor u), E.encodeInt index, optional d]+ Spend u r d -> fields 1 [bytes (Utxo.encodeCbor u), argument r, optional d]+ Reference u -> fields 2 [bytes (Utxo.encodeCbor u)]+ Script s -> fields 3 [bytes (Script.encodeCbor s)]+ Mint Ada _ _ -> fields 4 []+ Mint (Native p n) amount (Just (Deferred index)) -> fields 13 [bytes (Policy.toBytes p), bytes (AssetName.toBytes n), E.encodeInt64 amount, E.encodeInt index]+ Mint (Native p n) amount r -> fields 4 [bytes (Policy.toBytes p), bytes (AssetName.toBytes n), E.encodeInt64 amount, argument r]+ Metadata label value -> fields 5 [E.encodeWord64 label, bytes (Metadata.encodeMetadatumCbor value)]+ Datum d -> fields 6 [bytes (Data.toCbor d)]+ Certificate c (Just (Deferred index)) -> fields 14 [bytes (Certificate.encodeCbor c), E.encodeInt index]+ Certificate c r -> fields 7 [bytes (Certificate.encodeCbor c), argument r]+ Withdraw a amount (Just (Deferred index)) -> fields 15 [bytes (Reward.toBytes a), E.encodeWord64 amount, E.encodeInt index]+ Withdraw a amount r -> fields 8 [bytes (Reward.toBytes a), E.encodeWord64 amount, argument r]+ Signer hash -> fields 9 [bytes (Credential.keyHashBytes hash)]+ From n -> fields 10 [E.encodeWord64 n]+ Until n -> fields 11 [E.encodeWord64 n]+ Guard credential redeemer -> fields 16 [bytes (credentialBytes credential), optional redeemer]+ DirectDeposit address amount -> fields 18 [bytes (Reward.toBytes address), E.encodeWord64 amount]+ AccountBalance address interval -> fields 19 [bytes (Reward.toBytes address), bytes (intervalBytes interval)]+ StartingBalance address interval -> fields 20 [bytes (Reward.toBytes address), bytes (intervalBytes interval)]+ Donation amount -> fields 21 [E.encodeWord64 amount]+ TreasuryValue amount -> fields 27 [E.encodeWord64 amount]+ Propose address action anchor (Just (Deferred index)) -> fields 28 [bytes (Proposal.encodeCbor (Proposal.Proposal deposit address action anchor)), E.encodeInt index]+ Propose address action anchor redeemer -> fields 22 [bytes (Proposal.encodeCbor (Proposal.Proposal deposit address action anchor)), argument redeemer]+ Vote voter action procedure (Just (Deferred index)) -> fields 24 [bytes (Voting.encodeVoter voter), bytes (ActionId.encodeCbor action), bytes (Voting.encodeProcedure procedure), E.encodeInt index]+ Vote voter action procedure redeemer -> fields 23 [bytes (Voting.encodeVoter voter), bytes (ActionId.encodeCbor action), bytes (Voting.encodeProcedure procedure), argument redeemer]+ TopLevelGuard credential datum -> fields 26 [bytes (credentialBytes credential), optional datum]+ Sub transaction resolved -> fields 25 [bytes (Sub.encodeCbor transaction), E.encodeListLen (fromIntegral (length resolved)) <> foldMap (C.raw . Utxo.encodeCbor) resolved]+ where+ fields tag xs = E.encodeListLen (fromIntegral (1 + length xs)) <> E.encodeWord tag <> mconcat xs+ bytes = E.encodeBytes+ argument Nothing = bytes mempty+ argument (Just (Immediate d)) = bytes (Data.toCbor d)+ argument (Just (Deferred index)) = E.encodeInt index+ optional = maybe (E.encodeBytes mempty) (bytes . Data.toCbor)++-- | Spend a resolved script output using a late argument and optional datum+-- witness. Register each spending input once when using a deferred argument.+spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan+spendWithDeferredRedeemer u callback datum = deferred (Spend u (Just (Deferred 0)) datum) callback++-- | Mint or burn several assets under one policy using one late argument.+-- Quantities for repeated names are combined; zero totals are omitted. Empty+-- or entirely cancelled groups never call the callback. Register each policy+-- once; combining separate deferred groups for one policy fails at build.+mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan+mintWithDeferredRedeemer policy assets callback =+ Plan+ (Seq.fromList [Mint (Native policy name) amount (Just (Deferred 0)) | (name, amount) <- assets])+ (Seq.singleton callback)++-- | Append a certificate authorized by a late Plutus argument.+certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan+certificateWithDeferredRedeemer cert = deferred (Certificate cert (Just (Deferred 0)))++-- | Withdraw rewards using a late argument. Register each reward account once+-- when using a deferred argument.+withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan+withdrawWithDeferredRedeemer address amount = deferred (Withdraw address amount (Just (Deferred 0)))++deferred :: Operation -> DeferredRedeemer -> Plan+deferred operation callback = Plan (Seq.singleton operation) (Seq.singleton callback)++deferredRedeemers :: Plan -> Seq.Seq DeferredRedeemer+deferredRedeemers (Plan _ callbacks) = callbacks++shiftCallbacks :: Int -> Operation -> Operation+shiftCallbacks offset operation = case operation of+ Spend u argument datum -> Spend u (shift <$> argument) datum+ Mint asset amount argument -> Mint asset amount (shift <$> argument)+ Certificate cert argument -> Certificate cert (shift <$> argument)+ Withdraw address amount argument -> Withdraw address amount (shift <$> argument)+ Vote voter action procedure argument -> Vote voter action procedure (shift <$> argument)+ Propose address action anchor argument -> Propose address action anchor (shift <$> argument)+ _ -> operation+ where+ shift (Deferred index) = Deferred (index + offset)+ shift argument = argument++-- | Require a key or script guard. Key guards require signatures; script guards+-- require a supplied script. Identical requirements are idempotent.+requireGuard :: Credential Guard -> Plan+requireGuard credential = one (Guard credential Nothing)++-- | Require a script guard with its guarding argument. Guard positions preserve+-- insertion order, including ordinary required signers. Supply a Plutus V4 script+-- for a top-level guard; attaching the script remains explicit.+guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan+guardWithRedeemer hash argument = one (Guard (Credential.ScriptCredential hash) (Just argument))++-- | Pay positive lovelace directly into a reward account. Repeated amounts add;+-- each amount and their total must fit the native signed 64-bit balance range.+directDeposit :: RewardAddress -> Word64 -> Plan+directDeposit account = one . DirectDeposit account++-- | Require the account balance when this transaction is applied. Identical+-- intervals compose idempotently; differing intervals fail at build time.+accountBalance :: RewardAddress -> BalanceInterval -> Plan+accountBalance account = one . AccountBalance account++-- | Require the account balance before any subtransaction of the batch applies.+startingAccountBalance :: RewardAddress -> BalanceInterval -> Plan+startingAccountBalance account = one . StartingBalance account++-- | Contribute lovelace to the treasury. Amounts add under composition, including+-- explicit zero; the total must fit the native signed 64-bit balance range.+donate :: Word64 -> Plan+donate = one . Donation++-- | Declare the current treasury balance in lovelace. This is a ledger-state+-- assertion, not a donation or a source of transaction funds. Repeating the same+-- value is idempotent; conflicting values fail when building. Zero is explicit.+currentTreasuryValue :: Word64 -> Plan+currentTreasuryValue = one . TreasuryValue++-- | Append a governance proposal using the configured protocol deposit. A+-- parameter-change or treasury-withdrawal action with a guardrails policy uses+-- the unit redeemer @Constr 0 []@. An action without a policy needs no redeemer.+-- Attach the policy script or resolve its reference input separately.+propose :: RewardAddress -> Action -> Anchor -> Plan+propose address action anchor = one (Propose address action anchor argument)+ where+ argument = if hasPolicy action then Just (Immediate (Data.fromData (Data.Constr 0 []))) else Nothing++-- | Append a proposal with an explicit guardrails argument. The action must+-- name a policy; other actions fail when building. Proposal order determines+-- the proposing redeemer index. Duplicate proposals fail rather than gaining+-- a second index. The configured protocol snapshot supplies the deposit.+proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan+proposeWithRedeemer address action anchor = one . Propose address action anchor . Just . Immediate++-- | Append a proposal whose guardrails argument is computed from the balanced+-- draft. The action must name a policy. The callback sees the proposal with its+-- configured deposit and may run repeatedly as balancing converges.+proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan+proposeWithDeferredRedeemer address action anchor = deferred (Propose address action anchor (Just (Deferred 0)))++hasPolicy :: Action -> Bool+hasPolicy (Action.ParameterChange _ _ policy) = isJust policy+hasPolicy (Action.TreasuryWithdrawals _ policy) = isJust policy+hasPolicy _ = False++-- | Cast a key-authorized vote. Identical voter/action instructions are+-- idempotent; conflicting choices fail when building.+vote :: Voter -> ActionId -> VotingProcedure -> Plan+vote voter action procedure = one (Vote voter action procedure Nothing)++-- | Cast several votes authorized by one voter and one immediate argument.+-- A voter has one voting redeemer across all of its governance actions.+voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan+voteWithRedeemer voter votes argument = foldMap (\(action, procedure) -> one (Vote voter action procedure (Just (Immediate argument)))) votes++-- | Cast several votes using one late argument for the voter. Empty groups do+-- not invoke the callback. Register each deferred voter once per plan.+voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan+voteWithDeferredRedeemer voter votes callback =+ Plan (Seq.fromList [Vote voter action procedure (Just (Deferred 0)) | (action, procedure) <- votes]) (Seq.singleton callback)++-- | Carry an independently built subtransaction, retaining its exact bytes and+-- signatures. Supply every spending and reference input as a resolved snapshot.+-- Spending inputs of different transaction levels must be disjoint. The parent+-- funds the batch's net deficit and supplies the fee and collateral.+attachSubTransaction :: SubTransaction -> [Utxo] -> Plan+attachSubTransaction transaction = one . Sub transaction++subTransactions :: Plan -> [(SubTransaction, [Utxo])]+subTransactions (Plan operations _) = [(transaction, resolved) | Sub transaction resolved <- toList operations]++subFields :: SubTransaction -> Fields.Fields+subFields = SubBody.fields . SubBody.toBody . Sub.body++validateSub :: (SubTransaction, [Utxo]) -> Either Error ()+validateSub (transaction, resolved) = do+ let fields = subFields transaction+ expected = Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields)+ actual = map Utxo.input resolved+ unless (all (`elem` actual) expected) (Left (InvalidTransactionPlan "Unresolved subtransaction spending or reference input"))+ unless (Set.size (Set.fromList actual) == length actual) (Left (InvalidTransactionPlan "Duplicate subtransaction resolved input"))++operationsFromFields :: Fields.Fields -> [Operation]+operationsFromFields fields =+ map Pay (Fields.fieldOutputs fields)+ <> [Mint asset (fromInteger amount) Nothing | Just minted <- [Fields.fieldMint fields], (asset, amount) <- Value.toList (Fields.mintValue minted)]+ <> [Withdraw account amount Nothing | Just entries <- [Fields.fieldWithdrawals fields], (account, amount) <- Fields.entries entries]+ <> [Certificate cert Nothing | Just certificates <- [Fields.fieldCertificates fields], cert <- Certificates.toList certificates]+ <> [DirectDeposit account amount | Just entries <- [Fields.fieldDirectDeposits fields], (account, amount) <- Fields.entries entries]+ <> [Donation amount | Just amount <- [Fields.fieldDonation fields]]++credentialBytes :: Credential authority -> ByteString+credentialBytes credential =+ C.encode $+ E.encodeListLen 2 <> case credential of+ Credential.KeyCredential hash -> E.encodeWord 0 <> E.encodeBytes (Credential.keyHashBytes hash)+ Credential.ScriptCredential hash -> E.encodeWord 1 <> E.encodeBytes (Credential.scriptHashBytes hash)++intervalBytes :: BalanceInterval -> ByteString+intervalBytes interval = C.encode $ case interval of+ ExactBalance amount -> E.encodeWord64 amount+ BalanceRange lower upper -> E.encodeListLen 2 <> maybe E.encodeNull E.encodeWord64 lower <> maybe E.encodeNull E.encodeWord64 upper++requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan+requireTopLevelGuard credential = one . TopLevelGuard credential++validateTopLevel :: Plan -> Either Error ()+validateTopLevel (Plan operations _) = unless (all permitted (toList operations)) (Left (InvalidTransactionPlan "Parent guard requirements belong to a subtransaction plan"))+ where+ permitted TopLevelGuard {} = False+ permitted _ = True++reservedInputs :: Plan -> [Cometa.Transaction.Input.Input]+reservedInputs plan = concatMap references (subTransactions plan)+ where+ references (transaction, _) = let fields = subFields transaction in Fields.fieldInputs fields <> fromMaybe [] (Fields.fieldReferenceInputs fields)++outerResolvedInputs :: Plan -> [Utxo]+outerResolvedInputs (Plan instructions _) = concatMap resolved (toList instructions)+ where+ resolved (Spend input _ _) = [input]+ resolved (Reference input) = [input]+ resolved _ = []
@@ -0,0 +1,76 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Signed native-range asset bundle encoding; no native references.+module Cometa.Internal.TransactionValue (encodeAssets, decodeAssets, validateOutput, validateMint) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as Name+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Value as Value+import Control.Monad (unless)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set++-- TYPES ----------------------------------------------------------------------++-- DEFINITIONS ----------------------------------------------------------------++validateOutput :: Value.Value -> Either Error ()+validateOutput value = mapM_ valid (Value.toList value)+ where+ valid (_, quantity)+ | quantity < 0 || quantity > toInteger (maxBound :: Int64) = Left (InvalidTransactionOutputValue quantity)+ | otherwise = Right ()++validateMint :: Value.Value -> Either Error ()+validateMint value = mapM_ valid (Value.toList value)+ where+ valid (asset, quantity)+ | asset == Ada = Left (InvalidTransactionField "Mint cannot contain Ada")+ | quantity < toInteger (minBound :: Int64) || quantity > toInteger (maxBound :: Int64) = Left (InvalidTransactionOutputValue quantity)+ | otherwise = Right ()++encodeAssets :: Value.Value -> E.Encoding+encodeAssets value = E.encodeMapLen (fromIntegral (Map.size policies)) <> foldMap encodePolicy (Map.toAscList policies)+ where+ policies = Map.fromListWith (++) [(policy, [(name, amount)]) | (Native policy name, amount) <- Value.toList value]+ encodePolicy (policy, assets) = E.encodeBytes (Policy.toBytes policy) <> E.encodeMapLen (fromIntegral (length assets)) <> foldMap (\(name, amount) -> E.encodeBytes (Name.toBytes name) <> E.encodeInteger amount) (sortOn (\(name, _) -> (B.length (Name.toBytes name), Name.toBytes name)) (Map.toAscList (Map.fromList assets)))++decodeAssets :: D.Decoder s Value.Value+decodeAssets = do+ policies <- Cbor.entries $ do+ bytes <- D.decodeBytes+ policy <- either (fail . show) pure (Policy.fromBytes bytes)+ assets <- Cbor.entries $ do+ nameBytes <- D.decodeBytes+ name <- either (fail . show) pure (Name.fromBytes nameBytes)+ amount <- D.decodeInteger+ unless (amount >= toInteger (minBound :: Int64) && amount <= toInteger (maxBound :: Int64)) (fail "Asset quantity exceeds int64")+ pure (name, amount)+ unless (Set.size (Set.fromList (map fst assets)) == length assets) (fail "Duplicate asset name")+ pure (policy, assets)+ unless (Set.size (Set.fromList (map fst policies)) == length policies) (fail "Duplicate policy")+ pure (Value.fromList [(Native policy name, amount) | (policy, assets) <- policies, (name, amount) <- assets])
@@ -0,0 +1,217 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE RoleAnnotations #-}++-- | Scoped encrypted software key storage. Each public-key operation requests a password+-- from the supplied action. Passwords are raw bytes (including NUL), 1 through+-- 128 bytes; no text normalization is performed. Keep application-owned inputs+-- and callback results only as long as your application requires: closing cannot+-- erase those Haskell values or copies made by the application.+--+-- A handler closes on every continuation exit, including exceptions. Escaped+-- handles reject further operations. Operations on independent handlers may run+-- concurrently; overlap and callback reentry on the same handler return+-- 'KeyHandlerBusy'. A password action must not wait for another operation on+-- its own handler. Cancellation waits for the password action and native work+-- to unwind; an action that masks cancellation can delay cleanup.+--+-- @+-- import qualified Cometa.KeyHandler.Software as Software+--+-- storeEntropy entropy encryptionPassword requestPassword =+-- Software.withEntropy entropy encryptionPassword requestPassword Software.serialize+-- @+module Cometa.KeyHandler.Software+ ( -- * Capabilities+ Handler,+ Bip32,+ Ed25519,+ LoadedHandler (..),++ -- * Scoped construction+ withEntropy,+ withSigningKey,+ withSerialized,++ -- * Operations+ close,+ accountPublicKey,+ publicKey,+ name,+ serialize,+ signTransaction,+ signTransactionAt,+ signSubTransaction,+ signSubTransactionAt,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PublicKey as Bip32Public+import Cometa.Crypto.DerivationPath (AccountPath)+import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.Crypto.Ed25519.PublicKey as EdPublic+import Cometa.Crypto.Ed25519.SigningKey (SigningKey)+import Cometa.Error (Error (..))+import Cometa.Internal.Ed25519SigningKey (SigningKey (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.KeyHandler as Internal+import qualified Cometa.SubTransaction as SubTransaction+import qualified Cometa.Transaction as Transaction+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (join)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.List.NonEmpty (NonEmpty)+import qualified Data.List.NonEmpty as NonEmpty+import Data.Text (Text)+import Data.Word (Word32)+import Foreign.C.Types (CUInt)++-- TYPES ----------------------------------------------------------------------++-- | BIP32 capability: derive an account public key from encrypted entropy.+data Bip32++-- | Ed25519 capability: recover the public key associated with encrypted key bytes.+data Ed25519++-- | A scoped handler whose capability determines the available operations.+-- No equality or printable representation exposes secret storage.+type role Handler nominal++newtype Handler mode = Handler Internal.Handler++-- | The serialized format determines the handler capability. Metadata is CRC+-- protected, not authenticated; accept storage only from a trusted source.+data LoadedHandler+ = -- | A handler storing BIP39 entropy for hierarchical account derivation.+ Bip32Handler (Handler Bip32)+ | -- | A handler storing a normal or extended Ed25519 signing key.+ Ed25519Handler (Handler Ed25519)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encrypt BIP39 entropy (16, 20, 24, 28 or 32 bytes) immediately with the+-- supplied encryption password, then run the continuation. The request action+-- supplies a fresh password for each derivation. Root derivation uses the empty+-- BIP39 password; the encryption password only protects storage.+withEntropy :: ByteString -> ByteString -> IO ByteString -> (Handler Bip32 -> IO (Either Error value)) -> IO (Either Error value)+withEntropy entropy password request action+ | size `notElem` [16, 20, 24, 28, 32] = pure (Left (InvalidBip39EntropyLength size))+ | otherwise = flatten <$> Internal.withEntropy entropy password request (action . Handler)+ where+ size = ByteString.length entropy++-- | Encrypt a copy of a scoped normal or extended signing key. The source stays+-- usable independently. A closed source returns 'SigningKeyClosed'.+withSigningKey :: SigningKey -> ByteString -> IO ByteString -> (Handler Ed25519 -> IO (Either Error value)) -> IO (Either Error value)+withSigningKey (SigningKey source) password request action = flatten <$> Internal.withSigningKey source password request (action . Handler)++-- | Open the native binary storage format. Validates framing, type, canonical+-- encrypted payload sizes and checksum before invoking the continuation. It does not+-- request a password or authenticate the encrypted payload until a public-key+-- operation is requested. Wrong passwords fail that later operation.+withSerialized :: ByteString -> IO ByteString -> (LoadedHandler -> IO (Either Error value)) -> IO (Either Error value)+withSerialized bytes request action =+ flatten+ <$> Internal.withSerialized+ bytes+ request+ ( \bip32 handler ->+ action (if bip32 then Bip32Handler (Handler handler) else Ed25519Handler (Handler handler))+ )++-- | Close immediately, or return 'KeyHandlerBusy' if an operation is active.+-- Repeated close succeeds. Scope exit waits for ongoing work and closes even+-- when a prior explicit close returned busy.+close :: Handler mode -> IO (Either Error ())+close (Handler handler) = mapFailure <$> Internal.close handler++-- | Derive the account extended public key at three hardened path components.+-- The public result remains usable after this handler closes.+accountPublicKey :: Handler Bip32 -> AccountPath -> IO (Either Error Bip32Public.PublicKey)+accountPublicKey (Handler handler) path = do+ result <- Internal.accountPublicKey handler (component Path.purpose) (component Path.coinType) (component Path.account)+ pure (mapFailure result >>= Bip32Public.fromBytes)+ where+ component field = Path.indexValue (field path)++-- | Recover the Ed25519 public key. Each call requests a password, and the+-- returned immutable key remains usable after this handler closes.+publicKey :: Handler Ed25519 -> IO (Either Error EdPublic.PublicKey)+publicKey (Handler handler) = do+ result <- Internal.publicKey handler+ pure (mapFailure result >>= EdPublic.fromBytes)++-- | Implementation name for diagnostics. Does not request a password.+name :: Handler mode -> IO (Either Error Text)+name (Handler handler) = mapFailure <$> Internal.name handler++-- | Copy encrypted storage bytes for persistence; does not request a password.+-- The binary format contains encrypted key material and CRC-protected metadata.+-- The metadata is not cryptographically authenticated. The result can outlive+-- the scope; protect it against unauthorized modification and password guessing.+serialize :: Handler mode -> IO (Either Error ByteString)+serialize (Handler handler) = mapFailure <$> Internal.serialize handler++-- | Sign the exact transaction-body hash using the encrypted Ed25519 key.+-- Requests a password once and returns partial witnesses, without changing the+-- transaction. Merge with 'Transaction.addWitnesses' to retain existing signatures.+-- Closed, busy, password and native failures follow the ordinary handler contract.+signTransaction :: Handler Ed25519 -> Transaction.Transaction -> IO (Either Error Witnesses.EncodedWitnesses)+signTransaction (Handler handler) = signEncoded handler 0 [] . Transaction.encodeCbor++-- | Derive each nonempty five-level path and sign the exact body hash. Requests+-- a password once for the whole batch. Returns only the generated witnesses;+-- duplicate paths are idempotent. No transaction bytes are changed.+signTransactionAt :: Handler Bip32 -> NonEmpty Path.DerivationPath -> Transaction.Transaction -> IO (Either Error Witnesses.EncodedWitnesses)+signTransactionAt (Handler handler) paths = signEncoded handler 1 (map pathComponents (NonEmpty.toList paths)) . Transaction.encodeCbor++-- | Sign a sub-transaction's own exact body hash using the encrypted Ed25519 key.+-- The enclosing body and its signatures are independent of this operation.+signSubTransaction :: Handler Ed25519 -> SubTransaction.SubTransaction -> IO (Either Error Witnesses.EncodedWitnesses)+signSubTransaction (Handler handler) = signEncoded handler 2 [] . SubTransaction.encodeCbor++-- | Derive the supplied paths and sign this sub-transaction's own body hash.+-- Requests a password once and returns partial witnesses without changing input.+signSubTransactionAt :: Handler Bip32 -> NonEmpty Path.DerivationPath -> SubTransaction.SubTransaction -> IO (Either Error Witnesses.EncodedWitnesses)+signSubTransactionAt (Handler handler) paths = signEncoded handler 3 (map pathComponents (NonEmpty.toList paths)) . SubTransaction.encodeCbor++signEncoded :: Internal.Handler -> CUInt -> [[Word32]] -> ByteString -> IO (Either Error Witnesses.EncodedWitnesses)+signEncoded handler kind paths bytes = do+ result <- Internal.signTransaction handler kind paths bytes+ pure (mapFailure result >>= Witnesses.decodeCbor)++pathComponents :: Path.DerivationPath -> [Word32]+pathComponents path =+ let account = Path.accountPrefix path+ in map Path.indexValue [Path.purpose account, Path.coinType account, Path.account account, Path.role path, Path.index path]++flatten :: Either Internal.Failure (Either Error value) -> Either Error value+flatten = join . mapFailure++mapFailure :: Either Internal.Failure value -> Either Error value+mapFailure = either (Left . publicFailure) Right++publicFailure :: Internal.Failure -> Error+publicFailure failure = case failure of+ Internal.Closed -> KeyHandlerClosed+ Internal.Busy -> KeyHandlerBusy+ Internal.PasswordLength size -> InvalidKeyHandlerPasswordLength size+ Internal.InvalidStorage -> InvalidKeyHandlerStorage+ Internal.SourceClosed -> SigningKeyClosed+ Internal.NativeFailure native -> fromNativeFailure native
@@ -0,0 +1,40 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | CIP-8 message signing with an address or key-hash binding. Payloads are+-- nonempty raw bytes, signed directly with @hashed = false@ and empty external+-- AAD. Detached payloads, prehashing and custom AAD are not supported by this API.+--+-- Signing records the supplied binding; it does not prove the key controls that+-- address or matches that hash. Applications and verifiers must check that link.+-- The result owns immutable public bytes and remains usable after the key closes.+module Cometa.Message.Cip8+ ( Binding,+ addressBinding,+ keyHashBinding,+ SignedMessage (..),+ sign,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.Message.Cip8+ ( Binding,+ SignedMessage (..),+ addressBinding,+ keyHashBinding,+ sign,+ )
@@ -0,0 +1,426 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Validated transaction metadata. Nested maps preserve pair order and duplicate+-- keys. Transaction labels are unique unsigned 64-bit numbers. Imported encodings+-- remain exact until the caller explicitly encodes their semantic view again.+--+-- @+-- {-# LANGUAGE OverloadedStrings #-}+-- import Cometa.Error (Error)+-- import qualified Cometa.Metadata as Metadata+--+-- message :: Either Error Metadata.Metadata+-- message = Metadata.singleton 674 . Metadata.list . pure <$> Metadata.mkText "hello"+-- @+module Cometa.Metadata+ ( -- * Nested values+ Metadatum,+ View (..),+ mkInteger,+ integerFromText,+ mkBytes,+ mkText,+ list,+ map,+ view,++ -- * Transaction labels+ Metadata,+ singleton,+ mkMetadata,+ toList,+ lookup,++ -- * CBOR and encoding identity+ EncodedMetadata,+ EncodedMetadatum,+ encodeCbor,+ decodeCbor,+ toCbor,+ toMetadata,+ encodeMetadatumCbor,+ decodeMetadatumCbor,+ toMetadatumCbor,+ toMetadatum,++ -- * Detailed JSON+ toDetailedJson,+ fromDetailedJson,+ metadatumToDetailedJson,+ metadatumFromDetailedJson,++ -- * Plain JSON+ metadatumToJson,+ metadatumFromJson,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import Codec.CBOR.Read (deserialiseFromBytes)+import Codec.CBOR.Write (toStrictByteString)+import qualified Cometa.Encoding.Integer as Integer+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Control.Monad (replicateM)+import Data.Aeson (Value (..), object, toJSON, (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KeyMap+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as LazyByteString+import qualified Data.Foldable+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import Data.Scientific (Scientific, base10Exponent, coefficient)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word64)+import Text.Read (readMaybe)+import Prelude hiding (lookup, map)+import qualified Prelude++-- TYPES ----------------------------------------------------------------------++-- | A metadata value whose integers fit primitive CBOR and whose byte/text+-- strings contain at most 64 bytes. Equality compares values and nested ordering.+newtype Metadatum = Metadatum View deriving (Eq, Show)++-- | A read-only view. Constructing a view cannot bypass 'Metadatum' validation.+data View+ = -- | A primitive CBOR integer in the inclusive range @-2^64 .. 2^64-1@.+ IntegerValue Integer+ | -- | Zero through 64 arbitrary bytes.+ BytesValue ByteString+ | -- | Text containing at most 64 UTF-8 bytes, without normalization.+ TextValue Text+ | -- | An ordered list of validated values.+ ListValue [Metadatum]+ | -- | Ordered key/value pairs; duplicate keys are preserved.+ MapValue [(Metadatum, Metadatum)]+ deriving (Eq, Show)++-- | Unique labels. Equality ignores insertion order. Combining values is+-- left-biased on duplicate labels, with empty metadata as identity.+newtype Metadata = Metadata (Map.Map Word64 Metadatum) deriving (Eq, Show)++instance Semigroup Metadata where+ Metadata left <> Metadata right = Metadata (Map.union left right)++instance Monoid Metadata where+ mempty = Metadata Map.empty++-- | Validated metadata plus its original bytes. Equality compares exact bytes.+data EncodedMetadata = EncodedMetadata ByteString Metadata deriving (Show)++instance Eq EncodedMetadata where+ EncodedMetadata a _ == EncodedMetadata b _ = a == b++-- | Validated metadatum plus its original bytes. Equality compares exact bytes.+data EncodedMetadatum = EncodedMetadatum ByteString Metadatum deriving (Show)++instance Eq EncodedMetadatum where+ EncodedMetadatum a _ == EncodedMetadatum b _ = a == b++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate the inclusive range @-2^64 .. 2^64-1@. Tagged bignums are excluded.+mkInteger :: Integer -> Either Error Metadatum+mkInteger n+ | n < negate (2 ^ (64 :: Int)) || n >= 2 ^ (64 :: Int) = Left (InvalidMetadataInteger n)+ | otherwise = Right (Metadatum (IntegerValue n))++-- | Parse native-compatible integer text in a validated radix, then apply the+-- ledger metadata integer bounds. Parsing errors are 'InvalidIntegerText';+-- out-of-range values return 'InvalidMetadataInteger'.+integerFromText :: Integer.Radix -> Text -> Either Error Metadatum+integerFromText radix text = Integer.fromText radix text >>= mkInteger++-- | Validate a byte string of 0 through 64 bytes.+mkBytes :: ByteString -> Either Error Metadatum+mkBytes b+ | ByteString.length b > 64 = Left (InvalidMetadataBytesLength (ByteString.length b))+ | otherwise = Right (Metadatum (BytesValue b))++-- | Validate at most 64 UTF-8 bytes; no Unicode normalization is performed.+mkText :: Text -> Either Error Metadatum+mkText t+ | size > 64 = Left (InvalidMetadataTextLength size)+ | otherwise = Right (Metadatum (TextValue t))+ where+ size = ByteString.length (Text.encodeUtf8 t)++-- | Assemble a list, preserving order. Empty lists are valid.+list :: [Metadatum] -> Metadatum+list = Metadatum . ListValue++-- | Assemble a map, preserving pair order and duplicate keys. Empty maps are valid.+map :: [(Metadatum, Metadatum)] -> Metadatum+map = Metadatum . MapValue++-- | Inspect a value without validation or effects.+view :: Metadatum -> View+view (Metadatum v) = v++-- | Assemble one transaction label and its validated value.+singleton :: Word64 -> Metadatum -> Metadata+singleton label value = Metadata (Map.singleton label value)++-- | Validate label uniqueness; duplicate labels return 'DuplicateMetadataLabel'.+mkMetadata :: [(Word64, Metadatum)] -> Either Error Metadata+mkMetadata = go Map.empty+ where+ go values [] = Right (Metadata values)+ go values ((label, value) : rest)+ | Map.member label values = Left (DuplicateMetadataLabel label)+ | otherwise = go (Map.insert label value values) rest++-- | Inspect entries in ascending numeric label order.+toList :: Metadata -> [(Word64, Metadatum)]+toList (Metadata m) = Map.toAscList m++-- | Find a label; missing labels are ordinary absence.+lookup :: Word64 -> Metadata -> Maybe Metadatum+lookup key (Metadata m) = Map.lookup key m++-- | Encode a semantic value with minimal integers and definite strings and+-- collections. Labels are ascending; nested map order is preserved. This is+-- normalization, not a claim of canonical sorting of arbitrary metadata keys.+encodeCbor :: Metadata -> ByteString+encodeCbor metadata = toStrictByteString (Encode.encodeMapLen (fromIntegral (length entries)) <> foldMap encodeEntry entries)+ where+ entries = Cometa.Metadata.toList metadata+ encodeEntry (label, value) = Encode.encodeWord64 label <> encodeValue value++-- | Decode exactly one metadata map. Rejects duplicate labels, trailing input,+-- invalid UTF-8, unsupported CBOR types, and out-of-bound values. Definite and+-- indefinite collections and strings are accepted; original bytes are retained.+decodeCbor :: ByteString -> Either Error EncodedMetadata+decodeCbor bytes = do+ entries <- decodeFull (decodeCollection Decode.decodeMapLenOrIndef ((,) <$> Decode.decodeWord64 <*> decodeValue)) bytes+ EncodedMetadata bytes <$> mkMetadata entries++-- | Retrieve the exact imported bytes without normalization.+toCbor :: EncodedMetadata -> ByteString+toCbor (EncodedMetadata bytes _) = bytes++-- | Inspect the semantic metadata view; encoding it again explicitly normalizes.+toMetadata :: EncodedMetadata -> Metadata+toMetadata (EncodedMetadata _ metadata) = metadata++-- | Encode a metadatum with minimal integers and definite strings/collections.+-- Map pair order and duplicate keys are preserved.+encodeMetadatumCbor :: Metadatum -> ByteString+encodeMetadatumCbor = toStrictByteString . encodeValue++-- | Decode one bounded metadatum, preserving exact bytes. The same restrictions+-- as 'decodeCbor' apply.+decodeMetadatumCbor :: ByteString -> Either Error EncodedMetadatum+decodeMetadatumCbor bytes = EncodedMetadatum bytes <$> decodeFull decodeValue bytes++-- | Retrieve exact imported metadatum bytes.+toMetadatumCbor :: EncodedMetadatum -> ByteString+toMetadatumCbor (EncodedMetadatum bytes _) = bytes++-- | Retrieve the validated semantic metadatum.+toMetadatum :: EncodedMetadatum -> Metadatum+toMetadatum (EncodedMetadatum _ value) = value++encodeValue :: Metadatum -> Encode.Encoding+encodeValue (Metadatum value) = case value of+ IntegerValue n -> Encode.encodeInteger n+ BytesValue b -> Encode.encodeBytes b+ TextValue t -> Encode.encodeString t+ ListValue xs -> Encode.encodeListLen (fromIntegral (length xs)) <> foldMap encodeValue xs+ MapValue xs -> Encode.encodeMapLen (fromIntegral (length xs)) <> foldMap (\(k, v) -> encodeValue k <> encodeValue v) xs++decodeFull :: (forall s. Decode.Decoder s a) -> ByteString -> Either Error a+decodeFull decoder bytes = case deserialiseFromBytes decoder (LazyByteString.fromStrict bytes) of+ Left _ -> Left (InvalidMetadataCbor "invalid metadata encoding")+ Right (rest, value)+ | LazyByteString.null rest -> Right value+ | otherwise -> Left (InvalidMetadataCbor "trailing input")++decodeValue :: Decode.Decoder s Metadatum+decodeValue = do+ token <- Decode.peekTokenType+ case token of+ Decode.TypeUInt -> integer+ Decode.TypeUInt64 -> integer+ Decode.TypeNInt -> integer+ Decode.TypeNInt64 -> integer+ Decode.TypeBytes -> Decode.decodeBytes >>= checked . mkBytes+ Decode.TypeBytesIndef -> Decode.decodeBytesIndef >> boundedChunks Decode.decodeBytes ByteString.length ByteString.concat >>= checked . mkBytes+ Decode.TypeString -> Decode.decodeString >>= checked . mkText+ Decode.TypeStringIndef -> Decode.decodeStringIndef >> boundedChunks Decode.decodeString (ByteString.length . Text.encodeUtf8) Text.concat >>= checked . mkText+ Decode.TypeListLen -> array+ Decode.TypeListLen64 -> array+ Decode.TypeListLenIndef -> array+ Decode.TypeMapLen -> pairs+ Decode.TypeMapLen64 -> pairs+ Decode.TypeMapLenIndef -> pairs+ _ -> fail "unsupported metadata type"+ where+ integer = Decode.decodeInteger >>= checked . mkInteger+ array = list <$> decodeCollection Decode.decodeListLenOrIndef decodeValue+ pairs = Cometa.Metadata.map <$> decodeCollection Decode.decodeMapLenOrIndef ((,) <$> decodeValue <*> decodeValue)++checked :: Either Error a -> Decode.Decoder s a+checked = either (const (fail "metadata value outside bounds")) pure++decodeCollection :: Decode.Decoder s (Maybe Int) -> Decode.Decoder s a -> Decode.Decoder s [a]+decodeCollection start item = do+ count <- start+ case count of+ Just n -> replicateM n item+ Nothing -> chunks item id++chunks :: Decode.Decoder s a -> ([a] -> b) -> Decode.Decoder s b+chunks item assemble = go []+ where+ go acc = do+ end <- Decode.decodeBreakOr+ if end then pure (assemble (reverse acc)) else item >>= \value -> go (value : acc)++-- Reject accumulated overlength strings before retaining further chunks.+boundedChunks :: Decode.Decoder s a -> (a -> Int) -> ([a] -> b) -> Decode.Decoder s b+boundedChunks item size assemble = go 0 []+ where+ go used acc = do+ end <- Decode.decodeBreakOr+ if end+ then pure (assemble (reverse acc))+ else do+ value <- item+ let next = used + size value+ if next > 64 then fail "metadata string outside bounds" else go next (value : acc)++-- | Lossless cardano-api detailed-schema JSON: top-level object keys are decimal+-- labels. This is distinct from CIP-116 inspector JSON. JSON object key order is+-- insignificant; nested map pair arrays preserve order and duplicates.+toDetailedJson :: Metadata -> Value+toDetailedJson = Object . KeyMap.fromList . Prelude.map (\(k, v) -> (Key.fromText (Text.pack (show k)), metadatumToDetailedJson v)) . Cometa.Metadata.toList++-- | Import detailed-schema JSON, validating labels and every leaf. Labels must+-- be canonical unsigned decimal strings, without leading zeros except zero.+fromDetailedJson :: Value -> Either Error Metadata+fromDetailedJson (Object values) = traverse entry (KeyMap.toList values) >>= mkMetadata+ where+ entry (key, value) = do+ let label = Key.toText key+ n <- maybe (Left (InvalidMetadataJson "invalid metadata label")) Right (readMaybe (Text.unpack label) :: Maybe Word64)+ if Text.pack (show n) /= label+ then Left (InvalidMetadataJson "noncanonical metadata label")+ else (,) n <$> metadatumFromDetailedJson value+fromDetailedJson _ = Left (InvalidMetadataJson "metadata must be an object")++-- | Convert every metadatum constructor without loss. Shapes are @{"int":n}@,+-- @{"bytes":"hex"}@, @{"string":"text"}@, @{"list":[...]}@ and+-- @{"map":[{"k":...,"v":...}]}@. Hex is lowercase without a prefix.+metadatumToDetailedJson :: Metadatum -> Value+metadatumToDetailedJson (Metadatum value) = case value of+ IntegerValue n -> object ["int" .= n]+ BytesValue b -> object ["bytes" .= Hex.encodeHex b]+ TextValue t -> object ["string" .= t]+ ListValue xs -> object ["list" .= Prelude.map metadatumToDetailedJson xs]+ MapValue xs -> object ["map" .= Prelude.map (\(k, v) -> object ["k" .= metadatumToDetailedJson k, "v" .= metadatumToDetailedJson v]) xs]++-- | Validate a detailed-schema metadatum. Integers remain exact; fractional+-- numbers, unsupported shapes, invalid hex and overlong strings fail.+metadatumFromDetailedJson :: Value -> Either Error Metadatum+metadatumFromDetailedJson = go+ where+ go :: Value -> Either Error Metadatum+ go (Object fields) = case KeyMap.toList fields of+ [("int", Number n)] -> scientificInteger n >>= mkInteger+ [("bytes", String s)] -> maybe (bad "invalid metadata hex") mkBytes (Hex.decodeHex s)+ [("string", String s)] -> mkText s+ [("list", Array xs)] -> list <$> traverse go (Data.Foldable.toList xs)+ [("map", Array xs)] -> Cometa.Metadata.map <$> traverse pair (Data.Foldable.toList xs)+ _ -> bad "invalid detailed metadata shape"+ go _ = bad "detailed metadata must be an object"+ pair (Object fields)+ | KeyMap.size fields == 2, Just k <- KeyMap.lookup "k" fields, Just v <- KeyMap.lookup "v" fields = (,) <$> go k <*> go v+ pair _ = bad "metadata map pair requires k and v"+ bad = Left . InvalidMetadataJson++-- Convert without negating an Int exponent or constructing an enormous power.+-- Negative exponents are consumed only while the coefficient has trailing zeros.+scientificInteger :: Scientific -> Either Error Integer+scientificInteger number+ | coefficientValue == 0 = Right 0+ | decimalExponent >= 0 =+ if decimalExponent > 19 then invalid else Right (coefficientValue * 10 ^ decimalExponent)+ | otherwise = divide (negate (toInteger decimalExponent)) coefficientValue+ where+ coefficientValue = coefficient number+ decimalExponent = base10Exponent number+ invalid = Left (InvalidMetadataJson "metadata integer required or outside bounds")+ divide 0 value = Right value+ divide remaining value = case quotRem value 10 of+ (next, 0) -> divide (remaining - 1) next+ _ -> invalid++-- | Convert a metadatum to ordinary JSON, matching cardano-c's plain JSON+-- schema: integers, text, arrays and objects with text keys. Bytes, nontext map+-- keys and duplicate object keys return 'InvalidMetadataJson' instead of losing+-- information. Object member ordering is not preserved by JSON. Integer output+-- retains the full metadata range, including negatives below -2^63 which the+-- native plain JSON importer does not accept. Use detailed JSON for all metadata+-- alternatives and exact ordered map pairs.+metadatumToJson :: Metadatum -> Either Error Value+metadatumToJson value = case view value of+ IntegerValue number -> Right (Number (fromInteger number))+ TextValue text -> Right (String text)+ BytesValue _ -> Left (InvalidMetadataJson "Plain JSON cannot represent metadata bytes")+ ListValue values -> toJSON <$> traverse metadatumToJson values+ MapValue pairs -> do+ entries <- traverse pair pairs+ let fields = KeyMap.fromList entries+ if KeyMap.size fields == length entries+ then Right (Object fields)+ else Left (InvalidMetadataJson "Plain JSON cannot preserve duplicate metadata map keys")+ where+ pair (key, item) = case view key of+ TextValue text -> (,) (Key.fromText text) <$> metadatumToJson item+ _ -> Left (InvalidMetadataJson "Plain JSON metadata map keys must be text")++-- | Import ordinary JSON as metadata, matching native plain JSON conversion.+-- Strings stay text, including @0x@ prefixes; object keys stay text, including+-- decimal names. Objects assemble pairs in lexicographic key order. Integers+-- must be in -2^63 through 2^64-1; fractions, booleans and null return+-- 'InvalidMetadataJson'. Text and object keys retain the 64 UTF-8 byte bound.+-- Invalid integer/text lengths return their existing metadata validation errors.+-- This is not cardano-api's no-schema conversion, which infers bytes and numeric+-- keys. Use 'metadatumFromDetailedJson' when those distinctions are needed.+metadatumFromJson :: Value -> Either Error Metadatum+metadatumFromJson json = case json of+ Number number -> do+ integer <- scientificInteger number+ if integer < toInteger (minBound :: Int64)+ then Left (InvalidMetadataJson "Plain JSON integer is below native signed 64-bit range")+ else mkInteger integer+ String text -> mkText text+ Array values -> list <$> traverse metadatumFromJson (Data.Foldable.toList values)+ Object fields -> Cometa.Metadata.map <$> traverse pair (KeyMap.toAscList fields)+ _ -> Left (InvalidMetadataJson "Plain JSON metadata accepts integers, text, arrays and objects")+ where+ pair (key, item) = (,) <$> mkText (Key.toText key) <*> metadatumFromJson item
@@ -0,0 +1,61 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Four-bit Shelley network identifiers, distinct from network magic.+--+-- @+-- import qualified Cometa.NetworkId as Network+--+-- network :: Network.NetworkId+-- network = Network.testnet+-- @+module Cometa.NetworkId (NetworkId, mkNetworkId, networkIdValue, mainnet, testnet) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (InvalidNetworkId))+import Data.Word (Word8)++-- TYPES ----------------------------------------------------------------------++-- | Four-bit network tag, 0 through 15. Tag 1 denotes mainnet; every other+-- tag uses the test-network Bech32 prefix. This tag is not a network magic.+-- Equality and ordering compare the number; 'Show' is diagnostic.+-- 'minBound' is 0 and 'maxBound' is 15.+newtype NetworkId = NetworkId Word8 deriving (Eq, Ord, Show)++instance Bounded NetworkId where+ minBound = NetworkId 0+ maxBound = NetworkId 15++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate a network tag. Values outside 0..15 return 'InvalidNetworkId'.+mkNetworkId :: Integer -> Either Error NetworkId+mkNetworkId value+ | value < 0 || value > 15 = Left (InvalidNetworkId value)+ | otherwise = Right (NetworkId (fromInteger value))++-- | Numeric four-bit tag.+networkIdValue :: NetworkId -> Word8+networkIdValue (NetworkId value) = value++-- | Mainnet tag 1.+mainnet :: NetworkId+mainnet = NetworkId 1++-- | Conventional test-network tag 0. Does not distinguish preview or preprod.+testnet :: NetworkId+testnet = NetworkId 0
@@ -0,0 +1,54 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Named protocol network magics. These are full 32-bit values, distinct from+-- the four-bit Shelley address tag in "Cometa.NetworkId". Custom networks can+-- use any 'Word32'; these constants do not select a provider or a network endpoint.+module Cometa.NetworkMagic (mainnet, preprod, preview, sanchonet, name) where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)+import Data.Word (Word32)++-- DEFINITIONS ----------------------------------------------------------------++-- | Cardano mainnet protocol magic, 764824073.+mainnet :: Word32+mainnet = 764824073++-- | Preprod protocol magic, 1.+preprod :: Word32+preprod = 1++-- | Preview protocol magic, 2.+preview :: Word32+preview = 2++-- | SanchoNet protocol magic, 4. A protocol identifier does not imply that a+-- hosted endpoint is currently available.+sanchonet :: Word32+sanchonet = 4++-- | Lowercase name for the four known magics, or @"unknown"@ for any other+-- value. Custom magic numbers remain valid even when they have no known name.+name :: Word32 -> Text+name value+ | value == mainnet = "mainnet"+ | value == preprod = "preprod"+ | value == preview = "preview"+ | value == sanchonet = "sanchonet"+ | otherwise = "unknown"
@@ -0,0 +1,256 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Assemble Plutus script arguments and datums as immutable Haskell values.+-- Maps preserve entry order and duplicate keys. Decode external datum CBOR into+-- 'EncodedPlutusData' to preserve the bytes that determine its hash.+--+-- @+-- import qualified Cometa.PlutusData as Data+--+-- main :: IO ()+-- main = print =<< Data.hash (Data.fromData (Data.Constr 0 [Data.Integer 42]))+-- @+module Cometa.PlutusData+ ( -- * Semantic data+ PlutusData (..),++ -- * CBOR and encoding identity+ EncodedPlutusData,+ encodeCbor,+ decodeCbor,+ fromData,+ integerFromText,+ toData,+ toCbor,++ -- * Datum hash+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Crypto.Blake2b (Blake2bHash)+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Encoding.Integer as Integer+import Cometa.Error (Error (..))+import Control.Monad (replicateM, unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Maybe (isNothing)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Semantic script data. Equality and ordering are structural: map entry order+-- and duplicates participate. Ordering follows constructor order, then payloads;+-- it does not define ledger map normalization.+data PlutusData+ = -- | Constructor alternative (0 through 2^64 - 1) and ordered fields.+ Constr Word64 [PlutusData]+ | -- | Ordered key/value pairs, including duplicate keys.+ Map [(PlutusData, PlutusData)]+ | -- | Ordered elements.+ List [PlutusData]+ | -- | An arbitrary-precision signed integer.+ Integer Integer+ | -- | Arbitrary bytes, including the empty byte string.+ Bytes ByteString+ deriving (Eq, Ord, Show)++-- | Valid script data together with its exact CBOR identity. Equality and+-- ordering compare the original encoded bytes; inspect 'toData' for semantic+-- comparison. 'Show' is diagnostic and is not an interchange format.+data EncodedPlutusData = EncodedPlutusData !ByteString !PlutusData+ deriving (Show)++instance Eq EncodedPlutusData where+ left == right = toCbor left == toCbor right++instance Ord EncodedPlutusData where+ compare left right = compare (toCbor left) (toCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | Parse an arbitrary-precision integer using a validated native-compatible+-- radix and assemble its fresh script-data encoding. No ledger metadata bounds+-- apply. Invalid text returns 'Cometa.Error.InvalidIntegerText'.+integerFromText :: Integer.Radix -> Text -> Either Error EncodedPlutusData+integerFromText radix text = fromData . Integer <$> Integer.fromText radix text++-- | Serialize fresh semantic data with shortest integer/tag encodings, definite+-- lists and maps, and byte chunks of at most 64 bytes. Map order and duplicates+-- are retained. Re-encoding inspected external data may change its datum hash;+-- use 'toCbor' to preserve an existing encoding.+encodeCbor :: PlutusData -> ByteString+encodeCbor = Write.toStrictByteString . encodeData++-- | Decode exactly one complete datum, accepting definite and indefinite lists,+-- maps and byte strings, nonminimal integer encodings, and constructor tags+-- 121..127, 1280..1400 and 102. Each definite byte leaf/chunk must contain at+-- most 64 bytes, including bignum payloads. Invalid input or trailing bytes+-- returns 'InvalidPlutusDataCbor'. The original bytes are retained unchanged.+decodeCbor :: ByteString -> Either Error EncodedPlutusData+decodeCbor bytes = case Read.deserialiseFromBytes decodeData (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidPlutusDataCbor (Text.pack (show failure)))+ Right (remaining, value)+ | Lazy.null remaining -> Right (EncodedPlutusData bytes value)+ | otherwise -> Left (InvalidPlutusDataCbor "Trailing bytes after Plutus data")++-- | Give fresh semantic data a newly serialized encoding identity.+fromData :: PlutusData -> EncodedPlutusData+fromData value = EncodedPlutusData (encodeCbor value) value++-- | Inspect semantic data without modifying its preserved encoding.+toData :: EncodedPlutusData -> PlutusData+toData (EncodedPlutusData _ value) = value++-- | Observe the exact original encoding, or the encoding assigned by 'fromData'.+toCbor :: EncodedPlutusData -> ByteString+toCbor (EncodedPlutusData bytes _) = bytes++-- | Compute the 32-byte BLAKE2b datum digest over the exact preserved CBOR.+-- Native allocation and operation failures return 'NativeError'.+hash :: EncodedPlutusData -> IO (Either Error Blake2bHash)+hash = Blake2b.compute 32 . toCbor++encodeData :: PlutusData -> Encode.Encoding+encodeData value = case value of+ Constr alternative fields+ | alternative < 7 -> Encode.encodeTag64 (121 + alternative) <> encodeList fields+ | alternative < 128 -> Encode.encodeTag64 (1280 + alternative - 7) <> encodeList fields+ | otherwise -> Encode.encodeTag 102 <> Encode.encodeListLen 2 <> Encode.encodeWord64 alternative <> encodeList fields+ Map pairs -> Encode.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, item) -> encodeData key <> encodeData item) pairs+ List values -> encodeList values+ Integer number+ | number >= negate (2 ^ (64 :: Int)), number < 2 ^ (64 :: Int) -> Encode.encodeInteger number+ | number >= 0 -> Encode.encodeTag 2 <> encodeBytes (integerBytes number)+ | otherwise -> Encode.encodeTag 3 <> encodeBytes (integerBytes (-1 - number))+ Bytes bytes -> encodeBytes bytes++encodeList :: [PlutusData] -> Encode.Encoding+encodeList values = Encode.encodeListLen (fromIntegral (length values)) <> foldMap encodeData values++encodeBytes :: ByteString -> Encode.Encoding+encodeBytes bytes+ | ByteString.length bytes <= 64 = Encode.encodeBytes bytes+ | otherwise = Encode.encodeBytesIndef <> chunks bytes <> Encode.encodeBreak+ where+ chunks remaining+ | ByteString.null remaining = mempty+ | otherwise = let (chunk, rest) = ByteString.splitAt 64 remaining in Encode.encodeBytes chunk <> chunks rest++integerBytes :: Integer -> ByteString+integerBytes = ByteString.reverse . ByteString.unfoldr step+ where+ step 0 = Nothing+ step number = Just (fromIntegral (number `mod` 256), number `div` 256)++decodeData :: Decode.Decoder s PlutusData+decodeData = do+ token <- Decode.peekTokenType+ case token of+ Decode.TypeUInt -> Integer <$> Decode.decodeInteger+ Decode.TypeUInt64 -> Integer <$> Decode.decodeInteger+ Decode.TypeNInt -> Integer <$> Decode.decodeInteger+ Decode.TypeNInt64 -> Integer <$> Decode.decodeInteger+ Decode.TypeInteger -> decodeTagged+ Decode.TypeBytes -> Bytes <$> decodeBytes+ Decode.TypeBytesIndef -> Bytes <$> decodeBytes+ Decode.TypeListLen -> List <$> decodeList+ Decode.TypeListLen64 -> List <$> decodeList+ Decode.TypeListLenIndef -> List <$> decodeList+ Decode.TypeMapLen -> Map <$> decodeMap+ Decode.TypeMapLen64 -> Map <$> decodeMap+ Decode.TypeMapLenIndef -> Map <$> decodeMap+ Decode.TypeTag -> decodeTagged+ Decode.TypeTag64 -> decodeTagged+ _ -> fail "Expected Plutus constructor, map, list, integer or bytes"++decodeTagged :: Decode.Decoder s PlutusData+decodeTagged = do+ tag <- Decode.decodeTag64+ case tag of+ 2 -> Integer . bytesInteger <$> decodeBytes+ 3 -> Integer . (-1 -) . bytesInteger <$> decodeBytes+ 102 -> do+ size <- Decode.decodeListLenOrIndef+ unless (isNothing size || size == Just 2) (fail "Extended constructor requires exactly two elements")+ alternative <- Decode.decodeWord64+ fields <- decodeList+ case size of+ Nothing -> do+ done <- Decode.decodeBreakOr+ unless done (fail "Extended constructor requires exactly two elements")+ Just _ -> pure ()+ pure (Constr alternative fields)+ _+ | tag >= 121 && tag <= 127 -> Constr (tag - 121) <$> decodeList+ | tag >= 1280 && tag <= 1400 -> Constr (tag - 1280 + 7) <$> decodeList+ | otherwise -> fail "Unknown Plutus constructor tag"++bytesInteger :: ByteString -> Integer+bytesInteger = ByteString.foldl' (\number byte -> number * 256 + fromIntegral byte) 0++decodeBytes :: Decode.Decoder s ByteString+decodeBytes = do+ token <- Decode.peekTokenType+ case token of+ Decode.TypeBytes -> boundedBytes+ Decode.TypeBytesIndef -> do+ Decode.decodeBytesIndef+ ByteString.concat <$> indefinite boundedBytes+ _ -> fail "Expected byte string"+ where+ boundedBytes = do+ bytes <- Decode.decodeBytes+ unless (ByteString.length bytes <= 64) (fail "Plutus byte chunk exceeds 64 bytes")+ pure bytes++decodeList :: Decode.Decoder s [PlutusData]+decodeList = do+ size <- Decode.decodeListLenOrIndef+ case size of+ Nothing -> indefinite decodeData+ Just count -> replicateM count decodeData++decodeMap :: Decode.Decoder s [(PlutusData, PlutusData)]+decodeMap = do+ size <- Decode.decodeMapLenOrIndef+ case size of+ Nothing -> indefinite pair+ Just count -> replicateM count pair+ where+ pair = (,) <$> decodeData <*> decodeData++indefinite :: Decode.Decoder s value -> Decode.Decoder s [value]+indefinite decoder = go []+ where+ go accumulated = do+ done <- Decode.decodeBreakOr+ if done+ then pure (reverse accumulated)+ else do+ value <- decoder+ go (value : accumulated)
@@ -0,0 +1,81 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Validated 28-byte native-asset policy identifiers.+-- Import assigns an identifier; it does not execute or hash a policy script.+--+-- @+-- import qualified Cometa.Credential as Credential+-- import qualified Cometa.PolicyId as PolicyId+--+-- policy :: Credential.ScriptHash -> PolicyId.PolicyId+-- policy = PolicyId.fromScriptHash+-- @+module Cometa.PolicyId+ ( PolicyId,+ fromBytes,+ toBytes,+ fromHex,+ toHex,+ fromScriptHash,+ toScriptHash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | A 28-byte script-policy hash. Equality and ordering compare bytes+-- lexicographically. 'Show' is diagnostic output.+newtype PolicyId = PolicyId Credential.ScriptHash deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 28 bytes. Other lengths return 'InvalidPolicyIdLength'+-- with the actual byte count. This does not compute a script hash.+fromBytes :: ByteString -> Either Error PolicyId+fromBytes bytes+ | ByteString.length bytes /= 28 = Left (InvalidPolicyIdLength (ByteString.length bytes))+ | otherwise = PolicyId <$> Credential.scriptHashFromBytes bytes++-- | Exact policy-hash bytes.+toBytes :: PolicyId -> ByteString+toBytes = Credential.scriptHashBytes . toScriptHash++-- | Import exactly 56 ASCII hexadecimal digits, accepting either case.+-- Malformed hexadecimal returns 'InvalidHex'; valid hex of another byte length+-- returns 'InvalidPolicyIdLength', including empty input.+fromHex :: Text -> Either Error PolicyId+fromHex text = maybe (Left InvalidHex) fromBytes (Hex.decodeHex text)++-- | Lowercase hexadecimal without a prefix, always 56 digits.+toHex :: PolicyId -> Text+toHex = Hex.encodeHex . toBytes++-- | Assign an already validated script hash as a minting-policy identifier.+fromScriptHash :: Credential.ScriptHash -> PolicyId+fromScriptHash = PolicyId++-- | The script hash identifying this policy.+toScriptHash :: PolicyId -> Credential.ScriptHash+toScriptHash (PolicyId scriptHash) = scriptHash
@@ -0,0 +1,49 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Stake-pool BLS public keys and proofs of possession. Validation checks+-- byte lengths only; it does not authenticate the key or verify its proof.+--+-- @mkBlsKey publicKey proof@ validates 96 key bytes and 48 proof bytes.+module Cometa.Pool.BlsKey+ ( BlsKey,+ mkBlsKey,+ publicKeyBytes,+ possessionProofBytes,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.Pool (BlsKey, mkBlsKey, possessionProofBytes, publicKeyBytes)+import qualified Cometa.Internal.Pool as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR with shortest integer encodings.+-- Re-encoding semantic data may change transaction identity.+encodeCbor :: BlsKey -> ByteString+encodeCbor = Internal.encode Internal.blsEncoding++-- | Decode the complete value. Definite or indefinite arrays and+-- nonminimal unsigned integers are accepted. All field bounds, arities, UTF-8+-- and trailing bytes are checked; violations return+-- 'Cometa.Error.InvalidPoolCbor'. The original encoding is not retained.+decodeCbor :: ByteString -> Either Error BlsKey+decodeCbor = Internal.decodeComplete Internal.blsDecoder
@@ -0,0 +1,62 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Off-chain stake-pool metadata references. Locations are not fetched.+-- Validate external input once, then assemble with the total constructor.+--+-- @Metadata location digest@ associates a location with its expected hash.+module Cometa.Pool.Metadata+ ( Url,+ mkUrl,+ urlText,+ MetadataHash,+ metadataHashFromBytes,+ metadataHashBytes,+ Metadata (..),+ hashData,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error)+import Cometa.Internal.Pool (Metadata (..), MetadataHash, Url, metadataHashBytes, metadataHashFromBytes, mkUrl, urlText)+import qualified Cometa.Internal.Pool as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR with shortest integer encodings.+-- Re-encoding semantic data may change transaction identity.+encodeCbor :: Metadata -> ByteString+encodeCbor = Internal.encode Internal.metadataEncoding++-- | Decode the complete value. Definite or indefinite arrays and+-- nonminimal unsigned integers are accepted. All field bounds, arities, UTF-8+-- and trailing bytes are checked; violations return+-- 'Cometa.Error.InvalidPoolCbor'. The original encoding is not retained.+decodeCbor :: ByteString -> Either Error Metadata+decodeCbor = Internal.decodeComplete Internal.metadataDecoder++-- | Compute the BLAKE2b-256 digest of the exact metadata payload bytes. No+-- JSON parsing or normalization occurs. Empty input or native hashing failures+-- return 'Cometa.Error.NativeError', following the BLAKE2b boundary.+hashData :: ByteString -> IO (Either Error MetadataHash)+hashData bytes = do+ result <- Blake2b.compute 32 bytes+ pure (result >>= metadataHashFromBytes . Blake2b.toBytes)
@@ -0,0 +1,71 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Typed stake-pool registration parameters. Validate hashes, relays,+-- metadata and margin once, then assemble or update the record without effects.+--+-- @parameters { metadata = Nothing }@ removes an optional metadata reference.+module Cometa.Pool.Parameters+ ( PoolParameters (..),+ VrfKeyHash,+ vrfKeyHashFromBytes,+ vrfKeyHashBytes,+ requiresOwnerWitnesses,+ encodeCbor,+ encodeCborWith,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error)+import Cometa.Internal.Pool (PoolParameters (..), VrfKeyHash, vrfKeyHashBytes, vrfKeyHashFromBytes)+import qualified Cometa.Internal.Pool as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR array containing the nine pool fields, or ten when+-- a BLS key is present after the VRF hash. Owners are sorted and tagged 258;+-- relay order and duplicates remain. Re-encoding semantic data may change+-- transaction identity.+encodeCbor :: PoolParameters -> ByteString+encodeCbor = Internal.encode Internal.parametersValueEncoding++-- | Fresh definite parameters with the requested tag on the sorted owner set.+-- Other fields use their usual encoding. This re-encodes semantic data; it is+-- not an edit to an imported transaction's exact bytes.+encodeCborWith :: SetEncoding -> PoolParameters -> ByteString+encodeCborWith requested = Internal.encode (Internal.parametersValueEncodingWith requested)++-- | Decode the complete array. Definite or indefinite arrays and+-- nonminimal unsigned integers are accepted. All field bounds, arities, UTF-8+-- and trailing bytes are checked; violations return+-- 'Cometa.Error.InvalidPoolCbor'. The original encoding is not retained.+-- Duplicate owners are rejected; untagged owner sets are accepted.+-- A null BLS placeholder is accepted and omitted on re-encoding.+decodeCbor :: ByteString -> Either Error PoolParameters+decodeCbor = Internal.decodeComplete Internal.parametersValueDecoder++-- | Whether a registration needs owner witnesses from protocol version 12.+-- Supply the latest registered parameters, preferring pending over active ones.+-- Unknown pools require owners. BLS-only changes, owner ordering and equivalent+-- margins do not affect this comparison. The operator remains required separately.+requiresOwnerWitnesses :: PoolParameters -> Maybe PoolParameters -> Bool+requiresOwnerWitnesses _ Nothing = True+requiresOwnerWitnesses proposed (Just latest) =+ proposed {blsKey = Nothing} /= latest {blsKey = Nothing}
@@ -0,0 +1,74 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Stake-pool relays with validated network-order addresses and DNS text.+-- Ports and addresses may legitimately be absent.+--+-- @SingleHostAddress Nothing Nothing Nothing@ represents an unspecified relay.+module Cometa.Pool.Relay+ ( Ipv4,+ ipv4FromBytes,+ ipv4Bytes,+ ipv4FromText,+ ipv4Text,+ Ipv6,+ ipv6FromBytes,+ ipv6Bytes,+ ipv6FromText,+ ipv6Text,+ DnsName,+ mkDnsName,+ dnsNameText,+ Relay (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.Pool+ ( DnsName,+ Ipv4,+ Ipv6,+ Relay (..),+ dnsNameText,+ ipv4Bytes,+ ipv4FromBytes,+ ipv4FromText,+ ipv4Text,+ ipv6Bytes,+ ipv6FromBytes,+ ipv6FromText,+ ipv6Text,+ mkDnsName,+ )+import qualified Cometa.Internal.Pool as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Fresh definite CBOR with shortest integer encodings.+-- Re-encoding semantic data may change transaction identity.+encodeCbor :: Relay -> ByteString+encodeCbor = Internal.encode Internal.relayEncoding++-- | Decode the complete value. Definite or indefinite arrays and+-- nonminimal unsigned integers are accepted. All field bounds, arities, UTF-8+-- and trailing bytes are checked; violations return+-- 'Cometa.Error.InvalidPoolCbor'. The original encoding is not retained.+decodeCbor :: ByteString -> Either Error Relay+decodeCbor = Internal.decodeComplete Internal.relayDecoder
@@ -0,0 +1,102 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Plutus cost models keyed by raw ledger language identifier.+-- Unknown identifiers are retained. Parameter vectors preserve order and signed+-- 64-bit costs; evaluator validity is a separate concern.+--+-- @mkCostModel 0 [1, 2, 3]@ validates a three-parameter vector.+module Cometa.Protocol.CostModels+ ( CostModel,+ mkCostModel,+ languageId,+ costs,+ CostModels,+ empty,+ fromList,+ insert,+ lookup,+ toList,+ encodeCostModelCbor,+ decodeCostModelCbor,+ encodeCbor,+ encodeLanguageViews,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.CostModels (CostModel, CostModels, costs, languageId, mkCostModel)+import qualified Cometa.Internal.CostModels as Model+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)+import qualified Data.List as List+import qualified Data.Map.Strict as Map+import Data.Word (Word8)+import Prelude hiding (lookup)++-- DEFINITIONS ----------------------------------------------------------------++-- | No configured language models.+empty :: CostModels+empty = Model.CostModels Map.empty++-- | Assemble models. Later models replace earlier models with the same language.+fromList :: [CostModel] -> CostModels+fromList = List.foldl' (flip insert) empty++-- | Replace the model for this language, preserving every other model.+insert :: CostModel -> CostModels -> CostModels+insert model (Model.CostModels models) = Model.CostModels (Map.insert (languageId model) model models)++-- | Find a model by raw language identifier, including unknown future languages.+lookup :: Word8 -> CostModels -> Maybe CostModel+lookup language (Model.CostModels models) = Map.lookup language models++-- | Models in ascending language-id order.+toList :: CostModels -> [CostModel]+toList (Model.CostModels models) = Map.elems models++-- | Encode only the ordered cost array. The language is supplied by the enclosing+-- ledger map and is deliberately absent from this encoding.+encodeCostModelCbor :: CostModel -> ByteString+encodeCostModelCbor = Internal.encodeBytes Model.encodeCostArray++-- | Decode one cost array for the supplied raw language id. Enforce signed 64-bit+-- costs and the 2048-parameter bound; reject trailing data.+decodeCostModelCbor :: Word8 -> ByteString -> Either Error CostModel+decodeCostModelCbor language = Internal.decodeBytes (Model.decodeCostArray language)++-- | Encode a ledger map in ascending language-id order.+encodeCbor :: CostModels -> ByteString+encodeCbor = Internal.encodeBytes Model.encodeCostModels++-- | Decode exactly one map. Duplicate language keys are rejected;+-- indefinite maps and arrays are accepted. Invalid values return+-- 'Cometa.Error.InvalidProtocolCbor'.+decodeCbor :: ByteString -> Either Error CostModels+decodeCbor = Internal.decodeBytes Model.decodeCostModels++-- | Encode the script-integrity language-view map for known Plutus languages+-- V1 through V4 (identifiers 0 through 3). Unknown language identifiers are+-- omitted from the script-data commitment. Supply only languages+-- actually used by the transaction; this operation does not select them or+-- validate parameter counts for execution. V1 uses the historical bytestring+-- key and bytestring-wrapped indefinite cost array, after the other languages.+-- This encoding differs from the protocol parameter map returned by 'encodeCbor'.+encodeLanguageViews :: CostModels -> ByteString+encodeLanguageViews = Internal.encodeBytes Model.encodeLanguageViews
@@ -0,0 +1,44 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Governance approval proportions for DReps.+-- Each field is an exact validated unit interval.+--+-- @DRepVotingThresholds t t t t t t t t t t@ assembles uniform thresholds.+module Cometa.Protocol.DRepVotingThresholds+ ( DRepVotingThresholds (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.ProtocolValues (DRepVotingThresholds (..))+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: DRepVotingThresholds -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeDRepVotingThresholds++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error DRepVotingThresholds+decodeCbor = Internal.decodeBytes Internal.decodeDRepVotingThresholds
@@ -0,0 +1,44 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Exact lovelace prices per memory unit and CPU step.+-- Prices may exceed one lovelace. Serialization places memory before steps.+--+-- @ExUnitPrices price price@ assembles prices from validated fractions.+module Cometa.Protocol.ExUnitPrices+ ( ExUnitPrices (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.ProtocolValues (ExUnitPrices (..))+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: ExUnitPrices -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeExUnitPrices++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error ExUnitPrices+decodeCbor = Internal.decodeBytes Internal.decodeExUnitPrices
@@ -0,0 +1,45 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Script execution budgets in memory units and CPU steps.+-- Each component fits an unsigned 64-bit integer.+--+-- @ExUnits 14000000 10000000000@ assembles a validated machine budget.+module Cometa.Protocol.ExUnits+ ( ExUnits (..),+ mkExUnits,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.ProtocolValues (ExUnits (..), mkExUnits)+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: ExUnits -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeExUnits++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error ExUnits+decodeCbor = Internal.decodeBytes Internal.decodeExUnits
@@ -0,0 +1,206 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Typed protocol parameter snapshots. Era-dependent fields record availability;+-- there is no network-independent default. Sizes and money use unsigned bounded+-- integers, exact rational values never use floating point. This representation+-- includes historical and Dijkstra fields; construction does not validate+-- activation or governance rules of a particular ledger era. Assemble changes with+-- "Cometa.Protocol.Parameters.Update".+--+-- @+-- import qualified Cometa.Protocol.Parameters as Parameters+-- import Data.Word (Word64)+--+-- feeTerms :: Parameters.Parameters -> (Word64, Word64)+-- feeTerms snapshot =+-- (Parameters.parameterMinFeeA snapshot, Parameters.parameterMinFeeB snapshot)+-- @+module Cometa.Protocol.Parameters+ ( Parameters (..),+ Nonce,+ neutralNonce,+ mkNonce,+ nonceBytes,+ ReferenceScriptCostStride,+ mkReferenceScriptCostStride,+ referenceScriptCostStride,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.CostModels (CostModels)+import Cometa.Internal.ProtocolValues (DRepVotingThresholds, ExUnitPrices, ExUnits, NonNegativeRational, PoolVotingThresholds, ProtocolVersion, UnitInterval)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Word (Word16, Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | A complete snapshot. Record updates preserve validated field invariants.+-- Optional era-dependent fields distinguish unavailable parameters from present+-- values. For nullable fields, Just Nothing means present but unbounded/unset.+data Parameters = Parameters+ { -- | Linear transaction fee coefficient in lovelace per byte.+ parameterMinFeeA :: !Word64,+ -- | Constant transaction fee in lovelace.+ parameterMinFeeB :: !Word64,+ -- | Maximum block body size in bytes.+ parameterMaxBlockBodySize :: !Word64,+ -- | Maximum transaction size in bytes.+ parameterMaxTxSize :: !Word64,+ -- | Maximum block header size in bytes.+ parameterMaxBlockHeaderSize :: !Word64,+ -- | Stake credential registration deposit in lovelace.+ parameterKeyDeposit :: !Word64,+ -- | Pool registration deposit in lovelace.+ parameterPoolDeposit :: !Word64,+ -- | Maximum pool retirement interval in epochs.+ parameterMaxEpoch :: !Word64,+ -- | Desired number of stake pools.+ parameterDesiredPoolCount :: !Word64,+ -- | Nonnegative pool pledge influence factor.+ parameterPoolPledgeInfluence :: !NonNegativeRational,+ -- | Monetary expansion fraction per epoch.+ parameterExpansionRate :: !UnitInterval,+ -- | Treasury growth fraction per epoch.+ parameterTreasuryGrowthRate :: !UnitInterval,+ -- | Decentralization fraction; deprecated after Alonzo.+ parameterDecentralization :: !(Maybe UnitInterval),+ -- | Extra entropy nonce; deprecated after Alonzo.+ parameterExtraEntropy :: !(Maybe Nonce),+ -- | Major and minor protocol version; updates deprecated after Babbage.+ parameterProtocolVersion :: !ProtocolVersion,+ -- | Minimum pool cost in lovelace per epoch.+ parameterMinPoolCost :: !Word64,+ -- | Minimum UTxO charge in lovelace per byte.+ parameterAdaPerUtxoByte :: !(Maybe Word64),+ -- | Language-indexed execution cost models.+ parameterCostModels :: !(Maybe CostModels),+ -- | Execution memory and step prices in lovelace per unit.+ parameterExecutionCosts :: !(Maybe ExUnitPrices),+ -- | Maximum execution units per transaction.+ parameterMaxTxExUnits :: !(Maybe ExUnits),+ -- | Maximum execution units per block.+ parameterMaxBlockExUnits :: !(Maybe ExUnits),+ -- | Maximum serialized value size in bytes.+ parameterMaxValueSize :: !(Maybe Word64),+ -- | Collateral as an integer percentage of script fees.+ parameterCollateralPercentage :: !(Maybe Word64),+ -- | Maximum number of collateral inputs.+ parameterMaxCollateralInputs :: !(Maybe Word64),+ -- | Stake pool governance voting thresholds.+ parameterPoolVotingThresholds :: !(Maybe PoolVotingThresholds),+ -- | DRep governance voting thresholds.+ parameterDrepVotingThresholds :: !(Maybe DRepVotingThresholds),+ -- | Minimum constitutional committee membership count.+ parameterMinCommitteeSize :: !(Maybe Word64),+ -- | Maximum committee term in epochs.+ parameterCommitteeTermLimit :: !(Maybe Word64),+ -- | Governance action lifetime in epochs.+ parameterGovernanceActionValidityPeriod :: !(Maybe Word64),+ -- | Governance action deposit in lovelace.+ parameterGovernanceActionDeposit :: !(Maybe Word64),+ -- | DRep registration deposit in lovelace.+ parameterDrepDeposit :: !(Maybe Word64),+ -- | DRep inactivity interval in epochs.+ parameterDrepInactivityPeriod :: !(Maybe Word64),+ -- | Base reference script charge in lovelace per byte.+ parameterRefScriptCostPerByte :: !(Maybe NonNegativeRational),+ -- | Maximum reference script size per block in bytes; Dijkstra.+ parameterMaxRefScriptSizePerBlock :: !(Maybe Word32),+ -- | Maximum reference script size per transaction in bytes; Dijkstra.+ parameterMaxRefScriptSizePerTx :: !(Maybe Word32),+ -- | Positive reference script tier stride in bytes; Dijkstra.+ parameterRefScriptCostStride :: !(Maybe ReferenceScriptCostStride),+ -- | Reference script tier multiplier; Dijkstra.+ parameterRefScriptCostMultiplier :: !(Maybe NonNegativeRational),+ -- | Maximum pledge leverage; @Just Nothing@ selects an unbounded value.+ parameterMaxPledgeLeverage :: !(Maybe (Maybe NonNegativeRational)),+ -- | Minimum stake pool profit margin fraction; Dijkstra.+ parameterMinPoolMargin :: !(Maybe UnitInterval),+ -- | Leios announcement period in milliseconds.+ parameterLeiosAnnouncementPeriodLength :: !(Maybe Word32),+ -- | Leios voting period in milliseconds.+ parameterLeiosVotePeriodLength :: !(Maybe Word32),+ -- | Leios diffusion period in milliseconds.+ parameterLeiosDiffusionPeriodLength :: !(Maybe Word32),+ -- | Leios committee member count.+ parameterLeiosCommitteeSize :: !(Maybe Word16),+ -- | Leios quorum fraction of stake.+ parameterLeiosQuorumStakeThreshold :: !(Maybe UnitInterval),+ -- | Maximum endorser block references size in bytes.+ parameterMaxEndorserBlockReferencesSize :: !(Maybe Word32),+ -- | Maximum endorser block transactions size in bytes.+ parameterMaxEndorserBlockTxsSize :: !(Maybe Word32),+ -- | Maximum execution units per endorser block.+ parameterMaxEndorserBlockExecutionUnits :: !(Maybe ExUnits),+ -- | Maximum reference script size per endorser block in bytes.+ parameterMaxRefScriptSizePerEndorserBlock :: !(Maybe Word32),+ -- | Minimum Peras candidate block age in slots.+ parameterPerasMinCandidateBlockAge :: !(Maybe Word32),+ -- | Peras healing factor.+ parameterPerasHealingFactor :: !(Maybe NonNegativeRational),+ -- | Peras certificate boost.+ parameterPerasCertBoost :: !(Maybe Word16),+ -- | Target Peras committee member count.+ parameterPerasTargetCommitteeSize :: !(Maybe Word16),+ -- | Manual Peras bootstrap round; @Just Nothing@ selects no round.+ parameterPerasBootstrapRound :: !(Maybe (Maybe Word32)),+ -- | Peras quorum safety margin fraction.+ parameterPerasQuorumThresholdSafetyMargin :: !(Maybe UnitInterval),+ -- | Reference input charge in lovelace per multi-asset byte.+ parameterRefInputsCostPerMultiAssetByte :: !(Maybe Word64),+ -- | Reference input charge in lovelace per datum byte.+ parameterRefInputsCostPerDatumByte :: !(Maybe Word64)+ }+ deriving (Eq, Show)++-- | A neutral entropy contribution or a 32-byte nonce digest.+-- Equality compares the neutral alternative or exact digest bytes.+newtype Nonce = Nonce ByteString deriving (Eq, Ord, Show)++-- | The neutral nonce, encoded as @[0]@ in a parameter update.+neutralNonce :: Nonce+neutralNonce = Nonce ByteString.empty++-- | Validate a nonce digest of exactly 32 bytes. Wrong lengths return+-- 'InvalidProtocolNonceLength'; use 'neutralNonce' for neutral entropy.+mkNonce :: ByteString -> Either Error Nonce+mkNonce bytes+ | ByteString.length bytes == 32 = Right (Nonce bytes)+ | otherwise = Left (InvalidProtocolNonceLength (ByteString.length bytes))++-- | Inspect the digest; 'Nothing' denotes the neutral nonce.+nonceBytes :: Nonce -> Maybe ByteString+nonceBytes (Nonce bytes)+ | ByteString.null bytes = Nothing+ | otherwise = Just bytes++-- | A positive 32-bit reference script tier stride, measured in bytes.+newtype ReferenceScriptCostStride = ReferenceScriptCostStride Word32 deriving (Eq, Ord, Show)++-- | Validate a byte stride in @1..4294967295@ inclusive. Invalid inputs return+-- 'InvalidReferenceScriptCostStride'.+mkReferenceScriptCostStride :: Integer -> Either Error ReferenceScriptCostStride+mkReferenceScriptCostStride value+ | value >= 1 && value <= 4294967295 = Right (ReferenceScriptCostStride (fromInteger value))+ | otherwise = Left (InvalidReferenceScriptCostStride value)++-- | Inspect the positive byte stride.+referenceScriptCostStride :: ReferenceScriptCostStride -> Word32+referenceScriptCostStride (ReferenceScriptCostStride value) = value
@@ -0,0 +1,588 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Sparse typed changes to protocol parameters. 'Nothing' leaves a field+-- unchanged. For nullable leverage and bootstrap round, @Just Nothing@ explicitly+-- removes the bound or round. The original imported encoding is available+-- separately from fresh serialization, which may normalize representation.+--+-- @+-- import qualified Cometa.Protocol.Parameters.Update as Update+--+-- change :: Update.Update+-- change = Update.empty { Update.updateMinFeeB = Just 155381 }+-- @+module Cometa.Protocol.Parameters.Update+ ( Update (..),+ empty,+ apply,+ fromParameters,+ EncodedUpdate,+ encodeCbor,+ decodeCbor,+ toCbor,+ toUpdate,+ toPlutusData,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Error (Error (..))+import Cometa.Internal.CostModels (CostModels)+import qualified Cometa.Internal.CostModels as Models+import qualified Cometa.Internal.ParameterUpdate as Native+import Cometa.Internal.ProtocolValues (DRepVotingThresholds, ExUnitPrices, ExUnits, NonNegativeRational, PoolVotingThresholds, ProtocolVersion, UnitInterval)+import qualified Cometa.Internal.ProtocolValues as Values+import qualified Cometa.PlutusData as Data+import Cometa.Protocol.Parameters (Nonce, Parameters (..), ReferenceScriptCostStride)+import qualified Cometa.Protocol.Parameters as Parameters+import Control.Applicative ((<|>))+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString.Lazy as Lazy+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import qualified Data.Text as Text+import Data.Word (Word16, Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | Independent optional changes. All constituent values are validated once;+-- constructing or applying a change is pure and cannot fail. Construction+-- does not validate activation or governance rules of a particular ledger era.+data Update = Update+ { -- | Linear transaction fee coefficient in lovelace per byte.+ updateMinFeeA :: !(Maybe Word64),+ -- | Constant transaction fee in lovelace.+ updateMinFeeB :: !(Maybe Word64),+ -- | Maximum block body size in bytes.+ updateMaxBlockBodySize :: !(Maybe Word64),+ -- | Maximum transaction size in bytes.+ updateMaxTxSize :: !(Maybe Word64),+ -- | Maximum block header size in bytes.+ updateMaxBlockHeaderSize :: !(Maybe Word64),+ -- | Stake credential registration deposit in lovelace.+ updateKeyDeposit :: !(Maybe Word64),+ -- | Pool registration deposit in lovelace.+ updatePoolDeposit :: !(Maybe Word64),+ -- | Maximum pool retirement interval in epochs.+ updateMaxEpoch :: !(Maybe Word64),+ -- | Desired number of stake pools.+ updateDesiredPoolCount :: !(Maybe Word64),+ -- | Nonnegative pool pledge influence factor.+ updatePoolPledgeInfluence :: !(Maybe NonNegativeRational),+ -- | Monetary expansion fraction per epoch.+ updateExpansionRate :: !(Maybe UnitInterval),+ -- | Treasury growth fraction per epoch.+ updateTreasuryGrowthRate :: !(Maybe UnitInterval),+ -- | Decentralization fraction; deprecated after Alonzo.+ updateDecentralization :: !(Maybe UnitInterval),+ -- | Extra entropy nonce; deprecated after Alonzo.+ updateExtraEntropy :: !(Maybe Nonce),+ -- | Major and minor protocol version; updates deprecated after Babbage.+ updateProtocolVersion :: !(Maybe ProtocolVersion),+ -- | Minimum pool cost in lovelace per epoch.+ updateMinPoolCost :: !(Maybe Word64),+ -- | Minimum UTxO charge in lovelace per byte.+ updateAdaPerUtxoByte :: !(Maybe Word64),+ -- | Language-indexed execution cost models.+ updateCostModels :: !(Maybe CostModels),+ -- | Execution memory and step prices in lovelace per unit.+ updateExecutionCosts :: !(Maybe ExUnitPrices),+ -- | Maximum execution units per transaction.+ updateMaxTxExUnits :: !(Maybe ExUnits),+ -- | Maximum execution units per block.+ updateMaxBlockExUnits :: !(Maybe ExUnits),+ -- | Maximum serialized value size in bytes.+ updateMaxValueSize :: !(Maybe Word64),+ -- | Collateral as an integer percentage of script fees.+ updateCollateralPercentage :: !(Maybe Word64),+ -- | Maximum number of collateral inputs.+ updateMaxCollateralInputs :: !(Maybe Word64),+ -- | Stake pool governance voting thresholds.+ updatePoolVotingThresholds :: !(Maybe PoolVotingThresholds),+ -- | DRep governance voting thresholds.+ updateDrepVotingThresholds :: !(Maybe DRepVotingThresholds),+ -- | Minimum constitutional committee membership count.+ updateMinCommitteeSize :: !(Maybe Word64),+ -- | Maximum committee term in epochs.+ updateCommitteeTermLimit :: !(Maybe Word64),+ -- | Governance action lifetime in epochs.+ updateGovernanceActionValidityPeriod :: !(Maybe Word64),+ -- | Governance action deposit in lovelace.+ updateGovernanceActionDeposit :: !(Maybe Word64),+ -- | DRep registration deposit in lovelace.+ updateDrepDeposit :: !(Maybe Word64),+ -- | DRep inactivity interval in epochs.+ updateDrepInactivityPeriod :: !(Maybe Word64),+ -- | Base reference script charge in lovelace per byte.+ updateRefScriptCostPerByte :: !(Maybe NonNegativeRational),+ -- | Maximum reference script size per block in bytes; Dijkstra.+ updateMaxRefScriptSizePerBlock :: !(Maybe Word32),+ -- | Maximum reference script size per transaction in bytes; Dijkstra.+ updateMaxRefScriptSizePerTx :: !(Maybe Word32),+ -- | Positive reference script tier stride in bytes; Dijkstra.+ updateRefScriptCostStride :: !(Maybe ReferenceScriptCostStride),+ -- | Reference script tier multiplier; Dijkstra.+ updateRefScriptCostMultiplier :: !(Maybe NonNegativeRational),+ -- | Maximum pledge leverage; @Just Nothing@ selects an unbounded value.+ updateMaxPledgeLeverage :: !(Maybe (Maybe NonNegativeRational)),+ -- | Minimum stake pool profit margin fraction; Dijkstra.+ updateMinPoolMargin :: !(Maybe UnitInterval),+ -- | Leios announcement period in milliseconds.+ updateLeiosAnnouncementPeriodLength :: !(Maybe Word32),+ -- | Leios voting period in milliseconds.+ updateLeiosVotePeriodLength :: !(Maybe Word32),+ -- | Leios diffusion period in milliseconds.+ updateLeiosDiffusionPeriodLength :: !(Maybe Word32),+ -- | Leios committee member count.+ updateLeiosCommitteeSize :: !(Maybe Word16),+ -- | Leios quorum fraction of stake.+ updateLeiosQuorumStakeThreshold :: !(Maybe UnitInterval),+ -- | Maximum endorser block references size in bytes.+ updateMaxEndorserBlockReferencesSize :: !(Maybe Word32),+ -- | Maximum endorser block transactions size in bytes.+ updateMaxEndorserBlockTxsSize :: !(Maybe Word32),+ -- | Maximum execution units per endorser block.+ updateMaxEndorserBlockExecutionUnits :: !(Maybe ExUnits),+ -- | Maximum reference script size per endorser block in bytes.+ updateMaxRefScriptSizePerEndorserBlock :: !(Maybe Word32),+ -- | Minimum Peras candidate block age in slots.+ updatePerasMinCandidateBlockAge :: !(Maybe Word32),+ -- | Peras healing factor.+ updatePerasHealingFactor :: !(Maybe NonNegativeRational),+ -- | Peras certificate boost.+ updatePerasCertBoost :: !(Maybe Word16),+ -- | Target Peras committee member count.+ updatePerasTargetCommitteeSize :: !(Maybe Word16),+ -- | Manual Peras bootstrap round; @Just Nothing@ selects no round.+ updatePerasBootstrapRound :: !(Maybe (Maybe Word32)),+ -- | Peras quorum safety margin fraction.+ updatePerasQuorumThresholdSafetyMargin :: !(Maybe UnitInterval),+ -- | Reference input charge in lovelace per multi-asset byte.+ updateRefInputsCostPerMultiAssetByte :: !(Maybe Word64),+ -- | Reference input charge in lovelace per datum byte.+ updateRefInputsCostPerDatumByte :: !(Maybe Word64)+ }+ deriving (Eq, Show)++-- | A validated update with its exact original CBOR bytes. Equality and ordering+-- compare those bytes, so alternative encodings of the same change can differ.+data EncodedUpdate = EncodedUpdate !ByteString !Update deriving (Show)++instance Eq EncodedUpdate where+ EncodedUpdate a _ == EncodedUpdate b _ = a == b++instance Ord EncodedUpdate where+ compare (EncodedUpdate a _) (EncodedUpdate b _) = compare a b++-- CONSTRUCTION ---------------------------------------------------------------++-- | The empty change. Applying it preserves every parameter field.+empty :: Update+empty =+ Update+ { updateMinFeeA = Nothing,+ updateMinFeeB = Nothing,+ updateMaxBlockBodySize = Nothing,+ updateMaxTxSize = Nothing,+ updateMaxBlockHeaderSize = Nothing,+ updateKeyDeposit = Nothing,+ updatePoolDeposit = Nothing,+ updateMaxEpoch = Nothing,+ updateDesiredPoolCount = Nothing,+ updatePoolPledgeInfluence = Nothing,+ updateExpansionRate = Nothing,+ updateTreasuryGrowthRate = Nothing,+ updateDecentralization = Nothing,+ updateExtraEntropy = Nothing,+ updateProtocolVersion = Nothing,+ updateMinPoolCost = Nothing,+ updateAdaPerUtxoByte = Nothing,+ updateCostModels = Nothing,+ updateExecutionCosts = Nothing,+ updateMaxTxExUnits = Nothing,+ updateMaxBlockExUnits = Nothing,+ updateMaxValueSize = Nothing,+ updateCollateralPercentage = Nothing,+ updateMaxCollateralInputs = Nothing,+ updatePoolVotingThresholds = Nothing,+ updateDrepVotingThresholds = Nothing,+ updateMinCommitteeSize = Nothing,+ updateCommitteeTermLimit = Nothing,+ updateGovernanceActionValidityPeriod = Nothing,+ updateGovernanceActionDeposit = Nothing,+ updateDrepDeposit = Nothing,+ updateDrepInactivityPeriod = Nothing,+ updateRefScriptCostPerByte = Nothing,+ updateMaxRefScriptSizePerBlock = Nothing,+ updateMaxRefScriptSizePerTx = Nothing,+ updateRefScriptCostStride = Nothing,+ updateRefScriptCostMultiplier = Nothing,+ updateMaxPledgeLeverage = Nothing,+ updateMinPoolMargin = Nothing,+ updateLeiosAnnouncementPeriodLength = Nothing,+ updateLeiosVotePeriodLength = Nothing,+ updateLeiosDiffusionPeriodLength = Nothing,+ updateLeiosCommitteeSize = Nothing,+ updateLeiosQuorumStakeThreshold = Nothing,+ updateMaxEndorserBlockReferencesSize = Nothing,+ updateMaxEndorserBlockTxsSize = Nothing,+ updateMaxEndorserBlockExecutionUnits = Nothing,+ updateMaxRefScriptSizePerEndorserBlock = Nothing,+ updatePerasMinCandidateBlockAge = Nothing,+ updatePerasHealingFactor = Nothing,+ updatePerasCertBoost = Nothing,+ updatePerasTargetCommitteeSize = Nothing,+ updatePerasBootstrapRound = Nothing,+ updatePerasQuorumThresholdSafetyMargin = Nothing,+ updateRefInputsCostPerMultiAssetByte = Nothing,+ updateRefInputsCostPerDatumByte = Nothing+ }++-- | Apply all present fields to a complete snapshot, preserving absent fields.+apply :: Update -> Parameters -> Parameters+apply change current =+ Parameters+ { parameterMinFeeA = fromMaybe (parameterMinFeeA current) (updateMinFeeA change),+ parameterMinFeeB = fromMaybe (parameterMinFeeB current) (updateMinFeeB change),+ parameterMaxBlockBodySize = fromMaybe (parameterMaxBlockBodySize current) (updateMaxBlockBodySize change),+ parameterMaxTxSize = fromMaybe (parameterMaxTxSize current) (updateMaxTxSize change),+ parameterMaxBlockHeaderSize = fromMaybe (parameterMaxBlockHeaderSize current) (updateMaxBlockHeaderSize change),+ parameterKeyDeposit = fromMaybe (parameterKeyDeposit current) (updateKeyDeposit change),+ parameterPoolDeposit = fromMaybe (parameterPoolDeposit current) (updatePoolDeposit change),+ parameterMaxEpoch = fromMaybe (parameterMaxEpoch current) (updateMaxEpoch change),+ parameterDesiredPoolCount = fromMaybe (parameterDesiredPoolCount current) (updateDesiredPoolCount change),+ parameterPoolPledgeInfluence = fromMaybe (parameterPoolPledgeInfluence current) (updatePoolPledgeInfluence change),+ parameterExpansionRate = fromMaybe (parameterExpansionRate current) (updateExpansionRate change),+ parameterTreasuryGrowthRate = fromMaybe (parameterTreasuryGrowthRate current) (updateTreasuryGrowthRate change),+ parameterDecentralization = updateDecentralization change <|> parameterDecentralization current,+ parameterExtraEntropy = updateExtraEntropy change <|> parameterExtraEntropy current,+ parameterProtocolVersion = fromMaybe (parameterProtocolVersion current) (updateProtocolVersion change),+ parameterMinPoolCost = fromMaybe (parameterMinPoolCost current) (updateMinPoolCost change),+ parameterAdaPerUtxoByte = updateAdaPerUtxoByte change <|> parameterAdaPerUtxoByte current,+ parameterCostModels = updateCostModels change <|> parameterCostModels current,+ parameterExecutionCosts = updateExecutionCosts change <|> parameterExecutionCosts current,+ parameterMaxTxExUnits = updateMaxTxExUnits change <|> parameterMaxTxExUnits current,+ parameterMaxBlockExUnits = updateMaxBlockExUnits change <|> parameterMaxBlockExUnits current,+ parameterMaxValueSize = updateMaxValueSize change <|> parameterMaxValueSize current,+ parameterCollateralPercentage = updateCollateralPercentage change <|> parameterCollateralPercentage current,+ parameterMaxCollateralInputs = updateMaxCollateralInputs change <|> parameterMaxCollateralInputs current,+ parameterPoolVotingThresholds = updatePoolVotingThresholds change <|> parameterPoolVotingThresholds current,+ parameterDrepVotingThresholds = updateDrepVotingThresholds change <|> parameterDrepVotingThresholds current,+ parameterMinCommitteeSize = updateMinCommitteeSize change <|> parameterMinCommitteeSize current,+ parameterCommitteeTermLimit = updateCommitteeTermLimit change <|> parameterCommitteeTermLimit current,+ parameterGovernanceActionValidityPeriod = updateGovernanceActionValidityPeriod change <|> parameterGovernanceActionValidityPeriod current,+ parameterGovernanceActionDeposit = updateGovernanceActionDeposit change <|> parameterGovernanceActionDeposit current,+ parameterDrepDeposit = updateDrepDeposit change <|> parameterDrepDeposit current,+ parameterDrepInactivityPeriod = updateDrepInactivityPeriod change <|> parameterDrepInactivityPeriod current,+ parameterRefScriptCostPerByte = updateRefScriptCostPerByte change <|> parameterRefScriptCostPerByte current,+ parameterMaxRefScriptSizePerBlock = updateMaxRefScriptSizePerBlock change <|> parameterMaxRefScriptSizePerBlock current,+ parameterMaxRefScriptSizePerTx = updateMaxRefScriptSizePerTx change <|> parameterMaxRefScriptSizePerTx current,+ parameterRefScriptCostStride = updateRefScriptCostStride change <|> parameterRefScriptCostStride current,+ parameterRefScriptCostMultiplier = updateRefScriptCostMultiplier change <|> parameterRefScriptCostMultiplier current,+ parameterMaxPledgeLeverage = updateMaxPledgeLeverage change <|> parameterMaxPledgeLeverage current,+ parameterMinPoolMargin = updateMinPoolMargin change <|> parameterMinPoolMargin current,+ parameterLeiosAnnouncementPeriodLength = updateLeiosAnnouncementPeriodLength change <|> parameterLeiosAnnouncementPeriodLength current,+ parameterLeiosVotePeriodLength = updateLeiosVotePeriodLength change <|> parameterLeiosVotePeriodLength current,+ parameterLeiosDiffusionPeriodLength = updateLeiosDiffusionPeriodLength change <|> parameterLeiosDiffusionPeriodLength current,+ parameterLeiosCommitteeSize = updateLeiosCommitteeSize change <|> parameterLeiosCommitteeSize current,+ parameterLeiosQuorumStakeThreshold = updateLeiosQuorumStakeThreshold change <|> parameterLeiosQuorumStakeThreshold current,+ parameterMaxEndorserBlockReferencesSize = updateMaxEndorserBlockReferencesSize change <|> parameterMaxEndorserBlockReferencesSize current,+ parameterMaxEndorserBlockTxsSize = updateMaxEndorserBlockTxsSize change <|> parameterMaxEndorserBlockTxsSize current,+ parameterMaxEndorserBlockExecutionUnits = updateMaxEndorserBlockExecutionUnits change <|> parameterMaxEndorserBlockExecutionUnits current,+ parameterMaxRefScriptSizePerEndorserBlock = updateMaxRefScriptSizePerEndorserBlock change <|> parameterMaxRefScriptSizePerEndorserBlock current,+ parameterPerasMinCandidateBlockAge = updatePerasMinCandidateBlockAge change <|> parameterPerasMinCandidateBlockAge current,+ parameterPerasHealingFactor = updatePerasHealingFactor change <|> parameterPerasHealingFactor current,+ parameterPerasCertBoost = updatePerasCertBoost change <|> parameterPerasCertBoost current,+ parameterPerasTargetCommitteeSize = updatePerasTargetCommitteeSize change <|> parameterPerasTargetCommitteeSize current,+ parameterPerasBootstrapRound = updatePerasBootstrapRound change <|> parameterPerasBootstrapRound current,+ parameterPerasQuorumThresholdSafetyMargin = updatePerasQuorumThresholdSafetyMargin change <|> parameterPerasQuorumThresholdSafetyMargin current,+ parameterRefInputsCostPerMultiAssetByte = updateRefInputsCostPerMultiAssetByte change <|> parameterRefInputsCostPerMultiAssetByte current,+ parameterRefInputsCostPerDatumByte = updateRefInputsCostPerDatumByte change <|> parameterRefInputsCostPerDatumByte current+ }++-- | Produce a change setting each available field, including explicit nulls.+-- Unavailable fields are omitted.+fromParameters :: Parameters -> Update+fromParameters current =+ Update+ { updateMinFeeA = Just (parameterMinFeeA current),+ updateMinFeeB = Just (parameterMinFeeB current),+ updateMaxBlockBodySize = Just (parameterMaxBlockBodySize current),+ updateMaxTxSize = Just (parameterMaxTxSize current),+ updateMaxBlockHeaderSize = Just (parameterMaxBlockHeaderSize current),+ updateKeyDeposit = Just (parameterKeyDeposit current),+ updatePoolDeposit = Just (parameterPoolDeposit current),+ updateMaxEpoch = Just (parameterMaxEpoch current),+ updateDesiredPoolCount = Just (parameterDesiredPoolCount current),+ updatePoolPledgeInfluence = Just (parameterPoolPledgeInfluence current),+ updateExpansionRate = Just (parameterExpansionRate current),+ updateTreasuryGrowthRate = Just (parameterTreasuryGrowthRate current),+ updateDecentralization = parameterDecentralization current,+ updateExtraEntropy = parameterExtraEntropy current,+ updateProtocolVersion = Just (parameterProtocolVersion current),+ updateMinPoolCost = Just (parameterMinPoolCost current),+ updateAdaPerUtxoByte = parameterAdaPerUtxoByte current,+ updateCostModels = parameterCostModels current,+ updateExecutionCosts = parameterExecutionCosts current,+ updateMaxTxExUnits = parameterMaxTxExUnits current,+ updateMaxBlockExUnits = parameterMaxBlockExUnits current,+ updateMaxValueSize = parameterMaxValueSize current,+ updateCollateralPercentage = parameterCollateralPercentage current,+ updateMaxCollateralInputs = parameterMaxCollateralInputs current,+ updatePoolVotingThresholds = parameterPoolVotingThresholds current,+ updateDrepVotingThresholds = parameterDrepVotingThresholds current,+ updateMinCommitteeSize = parameterMinCommitteeSize current,+ updateCommitteeTermLimit = parameterCommitteeTermLimit current,+ updateGovernanceActionValidityPeriod = parameterGovernanceActionValidityPeriod current,+ updateGovernanceActionDeposit = parameterGovernanceActionDeposit current,+ updateDrepDeposit = parameterDrepDeposit current,+ updateDrepInactivityPeriod = parameterDrepInactivityPeriod current,+ updateRefScriptCostPerByte = parameterRefScriptCostPerByte current,+ updateMaxRefScriptSizePerBlock = parameterMaxRefScriptSizePerBlock current,+ updateMaxRefScriptSizePerTx = parameterMaxRefScriptSizePerTx current,+ updateRefScriptCostStride = parameterRefScriptCostStride current,+ updateRefScriptCostMultiplier = parameterRefScriptCostMultiplier current,+ updateMaxPledgeLeverage = parameterMaxPledgeLeverage current,+ updateMinPoolMargin = parameterMinPoolMargin current,+ updateLeiosAnnouncementPeriodLength = parameterLeiosAnnouncementPeriodLength current,+ updateLeiosVotePeriodLength = parameterLeiosVotePeriodLength current,+ updateLeiosDiffusionPeriodLength = parameterLeiosDiffusionPeriodLength current,+ updateLeiosCommitteeSize = parameterLeiosCommitteeSize current,+ updateLeiosQuorumStakeThreshold = parameterLeiosQuorumStakeThreshold current,+ updateMaxEndorserBlockReferencesSize = parameterMaxEndorserBlockReferencesSize current,+ updateMaxEndorserBlockTxsSize = parameterMaxEndorserBlockTxsSize current,+ updateMaxEndorserBlockExecutionUnits = parameterMaxEndorserBlockExecutionUnits current,+ updateMaxRefScriptSizePerEndorserBlock = parameterMaxRefScriptSizePerEndorserBlock current,+ updatePerasMinCandidateBlockAge = parameterPerasMinCandidateBlockAge current,+ updatePerasHealingFactor = parameterPerasHealingFactor current,+ updatePerasCertBoost = parameterPerasCertBoost current,+ updatePerasTargetCommitteeSize = parameterPerasTargetCommitteeSize current,+ updatePerasBootstrapRound = parameterPerasBootstrapRound current,+ updatePerasQuorumThresholdSafetyMargin = parameterPerasQuorumThresholdSafetyMargin current,+ updateRefInputsCostPerMultiAssetByte = parameterRefInputsCostPerMultiAssetByte current,+ updateRefInputsCostPerDatumByte = parameterRefInputsCostPerDatumByte current+ }++-- CBOR -----------------------------------------------------------------------++-- | Serialize present fields in ascending parameter-key order, using definite+-- collections and minimal integer encodings. Rational pairs remain exact;+-- imported representation is preserved only by 'toCbor'.+encodeCbor :: Update -> ByteString+encodeCbor change = Write.toStrictByteString (Encode.encodeMapLen (fromIntegral (length entries)) <> mconcat entries)+ where+ entries =+ concat+ [ field 0 Encode.encodeWord64 (updateMinFeeA change),+ field 1 Encode.encodeWord64 (updateMinFeeB change),+ field 2 Encode.encodeWord64 (updateMaxBlockBodySize change),+ field 3 Encode.encodeWord64 (updateMaxTxSize change),+ field 4 Encode.encodeWord64 (updateMaxBlockHeaderSize change),+ field 5 Encode.encodeWord64 (updateKeyDeposit change),+ field 6 Encode.encodeWord64 (updatePoolDeposit change),+ field 7 Encode.encodeWord64 (updateMaxEpoch change),+ field 8 Encode.encodeWord64 (updateDesiredPoolCount change),+ field 9 Values.encodeRational (updatePoolPledgeInfluence change),+ field 10 Values.encodeUnitInterval (updateExpansionRate change),+ field 11 Values.encodeUnitInterval (updateTreasuryGrowthRate change),+ field 12 Values.encodeUnitInterval (updateDecentralization change),+ field 13 encodeNonce (updateExtraEntropy change),+ field 14 Values.encodeProtocolVersion (updateProtocolVersion change),+ field 16 Encode.encodeWord64 (updateMinPoolCost change),+ field 17 Encode.encodeWord64 (updateAdaPerUtxoByte change),+ field 18 Models.encodeCostModels (updateCostModels change),+ field 19 Values.encodeExUnitPrices (updateExecutionCosts change),+ field 20 Values.encodeExUnits (updateMaxTxExUnits change),+ field 21 Values.encodeExUnits (updateMaxBlockExUnits change),+ field 22 Encode.encodeWord64 (updateMaxValueSize change),+ field 23 Encode.encodeWord64 (updateCollateralPercentage change),+ field 24 Encode.encodeWord64 (updateMaxCollateralInputs change),+ field 25 Values.encodePoolVotingThresholds (updatePoolVotingThresholds change),+ field 26 Values.encodeDRepVotingThresholds (updateDrepVotingThresholds change),+ field 27 Encode.encodeWord64 (updateMinCommitteeSize change),+ field 28 Encode.encodeWord64 (updateCommitteeTermLimit change),+ field 29 Encode.encodeWord64 (updateGovernanceActionValidityPeriod change),+ field 30 Encode.encodeWord64 (updateGovernanceActionDeposit change),+ field 31 Encode.encodeWord64 (updateDrepDeposit change),+ field 32 Encode.encodeWord64 (updateDrepInactivityPeriod change),+ field 33 Values.encodeRational (updateRefScriptCostPerByte change),+ field 34 Encode.encodeWord32 (updateMaxRefScriptSizePerBlock change),+ field 35 Encode.encodeWord32 (updateMaxRefScriptSizePerTx change),+ field 36 (Encode.encodeWord32 . Parameters.referenceScriptCostStride) (updateRefScriptCostStride change),+ field 37 Values.encodeRational (updateRefScriptCostMultiplier change),+ field 38 (encodeNullable Values.encodeRational) (updateMaxPledgeLeverage change),+ field 39 Values.encodeUnitInterval (updateMinPoolMargin change),+ field 40 Encode.encodeWord32 (updateLeiosAnnouncementPeriodLength change),+ field 41 Encode.encodeWord32 (updateLeiosVotePeriodLength change),+ field 42 Encode.encodeWord32 (updateLeiosDiffusionPeriodLength change),+ field 43 Encode.encodeWord16 (updateLeiosCommitteeSize change),+ field 44 Values.encodeUnitInterval (updateLeiosQuorumStakeThreshold change),+ field 45 Encode.encodeWord32 (updateMaxEndorserBlockReferencesSize change),+ field 46 Encode.encodeWord32 (updateMaxEndorserBlockTxsSize change),+ field 47 Values.encodeExUnits (updateMaxEndorserBlockExecutionUnits change),+ field 48 Encode.encodeWord32 (updateMaxRefScriptSizePerEndorserBlock change),+ field 49 Encode.encodeWord32 (updatePerasMinCandidateBlockAge change),+ field 50 Values.encodeRational (updatePerasHealingFactor change),+ field 51 Encode.encodeWord16 (updatePerasCertBoost change),+ field 52 Encode.encodeWord16 (updatePerasTargetCommitteeSize change),+ field 53 (encodeNullable Encode.encodeWord32) (updatePerasBootstrapRound change),+ field 54 Values.encodeUnitInterval (updatePerasQuorumThresholdSafetyMargin change),+ field 55 Encode.encodeWord64 (updateRefInputsCostPerMultiAssetByte change),+ field 56 Encode.encodeWord64 (updateRefInputsCostPerDatumByte change)+ ]++-- | Decode one complete update, retaining exact bytes. Unknown or duplicate+-- parameter keys, invalid field bounds/arity, malformed CBOR and trailing input+-- return 'InvalidProtocolParametersCbor'. Historical fields are accepted without+-- applying era-specific governance validity rules.+decodeCbor :: ByteString -> Either Error EncodedUpdate+decodeCbor bytes = case Read.deserialiseFromBytes decodeUpdate (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidProtocolParametersCbor (Text.pack (show failure)))+ Right (trailing, change)+ | Lazy.null trailing -> Right (EncodedUpdate bytes change)+ | otherwise -> Left (InvalidProtocolParametersCbor "Trailing bytes after protocol update")++-- | Return the exact validated input encoding.+toCbor :: EncodedUpdate -> ByteString+toCbor (EncodedUpdate bytes _) = bytes++-- | Inspect the Haskell-owned change without altering its original encoding.+toUpdate :: EncodedUpdate -> Update+toUpdate (EncodedUpdate _ change) = change++field :: Word64 -> (a -> Encode.Encoding) -> Maybe a -> [Encode.Encoding]+field key encode = maybe [] (\value -> [Encode.encodeWord64 key <> encode value])++encodeNullable :: (a -> Encode.Encoding) -> Maybe a -> Encode.Encoding+encodeNullable = maybe Encode.encodeNull++encodeNonce :: Nonce -> Encode.Encoding+encodeNonce nonce = case Parameters.nonceBytes nonce of+ Nothing -> Encode.encodeListLen 1 <> Encode.encodeWord 0+ Just bytes -> Encode.encodeListLen 2 <> Encode.encodeWord 1 <> Encode.encodeBytes bytes++decodeNullable :: Decode.Decoder s a -> Decode.Decoder s (Maybe a)+decodeNullable decode = do+ token <- Decode.peekTokenType+ if token == Decode.TypeNull then Decode.decodeNull >> pure Nothing else Just <$> decode++decodeNonce :: Decode.Decoder s Nonce+decodeNonce = do+ size <- Decode.decodeListLen+ tag <- Decode.decodeWord+ case (size, tag) of+ (1, 0) -> pure Parameters.neutralNonce+ (2, 1) -> do+ bytes <- Decode.decodeBytes+ either (const (fail "Nonce digest must contain 32 bytes")) pure (Parameters.mkNonce bytes)+ _ -> fail "Invalid entropy nonce variant or arity"++decodeStride :: Decode.Decoder s ReferenceScriptCostStride+decodeStride = do+ value <- Decode.decodeWord32+ either (const (fail "Reference script cost stride must be positive")) pure (Parameters.mkReferenceScriptCostStride (toInteger value))++decodeUpdate :: Decode.Decoder s Update+decodeUpdate = do+ count <- Decode.decodeMapLenOrIndef+ go count Set.empty empty+ where+ go (Just 0) _ change = pure change+ go count seen change = do+ ended <- case count of+ Nothing -> Decode.decodeBreakOr+ Just _ -> pure False+ if ended+ then pure change+ else do+ key <- Decode.decodeWord64+ unless (Set.notMember key seen) (fail "Duplicate protocol parameter key")+ next <- case key of+ 0 -> (\value -> change {updateMinFeeA = Just value}) <$> Decode.decodeWord64+ 1 -> (\value -> change {updateMinFeeB = Just value}) <$> Decode.decodeWord64+ 2 -> (\value -> change {updateMaxBlockBodySize = Just value}) <$> Decode.decodeWord64+ 3 -> (\value -> change {updateMaxTxSize = Just value}) <$> Decode.decodeWord64+ 4 -> (\value -> change {updateMaxBlockHeaderSize = Just value}) <$> Decode.decodeWord64+ 5 -> (\value -> change {updateKeyDeposit = Just value}) <$> Decode.decodeWord64+ 6 -> (\value -> change {updatePoolDeposit = Just value}) <$> Decode.decodeWord64+ 7 -> (\value -> change {updateMaxEpoch = Just value}) <$> Decode.decodeWord64+ 8 -> (\value -> change {updateDesiredPoolCount = Just value}) <$> Decode.decodeWord64+ 9 -> (\value -> change {updatePoolPledgeInfluence = Just value}) <$> Values.decodeRational+ 10 -> (\value -> change {updateExpansionRate = Just value}) <$> Values.decodeUnitInterval+ 11 -> (\value -> change {updateTreasuryGrowthRate = Just value}) <$> Values.decodeUnitInterval+ 12 -> (\value -> change {updateDecentralization = Just value}) <$> Values.decodeUnitInterval+ 13 -> (\value -> change {updateExtraEntropy = Just value}) <$> decodeNonce+ 14 -> (\value -> change {updateProtocolVersion = Just value}) <$> Values.decodeProtocolVersion+ 16 -> (\value -> change {updateMinPoolCost = Just value}) <$> Decode.decodeWord64+ 17 -> (\value -> change {updateAdaPerUtxoByte = Just value}) <$> Decode.decodeWord64+ 18 -> (\value -> change {updateCostModels = Just value}) <$> Models.decodeCostModels+ 19 -> (\value -> change {updateExecutionCosts = Just value}) <$> Values.decodeExUnitPrices+ 20 -> (\value -> change {updateMaxTxExUnits = Just value}) <$> Values.decodeExUnits+ 21 -> (\value -> change {updateMaxBlockExUnits = Just value}) <$> Values.decodeExUnits+ 22 -> (\value -> change {updateMaxValueSize = Just value}) <$> Decode.decodeWord64+ 23 -> (\value -> change {updateCollateralPercentage = Just value}) <$> Decode.decodeWord64+ 24 -> (\value -> change {updateMaxCollateralInputs = Just value}) <$> Decode.decodeWord64+ 25 -> (\value -> change {updatePoolVotingThresholds = Just value}) <$> Values.decodePoolVotingThresholds+ 26 -> (\value -> change {updateDrepVotingThresholds = Just value}) <$> Values.decodeDRepVotingThresholds+ 27 -> (\value -> change {updateMinCommitteeSize = Just value}) <$> Decode.decodeWord64+ 28 -> (\value -> change {updateCommitteeTermLimit = Just value}) <$> Decode.decodeWord64+ 29 -> (\value -> change {updateGovernanceActionValidityPeriod = Just value}) <$> Decode.decodeWord64+ 30 -> (\value -> change {updateGovernanceActionDeposit = Just value}) <$> Decode.decodeWord64+ 31 -> (\value -> change {updateDrepDeposit = Just value}) <$> Decode.decodeWord64+ 32 -> (\value -> change {updateDrepInactivityPeriod = Just value}) <$> Decode.decodeWord64+ 33 -> (\value -> change {updateRefScriptCostPerByte = Just value}) <$> Values.decodeRational+ 34 -> (\value -> change {updateMaxRefScriptSizePerBlock = Just value}) <$> Decode.decodeWord32+ 35 -> (\value -> change {updateMaxRefScriptSizePerTx = Just value}) <$> Decode.decodeWord32+ 36 -> (\value -> change {updateRefScriptCostStride = Just value}) <$> decodeStride+ 37 -> (\value -> change {updateRefScriptCostMultiplier = Just value}) <$> Values.decodeRational+ 38 -> (\value -> change {updateMaxPledgeLeverage = Just value}) <$> decodeNullable Values.decodeRational+ 39 -> (\value -> change {updateMinPoolMargin = Just value}) <$> Values.decodeUnitInterval+ 40 -> (\value -> change {updateLeiosAnnouncementPeriodLength = Just value}) <$> Decode.decodeWord32+ 41 -> (\value -> change {updateLeiosVotePeriodLength = Just value}) <$> Decode.decodeWord32+ 42 -> (\value -> change {updateLeiosDiffusionPeriodLength = Just value}) <$> Decode.decodeWord32+ 43 -> (\value -> change {updateLeiosCommitteeSize = Just value}) <$> Decode.decodeWord16+ 44 -> (\value -> change {updateLeiosQuorumStakeThreshold = Just value}) <$> Values.decodeUnitInterval+ 45 -> (\value -> change {updateMaxEndorserBlockReferencesSize = Just value}) <$> Decode.decodeWord32+ 46 -> (\value -> change {updateMaxEndorserBlockTxsSize = Just value}) <$> Decode.decodeWord32+ 47 -> (\value -> change {updateMaxEndorserBlockExecutionUnits = Just value}) <$> Values.decodeExUnits+ 48 -> (\value -> change {updateMaxRefScriptSizePerEndorserBlock = Just value}) <$> Decode.decodeWord32+ 49 -> (\value -> change {updatePerasMinCandidateBlockAge = Just value}) <$> Decode.decodeWord32+ 50 -> (\value -> change {updatePerasHealingFactor = Just value}) <$> Values.decodeRational+ 51 -> (\value -> change {updatePerasCertBoost = Just value}) <$> Decode.decodeWord16+ 52 -> (\value -> change {updatePerasTargetCommitteeSize = Just value}) <$> Decode.decodeWord16+ 53 -> (\value -> change {updatePerasBootstrapRound = Just value}) <$> decodeNullable Decode.decodeWord32+ 54 -> (\value -> change {updatePerasQuorumThresholdSafetyMargin = Just value}) <$> Values.decodeUnitInterval+ 55 -> (\value -> change {updateRefInputsCostPerMultiAssetByte = Just value}) <$> Decode.decodeWord64+ 56 -> (\value -> change {updateRefInputsCostPerDatumByte = Just value}) <$> Decode.decodeWord64+ _ -> fail "Unknown protocol parameter key"+ go (subtract 1 <$> count) (Set.insert key seen) next++-- | Encode changed parameters for a Plutus governance script. The result is a+-- map keyed by parameter identifiers; absent fields are omitted. Rational values+-- are reduced fractions represented as numerator/denominator lists. Historical+-- decentralization, entropy and protocol-version changes are excluded. This is+-- script data, distinct from protocol-update CBOR, and does not validate whether+-- the changes are permitted in a particular ledger era. Conversion failures+-- return 'NativeError'.+toPlutusData :: Update -> IO (Either Error Data.PlutusData)+toPlutusData = Native.toPlutusData . encodeCbor
@@ -0,0 +1,44 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Governance approval proportions for stake pools.+-- Each field is an exact validated unit interval.+--+-- @PoolVotingThresholds t t t t t@ assembles uniform thresholds.+module Cometa.Protocol.PoolVotingThresholds+ ( PoolVotingThresholds (..),+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.ProtocolValues (PoolVotingThresholds (..))+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: PoolVotingThresholds -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodePoolVotingThresholds++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error PoolVotingThresholds+decodeCbor = Internal.decodeBytes Internal.decodePoolVotingThresholds
@@ -0,0 +1,156 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Legacy genesis-authorized protocol update proposals. These envelopes are+-- distinct from Conway parameter-change governance actions. Validate input hashes+-- once, then collect changes with 'fromList' and assemble @UpdateProposal epoch changes@.+module Cometa.Protocol.ProposedUpdates+ ( ProposedUpdates,+ empty,+ fromList,+ toList,+ UpdateProposal (..),+ EncodedUpdates,+ encodeCbor,+ decodeCbor,+ toUpdates,+ toCbor,+ EncodedProposal,+ encodeProposal,+ decodeProposal,+ toProposal,+ proposalCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Credential (Genesis, KeyHash)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.ProposalCbor as Cbor+import Cometa.Protocol.Parameters.Update (Update)+import qualified Cometa.Protocol.Parameters.Update as Update+import Data.ByteString (ByteString)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Unique 28-byte genesis key hashes and their sparse parameter changes.+-- Equality is semantic; fresh encoding sorts by hash bytes.+newtype ProposedUpdates = ProposedUpdates (Map (KeyHash Genesis) Update) deriving (Eq, Show)++-- | Proposed changes and their activation epoch (unsigned 64-bit).+-- Assembly does not establish era eligibility or authorization.+data UpdateProposal = UpdateProposal+ { -- | Epoch in which the proposal takes effect if accepted.+ updateProposalEpoch :: !Word64,+ -- | Genesis-authorized sparse protocol parameter changes.+ updateProposalChanges :: !ProposedUpdates+ }+ deriving (Eq, Show)++-- | Exact map bytes with semantic changes. Equality and ordering compare bytes.+data EncodedUpdates = EncodedUpdates !ByteString !ProposedUpdates deriving (Show)++instance Eq EncodedUpdates where+ left == right = toCbor left == toCbor right++instance Ord EncodedUpdates where+ compare left right = compare (toCbor left) (toCbor right)++-- | Exact proposal bytes with semantic epoch and changes. Equality and ordering+-- compare encoded bytes, not semantic data.+data EncodedProposal = EncodedProposal !ByteString !UpdateProposal deriving (Show)++instance Eq EncodedProposal where+ left == right = proposalCbor left == proposalCbor right++instance Ord EncodedProposal where+ compare left right = compare (proposalCbor left) (proposalCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | No proposed changes.+empty :: ProposedUpdates+empty = ProposedUpdates Map.empty++-- | Validate unique genesis hashes. Repeated keys return 'DuplicateProtocolUpdate'+-- even when their updates agree, rather than silently discarding an instruction.+fromList :: [(KeyHash Genesis, Update)] -> Either Error ProposedUpdates+fromList values = ProposedUpdates <$> Cbor.uniqueMap DuplicateProtocolUpdate values++-- | Entries sorted by exact genesis hash bytes.+toList :: ProposedUpdates -> [(KeyHash Genesis, Update)]+toList (ProposedUpdates values) = Map.toAscList values++-- | Fresh definite map, with sorted hashes and fresh sparse update encodings.+encodeCbor :: ProposedUpdates -> ByteString+encodeCbor value =+ Cbor.encode+ ( E.encodeMapLen (fromIntegral (length entries))+ <> foldMap (\(key, change) -> E.encodeBytes (Credential.keyHashBytes key) <> Cbor.raw (Update.encodeCbor change)) entries+ )+ where+ entries = toList value++-- | Decode one complete map and retain original bytes. Duplicate hashes,+-- incorrect hash lengths, invalid updates and trailing bytes return+-- 'Cometa.Error.InvalidProposalCbor'.+decodeCbor :: ByteString -> Either Error EncodedUpdates+decodeCbor bytes = EncodedUpdates bytes <$> Cbor.decode updatesDecoder bytes++-- | Inspect semantic changes without altering the exact encoding.+toUpdates :: EncodedUpdates -> ProposedUpdates+toUpdates (EncodedUpdates _ value) = value++-- | Exact imported update-map CBOR.+toCbor :: EncodedUpdates -> ByteString+toCbor (EncodedUpdates bytes _) = bytes++-- | Fresh definite @[changes, epoch]@ array with shortest integers.+encodeProposal :: UpdateProposal -> ByteString+encodeProposal (UpdateProposal epoch changes) =+ Cbor.encode+ (E.encodeListLen 2 <> Cbor.raw (encodeCbor changes) <> E.encodeWord64 epoch)++-- | Decode a complete legacy proposal and retain exact bytes. Invalid schema+-- or trailing bytes returns 'Cometa.Error.InvalidProposalCbor'.+decodeProposal :: ByteString -> Either Error EncodedProposal+decodeProposal bytes =+ EncodedProposal bytes+ <$> Cbor.decode+ (Cbor.array 2 (flip UpdateProposal <$> updatesDecoder <*> D.decodeWord64))+ bytes++-- | Inspect activation epoch and changes without altering retained bytes.+toProposal :: EncodedProposal -> UpdateProposal+toProposal (EncodedProposal _ value) = value++-- | Exact imported legacy proposal CBOR.+proposalCbor :: EncodedProposal -> ByteString+proposalCbor (EncodedProposal bytes _) = bytes++updatesDecoder :: D.Decoder s ProposedUpdates+updatesDecoder = do+ entries <- Cbor.entries $ do+ key <- D.decodeBytes >>= either (fail . show) pure . Credential.keyHashFromBytes+ change <- Update.toUpdate <$> Cbor.nested Update.decodeCbor+ pure (key, change)+ either (fail . show) pure (fromList entries)
@@ -0,0 +1,90 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Exact nonnegative protocol fractions, with positive denominators.+-- Numerators and denominators are unsigned 64-bit values. Input pairs remain+-- unreduced for serialization; equality and ordering compare numeric values.+--+-- @mkNonNegativeRational 577 10000@ constructs an exact execution price.+module Cometa.Protocol.Rational+ ( NonNegativeRational,+ mkNonNegativeRational,+ fromDouble,+ toDouble,+ numerator,+ denominator,+ toRational,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.ProtocolValues (NonNegativeRational, mkNonNegativeRational)+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)+import Data.Word (Word64)+import Prelude hiding (toRational)++-- DEFINITIONS ----------------------------------------------------------------++-- | Convert a finite nonnegative Double using the native decimal-floor rule+-- on its fractional part, then add the whole part. Reduce that fractional pair+-- before adding the whole part, retaining native numerator/denominator choices.+-- Nonfinite, negative or out-of-uint64 whole parts return 'InvalidProtocolDouble'.+-- If the resulting exact numerator exceeds uint64, return+-- 'InvalidProtocolRational' instead of reproducing native unsigned overflow.+fromDouble :: Double -> Either Error NonNegativeRational+fromDouble value+ | isNaN value || isInfinite value || value < 0 = Left InvalidProtocolDouble+ | whole > toInteger (maxBound :: Word64) = Left InvalidProtocolDouble+ | otherwise =+ let fractionalNumerator = floor ((value - fromInteger whole) * 1000000000000000)+ fractionalDenominator = 1000000000000000+ divisor = gcd fractionalNumerator fractionalDenominator+ d = fractionalDenominator `quot` divisor+ n = fractionalNumerator `quot` divisor + whole * d+ in mkNonNegativeRational n d+ where+ whole = floor value++-- | Convert numerator and denominator separately to Double and divide, matching+-- the native approximation without changing the stored exact pair.+toDouble :: NonNegativeRational -> Double+toDouble value = fromIntegral (numerator value) / fromIntegral (denominator value)++-- | Original numerator, without fraction reduction.+numerator :: NonNegativeRational -> Word64+numerator = Internal.rationalNumerator++-- | Original positive denominator, without fraction reduction.+denominator :: NonNegativeRational -> Word64+denominator = Internal.rationalDenominator++-- | Exact numeric value, reduced by the standard Rational representation.+toRational :: NonNegativeRational -> Rational+toRational = Internal.rationalValue++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: NonNegativeRational -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeRational++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error NonNegativeRational+decodeCbor = Internal.decodeBytes Internal.decodeRational
@@ -0,0 +1,44 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Ledger protocol versions with unsigned 64-bit major and 32-bit minor numbers.+--+-- @ProtocolVersion 9 0@ represents protocol version 9.0.+module Cometa.Protocol.Version+ ( ProtocolVersion (..),+ mkProtocolVersion,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.ProtocolValues (ProtocolVersion (..), mkProtocolVersion)+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: ProtocolVersion -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeProtocolVersion++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error ProtocolVersion+decodeCbor = Internal.decodeBytes Internal.decodeProtocolVersion
@@ -0,0 +1,105 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Inject blockchain queries and explicit transaction effects as ordinary IO+-- functions. Missing values use Maybe, successful empty queries use empty lists,+-- and expected failures use Either. These independent observations do not imply+-- an atomic ledger snapshot. Operations never submit a transaction implicitly.+--+-- @+-- fake = (unavailable "Offline fixture" 42) {utxosAt = \_ -> pure (Right [])}+-- @+module Cometa.Provider (Provider (..), unavailable) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address (Address)+import Cometa.Address.Reward (RewardAddress)+import Cometa.AssetId (AssetId)+import Cometa.Error (Error (..))+import Cometa.Evaluation (Budgets)+import Cometa.PlutusData (EncodedPlutusData)+import Cometa.Protocol.Parameters (Parameters)+import Cometa.Transaction (Transaction)+import Cometa.Transaction.Datum (Hash32)+import Cometa.Transaction.Input (Input)+import Cometa.Transaction.Utxo (Utxo)+import Cometa.TransactionId (TransactionId)+import Data.Text (Text)+import Data.Word (Word32, Word64)++-- TYPES ----------------------------------------------------------------------++-- | An application-supplied backend. Fields may perform network effects, use a+-- local cache or return deterministic fixtures. Exceptions propagate normally;+-- expected backend failures belong in Left. No equality or Show instance is+-- defined for function-valued capabilities.+data Provider = Provider+ { -- | Diagnostic name. When used in Cometa operations, supply at most 255+ -- UTF-8 bytes and no NUL character. The name is not a credential or endpoint URL.+ name :: !Text,+ -- | Network magic, distinct from a four-bit address network identifier.+ networkMagic :: !Word32,+ -- | Complete protocol snapshot; optional era fields retain availability.+ protocolParameters :: IO (Either Error Parameters),+ -- | Unspent outputs at an address. Empty is a successful no-match query.+ utxosAt :: Address -> IO (Either Error [Utxo]),+ -- | Current reward balance, in lovelace from zero through 2^64 - 1.+ rewardBalance :: RewardAddress -> IO (Either Error Word64),+ -- | Unspent outputs at the address containing the specified asset.+ utxosWithAsset :: Address -> AssetId -> IO (Either Error [Utxo]),+ -- | The unique output containing an asset assumed to be an NFT. Nothing+ -- means absent; ambiguous matches must return an expected backend failure.+ utxoWithAsset :: AssetId -> IO (Either Error (Maybe Utxo)),+ -- | Resolve references. Missing inputs are omitted, not turned into errors;+ -- callers needing complete resolution must check every requested reference.+ resolveInputs :: [Input] -> IO (Either Error [Utxo]),+ -- | Resolve exact datum bytes. Nothing means the datum is unavailable.+ resolveDatum :: Hash32 -> IO (Either Error (Maybe EncodedPlutusData)),+ -- | Wait up to the supplied timeout in milliseconds. False means not+ -- confirmed within that interval; transport failures remain Left.+ awaitTransaction :: TransactionId -> Word64 -> IO (Either Error Bool),+ -- | Explicitly submit exact transaction bytes and return the accepted ID.+ -- A successful result does not claim confirmation or finality.+ submitTransaction :: Transaction -> IO (Either Error TransactionId),+ -- | Evaluate top-level redeemers with additional resolved UTxOs. Return+ -- budgets for every existing top-level purpose/index without changing input.+ -- No partial-success or evaluation-log information is implied.+ evaluateTransaction :: Transaction -> [Utxo] -> IO (Either Error Budgets)+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Total default backend with explicit metadata. Override only the capabilities+-- required by a workflow. Every operation initially returns UnsupportedOperation+-- naming that operation; none acquires a connection or performs network work.+unavailable :: Text -> Word32 -> Provider+unavailable backendName magic =+ Provider+ backendName+ magic+ (unsupported "provider.protocolParameters")+ (\_ -> unsupported "provider.utxosAt")+ (\_ -> unsupported "provider.rewardBalance")+ (\_ _ -> unsupported "provider.utxosWithAsset")+ (\_ -> unsupported "provider.utxoWithAsset")+ (\_ -> unsupported "provider.resolveInputs")+ (\_ -> unsupported "provider.resolveDatum")+ (\_ _ -> unsupported "provider.awaitTransaction")+ (\_ -> unsupported "provider.submitTransaction")+ (\_ _ -> unsupported "provider.evaluateTransaction")+ where+ unsupported operation = pure (Left (UnsupportedOperation operation))
@@ -0,0 +1,65 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | A scoped Blockfrost backend for the ordinary 'Provider' record. Queries+-- return domain values and report explicit errors. Pagination uses ascending+-- pages of 100 results, rejects repeated identities, and permits at most 10000+-- pages per query. Independent requests do not form an atomic ledger snapshot.+--+-- Submission is explicit and never retried automatically. Confirmation means+-- the transaction appears in a block; it does not establish finality. Remote+-- evaluation uses the Ogmios v6 dialect, preserving inline data and reference+-- scripts in additional inputs and covering all six redeemer purposes. Nested+-- transactions and guarded account features fail explicitly; local+-- "Cometa.Evaluation.Native" supports the binding's native VM.+--+-- @+-- withProvider (defaultConfig Preview (Just project)) $ \provider ->+-- Cometa.Provider.utxosAt provider address+-- @+module Cometa.Provider.Blockfrost+ ( Network (..),+ ProjectId,+ mkProjectId,+ Config (..),+ defaultConfig,+ withProvider,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Provider (Provider)+import Cometa.Provider.Blockfrost.Internal.Config (Config (..), Network (..), ProjectId, defaultConfig, mkProjectId)+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import Cometa.Provider.Blockfrost.Internal.Provider (providerWithTransport)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate an absolute HTTP or HTTPS endpoint and configuration, share one+-- scoped HTTP transport, and run a caller workflow with one expected-error+-- boundary. Supply credentials from application configuration, or omit them for+-- a service that does not require authentication. Custom path prefixes and base+-- query parameters are retained; operation+-- query parameters take precedence. No environment variables or files are read+-- implicitly. Escaped provider operations fail with+-- 'Cometa.Error.RuntimeClosed' after the scope.+-- Scope exit waits for active requests; cancellation propagates after cleanup.+withProvider :: Config -> (Provider -> IO (Either Error a)) -> IO (Either Error a)+withProvider config action = case Config.validateConfig config of+ Left failure -> pure (Left failure)+ Right () -> Http.withTransport config (action . providerWithTransport config)
@@ -0,0 +1,153 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Endpoint and credential configuration with bounded HTTP schedules.+module Cometa.Provider.Blockfrost.Internal.Config+ ( Network (..),+ ProjectId,+ mkProjectId,+ Config (..),+ defaultConfig,+ validateConfig,+ parseEndpoint,+ baseUrl,+ networkMagic,+ projectIdBytes,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Control.Monad (foldM, void)+import Data.ByteString (ByteString)+import Data.Char (isAlphaNum, isAscii, isDigit, ord)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word32)+import qualified Network.HTTP.Client as Http+import qualified Network.URI as URI++-- TYPES ----------------------------------------------------------------------++-- | Cardano chain identity. A custom endpoint does not change its network magic.+data Network+ = -- | Cardano mainnet, with network magic 764824073.+ Mainnet+ | -- | Pre-production test network, with network magic 1.+ Preprod+ | -- | Preview test network, with network magic 2.+ Preview+ deriving (Eq, Ord, Show, Enum, Bounded)++-- | An opaque API credential. No printable instance exposes its contents.+newtype ProjectId = ProjectId ByteString deriving (Eq)++-- | HTTP and confirmation-poll settings. Validate once with @withProvider@.+-- Millisecond durations must be between 1 and 60,000 inclusive.+data Config = Config+ { -- | Chain identity and network magic, independent of the endpoint URL.+ network :: !Network,+ -- | Absolute HTTP or HTTPS base URL, including any path prefix and query+ -- parameters. User information and fragments are not supported. Operation+ -- query parameters override base parameters with the same name.+ endpoint :: !Text,+ -- | Optional project credential. 'Nothing' omits the project_id header.+ projectId :: !(Maybe ProjectId),+ -- | Whole-request deadline, in milliseconds, from 1 through 60000.+ responseTimeoutMillis :: !Int,+ -- | Delay between confirmation polls, in milliseconds, from 1 through 60000.+ pollIntervalMillis :: !Int+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Import 1 through 128 ASCII letters, digits, hyphens or underscores.+-- Whitespace and header delimiters are rejected without echoing the input.+mkProjectId :: Text -> Either Error ProjectId+mkProjectId value+ | Text.null value || Text.length value > 128 || not (Text.all allowed value) =+ Left (InvalidProviderConfiguration "Project identifier must contain 1 through 128 ASCII letters, digits, hyphens or underscores")+ | otherwise = Right (ProjectId (Text.encodeUtf8 value))+ where+ allowed character = isAscii character && (isAlphaNum character || character == '-' || character == '_')++-- | The network's official HTTPS endpoint, a 30-second whole-request timeout,+-- and a one-second confirmation poll period. Supply 'Nothing' when the endpoint+-- does not require a project credential; set 'endpoint' for a custom service.+defaultConfig :: Network -> Maybe ProjectId -> Config+defaultConfig selected credential = Config selected (Text.pack (baseUrl selected)) credential 30000 1000++validateConfig :: Config -> Either Error ()+validateConfig config+ | invalid (responseTimeoutMillis config) = Left (InvalidProviderConfiguration "HTTP timeout must be between 1 and 60000 milliseconds")+ | invalid (pollIntervalMillis config) = Left (InvalidProviderConfiguration "Polling interval must be between 1 and 60000 milliseconds")+ | otherwise = void (parseEndpoint (endpoint config))+ where+ invalid value = value < 1 || value > 60000++-- | The standard URI parser handles authority, percent escapes and bracketed+-- IPv6. The HTTP client's pure conversion checks its supported schemes and port+-- representation. Neither parser's diagnostic is exposed: URLs can contain query+-- credentials, and userinfo would install implicit Basic authentication.+parseEndpoint :: Text -> Either Error Http.Request+parseEndpoint value = case URI.parseURI (Text.unpack value) of+ Just uri+ | Just authority <- URI.uriAuthority uri,+ not (null (URI.uriRegName authority)),+ null (URI.uriUserInfo authority),+ validPort (URI.uriPort authority),+ null (URI.uriFragment uri) -> case Http.requestFromURI uri :: Maybe Http.Request of+ Just request | Http.port request >= 1 && Http.port request <= 65535 -> Right request+ _ -> invalidEndpoint+ _ -> invalidEndpoint+ where+ invalidEndpoint = Left (InvalidProviderConfiguration "Endpoint must be an absolute HTTP or HTTPS URL with a host and valid port, without user information or a fragment")++-- Validate the URI authority's decimal port before the client's Int conversion:+-- http-client 0.7.19 uses Read Int, which can wrap excessively large values.+-- The accumulator never exceeds 65535, including with arbitrarily many zeros.+validPort :: String -> Bool+validPort "" = True+validPort (':' : digits) =+ not (null digits) && case foldM digit 0 digits of+ Just value -> value >= 1+ Nothing -> False+ where+ digit :: Int -> Char -> Maybe Int+ digit current character+ | isDigit character && next <= 65535 = Just next+ | otherwise = Nothing+ where+ next = current * 10 + ord character - ord '0'+validPort _ = False++baseUrl :: Network -> String+baseUrl selected = case selected of+ Mainnet -> "https://cardano-mainnet.blockfrost.io/api/v0"+ Preprod -> "https://cardano-preprod.blockfrost.io/api/v0"+ Preview -> "https://cardano-preview.blockfrost.io/api/v0"++networkMagic :: Network -> Word32+networkMagic selected = case selected of+ Mainnet -> 764824073+ Preprod -> 1+ Preview -> 2++projectIdBytes :: ProjectId -> ByteString+projectIdBytes (ProjectId bytes) = bytes
@@ -0,0 +1,200 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | HTTP and TLS connections with joined cancellation of Windows socket I/O.+module Cometa.Provider.Blockfrost.Internal.Connection (managerSettings, managerSettingsWithStore, socketBackend) where++-- IMPORTS --------------------------------------------------------------------++import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar, threadDelay)+import Control.Concurrent.Async (forConcurrently, withAsync)+import Control.Concurrent.MVar (tryPutMVar, tryTakeMVar)+import Control.Concurrent.STM (retry)+import Control.Exception (IOException, bracketOnError, mask, onException, throwIO, try)+import Control.Monad (unless, void)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as C+import qualified Data.ByteString.Lazy as Lazy+import Data.List (find)+import Data.Void (Void, absurd)+import Data.X509.CertificateStore (CertificateStore)+import qualified Network.HTTP.Client as Http+import qualified Network.HTTP.Client.Internal as HttpConnection+import qualified Network.HTTP.Client.TLS as TLS+import qualified Network.Socket as Socket+import qualified Network.Socket.ByteString as Socket+import qualified Network.TLS as Tls+import qualified Network.TLS.Extra.Cipher as Cipher+import System.X509 (getSystemCertificateStore)++-- DEFINITIONS ----------------------------------------------------------------++-- http-client's default plain socket reads, and tls's Socket backend reads,+-- block in safe FFI calls on Windows. An async exception cannot reach them.+-- Keep http-client's connection/proxy and TLS validation contracts, replacing+-- only the backend socket reads/writes with operations that cancel and JOIN+-- their own OVERLAPPED I/O before propagating an exception.+managerSettings :: IO Http.ManagerSettings+managerSettings = managerSettingsWithStore <$> getSystemCertificateStore++-- The injectable trust store is private and used only by deterministic TLS tests.+-- Every certificate and hostname check still runs through tls's default hooks.+managerSettingsWithStore :: CertificateStore -> Http.ManagerSettings+managerSettingsWithStore certificates =+ let parameters :: String -> Int -> Tls.ClientParams+ parameters host port =+ let defaults = Tls.defaultParamsClient (Http.strippedHostName host) (C.pack (show port))+ in defaults+ { Tls.clientSupported = Tls.defaultSupported {Tls.supportedCiphers = Cipher.ciphersuite_default},+ Tls.clientShared = (Tls.clientShared defaults) {Tls.sharedCAStore = certificates}+ }+ secure address host port =+ bracketOnError (rawConnection address host port) HttpConnection.connectionClose (secureConnection (parameters host port))+ proxy connectBytes checkConnection serverName address host port =+ bracketOnError (rawConnection address host port) HttpConnection.connectionClose $ \connection -> do+ HttpConnection.connectionWrite connection connectBytes+ void (checkConnection connection)+ targetPort <- proxyTargetPort connectBytes+ secureConnection (parameters serverName targetPort) connection+ in TLS.tlsManagerSettings+ { Http.managerRawConnection = pure rawConnection,+ Http.managerTlsConnection = pure secure,+ HttpConnection.managerTlsProxyConnection = pure proxy,+ Http.managerRetryableException = const False,+ -- closeManager is a deprecated no-op. With no idle sockets, response+ -- scopes close their connections without needing a manager GC cycle.+ Http.managerIdleConnectionCount = 0+ }++rawConnection :: Maybe Socket.HostAddress -> String -> Int -> IO HttpConnection.Connection+rawConnection address host port =+ bracketOnError (connectSocket address host port) Socket.close socketConnection++socketConnection :: Socket.Socket -> IO HttpConnection.Connection+socketConnection socket =+ Http.makeConnection+ (completed (Socket.recvWith socket 8192 retry))+ (\bytes -> completed (Socket.sendAllWith socket bytes retry))+ (Socket.close socket)++-- Preserve http-client's staggered parallel address attempts. Each attempt owns+-- its socket until it publishes the winner; cancelled/losing attempts close it.+connectSocket :: Maybe Socket.HostAddress -> String -> Int -> IO Socket.Socket+connectSocket address host port = do+ addresses <- case address of+ Just ipv4 -> pure [Socket.defaultHints {Socket.addrFamily = Socket.AF_INET, Socket.addrSocketType = Socket.Stream, Socket.addrAddress = Socket.SockAddrInet (fromIntegral port) ipv4}]+ Nothing -> resolve host port+ mask $ \restore -> do+ result <- newEmptyMVar+ let attempt (info, delay) = mask $ \restoreAttempt -> do+ socket <- try (threadDelay delay >> open restoreAttempt info)+ case socket of+ Left failure -> pure (Just (failure :: IOException))+ Right connected -> do+ published <- tryPutMVar result (Right connected)+ unless published (Socket.close connected)+ pure Nothing+ run = do+ failures <- forConcurrently (zip addresses [0, 250000 ..]) attempt+ case find isFailure failures of+ Just (Just failure) -> void (tryPutMVar result (Left failure))+ _ -> pure ()+ abandon = do+ pending <- tryTakeMVar result+ case pending of+ Just (Right socket) -> Socket.close socket+ _ -> pure ()+ winner <- withAsync (restore run) (const (takeMVar result)) `onException` abandon+ either throwIO pure winner+ where+ isFailure Nothing = False+ isFailure (Just _) = True+ open restoreConnect info = bracketOnError (Socket.socket (Socket.addrFamily info) Socket.Stream (Socket.addrProtocol info)) Socket.close $ \socket -> do+ _ <- restoreConnect $ do+ Socket.setSocketOption socket Socket.NoDelay 1+ completed (Socket.connectWith socket (Socket.addrAddress info) retry)+ pure socket++-- getaddrinfo is itself a noninterruptible foreign call on Windows. Its worker+-- owns all temporary resolver buffers and no connection or request-body state.+-- A cancelled caller stops waiting immediately; the OS lookup frees its own+-- buffers when it returns. Killing and joining that worker would defeat the+-- whole-request DNS deadline before any socket had even been acquired.+resolve :: String -> Int -> IO [Socket.AddrInfo]+resolve host port = do+ result <- newEmptyMVar+ _ <- forkFinally (Socket.getAddrInfo (Just Socket.defaultHints {Socket.addrSocketType = Socket.Stream}) (Just (Http.strippedHostName host)) (Just (show port))) (putMVar result)+ addresses <- takeMVar result >>= either throwIO pure+ if null addresses then ioError (userError "HTTP destination has no addresses") else pure addresses++proxyTargetPort :: ByteString -> IO Int+proxyTargetPort request = case C.words (C.takeWhile (/= '\r') request) of+ ["CONNECT", authority, "HTTP/1.1"] -> case C.readInt (snd (C.breakEnd (== ':') authority)) of+ Just (port, rest) | B.null rest && port > 0 && port <= 65535 -> pure port+ _ -> invalid+ _ -> invalid+ where+ invalid = ioError (userError "Invalid HTTP proxy CONNECT authority")++completed :: IO (Either Void a) -> IO a+completed operation = do+ result <- operation+ case result of+ Left impossible -> absurd impossible+ Right value -> pure value++secureConnection :: Tls.ClientParams -> HttpConnection.Connection -> IO HttpConnection.Connection+secureConnection parameters connection =+ bracketOnError (Tls.contextNew backend parameters) Tls.contextClose $ \context -> do+ Tls.handshake context+ Http.makeConnection+ (Tls.recvData context)+ (Tls.sendData context . Lazy.fromStrict)+ (Tls.contextClose context)+ where+ backend = connectionBackend connection++-- No close-notify write is attempted during cleanup: an aborted peer may not be+-- reading and cleanup runs masked, after the request's timeout has already fired.+-- Closing joins all in-flight backend I/O first and never starts another write.+socketBackend :: Socket.Socket -> IO Tls.Backend+socketBackend socket = connectionBackend <$> socketConnection socket++connectionBackend :: HttpConnection.Connection -> Tls.Backend+connectionBackend connection =+ Tls.Backend+ { Tls.backendFlush = pure (),+ Tls.backendClose = HttpConnection.connectionClose connection,+ Tls.backendSend = HttpConnection.connectionWrite connection,+ Tls.backendRecv = receiveExactly connection+ }++-- TLS needs exactly the requested record bytes. Retaining http-client's unread+-- stack also preserves any bytes buffered while checking an HTTP CONNECT reply.+receiveExactly :: HttpConnection.Connection -> Int -> IO ByteString+receiveExactly connection count = go count []+ where+ go 0 chunks = pure (B.concat (reverse chunks))+ go remaining chunks = do+ bytes <- HttpConnection.connectionRead connection+ if B.null bytes+ then pure (B.concat (reverse chunks))+ else do+ let (wanted, rest) = B.splitAt remaining bytes+ unless (B.null rest) (HttpConnection.connectionUnread connection rest)+ go (remaining - B.length wanted) (wanted : chunks)
@@ -0,0 +1,197 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Private bounded HTTP transport. Credentials never enter diagnostics.+module Cometa.Provider.Blockfrost.Internal.Http+ ( Method (..),+ Request (..),+ Response (..),+ HttpFailure (..),+ Transport (..),+ withTransport,+ withHeaders,+ withEndpoint,+ withEndpointSettings,+ maximumResponseBytes,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Connection as Connection+import Control.Concurrent.MVar (MVar, modifyMVar, newEmptyMVar, newMVar, putMVar, takeMVar, withMVar)+import Control.Exception (bracket, finally, mask, try, uninterruptibleMask_)+import Control.Monad (when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Maybe (fromMaybe, isNothing)+import Data.Text (Text)+import qualified Data.Text as TextValue+import qualified Data.Text.Encoding as Text+import qualified Network.HTTP.Client as Http+import qualified Network.HTTP.Types as HTTP+import qualified Network.HTTP.Types.URI as URI+import System.Timeout (timeout)++-- TYPES ----------------------------------------------------------------------++data Method = Get | Post deriving (Eq, Show)++-- No Show instance: request bodies may contain private transaction material.+data Request = Request+ { method :: !Method,+ path :: ![Text],+ query :: ![(Text, Maybe Text)],+ body :: !ByteString,+ contentType :: !ByteString,+ requestTimeoutMillis :: !(Maybe Int)+ }++data Response = Response+ { status :: !Int,+ bodyBytes :: !ByteString,+ retryAfter :: !(Maybe ByteString)+ }+ deriving (Eq, Show)++-- No raw exception/request/header/body text is retained.+data HttpFailure = Timeout | ConnectionFailure | ResponseTooLarge | Closed+ deriving (Eq, Show)++data Transport = Transport+ { send :: Request -> IO (Either HttpFailure Response),+ checkOpen :: IO (Either HttpFailure ())+ }++-- A closed scope drops its manager immediately; active calls hold their own+-- references until response cleanup. The last active caller signals drainage.+type Scope = MVar (Maybe Http.Manager, Int)++-- DEFINITIONS ----------------------------------------------------------------++maximumResponseBytes :: Int+maximumResponseBytes = 8 * 1024 * 1024++withTransport :: Config.Config -> (Transport -> IO a) -> IO a+withTransport config = withEndpoint config (TextValue.unpack (Config.endpoint config))++-- | Private endpoint override for deterministic HTTP fixture servers.+withEndpoint :: Config.Config -> String -> (Transport -> IO a) -> IO a+withEndpoint = withEndpointSettings Connection.managerSettings++-- Private settings injection keeps fixture trust roots separate from system roots.+withEndpointSettings :: IO Http.ManagerSettings -> Config.Config -> String -> (Transport -> IO a) -> IO a+withEndpointSettings acquireSettings config endpoint =+ withHeadersSettings acquireSettings config endpoint [("project_id", Config.projectIdBytes credential) | Just credential <- [Config.projectId config]]++-- | Scoped transport with explicitly supplied authentication headers.+withHeaders :: Config.Config -> HTTP.RequestHeaders -> (Transport -> IO a) -> IO a+withHeaders config = withHeadersSettings Connection.managerSettings config (TextValue.unpack (Config.endpoint config))++withHeadersSettings :: IO Http.ManagerSettings -> Config.Config -> String -> HTTP.RequestHeaders -> (Transport -> IO a) -> IO a+withHeadersSettings acquireSettings config endpoint authentication action =+ either+ (const (ioError (userError "Invalid Blockfrost transport configuration")))+ acquire+ (Config.validateConfig config >> Config.parseEndpoint (TextValue.pack endpoint))+ where+ acquire template = do+ settings <- acquireSettings+ manager <- Http.newManager settings+ drained <- newEmptyMVar+ bracket (newMVar (Just manager, 0)) (closeScope drained) $ \scope ->+ action (Transport (sendScoped scope drained config authentication template) (scopeOpen scope))++-- | Check scope liveness without opening a connection or performing HTTP.+scopeOpen :: Scope -> IO (Either HttpFailure ())+scopeOpen scope = withMVar scope $ \(manager, _) -> pure (maybe (Left Closed) (const (Right ())) manager)++closeScope :: MVar () -> Scope -> IO ()+closeScope drained scope = uninterruptibleMask_ $ do+ active <- modifyMVar scope $ \(_, count) -> pure ((Nothing, count), count)+ when (active /= 0) (takeMVar drained)++sendScoped :: Scope -> MVar () -> Config.Config -> HTTP.RequestHeaders -> Http.Request -> Request -> IO (Either HttpFailure Response)+sendScoped scope drained config authentication template request = mask $ \restore -> do+ acquired <- modifyMVar scope $ \(manager, count) ->+ pure ((manager, maybe count (const (count + 1)) manager), manager)+ case acquired of+ Nothing -> pure (Left Closed)+ Just manager ->+ restore (sendOnce config authentication template manager request) `finally` release+ where+ release = modifyMVar scope $ \(manager, count) -> do+ when (count == 1 && isNothing manager) (putMVar drained ())+ pure ((manager, count - 1), ())++sendOnce :: Config.Config -> HTTP.RequestHeaders -> Http.Request -> Http.Manager -> Request -> IO (Either HttpFailure Response)+sendOnce config authentication template manager request = do+ -- The outer deadline also covers connection acquisition, DNS and body reads;+ -- responseTimeout alone resets around individual network reads.+ result <- timeout (milliseconds * 1000) (tryHttp perform)+ pure $ case result of+ Nothing -> Left Timeout+ Just (Left failure) -> Left (classify failure)+ Just (Right response) -> response+ where+ milliseconds = max 1 (min (Config.responseTimeoutMillis config) (fromMaybe (Config.responseTimeoutMillis config) (requestTimeoutMillis request)))+ prefix = Http.path template+ separator = if B.isSuffixOf "/" prefix then "" else "/"+ requestPath = case path request of+ [] -> prefix+ segments -> prefix <> separator <> B.intercalate "/" (map (URI.urlEncode False . Text.encodeUtf8) segments)+ operationQuery = [(Text.encodeUtf8 key, Text.encodeUtf8 <$> value) | (key, value) <- query request]+ baseQuery = filter (\(key, _) -> key `notElem` map fst operationQuery) (HTTP.parseQuery (Http.queryString template))+ headers =+ [("Accept", "application/json")]+ <> authentication+ <> [("Content-Type", contentType request) | not (B.null (contentType request))]+ prepared =+ Http.setQueryString (baseQuery <> operationQuery) $+ template+ { Http.method = case method request of Get -> "GET"; Post -> "POST",+ Http.path = requestPath,+ Http.requestHeaders = headers,+ Http.requestBody = Http.RequestBodyBS (body request),+ Http.redirectCount = 0,+ Http.checkResponse = \_ _ -> pure (),+ Http.responseTimeout = Http.responseTimeoutMicro (milliseconds * 1000),+ Http.cookieJar = Nothing+ }+ perform = Http.withResponse prepared manager $ \response -> do+ bytes <- readBounded maximumResponseBytes [] (Http.responseBody response)+ pure $ fmap (\payload -> Response (HTTP.statusCode (Http.responseStatus response)) payload (B.take 128 <$> lookup "Retry-After" (Http.responseHeaders response))) bytes++tryHttp :: IO a -> IO (Either Http.HttpException a)+tryHttp = try++classify :: Http.HttpException -> HttpFailure+classify failure = case failure of+ Http.HttpExceptionRequest _ Http.ResponseTimeout -> Timeout+ Http.HttpExceptionRequest _ Http.ConnectionTimeout -> Timeout+ _ -> ConnectionFailure++readBounded :: Int -> [ByteString] -> Http.BodyReader -> IO (Either HttpFailure ByteString)+readBounded remaining chunks reader = do+ chunk <- Http.brRead reader+ if B.null chunk+ then pure (Right (B.concat (reverse chunks)))+ else+ if B.length chunk > remaining+ then pure (Left ResponseTooLarge)+ else readBounded (remaining - B.length chunk) (chunk : chunks) reader
@@ -0,0 +1,253 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Strict owned response values and the Ogmios v6 evaluation dialect.+module Cometa.Provider.Blockfrost.Internal.Json+ ( Row (..),+ decodeValue,+ parseValue,+ rows,+ transactionAddresses,+ parseHex,+ parseQuantity,+ parseNatural,+ parseAsset,+ assetText,+ nativeScript,+ decodeBudgets,+ evaluationPayload,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Monad (unless, void, when, (>=>))+import Data.Aeson (Value (..), eitherDecodeStrict', object, (.:), (.:?), (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KeyMap+import Data.Aeson.Types (Parser, parseEither, withArray, withObject, withScientific)+import Data.ByteString (ByteString)+import Data.Char (isDigit)+import Data.Foldable (toList, traverse_)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe, isJust)+import Data.Scientific (base10Exponent, toBoundedInteger)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Read as Text+import Data.Word (Word32, Word64)++-- TYPES ----------------------------------------------------------------------++data Row = Row+ { rowInput :: !Input.Input,+ rowAddress :: !Address.Address,+ rowValue :: !Amount.Value,+ rowDatum :: !Datum.Datum,+ rowDatumHash :: !(Maybe Datum.Hash32),+ rowScriptHash :: !(Maybe Credential.ScriptHash)+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++decodeValue :: Text -> ByteString -> Either Error Value+decodeValue operation = either (const (Left (InvalidProviderResponse operation))) Right . eitherDecodeStrict'++parseValue :: Text -> (Value -> Parser a) -> Value -> Either Error a+parseValue operation parser = either (const (Left (InvalidProviderResponse operation))) Right . parseEither parser++liftDomain :: Either Error a -> Parser a+liftDomain = either (const (fail "Invalid domain value")) pure++parseHex :: Text -> Parser ByteString+parseHex = maybe (fail "Invalid hexadecimal bytes") pure . Hex.decodeHex++parseQuantity :: Text -> Parser Word64+parseQuantity text+ | Text.null text || Text.length text > 20 || not (Text.all isDigit text) = fail "Invalid unsigned quantity"+ | otherwise = case Text.decimal text of+ Right (value, rest) | Text.null rest && value <= toInteger (maxBound :: Word64) -> pure (fromInteger value)+ _ -> fail "Unsigned quantity overflow"++parseNatural :: Value -> Parser Word64+parseNatural = withScientific "unsigned integer" $ \number ->+ if base10Exponent number < -100 || base10Exponent number > 100+ then fail "Numeric exponent exceeds response bounds"+ else case toBoundedInteger number :: Maybe Word64 of+ Just value -> pure value+ _ -> fail "Invalid unsigned integer"++parseAsset :: Text -> Parser AssetId+parseAsset "lovelace" = pure Ada+parseAsset text = do+ let (policy, name) = Text.splitAt 56 text+ Native <$> liftDomain (Policy.fromHex policy) <*> liftDomain (AssetName.fromHex name)++assetText :: AssetId -> Text+assetText Ada = "lovelace"+assetText (Native policy name) = Policy.toHex policy <> AssetName.toHex name++rows :: Value -> Parser [Row]+rows = withArray "UTxO list" (traverse row . toList)++row :: Value -> Parser Row+row = withObject "UTxO" $ \value -> do+ transaction <- value .: "tx_hash" >>= liftDomain . TxId.fromHex+ index <- value .: "output_index" >>= parseNatural+ address <- value .: "address" >>= liftDomain . Address.fromText+ amounts <- value .: "amount" >>= withArray "amounts" (traverse amount . toList)+ unless (Set.size (Set.fromList (map fst amounts)) == length amounts && any ((== Ada) . fst) amounts) (fail "Duplicate units or missing lovelace")+ hash <- value .: "data_hash" >>= traverse (parseHex >=> liftDomain . Datum.hashFromBytes)+ inline <- value .: "inline_datum" >>= traverse (parseHex >=> liftDomain . Data.decodeCbor)+ scriptHash <- value .: "reference_script_hash" >>= traverse (parseHex >=> liftDomain . Credential.scriptHashFromBytes)+ let datum = maybe (maybe Datum.NoDatum Datum.DatumHash hash) Datum.InlineDatum inline+ total = foldMap (\(asset, quantity) -> Amount.singleton asset (toInteger quantity)) amounts+ _ <- liftDomain (Output.mkOutput address total datum Nothing)+ pure (Row (Input.input transaction index) address total datum hash scriptHash)+ where+ amount = withObject "amount" $ \value -> (,) <$> (value .: "unit" >>= parseAsset) <*> (value .: "quantity" >>= parseQuantity)++-- A transaction endpoint describes historical outputs. Only extract the address+-- needed for a current address-UTxO cross-check; never call these outputs unspent.+transactionAddresses :: TxId.TransactionId -> Value -> Parser [(Input.Input, Address.Address)]+transactionAddresses expected = withObject "transaction outputs" $ \value -> do+ actual <- value .: "hash" >>= liftDomain . TxId.fromHex+ unless (actual == expected) (fail "Transaction identity mismatch")+ outputs <- value .: "outputs" >>= withArray "outputs" (traverse output . toList)+ unless (Set.size (Set.fromList (map (\(reference, _, _) -> Input.index reference) outputs)) == length outputs) (fail "Duplicate output index")+ pure [(reference, address) | (reference, address, unspent) <- outputs, unspent]+ where+ output = withObject "output address" $ \value -> do+ address <- value .: "address" >>= liftDomain . Address.fromText+ index <- value .: "output_index" >>= parseNatural+ consumed <- value .:? "consumed_by_tx"+ case consumed of+ Nothing -> pure ()+ Just hash -> void (liftDomain (TxId.fromHex hash))+ pure (Input.input expected index, address, consumed == (Nothing :: Maybe Text))++nativeScript :: Value -> Parser Native.NativeScript+nativeScript = withObject "native script" $ \value -> do+ kind <- value .: "type"+ case kind :: Text of+ "sig" -> Native.signature <$> (value .: "keyHash" >>= parseHex >>= liftDomain . Credential.keyHashFromBytes)+ "all" -> Native.allOf <$> (value .: "scripts" >>= traverse nativeScript)+ "any" -> Native.anyOf <$> (value .: "scripts" >>= traverse nativeScript)+ "atLeast" -> Native.atLeast <$> (value .: "required" >>= parseNatural) <*> (value .: "scripts" >>= traverse nativeScript)+ "before" -> Native.invalidAfter <$> (value .: "slot" >>= parseNatural)+ "after" -> Native.invalidBefore <$> (value .: "slot" >>= parseNatural)+ _ -> fail "Unsupported native script"++decodeBudgets :: Tx.Transaction -> Value -> Either Error Evaluation.Budgets+decodeBudgets transaction value = do+ case value of+ Object envelope | Just (Object result) <- KeyMap.lookup "result" envelope, KeyMap.member "EvaluationFailure" result -> Left (InvalidEvaluationResult "Blockfrost script evaluation failed")+ _ -> pure ()+ pairs <- parseValue operation parser value+ budgets <- Evaluation.mkBudgets pairs+ let expected = Set.fromList [Evaluation.RedeemerId (Redeemer.purpose redeemer) (Redeemer.index redeemer) | redeemer <- Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction))]+ unless (Set.fromList (map fst (Evaluation.budgets budgets)) == expected) (Left (InvalidEvaluationResult "Blockfrost budgets do not cover exactly the existing redeemers"))+ pure budgets+ where+ operation = "blockfrost.evaluateTransaction"+ parser = withObject "evaluation envelope" $ \envelope -> envelope .: "result" >>= withObject "evaluation result" (\result -> result .: "EvaluationResult" >>= withObject "budgets" (traverse budget . KeyMap.toList))+ budget (key, payload) = do+ identifier <- pointer (Key.toText key)+ units <- withObject "budget" (\entry -> ExUnits <$> (entry .: "memory" >>= parseNatural) <*> (entry .: "steps" >>= parseNatural)) payload+ pure (identifier, units)+ pointer text = case Text.splitOn ":" text of+ [purpose, index] -> do+ tag <- case purpose of+ "spend" -> pure Redeemer.Spending+ "mint" -> pure Redeemer.Minting+ "certificate" -> pure Redeemer.Certifying+ "withdrawal" -> pure Redeemer.Rewarding+ "publish" -> pure Redeemer.Certifying+ "withdraw" -> pure Redeemer.Rewarding+ "vote" -> pure Redeemer.Voting+ "propose" -> pure Redeemer.Proposing+ _ -> fail "Unsupported redeemer purpose"+ number <- parseQuantity index+ when (number > fromIntegral (maxBound :: Word32)) (fail "Redeemer index overflow")+ pure (Evaluation.RedeemerId tag (fromIntegral number))+ _ -> fail "Invalid redeemer pointer"++evaluationPayload :: Tx.Transaction -> [Utxo.Utxo] -> Either Error Value+evaluationPayload transaction resolved = do+ let body = Body.toBody (Tx.body transaction)+ fields = Body.bodyFields body+ subs = fromMaybe [] (Body.bodySubTransactions body)+ unsupportedFields = [isJust (Fields.fieldDirectDeposits fields), isJust (Fields.fieldAccountBalanceIntervals fields), isJust (Fields.fieldRequiredTopLevelGuards fields), isJust (Body.bodyStartingAccountBalanceIntervals body)]+ hasScriptGuard = any isScriptGuard (fromMaybe [] (Fields.fieldGuards fields))+ unless (null subs && not (or unsupportedFields) && not hasScriptGuard) unsupported+ unless (Set.size (Set.fromList (map Utxo.input resolved)) == length resolved) (Left (InvalidEvaluationRequest "Duplicate resolved input reference"))+ traverse_ scriptValue (Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses transaction)))+ additional <- traverse utxoValue resolved+ pure (object ["cbor" .= Hex.encodeHex (Tx.encodeCbor transaction), "additionalUtxo" .= concat additional])+ where+ isScriptGuard (Credential.ScriptCredential _) = True+ isScriptGuard _ = False+ unsupported = Left (UnsupportedOperation "Blockfrost cannot evaluate nested transactions or guarded account features")+ utxoValue utxo = do+ let input = Utxo.input utxo+ output = Utxo.output utxo+ unless (Input.index input <= fromIntegral (maxBound :: Word32)) unsupported+ reference <- traverse scriptValue (Output.referenceScript output)+ let value = Output.value output+ policies = Map.fromListWith (<>) [(Policy.toHex policy, [(Key.fromText (AssetName.toHex name), Number (fromInteger quantity))]) | (Native policy name, quantity) <- Amount.toList value]+ valueFields = ("ada", object ["lovelace" .= Amount.quantity Ada value]) : [(Key.fromText policy, Object (KeyMap.fromList entries)) | (policy, entries) <- Map.toList policies]+ datumFields = case Output.datum output of+ Datum.NoDatum -> []+ Datum.DatumHash hash -> ["datumHash" .= Hex.encodeHex (Datum.hashBytes hash)]+ Datum.InlineDatum encoded -> ["datum" .= Hex.encodeHex (Data.toCbor encoded)]+ pure+ [ object ["id" .= TxId.toHex (Input.transactionId input), "index" .= Input.index input],+ object (["address" .= Address.toText (Output.address output), "value" .= Object (KeyMap.fromList valueFields)] <> datumFields <> maybe [] (pure . ("script" .=)) reference)+ ]+ scriptValue (Script.Native script) = Right (object ["language" .= ("native" :: Text), "cbor" .= Hex.encodeHex (Native.encodeCbor script)])+ scriptValue (Script.Plutus script) = Right (object ["language" .= language (Plutus.version script), "cbor" .= Hex.encodeHex (Plutus.toBytes script)])+ language version = case version of+ Plutus.V1 -> "plutus:v1" :: Text+ Plutus.V2 -> "plutus:v2"+ Plutus.V3 -> "plutus:v3"+ Plutus.V4 -> "plutus:v4"
@@ -0,0 +1,241 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Decode the documented Blockfrost protocol snapshot without rounding money+-- or execution prices. Absent era fields remain unavailable.+module Cometa.Provider.Blockfrost.Internal.Protocol (decodeProtocolParameters, fraction, bounded, integer) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.DRepVotingThresholds (DRepVotingThresholds (..))+import Cometa.Protocol.ExUnitPrices (ExUnitPrices (..))+import qualified Cometa.Protocol.ExUnits as Units+import qualified Cometa.Protocol.Parameters as P+import Cometa.Protocol.PoolVotingThresholds (PoolVotingThresholds (..))+import qualified Cometa.Protocol.Rational as Fraction+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.UnitInterval as Interval+import Data.Aeson (Object, Value (..))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KeyMap+import Data.Aeson.Types (Parser, parseEither, withArray, withObject)+import qualified Data.ByteString as ByteString+import Data.Char (digitToInt, isDigit, isHexDigit)+import Data.Foldable (toList)+import Data.Int (Int64)+import Data.Ratio (denominator, numerator, (%))+import Data.Scientific (base10Exponent, floatingOrInteger)+import qualified Data.Text as Text+import Text.Read (readMaybe)++-- DEFINITIONS ----------------------------------------------------------------++-- | Reject incomplete grouped fields and invalid numeric domains. The failure+-- contains only the operation name, never response data.+decodeProtocolParameters :: Value -> Either Error P.Parameters+decodeProtocolParameters value = case parseEither (withObject "parameters" parameters) value of+ Left _ -> Left (InvalidProviderResponse "provider.protocolParameters")+ Right result -> Right result++parameters :: Object -> Parser P.Parameters+parameters object = do+ version <- Version.ProtocolVersion <$> required object "protocol_major_ver" bounded <*> required object "protocol_minor_ver" bounded+ byteCost <- optional object "coins_per_utxo_size" bounded+ -- Before Babbage this field has word units and cannot represent a byte cost.+ let utxoByteCost = if Version.major version >= 7 then byteCost else Nothing+ P.Parameters+ <$> required object "min_fee_a" bounded+ <*> required object "min_fee_b" bounded+ <*> required object "max_block_size" bounded+ <*> required object "max_tx_size" bounded+ <*> required object "max_block_header_size" bounded+ <*> required object "key_deposit" bounded+ <*> required object "pool_deposit" bounded+ <*> required object "e_max" bounded+ <*> required object "n_opt" bounded+ <*> required object "a0" fraction+ <*> required object "rho" interval+ <*> required object "tau" interval+ <*> optional object "decentralisation_param" interval+ <*> nonce object+ <*> pure version+ <*> required object "min_pool_cost" bounded+ <*> pure utxoByteCost+ <*> optional object "cost_models_raw" costModels+ <*> grouped object ["price_mem", "price_step"] (ExUnitPrices <$> required object "price_mem" fraction <*> required object "price_step" fraction)+ <*> exUnits object "max_tx_ex_mem" "max_tx_ex_steps"+ <*> exUnits object "max_block_ex_mem" "max_block_ex_steps"+ <*> optional object "max_val_size" bounded+ <*> optional object "collateral_percent" bounded+ <*> optional object "max_collateral_inputs" bounded+ <*> poolThresholds object+ <*> drepThresholds object+ <*> optional object "committee_min_size" bounded+ <*> optional object "committee_max_term_length" bounded+ <*> optional object "gov_action_lifetime" bounded+ <*> optional object "gov_action_deposit" bounded+ <*> optional object "drep_deposit" bounded+ <*> optional object "drep_activity" bounded+ <*> optional object "min_fee_ref_script_cost_per_byte" fraction+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing+ <*> pure Nothing++required :: Object -> Key.Key -> (Value -> Parser a) -> Parser a+required object key parser = maybe (fail "missing field") parser (KeyMap.lookup key object)++optional :: Object -> Key.Key -> (Value -> Parser a) -> Parser (Maybe a)+optional object key parser = case KeyMap.lookup key object of+ Nothing -> pure Nothing+ Just Null -> pure Nothing+ Just value -> Just <$> parser value++grouped :: Object -> [Key.Key] -> Parser a -> Parser (Maybe a)+grouped object keys parser+ | all absent keys = pure Nothing+ | any absent keys = fail "incomplete group"+ | otherwise = Just <$> parser+ where+ absent key = maybe True (== Null) (KeyMap.lookup key object)++integer :: Value -> Parser Integer+integer (Number value)+ | base10Exponent value >= -100 && base10Exponent value <= 100 = either (const (fail "integer required")) pure (floatingOrInteger value :: Either Double Integer)+integer (String value)+ | Text.length value <= 21 && not (Text.null value) && Text.all (\c -> isDigit c || c == '-') value = maybe (fail "integer required") pure (readMaybe (Text.unpack value))+integer _ = fail "integer required"++bounded :: (Integral a, Bounded a) => Value -> Parser a+bounded value = do+ number <- integer value+ checkedBound number++checkedBound :: (Integral a, Bounded a) => Integer -> Parser a+checkedBound number = result+ where+ result+ | number >= toInteger (minBound `asTypeOf` value) && number <= toInteger (maxBound `asTypeOf` value) = pure value+ | otherwise = fail "integer outside bounds"+ value = fromInteger number++exact :: Value -> Parser Rational+exact (Number value)+ | base10Exponent value >= -100 && base10Exponent value <= 100 = pure (toRational value)+exact (String value)+ | Text.length value <= 43 = case Text.splitOn "/" value of+ [n, d] -> do+ a <- integer (String n)+ b <- integer (String d)+ if a >= 0 && b > 0 then pure (a % b) else fail "invalid ratio"+ _ -> fail "fraction required"+exact _ = fail "fraction required"++fraction :: Value -> Parser Fraction.NonNegativeRational+fraction value = do+ ratio <- exact value+ checked (Fraction.mkNonNegativeRational (numerator ratio) (denominator ratio))++interval :: Value -> Parser Interval.UnitInterval+interval value = do+ ratio <- exact value+ checked (Interval.mkUnitInterval (numerator ratio) (denominator ratio))++checked :: Either Error a -> Parser a+checked = either (const (fail "invalid domain value")) pure++nonce :: Object -> Parser (Maybe P.Nonce)+nonce object = case KeyMap.lookup "extra_entropy" object of+ Nothing -> pure Nothing+ Just Null -> pure (Just P.neutralNonce)+ Just (String value)+ | Text.length value == 64 && Text.all isHexDigit value -> Just <$> checked (P.mkNonce (ByteString.pack (pairs (Text.unpack value))))+ _ -> fail "invalid entropy"+ where+ pairs (a : b : rest) = fromIntegral (digitToInt a * 16 + digitToInt b) : pairs rest+ pairs _ = []++costModels :: Value -> Parser Models.CostModels+costModels = withObject "cost models" $ \object -> Models.fromList <$> traverse model (KeyMap.toList object)+ where+ model (key, value) = do+ language <- case Key.toText key of+ "PlutusV1" -> pure 0+ "PlutusV2" -> pure 1+ "PlutusV3" -> pure 2+ "PlutusV4" -> pure 3+ _ -> fail "unknown cost model language"+ costs <- withArray "cost vector" (traverse bounded . toList) value :: Parser [Int64]+ checked (Models.mkCostModel language costs)++exUnits :: Object -> Key.Key -> Key.Key -> Parser (Maybe Units.ExUnits)+exUnits object memory steps = grouped object [memory, steps] $ do+ memoryValue <- required object memory integer+ stepValue <- required object steps integer+ checked (Units.mkExUnits memoryValue stepValue)++poolThresholds :: Object -> Parser (Maybe PoolVotingThresholds)+poolThresholds object =+ grouped object keys $+ PoolVotingThresholds+ <$> get "pvt_motion_no_confidence"+ <*> get "pvt_committee_normal"+ <*> get "pvt_committee_no_confidence"+ <*> get "pvt_hard_fork_initiation"+ <*> get "pvt_p_p_security_group"+ where+ keys = ["pvt_motion_no_confidence", "pvt_committee_normal", "pvt_committee_no_confidence", "pvt_hard_fork_initiation", "pvt_p_p_security_group"]+ get key = required object key interval++drepThresholds :: Object -> Parser (Maybe DRepVotingThresholds)+drepThresholds object =+ grouped object keys $+ DRepVotingThresholds+ <$> get "dvt_motion_no_confidence"+ <*> get "dvt_committee_normal"+ <*> get "dvt_committee_no_confidence"+ <*> get "dvt_update_to_constitution"+ <*> get "dvt_hard_fork_initiation"+ <*> get "dvt_p_p_network_group"+ <*> get "dvt_p_p_economic_group"+ <*> get "dvt_p_p_technical_group"+ <*> get "dvt_p_p_gov_group"+ <*> get "dvt_treasury_withdrawal"+ where+ keys = ["dvt_motion_no_confidence", "dvt_committee_normal", "dvt_committee_no_confidence", "dvt_update_to_constitution", "dvt_hard_fork_initiation", "dvt_p_p_network_group", "dvt_p_p_economic_group", "dvt_p_p_technical_group", "dvt_p_p_gov_group", "dvt_treasury_withdrawal"]+ get key = required object key interval
@@ -0,0 +1,317 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Provider queries over an injectable, bounded HTTP transport. No operation+-- retries a POST or emits credential-bearing response/request diagnostics.+module Cometa.Provider.Blockfrost.Internal.Provider (providerWithTransport) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (..))+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import Cometa.Provider.Blockfrost.Internal.Config (Config)+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Provider.Blockfrost.Internal.Protocol as Protocol+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Concurrent (threadDelay)+import Control.Monad (foldM, unless, when)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Aeson (Value (..), encode, (.:))+import Data.Aeson.Types (Parser, withObject, withText)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)++-- DEFINITIONS ----------------------------------------------------------------++providerWithTransport :: Config -> Http.Transport -> Provider.Provider+providerWithTransport config transport =+ (Provider.unavailable ("Blockfrost " <> Text.pack (show (Config.network config))) (Config.networkMagic (Config.network config)))+ { Provider.protocolParameters = guarded transport "blockfrost.protocolParameters" $ runExceptT $ do+ value <- requiredJSON transport "blockfrost.protocolParameters" ["epochs", "latest", "parameters"] []+ except (Protocol.decodeProtocolParameters value),+ Provider.utxosAt = \address -> guarded transport "blockfrost.utxosAt" (atAddress transport "blockfrost.utxosAt" address Nothing),+ Provider.utxosWithAsset = \address asset -> guarded transport "blockfrost.utxosWithAsset" (atAddress transport "blockfrost.utxosWithAsset" address (Just asset)),+ Provider.utxoWithAsset = guarded transport "blockfrost.utxoWithAsset" . uniqueAsset transport,+ Provider.resolveInputs = guarded transport "blockfrost.resolveInputs" . resolve transport,+ Provider.resolveDatum = guarded transport "blockfrost.resolveDatum" . datum transport,+ Provider.rewardBalance = guarded transport "blockfrost.rewardBalance" . rewards transport,+ Provider.submitTransaction = guarded transport "blockfrost.submitTransaction" . submit transport,+ Provider.evaluateTransaction = \transaction inputs -> guarded transport "blockfrost.evaluateTransaction" (evaluate transport transaction inputs),+ Provider.awaitTransaction = \identifier timeout -> guarded transport "blockfrost.awaitTransaction" (await config transport identifier timeout)+ }++guarded :: Http.Transport -> Text -> IO (Either Error a) -> IO (Either Error a)+guarded transport operation action = do+ current <- Http.checkOpen transport+ case current of+ Left failure -> pure (Left (transportError operation failure))+ Right () -> action++transportError :: Text -> Http.HttpFailure -> Error+transportError operation failure = case failure of+ Http.Closed -> RuntimeClosed+ Http.Timeout -> ProviderTransportError operation "timeout"+ Http.ConnectionFailure -> ProviderTransportError operation "connection failure"+ Http.ResponseTooLarge -> ProviderTransportError operation "response too large"++getRequest :: [Text] -> [(Text, Text)] -> Http.Request+getRequest path query = Http.Request Http.Get path [(key, Just value) | (key, value) <- query] "" "" Nothing++send :: Http.Transport -> Text -> Http.Request -> IO (Either Error Http.Response)+send transport operation request = either (Left . transportError operation) Right <$> Http.send transport request++getJSON :: Http.Transport -> Text -> [Text] -> [(Text, Text)] -> Bool -> IO (Either Error (Maybe Value))+getJSON transport operation path query missing = do+ result <- send transport operation (getRequest path query)+ pure $ do+ response <- result+ case Http.status response of+ 200 -> Just <$> Json.decodeValue operation (Http.bodyBytes response)+ 404 | missing -> Right Nothing+ code -> Left (ProviderHttpError operation code)++requiredJSON :: Http.Transport -> Text -> [Text] -> [(Text, Text)] -> ExceptT Error IO Value+requiredJSON transport operation path query = do+ value <- ExceptT (getJSON transport operation path query False)+ maybe (throwE (InvalidProviderResponse operation)) pure value++-- Reject repeated identities rather than quietly truncate or retain conflicting+-- snapshots across pages. A fixed request bound prevents endless distinct pages.+pages :: Http.Transport -> Text -> [Text] -> IO (Either Error [Json.Row])+pages transport operation path = runExceptT (go 1 Set.empty [])+ where+ go page seen chunks = do+ when (page > 10000) (throwE (InvalidProviderResponse operation))+ response <- ExceptT (getJSON transport operation path [("count", "100"), ("page", Text.pack (show page)), ("order", "asc")] (page == (1 :: Int)))+ current <- maybe (pure []) (except . Json.parseValue operation Json.rows) response+ let identities = map Json.rowInput current+ unless (length current <= 100 && Set.size (Set.fromList identities) == length identities && all (`Set.notMember` seen) identities) (throwE (InvalidProviderResponse operation))+ let completed = current : chunks+ if length current < 100+ then pure (concat (reverse completed))+ else go (page + 1) (Set.union seen (Set.fromList identities)) completed++atAddress :: Http.Transport -> Text -> Address.Address -> Maybe AssetId -> IO (Either Error [Utxo.Utxo])+atAddress transport operation address asset = runExceptT $ do+ let suffix = case asset of Just value@Native {} -> [Json.assetText value]; _ -> []+ found <- ExceptT (pages transport operation (["addresses", Address.toText address, "utxos"] <> suffix))+ unless (all ((== address) . Json.rowAddress) found) (throwE (InvalidProviderResponse operation))+ values <- ExceptT (materialize transport operation found)+ pure $ case asset of Nothing -> values; Just value -> filter ((> 0) . Amount.quantity value . Output.value . Utxo.output) values++uniqueAsset :: Http.Transport -> AssetId -> IO (Either Error (Maybe Utxo.Utxo))+uniqueAsset _ Ada = pure (Left (UnsupportedOperation "NFT lookup requires a native asset"))+uniqueAsset transport asset = runExceptT $ do+ found <- ExceptT (pages transport operation ["assets", Json.assetText asset, "utxos"])+ values <- ExceptT (materialize transport operation found)+ case values of+ [] -> pure Nothing+ [value] | Amount.quantity asset (Output.value (Utxo.output value)) == 1 -> pure (Just value)+ _ -> throwE (InvalidProviderResponse operation)+ where+ operation = "blockfrost.utxoWithAsset"++materialize :: Http.Transport -> Text -> [Json.Row] -> IO (Either Error [Utxo.Utxo])+materialize transport operation found = runExceptT $ reverse . snd <$> foldM step (Map.empty, []) found+ where+ step (scripts, values) row = do+ case (Json.rowDatum row, Json.rowDatumHash row) of+ (Datum.InlineDatum encoded, Just expected) -> verifyDatum operation expected encoded+ _ -> pure ()+ (updated, script) <- case Json.rowScriptHash row of+ Nothing -> pure (scripts, Nothing)+ Just hash -> case Map.lookup hash scripts of+ Just known -> pure (scripts, Just known)+ Nothing -> do+ fetched <- fetchScript transport operation hash+ pure (Map.insert hash fetched scripts, Just fetched)+ output <- except (mapResponse operation (Output.mkOutput (Json.rowAddress row) (Json.rowValue row) (Json.rowDatum row) script))+ pure (updated, Utxo.utxo (Json.rowInput row) output : values)++mapResponse :: Text -> Either Error a -> Either Error a+mapResponse operation = either (const (Left (InvalidProviderResponse operation))) Right++fetchScript :: Http.Transport -> Text -> Credential.ScriptHash -> ExceptT Error IO Script.Script+fetchScript transport operation expected = do+ let path = ["scripts", Hex.encodeHex (Credential.scriptHashBytes expected)]+ metadata <- requiredJSON transport operation path []+ (hash, kind) <- except (Json.parseValue operation (withObject "script metadata" (\entry -> (,) <$> (entry .: "script_hash" >>= Json.parseHex) <*> entry .: "type")) metadata)+ unless (hash == Credential.scriptHashBytes expected) (throwE (InvalidProviderResponse operation))+ script <- case kind :: Text of+ "timelock" -> do+ payload <- requiredJSON transport operation (path <> ["json"]) []+ Script.Native <$> except (Json.parseValue operation (withObject "script JSON" (\entry -> entry .: "json" >>= Json.nativeScript)) payload)+ _ -> do+ version <- except $ case kind of+ "plutusV1" -> Right Plutus.V1+ "plutusV2" -> Right Plutus.V2+ "plutusV3" -> Right Plutus.V3+ _ -> Left (UnsupportedOperation "Blockfrost returned an unsupported reference script language")+ payload <- requiredJSON transport operation (path <> ["cbor"]) []+ bytes <- except (Json.parseValue operation cborField payload)+ Script.Plutus <$> except (mapResponse operation (Plutus.fromBytes version bytes))+ actual <- ExceptT (Script.hash script)+ unless (actual == expected) (throwE (InvalidProviderResponse operation))+ pure script++cborField :: Value -> Parser ByteString+cborField = withObject "CBOR response" (\entry -> entry .: "cbor" >>= Json.parseHex)++verifyDatum :: Text -> Datum.Hash32 -> Data.EncodedPlutusData -> ExceptT Error IO ()+verifyDatum operation expected encoded = do+ actual <- ExceptT (Data.hash encoded)+ unless (Blake2b.toBytes actual == Datum.hashBytes expected) (throwE (InvalidProviderResponse operation))++datum :: Http.Transport -> Datum.Hash32 -> IO (Either Error (Maybe Data.EncodedPlutusData))+datum transport hash = runExceptT $ do+ response <- ExceptT (getJSON transport operation ["scripts", "datum", Hex.encodeHex (Datum.hashBytes hash), "cbor"] [] True)+ case response of+ Nothing -> pure Nothing+ Just value -> do+ bytes <- except (Json.parseValue operation cborField value)+ encoded <- except (mapResponse operation (Data.decodeCbor bytes))+ verifyDatum operation hash encoded+ pure (Just encoded)+ where+ operation = "blockfrost.resolveDatum"++rewards :: Http.Transport -> Reward.RewardAddress -> IO (Either Error Word64)+rewards transport account = runExceptT $ do+ response <- ExceptT (getJSON transport operation ["accounts", Reward.toText account] [] True)+ maybe (pure 0) (except . Json.parseValue operation parser) response+ where+ operation = "blockfrost.rewardBalance"+ parser = withObject "reward account" $ \entry -> do+ text <- entry .: "stake_address"+ actual <- either (const (fail "Invalid reward account")) pure (Reward.fromText text)+ unless (actual == account) (fail "Account identity mismatch")+ entry .: "withdrawable_amount" >>= Json.parseQuantity++-- Historical tx outputs alone do not establish spendability. Cross-check each+-- discovered address through the current UTxO endpoint, then return only the+-- requested identities in first-request order. These observations are not atomic.+resolve :: Http.Transport -> [Input.Input] -> IO (Either Error [Utxo.Utxo])+resolve transport requested = runExceptT $ do+ let unique = distinct requested+ transactionIds = distinct (map Input.transactionId unique)+ discovered <- concat <$> traverse discover transactionIds+ let addresses = distinct (map snd discovered)+ eligible = Set.fromList (map fst discovered)+ snapshots <- traverse (\address -> ExceptT (atAddress transport operation address Nothing)) addresses+ let found = Map.fromList [(Utxo.input value, value) | value <- concat snapshots, Set.member (Utxo.input value) eligible]+ pure (mapMaybe (`Map.lookup` found) unique)+ where+ operation = "blockfrost.resolveInputs"+ discover transaction = do+ response <- ExceptT (getJSON transport operation ["txs", TxId.toHex transaction, "utxos"] [] True)+ entries <- maybe (pure []) (except . Json.parseValue operation (Json.transactionAddresses transaction)) response+ pure [(reference, address) | (reference, address) <- entries, reference `elem` requested]++distinct :: (Ord a) => [a] -> [a]+distinct = go Set.empty+ where+ go _ [] = []+ go seen (value : rest)+ | Set.member value seen = go seen rest+ | otherwise = value : go (Set.insert value seen) rest++submit :: Http.Transport -> Tx.Transaction -> IO (Either Error TxId.TransactionId)+submit transport transaction = runExceptT $ do+ expected <- ExceptT (Tx.transactionId transaction)+ response <- ExceptT (send transport operation (Http.Request Http.Post ["tx", "submit"] [] (Tx.encodeCbor transaction) "application/cbor" Nothing))+ unless (Http.status response == 200) (throwE (ProviderHttpError operation (Http.status response)))+ value <- except (Json.decodeValue operation (Http.bodyBytes response))+ identifier <- except (Json.parseValue operation (withText "transaction hash" (either (const (fail "Invalid transaction hash")) pure . TxId.fromHex)) value)+ unless (identifier == expected) (throwE (InvalidProviderResponse operation))+ pure identifier+ where+ operation = "blockfrost.submitTransaction"++evaluate :: Http.Transport -> Tx.Transaction -> [Utxo.Utxo] -> IO (Either Error Evaluation.Budgets)+evaluate transport transaction inputs = runExceptT $ do+ payload <- except (Json.evaluationPayload transaction inputs)+ response <- ExceptT (send transport operation (Http.Request Http.Post ["utils", "txs", "evaluate", "utxos"] [("version", Just "6")] (Lazy.toStrict (encode payload)) "application/json" Nothing))+ unless (Http.status response == 200) (throwE (ProviderHttpError operation (Http.status response)))+ value <- except (Json.decodeValue operation (Http.bodyBytes response))+ except (Json.decodeBudgets transaction value)+ where+ operation = "blockfrost.evaluateTransaction"++await :: Config -> Http.Transport -> TxId.TransactionId -> Word64 -> IO (Either Error Bool)+await _ _ _ 0 = pure (Right False)+await config transport identifier milliseconds = do+ started <- getMonotonicTimeNSec+ loop (toInteger started + toInteger milliseconds * 1000000)+ where+ operation = "blockfrost.awaitTransaction"+ loop deadline = do+ now <- toInteger <$> getMonotonicTimeNSec+ if now >= deadline+ then pure (Right False)+ else do+ let remaining = max 1 ((deadline - now + 999999) `div` 1000000)+ request = (getRequest ["txs", TxId.toHex identifier] []) {Http.requestTimeoutMillis = Just (fromInteger (min remaining (toInteger (Config.responseTimeoutMillis config))))}+ result <- send transport operation request+ case result of+ Left failure -> do+ finished <- toInteger <$> getMonotonicTimeNSec+ pure $ if finished >= deadline && failure == ProviderTransportError operation "timeout" then Right False else Left failure+ Right response -> case Http.status response of+ 200 -> pure $ do+ value <- Json.decodeValue operation (Http.bodyBytes response)+ Json.parseValue operation confirmed value+ pure True+ 404 -> do+ finished <- toInteger <$> getMonotonicTimeNSec+ let delay = min (toInteger (Config.pollIntervalMillis config) * 1000) (max 0 ((deadline - finished) `div` 1000))+ when (delay > 0) (threadDelay (fromInteger delay))+ loop deadline+ code -> pure (Left (ProviderHttpError operation code))+ confirmed = withObject "confirmed transaction" $ \entry -> do+ text <- entry .: "hash"+ actual <- either (const (fail "Invalid transaction hash")) pure (TxId.fromHex text)+ unless (actual == identifier) (fail "Transaction identity mismatch")+ block <- entry .: "block" >>= Json.parseHex+ unless (B.length block == 32) (fail "Invalid block hash")+ _ <- entry .: "block_height" >>= Json.parseNatural+ pure ()
@@ -0,0 +1,75 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Scoped Hydra queries and explicit submission through the ordinary Provider+-- record. Responses are bounded to 8 MiB. Submission is never retried.+-- Submissions target /transaction on an existing+-- Conway Head. Remote evaluation and staking rewards are unsupported.+-- Confirmation polls the latest signed snapshot transaction list: older+-- transactions absent from that list cannot be rediscovered. This is L2+-- confirmation, not Cardano L1 settlement. Head lifecycle operations are external.+--+-- @+-- withProvider (defaultConfig Preprod "http://localhost:4001") $ \provider ->+-- Cometa.Provider.protocolParameters provider+-- @+module Cometa.Provider.Hydra (Network (..), ApiKey, mkApiKey, Config (..), defaultConfig, withProvider) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Provider (Provider)+import qualified Cometa.Provider.Blockfrost.Internal.Config as HttpConfig+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import Cometa.Provider.Internal.Config (ApiKey, Network (..), apiKeyBytes, mkApiKey, transportConfig)+import qualified Cometa.Provider.Internal.Hydra as Hydra+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | Explicit chain, endpoint, credentials and bounded timing settings.+-- No environment variables or files are read implicitly.+data Config = Config+ { -- | Chain identity, independent of the custom endpoint.+ network :: !Network,+ -- | Absolute HTTP(S) URL. No user information or fragment is accepted.+ -- Base path and query parameters are retained; operation queries win.+ endpoint :: !Text,+ -- | Optional credential; Nothing supports an unauthenticated proxy.+ apiKey :: !(Maybe ApiKey),+ -- | Whole-request timeout in milliseconds, from 1 through 60000.+ responseTimeoutMillis :: !Int,+ -- | Confirmation poll interval in milliseconds, from 1 through 60000.+ pollIntervalMillis :: !Int+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Explicit endpoint, 30-second request timeout and one-second poll interval.+defaultConfig :: Network -> Text -> Config+defaultConfig selected url = Config selected url Nothing 30000 1000++-- | Validate configuration, acquire a scoped connection pool and run a workflow.+-- Scope exit drains active requests; cancellation propagates after cleanup.+-- An escaped provider returns RuntimeClosed without opening a connection.+withProvider :: Config -> (Provider -> IO (Either Error a)) -> IO (Either Error a)+withProvider config action = case HttpConfig.validateConfig settings of+ Left failure -> pure (Left failure)+ Right () -> Http.withHeaders settings headers $ \transport ->+ action (Hydra.provider settings transport)+ where+ settings = transportConfig (network config) (endpoint config) (responseTimeoutMillis config) (pollIntervalMillis config)+ headers = [("Authorization", "Bearer " <> apiKeyBytes key) | Just key <- [apiKey config]]
@@ -0,0 +1,237 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Owned ledger values for the Koios and Ogmios wire formats.+module Cometa.Provider.Internal.Codec+ ( parse,+ field,+ list,+ natural,+ checked,+ inputText,+ input,+ unique,+ datum,+ script,+ koiosOutput,+ ogmiosOutput,+ evaluationPayload,+ budgets,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.ExUnits as Units+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Monad (unless, when, (>=>))+import Control.Monad.Trans.Except (ExceptT (..), except, throwE)+import Data.Aeson (Value (..), object, (.:), (.:?), (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (Parser, withArray, withObject)+import Data.Foldable (toList)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++parse :: (Value -> Parser a) -> Value -> Either Error a+parse = Json.parseValue "provider.response"++checked :: Either Error a -> Parser a+checked = either (const (fail "Invalid ledger value")) pure++field :: Text -> Value -> Parser Value+field name = withObject "object" (.: Key.fromText name)++list :: Value -> Parser [Value]+list = withArray "array" (pure . toList)++natural :: Value -> Parser Word64+natural (String value) = Json.parseQuantity value+natural value = Json.parseNatural value++inputText :: Input.Input -> Text+inputText value = TxId.toHex (Input.transactionId value) <> "#" <> Text.pack (show (Input.index value))++input :: Text -> Text -> Value -> Parser Input.Input+input hashKey indexKey = withObject "output reference" $ \entry -> do+ tx <- entry .: Key.fromText hashKey >>= checked . TxId.fromHex+ index <- entry .: Key.fromText indexKey >>= natural+ when (index > 65535) (fail "Output index exceeds ledger bounds")+ pure (Input.input tx index)++unique :: (Ord a) => [a] -> Either Error ()+unique values = unless (Set.size (Set.fromList values) == length values) (Left (InvalidProviderResponse "Duplicate response identity"))++-- Hash checks are effectful native operations; decoded values remain Haskell-owned.+datum :: Datum.Hash32 -> Text -> ExceptT Error IO Data.EncodedPlutusData+datum expected text = do+ bytes <- except (parse (const (Json.parseHex text)) Null)+ encoded <- except (Data.decodeCbor bytes)+ hash <- ExceptT (Data.hash encoded)+ unless (Blake2b.toBytes hash == Datum.hashBytes expected) (throwE (InvalidProviderResponse "Datum hash mismatch"))+ pure encoded++script :: Text -> Maybe Text -> Maybe Value -> Text -> ExceptT Error IO Script.Script+script language bytes json expected = do+ value <- except $ parse (const decode) Null+ hash <- ExceptT (Script.hash value)+ unless (Hex.encodeHex (Credential.scriptHashBytes hash) == Text.toLower expected) (throwE (InvalidProviderResponse "Reference script hash mismatch"))+ pure value+ where+ decode = case language of+ "timelock" | Nothing <- bytes, Just value <- json -> Script.Native <$> Json.nativeScript value+ "timelock" -> native+ "native" -> native+ _ -> do+ version <- maybe (fail "Unsupported reference script language") pure (lookup language versions)+ Script.Plutus <$> (raw >>= checked . Plutus.fromBytes version)+ raw = maybe (fail "Missing script bytes") Json.parseHex bytes+ native = Script.Native <$> (raw >>= checked . Native.decodeCbor)+ versions =+ [ ("plutusV1", Plutus.V1),+ ("plutusV2", Plutus.V2),+ ("plutusV3", Plutus.V3),+ ("plutusV4", Plutus.V4),+ ("plutus:v1", Plutus.V1),+ ("plutus:v2", Plutus.V2),+ ("plutus:v3", Plutus.V3),+ ("plutus:v4", Plutus.V4)+ ]++koiosOutput :: Value -> ExceptT Error IO Utxo.Utxo+koiosOutput source = do+ (reference, address, amount, hash, inline, referenceScript) <- except (parse parser source)+ dat <- case (hash, inline) of+ (Just expected, Just bytes) -> Datum.InlineDatum <$> datum expected bytes+ (Nothing, Just _) -> throwE (InvalidProviderResponse "Missing inline datum hash")+ (Just expected, Nothing) -> pure (Datum.DatumHash expected)+ _ -> pure Datum.NoDatum+ ref <- traverse (\(kind, bytes, json, expected) -> script kind bytes json expected) referenceScript+ output <- except (Output.mkOutput address amount dat ref)+ pure (Utxo.utxo reference output)+ where+ parser = withObject "Koios output" $ \entry -> do+ reference <- input "tx_hash" "tx_index" (Object entry)+ address <- entry .: "address" >>= checked . Address.fromText+ coins <- entry .: "value" >>= natural+ assets <- entry .:? "asset_list" >>= traverse asset . fromMaybe []+ checked (unique (map fst assets))+ hash <- entry .:? "datum_hash" >>= traverse (Json.parseHex >=> checked . Datum.hashFromBytes)+ inline <- entry .:? "inline_datum" >>= traverse (withObject "inline datum" (.: "bytes"))+ ref <- entry .:? "reference_script" >>= traverse (withObject "reference script" (\s -> (,,,) <$> s .: "type" <*> s .:? "bytes" <*> s .:? "value" <*> s .: "hash"))+ pure (reference, address, Amount.lovelace (toInteger coins) <> foldMap (uncurry Amount.singleton) assets, hash, inline, ref)+ asset = withObject "asset" $ \entry -> do+ policy <- entry .: "policy_id" >>= checked . Policy.fromHex+ name <- entry .: "asset_name" >>= checked . AssetName.fromHex+ quantity <- entry .: "quantity" >>= natural+ when (quantity == 0) (fail "Zero asset quantity")+ pure (Native policy name, toInteger quantity)++ogmiosOutput :: Utxo.Utxo -> Either Error Value+ogmiosOutput utxo = do+ unless (Input.index reference <= 65535) (Left (InvalidEvaluationRequest "Output index exceeds ledger bounds"))+ let amounts = Amount.toList (Output.value output)+ policies = Map.fromListWith (<>) [(Policy.toHex policy, [(Key.fromText (AssetName.toHex name), Number (fromInteger quantity))]) | (Native policy name, quantity) <- amounts]+ value = Object (KM.fromList (("ada", object ["lovelace" .= Amount.quantity Ada (Output.value output)]) : [(Key.fromText policy, Object (KM.fromList entries)) | (policy, entries) <- Map.toList policies]))+ dat = case Output.datum output of+ Datum.NoDatum -> []+ Datum.DatumHash hash -> ["datumHash" .= Hex.encodeHex (Datum.hashBytes hash)]+ Datum.InlineDatum encoded -> ["datum" .= Hex.encodeHex (Data.toCbor encoded)]+ ref = case Output.referenceScript output of+ Nothing -> []+ Just (Script.Native native) -> ["script" .= object ["language" .= ("native" :: Text), "cbor" .= Hex.encodeHex (Native.encodeCbor native)]]+ Just (Script.Plutus plutus) -> ["script" .= object ["language" .= language (Plutus.version plutus), "cbor" .= Hex.encodeHex (Plutus.toBytes plutus)]]+ pure+ ( object+ ( [ "transaction" .= object ["id" .= TxId.toHex (Input.transactionId reference)],+ "index" .= Input.index reference,+ "address" .= Address.toText (Output.address output),+ "value" .= value+ ]+ <> dat+ <> ref+ )+ )+ where+ reference = Utxo.input utxo+ output = Utxo.output utxo+ language version = case version of+ Plutus.V1 -> "plutus:v1" :: Text+ Plutus.V2 -> "plutus:v2"+ Plutus.V3 -> "plutus:v3"+ Plutus.V4 -> "plutus:v4"++evaluationPayload :: Tx.Transaction -> [Utxo.Utxo] -> Either Error Value+evaluationPayload transaction additional = do+ unique (map Utxo.input additional)+ outputs <- traverse ogmiosOutput additional+ pure $ object ["transaction" .= object ["cbor" .= cbor], "additionalUtxo" .= outputs]+ where+ cbor = Hex.encodeHex (Tx.encodeCbor transaction)++budgets :: Tx.Transaction -> Value -> Either Error Evaluation.Budgets+budgets transaction value = do+ pairs <- parse (list >=> traverse budget) value+ result <- Evaluation.mkBudgets pairs+ let expected = Set.fromList [Evaluation.RedeemerId (Redeemer.purpose r) (Redeemer.index r) | r <- Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction))]+ unless (Set.fromList (map fst pairs) == expected) (Left (InvalidEvaluationResult "Budgets must cover exactly the existing redeemers"))+ pure result+ where+ budget = withObject "budget" $ \entry -> do+ validator <- entry .: "validator"+ (purpose, index) <- withObject "validator" (\v -> (,) <$> v .: "purpose" <*> (v .: "index" >>= natural)) validator+ when (index > 4294967295) (fail "Redeemer index overflow")+ tag <- maybe (fail "Unsupported redeemer purpose") pure (lookup purpose tags)+ units <- entry .: "budget" >>= withObject "units" (\u -> Units.ExUnits <$> (u .: "memory" >>= natural) <*> (u .: "cpu" >>= natural))+ pure (Evaluation.RedeemerId tag (fromIntegral index), units)+ tags =+ [ ("spend" :: Text, Redeemer.Spending),+ ("mint", Redeemer.Minting),+ ("publish", Redeemer.Certifying),+ ("withdraw", Redeemer.Rewarding),+ ("vote", Redeemer.Voting),+ ("propose", Redeemer.Proposing)+ ]
@@ -0,0 +1,47 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Validated credentials and shared transport settings.+module Cometa.Provider.Internal.Config (Network (..), ApiKey, mkApiKey, apiKeyBytes, transportConfig) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Provider.Blockfrost.Internal.Config (Network (..))+import qualified Cometa.Provider.Blockfrost.Internal.Config as Http+import Data.ByteString (ByteString)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text++-- DEFINITIONS ----------------------------------------------------------------++-- | Opaque HTTP credential. Its contents have no printable instance.+newtype ApiKey = ApiKey ByteString deriving (Eq)++-- | Validate 1 through 4096 printable ASCII characters, excluding whitespace.+-- This accepts opaque API keys and bearer tokens without exposing diagnostics.+mkApiKey :: Text -> Either Error ApiKey+mkApiKey value+ | Text.null value || Text.length value > 4096 || not (Text.all (\c -> c >= '!' && c <= '~') value) = Left (InvalidProviderConfiguration "Invalid API credential")+ | otherwise = Right (ApiKey (Text.encodeUtf8 value))++apiKeyBytes :: ApiKey -> ByteString+apiKeyBytes (ApiKey bytes) = bytes++transportConfig :: Network -> Text -> Int -> Int -> Http.Config+transportConfig network endpoint = Http.Config network endpoint Nothing
@@ -0,0 +1,236 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Hydra's HTTP operations for an existing Conway Head. No L1 submission or+-- head-lifecycle command is issued by this provider.+module Cometa.Provider.Internal.Hydra (provider) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (..))+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Provider.Internal.Codec as C+import qualified Cometa.Provider.Internal.Protocol as Protocol+import Cometa.Provider.Internal.Remote (json, jsonRequest, parse, request, transportError)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Concurrent (threadDelay)+import Control.Monad (unless, when, (>=>))+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Aeson (Value (..), object, (.:), (.:?), (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (Parser, withObject)+import qualified Data.Map.Strict as Map+import Data.Maybe (isJust, mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)++-- DEFINITIONS ----------------------------------------------------------------++provider :: Config.Config -> Http.Transport -> Provider.Provider+provider config transport =+ (Provider.unavailable "Hydra" (Config.networkMagic (Config.network config)))+ { Provider.protocolParameters = run (get ["protocol-parameters"] >>= except . Protocol.decodeHydraParameters),+ Provider.utxosAt = \address -> run (filter ((== address) . Output.address . Utxo.output) <$> outputs),+ Provider.utxosWithAsset = \address asset -> run (filter (\u -> Output.address (Utxo.output u) == address && quantity asset u > 0) <$> outputs),+ Provider.utxoWithAsset = \asset -> run $ do+ when (asset == Ada) (throwE (UnsupportedOperation "NFT lookup requires a native asset"))+ found <- filter ((> 0) . quantity asset) <$> outputs+ case found of+ [] -> pure Nothing+ [u] | quantity asset u == 1 -> pure (Just u)+ _ -> invalid,+ Provider.resolveInputs = \references -> run $ do+ values <- outputs+ let table = Map.fromList [(Utxo.input u, u) | u <- values]+ pure (mapMaybe (`Map.lookup` table) (distinct references)),+ Provider.resolveDatum = \hash -> run (outputs >>= findDatum hash),+ Provider.rewardBalance = \_ -> run (throwE (UnsupportedOperation "Hydra Heads do not support staking rewards")),+ Provider.evaluateTransaction = \_ _ -> run (throwE (UnsupportedOperation "Hydra has no remote evaluation endpoint; configure a local evaluator")),+ Provider.submitTransaction = run . submit transport,+ Provider.awaitTransaction = \identifier timeout -> run (await config transport identifier timeout)+ }+ where+ run action = runExceptT $ do+ ExceptT (fmap (either (Left . transportError) Right) (Http.checkOpen transport))+ action+ get path = json transport (jsonRequest Http.Get path [] Nothing) False >>= maybe invalid pure+ outputs = get ["snapshot", "utxo"] >>= parse (withObject "UTxO" (pure . KM.toList)) >>= traverse output+ quantity asset = Amount.quantity asset . Output.value . Utxo.output++invalid :: ExceptT Error IO a+invalid = throwE (InvalidProviderResponse "hydra.response")++distinct :: (Ord a) => [a] -> [a]+distinct = go Set.empty+ where+ go _ [] = []+ go seen (x : xs)+ | Set.member x seen = go seen xs+ | otherwise = x : go (Set.insert x seen) xs++output :: (Key.Key, Value) -> ExceptT Error IO Utxo.Utxo+output (key, row) = do+ (reference, address, amount, hash, raw, inlineHash, inlinePresent, script) <- parse parser row+ dat <- case raw of+ Just bytes -> do+ when (isJust hash) invalid+ encoded <- except (Data.decodeCbor bytes)+ case inlineHash of+ Nothing -> pure ()+ Just expected -> do+ actual <- ExceptT (Data.hash encoded)+ unless (Blake2b.toBytes actual == Datum.hashBytes expected) invalid+ pure (Datum.InlineDatum encoded)+ Nothing -> do+ when (inlinePresent || isJust inlineHash) invalid+ pure (maybe Datum.NoDatum Datum.DatumHash hash)+ result <- except (Output.mkOutput address amount dat script)+ pure (Utxo.utxo reference result)+ where+ parser = withObject "Hydra output" $ \o -> do+ reference <- case Text.splitOn "#" (Key.toText key) of+ [tx, index] -> C.input "tx_hash" "index" (object ["tx_hash" .= tx, "index" .= index])+ _ -> fail "Invalid input reference"+ address <- o .: "address" >>= C.checked . Address.fromText+ amount <-+ o .: "value"+ >>= withObject+ "value"+ ( \v -> do+ coins <- maybe (pure 0) C.natural (KM.lookup "lovelace" v)+ assets <- concat <$> traverse asset [(p, a) | (p, a) <- KM.toList v, p /= "lovelace"]+ C.checked (C.unique (map fst assets))+ pure (Amount.lovelace (toInteger coins) <> foldMap (uncurry Amount.singleton) assets)+ )+ hash <- o .:? "datumhash" >>= traverse hashValue+ raw <- o .:? "inlineDatumRaw" >>= traverse Json.parseHex+ inlineHash <- o .:? "inlineDatumhash" >>= traverse hashValue+ inline <- o .:? "inlineDatum" :: Parser (Maybe Value)+ script <- o .:? "referenceScript" >>= traverse scriptValue+ pure (reference, address, amount, hash, raw, inlineHash, isJust inline, script)+ hashValue text = Json.parseHex text >>= C.checked . Datum.hashFromBytes+ asset (policy, value) = withObject "assets" (traverse (token (Key.toText policy)) . KM.toList) value+ token policy (name, value) = do+ identifier <- Json.parseAsset (policy <> Key.toText name)+ quantity <- C.natural value+ when (quantity == 0) (fail "Zero asset quantity")+ pure (identifier, toInteger quantity)+ scriptValue = withObject "reference script" $ \o -> do+ language <- o .: "scriptLanguage"+ o .: "script"+ >>= withObject+ "script envelope"+ ( \s -> do+ kind <- s .: "type"+ bytes <- s .: "cborHex" >>= Json.parseHex+ if kind == ("SimpleScript" :: Text)+ then do+ unless (language == ("SimpleScriptLanguage" :: Text)) (fail "Script language mismatch")+ Script.Native <$> C.checked (Native.decodeCbor bytes)+ else do+ version <- maybe (fail "Unsupported Hydra script language") pure (lookup kind [("PlutusScriptV1", Plutus.V1), ("PlutusScriptV2", Plutus.V2), ("PlutusScriptV3", Plutus.V3)])+ unless (language == "PlutusScriptLanguage " <> kind) (fail "Script language mismatch")+ Script.Plutus <$> C.checked (Plutus.decodeCbor version bytes)+ )++findDatum :: Datum.Hash32 -> [Utxo.Utxo] -> ExceptT Error IO (Maybe Data.EncodedPlutusData)+findDatum _ [] = pure Nothing+findDatum expected (u : rest) = case Output.datum (Utxo.output u) of+ Datum.InlineDatum encoded -> do+ hash <- ExceptT (Data.hash encoded)+ if Blake2b.toBytes hash == Datum.hashBytes expected then pure (Just encoded) else findDatum expected rest+ _ -> findDatum expected rest++submit :: Http.Transport -> Tx.Transaction -> ExceptT Error IO TxId.TransactionId+submit transport transaction = do+ expected <- ExceptT (Tx.transactionId transaction)+ response <- request transport (jsonRequest Http.Post ["transaction"] [] (Just (object ["type" .= ("Tx ConwayEra" :: Text), "description" .= ("" :: Text), "cborHex" .= Hex.encodeHex (Tx.encodeCbor transaction)])))+ value <- except (Json.decodeValue "hydra.submitTransaction" (Http.bodyBytes response))+ tag <- parse (withObject "submission" (.: "tag")) value+ case (Http.status response, tag :: Text) of+ (200, "SubmitTxConfirmed") -> parse (C.field "snapshotNumber" >=> C.natural) value >> pure expected+ (202, "SubmitTxSubmitted") -> pure expected+ (status, _) | status /= 200 && status /= 202 -> throwE (ProviderHttpError "hydra.submitTransaction" status)+ _ -> invalid++-- Poll only explicit confirmed transaction records. A committed L1 output is+-- not evidence that its originating transaction was executed inside the Head.+confirmed :: Http.Transport -> TxId.TransactionId -> Int -> ExceptT Error IO Bool+confirmed transport expected remaining = do+ result <- json transport ((jsonRequest Http.Get ["snapshot"] [] Nothing) {Http.requestTimeoutMillis = Just remaining}) True+ case result of+ Nothing -> pure False+ Just value -> do+ tag <- parse (withObject "snapshot" (.: "tag")) value+ case tag :: Text of+ "InitialSnapshot" -> pure False+ "ConfirmedSnapshot" -> do+ snapshot <- parse (C.field "snapshot") value+ _ <- parse (C.field "number" >=> C.natural) snapshot+ rows <- parse (C.field "confirmed" >=> C.list) snapshot+ identifiers <- traverse identifier rows+ pure (expected `elem` identifiers)+ _ -> invalid+ where+ identifier row = do+ (encoded, claimed) <- parse (withObject "transaction" (\o -> (,) <$> (o .: "cborHex" >>= Json.parseHex >>= C.checked . Tx.decodeCbor) <*> o .:? "txId")) row+ actual <- ExceptT (Tx.transactionId encoded)+ unless (maybe True (== TxId.toHex actual) claimed) invalid+ pure actual++await :: Config.Config -> Http.Transport -> TxId.TransactionId -> Word64 -> ExceptT Error IO Bool+await _ _ _ 0 = pure False+await config transport identifier milliseconds = ExceptT $ do+ start <- toInteger <$> getMonotonicTimeNSec+ loop (start + toInteger milliseconds * 1000000)+ where+ loop deadline = do+ now <- toInteger <$> getMonotonicTimeNSec+ if now >= deadline+ then pure (Right False)+ else do+ let remaining = fromInteger (min (toInteger (Config.responseTimeoutMillis config)) ((deadline - now + 999999) `div` 1000000))+ result <- runExceptT (confirmed transport identifier remaining)+ finished <- toInteger <$> getMonotonicTimeNSec+ case result of+ Left failure | finished >= deadline && failure == transportError Http.Timeout -> pure (Right False)+ Left failure -> pure (Left failure)+ Right True -> pure (Right (finished <= deadline))+ Right False -> do+ let delay = min (toInteger (Config.pollIntervalMillis config) * 1000) (max 0 ((deadline - finished) `div` 1000))+ when (delay > 0) (threadDelay (fromInteger delay))+ loop deadline
@@ -0,0 +1,204 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Normalize Ogmios field names without rounding exact ratios.+module Cometa.Provider.Internal.Protocol (decodeParameters, decodeHydraParameters) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Provider.Blockfrost.Internal.Protocol as Common+import Control.Monad (foldM, unless)+import Data.Aeson (Value (..))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (Parser, withObject)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import qualified Data.Text as Text++-- DEFINITIONS ----------------------------------------------------------------++decodeParameters :: Value -> Either Error P.Parameters+decodeParameters value = do+ (normalized, block, tx, stride, multiplier) <- Json.parseValue "provider.protocolParameters" parser value+ parameters <- Common.decodeProtocolParameters normalized+ pure+ parameters+ { P.parameterMaxRefScriptSizePerBlock = block,+ P.parameterMaxRefScriptSizePerTx = tx,+ P.parameterRefScriptCostStride = Just stride,+ P.parameterRefScriptCostMultiplier = Just multiplier+ }+ where+ parser source = do+ fields <- traverse (\(name, path) -> (,) (Key.fromText name) <$> at source path) mapping+ models <- at source ["plutusCostModels"] >>= withObject "cost models" (traverse model . KM.toList)+ stride <- at source ["minFeeReferenceScripts", "range"] >>= Common.integer >>= checked . P.mkReferenceScriptCostStride+ multiplier <- at source ["minFeeReferenceScripts", "multiplier"] >>= Common.fraction+ block <- optionalBytes source "maxReferenceScriptsSizePerBlock"+ tx <- optionalBytes source "maxReferenceScriptsSizePerTransaction"+ pure (Object (KM.fromList (("cost_models_raw", Object (KM.fromList models)) : fields)), block, tx, stride, multiplier)+ key = Key.fromText+ at source [] = pure source+ at source (part : rest) = withObject "protocol parameters" (maybe (fail "Missing parameter") (`at` rest) . KM.lookup (key part)) source+ optionalBytes source name =+ withObject+ "protocol parameters"+ ( \o -> case KM.lookup (key name) o of+ Nothing -> pure Nothing+ Just v -> Just <$> (at v ["bytes"] >>= Common.bounded)+ )+ source+ model (language, costs) = do+ let names = [("plutus:v1", "PlutusV1"), ("plutus:v2", "PlutusV2"), ("plutus:v3", "PlutusV3"), ("plutus:v4", "PlutusV4")]+ name <- maybe (fail "Unknown script language") pure (lookup language names)+ pure (name, costs)+ checked = either (const (fail "Invalid parameter")) pure++mapping :: [(Text, [Text])]+mapping =+ [ ("protocol_major_ver", ["version", "major"]),+ ("protocol_minor_ver", ["version", "minor"]),+ ("min_fee_a", ["minFeeCoefficient"]),+ ("min_fee_b", ["minFeeConstant", "ada", "lovelace"]),+ ("max_block_size", ["maxBlockBodySize", "bytes"]),+ ("max_tx_size", ["maxTransactionSize", "bytes"]),+ ("max_block_header_size", ["maxBlockHeaderSize", "bytes"]),+ ("key_deposit", ["stakeCredentialDeposit", "ada", "lovelace"]),+ ("pool_deposit", ["stakePoolDeposit", "ada", "lovelace"]),+ ("e_max", ["stakePoolRetirementEpochBound"]),+ ("n_opt", ["desiredNumberOfStakePools"]),+ ("a0", ["stakePoolPledgeInfluence"]),+ ("rho", ["monetaryExpansion"]),+ ("tau", ["treasuryExpansion"]),+ ("min_pool_cost", ["minStakePoolCost", "ada", "lovelace"]),+ ("coins_per_utxo_size", ["minUtxoDepositCoefficient"]),+ ("price_mem", ["scriptExecutionPrices", "memory"]),+ ("price_step", ["scriptExecutionPrices", "cpu"]),+ ("max_tx_ex_mem", ["maxExecutionUnitsPerTransaction", "memory"]),+ ("max_tx_ex_steps", ["maxExecutionUnitsPerTransaction", "cpu"]),+ ("max_block_ex_mem", ["maxExecutionUnitsPerBlock", "memory"]),+ ("max_block_ex_steps", ["maxExecutionUnitsPerBlock", "cpu"]),+ ("max_val_size", ["maxValueSize", "bytes"]),+ ("collateral_percent", ["collateralPercentage"]),+ ("max_collateral_inputs", ["maxCollateralInputs"]),+ ("committee_min_size", ["constitutionalCommitteeMinSize"]),+ ("committee_max_term_length", ["constitutionalCommitteeMaxTermLength"]),+ ("gov_action_lifetime", ["governanceActionLifetime"]),+ ("gov_action_deposit", ["governanceActionDeposit", "ada", "lovelace"]),+ ("drep_deposit", ["delegateRepresentativeDeposit", "ada", "lovelace"]),+ ("drep_activity", ["delegateRepresentativeMaxIdleTime"]),+ ("min_fee_ref_script_cost_per_byte", ["minFeeReferenceScripts", "base"]),+ ("pvt_motion_no_confidence", ["stakePoolVotingThresholds", "noConfidence"]),+ ("pvt_committee_normal", ["stakePoolVotingThresholds", "constitutionalCommittee", "default"]),+ ("pvt_committee_no_confidence", ["stakePoolVotingThresholds", "constitutionalCommittee", "stateOfNoConfidence"]),+ ("pvt_hard_fork_initiation", ["stakePoolVotingThresholds", "hardForkInitiation"]),+ ("pvt_p_p_security_group", ["stakePoolVotingThresholds", "protocolParametersUpdate", "security"]),+ ("dvt_motion_no_confidence", ["delegateRepresentativeVotingThresholds", "noConfidence"]),+ ("dvt_committee_normal", ["delegateRepresentativeVotingThresholds", "constitutionalCommittee", "default"]),+ ("dvt_committee_no_confidence", ["delegateRepresentativeVotingThresholds", "constitutionalCommittee", "stateOfNoConfidence"]),+ ("dvt_update_to_constitution", ["delegateRepresentativeVotingThresholds", "constitution"]),+ ("dvt_hard_fork_initiation", ["delegateRepresentativeVotingThresholds", "hardForkInitiation"]),+ ("dvt_p_p_network_group", ["delegateRepresentativeVotingThresholds", "protocolParametersUpdate", "network"]),+ ("dvt_p_p_economic_group", ["delegateRepresentativeVotingThresholds", "protocolParametersUpdate", "economic"]),+ ("dvt_p_p_technical_group", ["delegateRepresentativeVotingThresholds", "protocolParametersUpdate", "technical"]),+ ("dvt_p_p_gov_group", ["delegateRepresentativeVotingThresholds", "protocolParametersUpdate", "governance"]),+ ("dvt_treasury_withdrawal", ["delegateRepresentativeVotingThresholds", "treasuryWithdrawals"])+ ]++-- | Hydra exposes the Cardano CLI parameter format. Conway's tier constants+-- are ledger constants, absent from that JSON. Reject newer eras explicitly.+decodeHydraParameters :: Value -> Either Error P.Parameters+decodeHydraParameters source = do+ normalized <- Json.parseValue "hydra.protocolParameters" normalize source+ decodeParameters normalized+ where+ normalize value = do+ fields <- traverse (\(target, path) -> (,) (Text.splitOn "." target) <$> at value (Text.splitOn "." path)) hydraMapping+ result <- foldM (\o (path, v) -> insertPath path v o) (Object KM.empty) fields+ version <- at value ["protocolVersion", "major"] >>= Common.integer+ unless (version >= 9 && version <= 11) (fail "Unsupported Hydra ledger version")+ models <- at value ["costModels"] >>= withObject "models" (traverse model . KM.toList)+ withModels <- insertPath ["plutusCostModels"] (Object (KM.fromList models)) result+ withRange <- insertPath ["minFeeReferenceScripts", "range"] (Number 25600) withModels+ insertPath ["minFeeReferenceScripts", "multiplier"] (String "6/5") withRange+ at value [] = pure value+ at value (key : rest) = withObject "parameter" (maybe (fail "Missing parameter") (`at` rest) . KM.lookup (Key.fromText key)) value+ model (key, costs) = case lookup key [("PlutusV1", "plutus:v1"), ("PlutusV2", "plutus:v2"), ("PlutusV3", "plutus:v3")] of+ Nothing -> fail "Unsupported Hydra script language"+ Just language -> pure (language, costs)++insertPath :: [Text] -> Value -> Value -> Parser Value+insertPath [] value = const (pure value)+insertPath (key : rest) value = withObject "parameters" $ \o -> do+ let name = Key.fromText key+ child <- insertPath rest value (fromMaybe (Object KM.empty) (KM.lookup name o))+ pure (Object (KM.insert name child o))++hydraMapping :: [(Text, Text)]+hydraMapping =+ [ ("minFeeCoefficient", "txFeePerByte"),+ ("minFeeConstant.ada.lovelace", "txFeeFixed"),+ ("maxBlockBodySize.bytes", "maxBlockBodySize"),+ ("maxTransactionSize.bytes", "maxTxSize"),+ ("maxBlockHeaderSize.bytes", "maxBlockHeaderSize"),+ ("stakeCredentialDeposit.ada.lovelace", "stakeAddressDeposit"),+ ("stakePoolDeposit.ada.lovelace", "stakePoolDeposit"),+ ("stakePoolRetirementEpochBound", "poolRetireMaxEpoch"),+ ("desiredNumberOfStakePools", "stakePoolTargetNum"),+ ("stakePoolPledgeInfluence", "poolPledgeInfluence"),+ ("monetaryExpansion", "monetaryExpansion"),+ ("treasuryExpansion", "treasuryCut"),+ ("minStakePoolCost.ada.lovelace", "minPoolCost"),+ ("minUtxoDepositCoefficient", "utxoCostPerByte"),+ ("scriptExecutionPrices.memory", "executionUnitPrices.priceMemory"),+ ("scriptExecutionPrices.cpu", "executionUnitPrices.priceSteps"),+ ("maxExecutionUnitsPerTransaction.memory", "maxTxExecutionUnits.memory"),+ ("maxExecutionUnitsPerTransaction.cpu", "maxTxExecutionUnits.steps"),+ ("maxExecutionUnitsPerBlock.memory", "maxBlockExecutionUnits.memory"),+ ("maxExecutionUnitsPerBlock.cpu", "maxBlockExecutionUnits.steps"),+ ("maxValueSize.bytes", "maxValueSize"),+ ("collateralPercentage", "collateralPercentage"),+ ("maxCollateralInputs", "maxCollateralInputs"),+ ("version.major", "protocolVersion.major"),+ ("version.minor", "protocolVersion.minor"),+ ("constitutionalCommitteeMinSize", "committeeMinSize"),+ ("constitutionalCommitteeMaxTermLength", "committeeMaxTermLength"),+ ("governanceActionLifetime", "govActionLifetime"),+ ("governanceActionDeposit.ada.lovelace", "govActionDeposit"),+ ("delegateRepresentativeDeposit.ada.lovelace", "dRepDeposit"),+ ("delegateRepresentativeMaxIdleTime", "dRepActivity"),+ ("minFeeReferenceScripts.base", "minFeeRefScriptCostPerByte"),+ ("stakePoolVotingThresholds.noConfidence", "poolVotingThresholds.motionNoConfidence"),+ ("stakePoolVotingThresholds.constitutionalCommittee.default", "poolVotingThresholds.committeeNormal"),+ ("stakePoolVotingThresholds.constitutionalCommittee.stateOfNoConfidence", "poolVotingThresholds.committeeNoConfidence"),+ ("stakePoolVotingThresholds.hardForkInitiation", "poolVotingThresholds.hardForkInitiation"),+ ("stakePoolVotingThresholds.protocolParametersUpdate.security", "poolVotingThresholds.ppSecurityGroup"),+ ("delegateRepresentativeVotingThresholds.noConfidence", "dRepVotingThresholds.motionNoConfidence"),+ ("delegateRepresentativeVotingThresholds.constitutionalCommittee.default", "dRepVotingThresholds.committeeNormal"),+ ("delegateRepresentativeVotingThresholds.constitutionalCommittee.stateOfNoConfidence", "dRepVotingThresholds.committeeNoConfidence"),+ ("delegateRepresentativeVotingThresholds.hardForkInitiation", "dRepVotingThresholds.hardForkInitiation"),+ ("delegateRepresentativeVotingThresholds.constitution", "dRepVotingThresholds.updateToConstitution"),+ ("delegateRepresentativeVotingThresholds.treasuryWithdrawals", "dRepVotingThresholds.treasuryWithdrawal"),+ ("delegateRepresentativeVotingThresholds.protocolParametersUpdate.network", "dRepVotingThresholds.ppNetworkGroup"),+ ("delegateRepresentativeVotingThresholds.protocolParametersUpdate.economic", "dRepVotingThresholds.ppEconomicGroup"),+ ("delegateRepresentativeVotingThresholds.protocolParametersUpdate.technical", "dRepVotingThresholds.ppTechnicalGroup"),+ ("delegateRepresentativeVotingThresholds.protocolParametersUpdate.governance", "dRepVotingThresholds.ppGovGroup")+ ]
@@ -0,0 +1,411 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# OPTIONS_HADDOCK hide #-}++-- | Backend operations over injected scoped transports. Authentication belongs+-- to the transport; error values never contain URLs, headers or response bodies.+module Cometa.Provider.Internal.Remote (Backend (..), provider, parse, transportError, request, jsonRequest, json) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (..))+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Provider.Internal.Codec as C+import qualified Cometa.Provider.Internal.Protocol as Protocol+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Concurrent (threadDelay)+import Control.Monad (unless, when, (>=>))+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Aeson (Value (..), encode, object, (.:), (.:?), (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (Parser, withObject)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Map.Strict as Map+import Data.Maybe (mapMaybe)+import qualified Data.Set as Set+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)++-- DEFINITIONS ----------------------------------------------------------------++data Backend = Koios | Kupmios deriving (Eq, Show)++data Service = Service !Backend !Config.Config !Http.Transport !Http.Transport++provider :: Backend -> Config.Config -> Http.Transport -> Http.Transport -> Provider.Provider+provider backend config indexer node =+ (Provider.unavailable (Text.pack (show backend)) (Config.networkMagic (Config.network config)))+ { Provider.protocolParameters = run $ do+ response <- rpc service "queryLedgerState/protocolParameters" (object [])+ except (Protocol.decodeParameters response),+ Provider.utxosAt = run . atAddress service,+ Provider.utxosWithAsset = \address asset -> run (filter ((> 0) . Amount.quantity asset . Output.value . Utxo.output) <$> atAddress service address),+ Provider.utxoWithAsset = run . nft service,+ Provider.resolveInputs = run . resolve service,+ Provider.resolveDatum = run . resolveDatum service,+ Provider.rewardBalance = run . rewards service,+ Provider.submitTransaction = run . submit service,+ Provider.evaluateTransaction = \transaction inputs -> run $ do+ payload <- except (C.evaluationPayload transaction inputs)+ response <- rpc service "evaluateTransaction" payload+ except (C.budgets transaction response),+ Provider.awaitTransaction = \tx timeout -> run (await service tx timeout)+ }+ where+ service = Service backend config indexer node+ -- Check both scopes even for operations that can return without HTTP.+ run action = runExceptT $ do+ ExceptT (fmap (either (Left . transportError) Right) (Http.checkOpen indexer))+ ExceptT (fmap (either (Left . transportError) Right) (Http.checkOpen node))+ action++parse :: (Value -> Parser a) -> Value -> ExceptT Error IO a+parse parser = except . C.parse parser++invalid :: ExceptT Error IO a+invalid = throwE (InvalidProviderResponse "provider.response")++transportError :: Http.HttpFailure -> Error+transportError failure = case failure of+ Http.Closed -> RuntimeClosed+ Http.Timeout -> ProviderTransportError "provider.request" "timeout"+ Http.ConnectionFailure -> ProviderTransportError "provider.request" "connection failure"+ Http.ResponseTooLarge -> ProviderTransportError "provider.request" "response too large"++request :: Http.Transport -> Http.Request -> ExceptT Error IO Http.Response+request transport value = ExceptT (fmap (either (Left . transportError) Right) (Http.send transport value))++jsonRequest :: Http.Method -> [Text] -> [(Text, Maybe Text)] -> Maybe Value -> Http.Request+jsonRequest method path query payload = Http.Request method path query (maybe B.empty (Lazy.toStrict . encode) payload) (maybe B.empty (const "application/json") payload) Nothing++json :: Http.Transport -> Http.Request -> Bool -> ExceptT Error IO (Maybe Value)+json transport req missing = do+ response <- request transport req+ case Http.status response of+ 200 -> Just <$> except (Json.decodeValue "provider.response" (Http.bodyBytes response))+ 404 | missing -> pure Nothing+ code -> throwE (ProviderHttpError "provider.request" code)++get :: Service -> [Text] -> [(Text, Maybe Text)] -> ExceptT Error IO Value+get (Service _ _ transport _) path query = json transport (jsonRequest Http.Get path query Nothing) False >>= maybe invalid pure++post :: Service -> [Text] -> [(Text, Maybe Text)] -> Value -> ExceptT Error IO Value+post (Service _ _ transport _) path query payload = json transport (jsonRequest Http.Post path query (Just payload)) False >>= maybe invalid pure++rpc :: Service -> Text -> Value -> ExceptT Error IO Value+rpc (Service backend _ _ node) method params = do+ -- Each request has an independent HTTP response; a constant correlation ID+ -- is sufficient and avoids shared mutable state across concurrent calls.+ response <- json node (jsonRequest Http.Post ["ogmios" | backend == Koios] [] (Just (object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("cometa" :: Text), "method" .= method, "params" .= params]))) False >>= maybe invalid pure+ parse+ ( withObject "RPC response" $ \entry -> do+ version <- entry .: "jsonrpc"+ identifier <- entry .: "id"+ replyMethod <- entry .:? "method"+ unless (version == ("2.0" :: Text) && identifier == ("cometa" :: Text) && maybe True (== method) replyMethod && not (KM.member "error" entry)) (fail "RPC failure")+ entry .: "result"+ )+ response++-- Offset iteration has a finite page bound; output identities are checked below.+pages :: Service -> [Text] -> [(Text, Maybe Text)] -> Maybe Value -> ExceptT Error IO [Value]+pages service path query payload = go 0 []+ where+ go count chunks = do+ when (count >= (10000 :: Int)) invalid+ let pagination = [("limit", Just "100"), ("offset", Just (Text.pack (show (count * 100)))), ("order", Just "tx_hash.asc,tx_index.asc")]+ response <- maybe (get service path (query <> pagination)) (post service path (query <> pagination)) payload+ rows <- parse C.list response+ when (length rows > 100) invalid+ let completed = rows : chunks+ if length rows < 100 then pure (concat (reverse completed)) else go (count + 1) completed++outputs :: Service -> [Text] -> [(Text, Maybe Text)] -> Maybe Value -> ExceptT Error IO [Utxo.Utxo]+outputs service@(Service backend _ _ _) path query payload = do+ rows <- if backend == Kupmios then get service path query >>= parse C.list else pages service path query payload+ live <- if backend == Koios then filterMUnspent rows else pure rows+ values <- traverse convert live+ except (C.unique (map Utxo.input values))+ pure values+ where+ convert value = case backend of+ Koios -> C.koiosOutput value+ Kupmios -> kupoOutput service value+ filterMUnspent rows = do+ pairs <- traverse (\row -> (,) row <$> parse (withObject "UTxO" (.: "is_spent")) row) rows+ pure [row | (row, False) <- pairs]++atAddress :: Service -> Address.Address -> ExceptT Error IO [Utxo.Utxo]+atAddress service@(Service backend _ _ _) address = do+ values <- case backend of+ Koios -> outputs service ["address_utxos"] [] (Just (object ["_addresses" .= [text], "_extended" .= True]))+ Kupmios -> outputs service ["matches", text] [("unspent", Nothing)] Nothing+ unless (all ((== address) . Output.address . Utxo.output) values) invalid+ pure values+ where+ text = Address.toText address++nft :: Service -> AssetId -> ExceptT Error IO (Maybe Utxo.Utxo)+nft _ Ada = throwE (UnsupportedOperation "NFT lookup requires a native asset")+nft service@(Service backend _ _ _) asset = do+ values <- case backend of+ Koios -> outputs service ["asset_utxos"] [] (Just (object ["_asset_list" .= [[policy, name]], "_extended" .= True]))+ Kupmios -> outputs service ["matches", "*"] [("unspent", Nothing), ("policy_id", Just policy), ("asset_name", Just name)] Nothing+ case values of+ [] -> pure Nothing+ [value] | Amount.quantity asset (Output.value (Utxo.output value)) == 1 -> pure (Just value)+ _ -> invalid+ where+ unit = Json.assetText asset+ (policy, name) = Text.splitAt 56 unit++resolve :: Service -> [Input.Input] -> ExceptT Error IO [Utxo.Utxo]+resolve service@(Service backend _ _ _) requested = do+ found <- concat <$> traverse batch (chunks (distinct requested))+ except (C.unique (map Utxo.input found))+ unless (all ((`elem` requested) . Utxo.input) found) invalid+ let table = Map.fromList [(Utxo.input value, value) | value <- found]+ pure (mapMaybe (`Map.lookup` table) (distinct requested))+ where+ batch references = case backend of+ Koios -> outputs service ["utxo_info"] [] (Just (object ["_utxo_refs" .= map C.inputText references, "_extended" .= True]))+ Kupmios -> concat <$> traverse (\ref -> outputs service ["matches", Text.pack (show (Input.index ref)) <> "@" <> TxId.toHex (Input.transactionId ref)] [("unspent", Nothing)] Nothing) references+ chunks [] = []+ chunks values = take 100 values : chunks (drop 100 values)++-- Preserve first-request order when callers repeat input references.+distinct :: (Ord a) => [a] -> [a]+distinct = go Set.empty+ where+ go _ [] = []+ go seen (x : xs)+ | Set.member x seen = go seen xs+ | otherwise = x : go (Set.insert x seen) xs++resolveDatum :: Service -> Datum.Hash32 -> ExceptT Error IO (Maybe Data.EncodedPlutusData)+resolveDatum service@(Service backend _ transport _) hash = do+ bytes <- case backend of+ Koios -> do+ response <- post service ["datum_info"] [] (object ["_datum_hashes" .= [text]]) >>= parse C.list+ case response of+ [] -> pure Nothing+ [row] ->+ Just+ <$> parse+ ( withObject+ "datum"+ ( \o -> do+ actual <- o .: "datum_hash"+ unless (actual == text) (fail "Datum mismatch")+ o .: "bytes"+ )+ )+ row+ _ -> invalid+ Kupmios -> do+ response <- json transport (jsonRequest Http.Get ["datums", text] [] Nothing) True+ case response of+ Nothing -> pure Nothing+ Just Null -> pure Nothing+ Just row -> Just <$> parse (withObject "datum" (.: "datum")) row+ traverse (C.datum hash) bytes+ where+ text = Hex.encodeHex (Datum.hashBytes hash)++kupoOutput :: Service -> Value -> ExceptT Error IO Utxo.Utxo+kupoOutput service row = do+ (reference, address, amount, hash, kind, scriptHash) <- parse parser row+ dat <- case (hash, kind) of+ (Nothing, Nothing) -> pure Datum.NoDatum+ (Just expected, Just "hash") -> pure (Datum.DatumHash expected)+ (Just expected, Just "inline") -> resolveDatum service expected >>= maybe invalid (pure . Datum.InlineDatum)+ _ -> invalid+ script <- traverse fetchScript scriptHash+ output <- except (Output.mkOutput address amount dat script)+ pure (Utxo.utxo reference output)+ where+ parser = withObject "Kupo output" $ \o -> do+ spent <- o .: "spent_at"+ unless (spent == Null) (fail "Spent output")+ reference <- C.input "transaction_id" "output_index" (Object o)+ address <- o .: "address" >>= C.checked . Address.fromText+ amount <-+ o .: "value"+ >>= withObject+ "value"+ ( \v -> do+ coins <- v .: "coins" >>= C.natural+ assets <- v .: "assets" >>= withObject "assets" (traverse asset . KM.toList)+ C.checked (C.unique (map fst assets))+ pure (Amount.lovelace (toInteger coins) <> foldMap (uncurry Amount.singleton) assets)+ )+ hash <- o .:? "datum_hash" >>= traverse (Json.parseHex >=> C.checked . Datum.hashFromBytes)+ kind <- o .:? "datum_type"+ scriptHash <- o .:? "script_hash"+ pure (reference, address, amount, hash, kind :: Maybe Text, scriptHash)+ asset (key, value) = do+ let text = Key.toText key+ (policy, suffix) = Text.splitAt 56 text+ name <- case Text.uncons suffix of+ Nothing -> pure ""+ Just ('.', rest) -> pure rest+ _ -> fail "Invalid Kupo asset"+ identifier <- Json.parseAsset (policy <> name)+ quantity <- C.natural value+ when (quantity == 0) (fail "Zero asset quantity")+ pure (identifier, toInteger quantity)+ fetchScript expected = do+ response <- get service ["scripts", expected] []+ (language, bytes) <- parse (withObject "script" (\s -> (,) <$> s .: "language" <*> s .: "script")) response+ C.script language (Just bytes) Nothing expected++rewards :: Service -> Reward.RewardAddress -> ExceptT Error IO Word64+rewards service@(Service backend _ _ _) account = case backend of+ Koios -> do+ rows <- post service ["account_info"] [] (object ["_stake_addresses" .= [text]]) >>= parse C.list+ case rows of+ [] -> pure 0+ [row] -> parse reward row+ _ -> invalid+ Kupmios -> do+ let (kind, key, hash) = case Reward.credential account of+ Credential.KeyCredential credential -> ("verificationKey", "keys", Credential.keyHashBytes credential)+ Credential.ScriptCredential credential -> ("script", "scripts", Credential.scriptHashBytes credential)+ hex = Hex.encodeHex hash+ rows <- rpc service "queryLedgerState/rewardAccountSummaries" (object [Key.fromText key .= [hex]]) >>= parse C.list+ case rows of+ [] -> pure 0+ [row] ->+ parse+ ( withObject+ "rewards"+ ( \o -> do+ actual <- o .: "credential"+ from <- o .: "from"+ unless (actual == hex && from == (kind :: Text)) (fail "Reward identity mismatch")+ o .: "rewards" >>= C.field "ada" >>= C.field "lovelace" >>= C.natural+ )+ )+ row+ _ -> invalid+ where+ text = Reward.toText account+ reward = withObject "reward account" $ \o -> do+ actual <- o .: "stake_address"+ unless (actual == text) (fail "Reward account mismatch")+ o .: "rewards_available" >>= C.natural++submit :: Service -> Tx.Transaction -> ExceptT Error IO TxId.TransactionId+submit service transaction = do+ expected <- ExceptT (Tx.transactionId transaction)+ response <- rpc service "submitTransaction" (object ["transaction" .= object ["cbor" .= Hex.encodeHex (Tx.encodeCbor transaction)]])+ actual <- parse (C.field "transaction" >=> withObject "transaction" (\o -> o .: "id" >>= C.checked . TxId.fromHex)) response+ unless (actual == expected) invalid+ pure expected++await :: Service -> TxId.TransactionId -> Word64 -> ExceptT Error IO Bool+await _ _ 0 = pure False+await service@(Service _ config _ _) identifier milliseconds = ExceptT $ do+ start <- toInteger <$> getMonotonicTimeNSec+ loop (start + toInteger milliseconds * 1000000)+ where+ loop deadline = do+ now <- toInteger <$> getMonotonicTimeNSec+ if now >= deadline+ then pure (Right False)+ else do+ let remaining = fromInteger (min (toInteger (Config.responseTimeoutMillis config)) ((deadline - now + 999999) `div` 1000000))+ result <- runExceptT (confirmed service identifier remaining)+ finished <- toInteger <$> getMonotonicTimeNSec+ case result of+ Left failure | finished >= deadline && failure == transportError Http.Timeout -> pure (Right False)+ Left failure -> pure (Left failure)+ Right True -> pure (Right (finished <= deadline))+ Right False -> do+ let delay = min (toInteger (Config.pollIntervalMillis config) * 1000) (max 0 ((deadline - finished) `div` 1000))+ when (delay > 0) (threadDelay (fromInteger delay))+ loop deadline++confirmed :: Service -> TxId.TransactionId -> Int -> ExceptT Error IO Bool+confirmed (Service backend _ transport _) identifier remaining = do+ let hash = TxId.toHex identifier+ base = case backend of+ Koios -> jsonRequest Http.Post ["tx_status"] [] (Just (object ["_tx_hashes" .= [hash]]))+ Kupmios -> jsonRequest Http.Get ["matches", "*@" <> hash] [] Nothing+ response <- json transport (base {Http.requestTimeoutMillis = Just remaining}) False+ case response of+ Nothing -> pure False+ Just value -> case backend of+ Koios -> do+ rows <- parse C.list value+ case rows of+ [] -> pure False+ [row] ->+ parse+ ( withObject+ "status"+ ( \o -> do+ actual <- o .: "tx_hash"+ unless (actual == hash) (fail "Transaction mismatch")+ confirmations <- o .: "num_confirmations"+ if confirmations == Null then pure False else (> 0) <$> C.natural confirmations+ )+ )+ row+ _ -> invalid+ Kupmios -> do+ rows <- parse C.list value+ checks <-+ traverse+ ( parse+ ( withObject+ "match"+ ( \o -> do+ actual <- o .: "transaction_id"+ unless (actual == hash) (fail "Transaction mismatch")+ o .: "created_at"+ >>= withObject+ "block"+ ( \b -> do+ _ <- b .: "slot_no" >>= C.natural+ block <- b .: "header_hash" >>= Json.parseHex+ unless (B.length block == 32) (fail "Invalid block")+ pure True+ )+ )+ )+ )+ rows+ pure (or checks)
@@ -0,0 +1,74 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Scoped Koios queries and explicit submission through the ordinary Provider+-- record. Responses are bounded to 8 MiB. Submission is never retried.+-- Confirmation observes block inclusion, not finality. Evaluation uses the+-- Conway-era service dialect and requires budgets for every existing redeemer.+--+-- @+-- withProvider (defaultConfig Preprod (Just credential)) $ \provider ->+-- Cometa.Provider.protocolParameters provider+-- @+module Cometa.Provider.Koios (Network (..), ApiKey, mkApiKey, Config (..), defaultConfig, withProvider) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Provider (Provider)+import qualified Cometa.Provider.Blockfrost.Internal.Config as HttpConfig+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import Cometa.Provider.Internal.Config (ApiKey, Network (..), apiKeyBytes, mkApiKey, transportConfig)+import qualified Cometa.Provider.Internal.Remote as Remote+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | Explicit chain, endpoint, credentials and bounded timing settings.+-- No environment variables or files are read implicitly.+data Config = Config+ { -- | Chain identity, independent of the custom endpoint.+ network :: !Network,+ -- | Absolute HTTP(S) URL. No user information or fragment is accepted.+ -- Base path and query parameters are retained; operation queries win.+ endpoint :: !Text,+ -- | Optional credential; Nothing supports an unauthenticated proxy.+ apiKey :: !(Maybe ApiKey),+ -- | Whole-request timeout in milliseconds, from 1 through 60000.+ responseTimeoutMillis :: !Int,+ -- | Confirmation poll interval in milliseconds, from 1 through 60000.+ pollIntervalMillis :: !Int+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Official endpoint, 30-second request timeout and one-second poll interval.+defaultConfig :: Network -> Maybe ApiKey -> Config+defaultConfig selected credential = Config selected url credential 30000 1000+ where+ url = case selected of Mainnet -> "https://api.koios.rest/api/v1"; Preprod -> "https://preprod.koios.rest/api/v1"; Preview -> "https://preview.koios.rest/api/v1"++-- | Validate configuration, acquire a scoped connection pool and run a workflow.+-- Scope exit drains active requests; cancellation propagates after cleanup.+-- An escaped provider returns RuntimeClosed without opening a connection.+withProvider :: Config -> (Provider -> IO (Either Error a)) -> IO (Either Error a)+withProvider config action = case HttpConfig.validateConfig settings of+ Left failure -> pure (Left failure)+ Right () -> Http.withHeaders settings headers $ \transport ->+ action (Remote.provider Remote.Koios settings transport transport)+ where+ settings = transportConfig (network config) (endpoint config) (responseTimeoutMillis config) (pollIntervalMillis config)+ headers = [("Authorization", "Bearer " <> apiKeyBytes key) | Just key <- [apiKey config]]
@@ -0,0 +1,76 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Kupo indexing with Ogmios v6 HTTP queries, evaluation and submission.+-- Kupo must index every address/asset queried and retain transaction history for+-- confirmation checks. An empty result describes that index, not the entire chain.+-- Each response is bounded to 8 MiB; submission is explicit and never retried.+--+-- @+-- withProvider (defaultConfig Preprod "http://localhost:1442" "http://localhost:1337") $ \provider ->+-- Cometa.Provider.protocolParameters provider+-- @+module Cometa.Provider.Kupmios (Network (..), ApiKey, mkApiKey, Config (..), defaultConfig, withProvider) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Provider (Provider)+import qualified Cometa.Provider.Blockfrost.Internal.Config as HttpConfig+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import Cometa.Provider.Internal.Config (ApiKey, Network (..), apiKeyBytes, mkApiKey, transportConfig)+import qualified Cometa.Provider.Internal.Remote as Remote+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | Explicit chain identity and separate HTTP(S) endpoints and credentials.+data Config = Config+ { -- | Chain identity; both services must use this chain.+ network :: !Network,+ -- | Absolute Kupo HTTP(S) endpoint, including an optional path prefix/query.+ kupoEndpoint :: !Text,+ -- | Absolute Ogmios v6 HTTP(S) endpoint, including an optional path prefix/query.+ ogmiosEndpoint :: !Text,+ -- | Optional bearer credential used only for Kupo.+ kupoApiKey :: !(Maybe ApiKey),+ -- | Optional bearer credential used only for Ogmios.+ ogmiosApiKey :: !(Maybe ApiKey),+ -- | Whole-request timeout in milliseconds, from 1 through 60000.+ responseTimeoutMillis :: !Int,+ -- | Confirmation poll interval in milliseconds, from 1 through 60000.+ pollIntervalMillis :: !Int+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Explicit endpoints, no credentials, 30-second timeout and one-second polling.+defaultConfig :: Network -> Text -> Text -> Config+defaultConfig selected kupo ogmios = Config selected kupo ogmios Nothing Nothing 30000 1000++-- | Validate both configurations and scope both connection pools. Cancellation+-- propagates after cleanup. Operations on an escaped provider return RuntimeClosed.+withProvider :: Config -> (Provider -> IO (Either Error a)) -> IO (Either Error a)+withProvider config action = case HttpConfig.validateConfig kupo >> HttpConfig.validateConfig ogmios of+ Left failure -> pure (Left failure)+ Right () -> Http.withHeaders kupo (headers (kupoApiKey config)) $ \indexer ->+ Http.withHeaders ogmios (headers (ogmiosApiKey config)) $ \node ->+ action (Remote.provider Remote.Kupmios kupo indexer node)+ where+ settings url = transportConfig (network config) url (responseTimeoutMillis config) (pollIntervalMillis config)+ kupo = settings (kupoEndpoint config)+ ogmios = settings (ogmiosEndpoint config)+ headers credential = [("Authorization", "Bearer " <> apiKeyBytes key) | Just key <- [credential]]
@@ -0,0 +1,112 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Native and versioned Plutus script alternatives. The combined CBOR form is+-- @[language, payload]@, where native is zero and Plutus versions are 1 through 4.+-- The envelope is normalized on encoding; each payload retains its exact bytes,+-- which determine script identity and hashing.+--+-- @+-- import qualified Cometa.Script as Script+-- import qualified Cometa.Script.Native as Native+--+-- script :: Script.Script+-- script = Script.Native (Native.allOf [])+-- @+module Cometa.Script+ ( Script (..),+ encodeCbor,+ decodeCbor,+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import Codec.CBOR.Term (decodeTerm)+import qualified Codec.CBOR.Write as Write+import Cometa.Credential (ScriptHash)+import Cometa.Error (Error (..))+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++-- | Script alternatives with Haskell-owned payloads. Equality and ordering+-- compare the alternative then its payload representation; native comes first.+data Script+ = -- | A signature/time/guard native script.+ Native !Native.NativeScript+ | -- | A compiled Plutus script carrying its language version.+ Plutus !Plutus.PlutusScript+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Encode a definite two-element array and minimal language tag, preserving the+-- payload's exact encoding. Nonminimal imported envelopes normalize on encoding;+-- they do not contribute to the script hash.+encodeCbor :: Script -> ByteString+encodeCbor script = Write.toStrictByteString (Encode.encodeListLen 2 <> payload)+ where+ payload = case script of+ Native native -> Encode.encodeWord 0 <> Encode.encodePreEncoded (Native.encodeCbor native)+ Plutus plutus -> Encode.encodeWord (fromIntegral (fromEnum (Plutus.version plutus) + 1)) <> Encode.encodePreEncoded (Plutus.encodeCbor plutus)++-- | Decode exactly one two-element native/Plutus envelope. Unknown language tags,+-- incorrect arity, malformed payloads and trailing bytes return+-- 'InvalidScriptCbor'. Payload validators also retain their documented errors.+-- The envelope's encoding is not retained; the payload's encoding is exact.+decodeCbor :: ByteString -> Either Error Script+decodeCbor bytes = case Read.deserialiseFromBytes decodeEnvelope (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidScriptCbor (Text.pack (show failure)))+ Right (trailing, (language, payload))+ | not (Lazy.null trailing) -> Left (InvalidScriptCbor "Trailing bytes after script envelope")+ | otherwise -> case language of+ 0 -> Native <$> Native.decodeCbor payload+ 1 -> Plutus <$> Plutus.decodeCbor Plutus.V1 payload+ 2 -> Plutus <$> Plutus.decodeCbor Plutus.V2 payload+ 3 -> Plutus <$> Plutus.decodeCbor Plutus.V3 payload+ 4 -> Plutus <$> Plutus.decodeCbor Plutus.V4 payload+ _ -> Left (InvalidScriptCbor "Unknown script language")+ where+ decodeEnvelope = do+ size <- Decode.decodeListLenOrIndef+ unless (maybe True (== 2) size) (fail "Invalid script envelope arity")+ language <- Decode.decodeWord+ (_, start, end) <- Decode.decodeWithByteSpan decodeTerm+ case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- Decode.decodeBreakOr+ unless ended (fail "Unexpected script envelope field")+ let payload = ByteString.take (fromIntegral (end - start)) (ByteString.drop (fromIntegral start) bytes)+ pure (language, payload)++-- | Hash using the native prefix zero or the declared Plutus version prefix.+-- The combined envelope is excluded. Native failures return 'Cometa.Error.NativeError'.+hash :: Script -> IO (Either Error ScriptHash)+hash script = case script of+ Native native -> Native.hash native+ Plutus plutus -> Plutus.hash plutus
@@ -0,0 +1,322 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Native signature, threshold, time and Dijkstra guard scripts. Values own+-- their exact CBOR encoding. Equality and ordering compare that encoding, so+-- semantically equivalent nonminimal encodings can differ. Slot numbers count+-- slots, with an inclusive lower bound and exclusive upper bound.+--+-- @+-- import qualified Cometa.Script.Native as Native+--+-- window :: Native.NativeScript+-- window = Native.allOf [Native.invalidBefore 100, Native.invalidAfter 200]+-- @+module Cometa.Script.Native+ ( -- * Script values+ NativeScript,+ NativeScriptView (..),++ -- * Conditions+ signature,+ allOf,+ anyOf,+ atLeast,+ invalidBefore,+ invalidAfter,+ requireGuard,++ -- * Inspection and encoding+ view,+ encodeCbor,+ decodeCbor,+ toJson,+ fromJson,++ -- * Script hash+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Credential (Credential, Guard, KeyHash, Payment, ScriptHash)+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Control.Monad (replicateM, unless)+import Data.Aeson ((.:), (.=))+import qualified Data.Aeson as Aeson+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.Aeson.Types as Aeson+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | An immutable script with validated hash lengths and unsigned thresholds.+-- Imported script encodings are retained exactly, including child encodings.+-- 'Show' is diagnostic, not an interchange format.+data NativeScript = NativeScript !ByteString !NativeScriptView+ deriving (Show)++instance Eq NativeScript where+ left == right = encodeCbor left == encodeCbor right++instance Ord NativeScript where+ compare left right = compare (encodeCbor left) (encodeCbor right)++-- | Read-only alternatives. Construct scripts with the functions below;+-- inspecting this value cannot bypass credential validation.+data NativeScriptView+ = -- | Requires a payment verification-key signature.+ RequireSignature !(KeyHash Payment)+ | -- | All children must succeed; an empty list succeeds.+ RequireAll ![NativeScript]+ | -- | One or more children must succeed; an empty list fails.+ RequireAny ![NativeScript]+ | -- | Required count followed by ordered children; zero always succeeds.+ RequireAtLeast !Word64 ![NativeScript]+ | -- | Inclusive lower slot bound.+ InvalidBefore !Word64+ | -- | Exclusive upper slot bound.+ InvalidAfter !Word64+ | -- | Credential must be present in transaction guards (Dijkstra onwards).+ RequireGuard !(Credential Guard)+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Require a signature from this payment key hash.+signature :: KeyHash Payment -> NativeScript+signature key = assemble (RequireSignature key)++-- | Require every child in order. Empty input is an always-succeeding script.+allOf :: [NativeScript] -> NativeScript+allOf = assemble . RequireAll++-- | Require at least one child. Empty input is an always-failing script.+anyOf :: [NativeScript] -> NativeScript+anyOf = assemble . RequireAny++-- | Require this many successful children. Counts above the child count are+-- valid and deliberately unsatisfiable. Duplicate children retain their positions+-- and count separately; zero with no children is valid and always succeeds.+atLeast :: Word64 -> [NativeScript] -> NativeScript+atLeast required children = assemble (RequireAtLeast required children)++-- | Require the validity interval to start at or after the supplied slot.+invalidBefore :: Word64 -> NativeScript+invalidBefore = assemble . InvalidBefore++-- | Require the validity interval to end at or before the supplied exclusive+-- upper bound. Slot zero is valid and yields an unsatisfiable time restriction.+invalidAfter :: Word64 -> NativeScript+invalidAfter = assemble . InvalidAfter++-- | Require a key or script guard credential. This alternative requires+-- Dijkstra ledger support; construction does not assert era availability.+requireGuard :: Credential Guard -> NativeScript+requireGuard = assemble . RequireGuard++-- | Inspect the semantic alternative and its ordered children.+view :: NativeScript -> NativeScriptView+view (NativeScript _ alternative) = alternative++-- | Exact imported bytes, or a definite-length encoding for assembled values.+-- Assembling a parent preserves each child's exact encoding.+encodeCbor :: NativeScript -> ByteString+encodeCbor (NativeScript bytes _) = bytes++-- | Decode exactly one complete script, checking all alternatives and credential+-- hash lengths. Malformed, trailing or schema-invalid bytes+-- return 'InvalidScriptCbor'. Nonminimal and indefinite encodings are retained.+decodeCbor :: ByteString -> Either Error NativeScript+decodeCbor bytes = case Read.deserialiseFromBytes (decodeScript bytes) (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidScriptCbor (Text.pack (show failure)))+ Right (trailing, script)+ | Lazy.null trailing -> Right script+ | otherwise -> Left (InvalidScriptCbor "Trailing bytes after native script")++-- | Compute BLAKE2b-224 over byte zero followed by the exact script encoding.+-- Native hashing failures return 'Cometa.Error.NativeError'.+hash :: NativeScript -> IO (Either Error ScriptHash)+hash script = do+ result <- Blake2b.compute 28 (ByteString.cons 0 (encodeCbor script))+ pure (result >>= Credential.scriptHashFromBytes . Blake2b.toBytes)++assemble :: NativeScriptView -> NativeScript+assemble alternative = NativeScript (Write.toStrictByteString (encodeView alternative)) alternative++encodeView :: NativeScriptView -> Encode.Encoding+encodeView alternative = case alternative of+ RequireSignature key -> pair 0 (Encode.encodeBytes (Credential.keyHashBytes key))+ RequireAll children -> pair 1 (encodeChildren children)+ RequireAny children -> pair 2 (encodeChildren children)+ RequireAtLeast required children -> Encode.encodeListLen 3 <> Encode.encodeWord 3 <> Encode.encodeWord64 required <> encodeChildren children+ InvalidBefore slot -> pair 4 (Encode.encodeWord64 slot)+ InvalidAfter slot -> pair 5 (Encode.encodeWord64 slot)+ RequireGuard credential -> pair 6 (encodeCredential credential)+ where+ pair tag payload = Encode.encodeListLen 2 <> Encode.encodeWord tag <> payload++encodeChildren :: [NativeScript] -> Encode.Encoding+encodeChildren children = Encode.encodeListLen (fromIntegral (length children)) <> foldMap (Encode.encodePreEncoded . encodeCbor) children++encodeCredential :: Credential Guard -> Encode.Encoding+encodeCredential credential =+ Encode.encodeListLen 2 <> case credential of+ Credential.KeyCredential key -> Encode.encodeWord 0 <> Encode.encodeBytes (Credential.keyHashBytes key)+ Credential.ScriptCredential script -> Encode.encodeWord 1 <> Encode.encodeBytes (Credential.scriptHashBytes script)++-- Byte spans point into the immutable complete input; every child snapshot is+-- retained independently of the decoder and can safely be assembled elsewhere.+decodeScript :: ByteString -> Decode.Decoder s NativeScript+decodeScript bytes = do+ (alternative, start, end) <- Decode.decodeWithByteSpan decodeAlternative+ pure (NativeScript (ByteString.take (fromIntegral (end - start)) (ByteString.drop (fromIntegral start) bytes)) alternative)+ where+ decodeAlternative = do+ size <- Decode.decodeListLenOrIndef+ tag <- Decode.decodeWord+ let arity = if tag == 3 then 3 else 2+ unless (maybe True (== arity) size) (fail "Invalid native script arity")+ alternative <- case tag of+ 0 -> RequireSignature <$> (decodeBytes >>= either (const (fail "Invalid signature hash length")) pure . Credential.keyHashFromBytes)+ 1 -> RequireAll <$> decodeChildren bytes+ 2 -> RequireAny <$> decodeChildren bytes+ 3 -> do+ required <- Decode.decodeWord64+ children <- decodeChildren bytes+ pure (RequireAtLeast required children)+ 4 -> InvalidBefore <$> Decode.decodeWord64+ 5 -> InvalidAfter <$> Decode.decodeWord64+ 6 -> RequireGuard <$> decodeCredential+ _ -> fail "Unknown native script alternative"+ finish size+ pure alternative++decodeChildren :: ByteString -> Decode.Decoder s [NativeScript]+decodeChildren bytes = do+ size <- Decode.decodeListLenOrIndef+ case size of+ Just count -> replicateM count (decodeScript bytes)+ Nothing -> loop []+ where+ loop accumulated = do+ ended <- Decode.decodeBreakOr+ if ended+ then pure (reverse accumulated)+ else do+ child <- decodeScript bytes+ loop (child : accumulated)++decodeCredential :: Decode.Decoder s (Credential Guard)+decodeCredential = do+ size <- Decode.decodeListLenOrIndef+ unless (maybe True (== 2) size) (fail "Invalid guard credential arity")+ tag <- Decode.decodeWord+ bytes <- decodeBytes+ credential <- case tag of+ 0 -> either (const (fail "Invalid guard key hash length")) (pure . Credential.KeyCredential) (Credential.keyHashFromBytes bytes)+ 1 -> either (const (fail "Invalid guard script hash length")) (pure . Credential.ScriptCredential) (Credential.scriptHashFromBytes bytes)+ _ -> fail "Unknown guard credential alternative"+ finish size+ pure credential++finish :: Maybe Int -> Decode.Decoder s ()+finish size = case size of+ Just _ -> pure ()+ Nothing -> do+ ended <- Decode.decodeBreakOr+ unless ended (fail "Unexpected script array field")++decodeBytes :: Decode.Decoder s ByteString+decodeBytes = do+ token <- Decode.peekTokenType+ if token == Decode.TypeBytesIndef+ then do+ Decode.decodeBytesIndef+ loop []+ else Decode.decodeBytes+ where+ loop accumulated = do+ ended <- Decode.decodeBreakOr+ if ended+ then pure (ByteString.concat (reverse accumulated))+ else do+ chunk <- Decode.decodeBytes+ loop (chunk : accumulated)++-- | Export the native script JSON construction schema, shared with cardano-api+-- for signatures, all/any/atLeast and before/after. Dijkstra guards use+-- @{"type":"guard","keyHash":"..."}@ or @"scriptHash"@ as accepted by+-- cardano-c. Numbers are unsigned JSON integers and hashes are lowercase hex.+-- This describes semantic conditions, so importing it creates fresh CBOR and+-- does not retain an imported script's original encoding or hash identity.+-- This construction schema is distinct from CIP-116 inspection JSON.+toJson :: NativeScript -> Aeson.Value+toJson script = case view script of+ RequireSignature key -> Aeson.object ["type" .= ("sig" :: Text.Text), "keyHash" .= Hex.encodeHex (Credential.keyHashBytes key)]+ RequireAll children -> childrenObject "all" children []+ RequireAny children -> childrenObject "any" children []+ RequireAtLeast required children -> childrenObject "atLeast" children ["required" .= required]+ InvalidBefore slot -> Aeson.object ["type" .= ("after" :: Text.Text), "slot" .= slot]+ InvalidAfter slot -> Aeson.object ["type" .= ("before" :: Text.Text), "slot" .= slot]+ RequireGuard credential ->+ Aeson.object+ ( ["type" .= ("guard" :: Text.Text)] <> case credential of+ Credential.KeyCredential credentialHash -> ["keyHash" .= Hex.encodeHex (Credential.keyHashBytes credentialHash)]+ Credential.ScriptCredential credentialHash -> ["scriptHash" .= Hex.encodeHex (Credential.scriptHashBytes credentialHash)]+ )+ where+ childrenObject kind children fields = Aeson.object (["type" .= (kind :: Text.Text), "scripts" .= map toJson children] <> fields)++-- | Import native script construction JSON. Required fields and hash lengths+-- are validated, thresholds and slots must be unsigned 64-bit integers, and+-- children preserve order and duplicates. A guard requires exactly one of+-- @keyHash@ or @scriptHash@. Other object fields are ignored. Invalid input+-- returns 'InvalidScriptJson'. Valid but unsatisfiable thresholds are retained.+-- Fresh definite CBOR is assembled; original JSON/CBOR encoding is not retained.+fromJson :: Aeson.Value -> Either Error NativeScript+fromJson = either (Left . InvalidScriptJson . Text.pack) Right . Aeson.parseEither parseScript+ where+ parseScript = Aeson.withObject "native script" $ \fields -> do+ kind <- fields .: "type"+ case (kind :: Text.Text) of+ "sig" -> signature <$> (fields .: "keyHash" >>= parseKey)+ "all" -> allOf <$> parseChildren fields+ "any" -> anyOf <$> parseChildren fields+ "atLeast" -> atLeast <$> fields .: "required" <*> parseChildren fields+ "after" -> invalidBefore <$> fields .: "slot"+ "before" -> invalidAfter <$> fields .: "slot"+ "guard" ->+ requireGuard <$> case (KeyMap.lookup "keyHash" fields, KeyMap.lookup "scriptHash" fields) of+ (Just key, Nothing) -> Credential.KeyCredential <$> (Aeson.parseJSON key >>= parseKey)+ (Nothing, Just hashValue) -> Credential.ScriptCredential <$> (Aeson.parseJSON hashValue >>= parseHash >>= either (fail . show) pure . Credential.scriptHashFromBytes)+ _ -> fail "guard requires exactly one keyHash or scriptHash"+ _ -> fail "unknown native script type"+ parseChildren fields = fields .: "scripts" >>= traverse parseScript+ parseKey text = parseHash text >>= either (fail . show) pure . Credential.keyHashFromBytes+ parseHash text = maybe (fail "invalid hash hexadecimal") pure (Hex.decodeHex text)
@@ -0,0 +1,184 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Versioned compiled Plutus scripts with exact byte identity. Compiled bytes+-- usually contain one CBOR bytestring around Flat code; script CBOR adds another+-- bytestring layer. Import never guesses or removes a layer. Raw-byte import+-- checks nonemptiness; CBOR import also checks outer framing. Neither checks+-- whether code is executable for its version.+--+-- @+-- import qualified Cometa.Script.Plutus as Plutus+-- import qualified Data.ByteString as ByteString+--+-- script = Plutus.fromBytes Plutus.V3 (ByteString.pack [0x45, 1, 0, 0, 0x24, 0x99])+-- @+module Cometa.Script.Plutus+ ( -- * Compiled scripts+ Version (..),+ PlutusScript,+ fromBytes,+ toBytes,+ version,++ -- * Script CBOR+ encodeCbor,+ decodeCbor,++ -- * Hashing and parameter application+ hash,+ applyParams,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Credential (ScriptHash)+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import Cometa.Internal.Error (fromNativeFailure)+import qualified Cometa.Internal.FFI.Cbor as Buffer+import qualified Cometa.Internal.FFI.Script as Native+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyStaticText, withOwnedOutput)+import Cometa.PlutusData (PlutusData)+import qualified Cometa.PlutusData as PlutusData+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (castPtr, nullPtr)+import Foreign.Storable (poke)++-- TYPES ----------------------------------------------------------------------++-- | Ledger language version; ordering follows version number. Availability+-- depends on the ledger era; this type does not assert deployment support.+data Version = V1 | V2 | V3 | V4+ deriving (Eq, Ord, Show, Enum, Bounded)++-- | Nonempty immutable compiled bytes and their version, with the exact outer+-- script CBOR preserved on import. Equality compares version and outer encoding;+-- ordering is version first, then lexicographic encoding. 'Show' is diagnostic.+data PlutusScript = PlutusScript !Version !ByteString !ByteString+ deriving (Show)++instance Eq PlutusScript where+ left == right = version left == version right && encodeCbor left == encodeCbor right++instance Ord PlutusScript where+ compare left right = compare (version left, encodeCbor left) (version right, encodeCbor right)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import opaque compiled bytes without decoding or normalizing their contents.+-- Empty input returns 'EmptyPlutusScript'. Executability is checked only when a+-- VM operation such as 'applyParams' decodes the program.+fromBytes :: Version -> ByteString -> Either Error PlutusScript+fromBytes language bytes+ | ByteString.null bytes = Left EmptyPlutusScript+ | otherwise = Right (PlutusScript language bytes (Write.toStrictByteString (Encode.encodeBytes bytes)))++-- | Exact compiled bytes, excluding the outer script CBOR bytestring layer.+toBytes :: PlutusScript -> ByteString+toBytes (PlutusScript _ bytes _) = bytes++-- | The declared ledger language version.+version :: PlutusScript -> Version+version (PlutusScript language _ _) = language++-- | Encode the outer script bytestring. Imported encodings retain their exact+-- form, including nonminimal lengths and indefinite chunks. Compiled bytes are+-- never normalized by this operation.+encodeCbor :: PlutusScript -> ByteString+encodeCbor (PlutusScript _ _ encoded) = encoded++-- | Decode exactly one nonempty outer bytestring for the supplied version.+-- Malformed, trailing or schema-invalid input returns 'InvalidScriptCbor'; an+-- empty payload returns 'EmptyPlutusScript'. Both outer and compiled bytes retain+-- their identity; this operation does not decode executable Flat code.+decodeCbor :: Version -> ByteString -> Either Error PlutusScript+decodeCbor language encoded = case Read.deserialiseFromBytes decodeBytes (Lazy.fromStrict encoded) of+ Left failure -> Left (InvalidScriptCbor (Text.pack (show failure)))+ Right (trailing, bytes)+ | not (Lazy.null trailing) -> Left (InvalidScriptCbor "Trailing bytes after Plutus script")+ | ByteString.null bytes -> Left EmptyPlutusScript+ | otherwise -> Right (PlutusScript language bytes encoded)++-- | Compute BLAKE2b-224 over the version prefix (1 through 4) followed by exact+-- compiled bytes. The outer script encoding does not participate in the hash.+-- Native hashing failures return 'Cometa.Error.NativeError'.+hash :: PlutusScript -> IO (Either Error ScriptHash)+hash script = do+ result <- Blake2b.compute 28 (ByteString.cons (fromIntegral (fromEnum (version script) + 1)) (toBytes script))+ pure (result >>= Credential.scriptHashFromBytes . Blake2b.toBytes)++-- | Decode a single-CBOR-wrapped Flat program, apply data constants in list+-- order, and serialize a new program with the same declared language version.+-- The first parameter is the innermost application. Even an empty list invokes+-- the VM and can normalize a noncanonical program encoding. The original script+-- is unchanged. Malformed programs or native failures return 'NativeError'.+-- This operation checks program decoding, not ledger-era or language validity.+applyParams :: PlutusScript -> [PlutusData] -> IO (Either Error PlutusScript)+applyParams script parameters =+ ByteString.useAsCStringLen (toBytes script) $ \(code, codeSize) ->+ ByteString.useAsCStringLen (PlutusData.encodeCbor (PlutusData.List parameters)) $ \(params, paramsSize) ->+ allocaBytes 1024 $ \diagnostic -> do+ poke diagnostic 0+ result <-+ withOwnedOutput+ "script.applyParams"+ Buffer.cBufferUnref+ (\output -> Native.cApplyParams (castPtr code) (fromIntegral codeSize) (castPtr params) (fromIntegral paramsSize) output diagnostic 1024)+ copyBuffer+ case result of+ Right bytes -> pure (fromBytes (version script) bytes)+ Left failure@(NativeContractFailure _) -> pure (Left (fromNativeFailure failure))+ Left (NativeFailure operation status fallback) -> do+ message <- copyStaticText diagnostic+ pure (Left (fromNativeFailure (NativeFailure operation status (if Text.null message then fallback else message))))+ where+ -- Copy borrowed result storage before the scoped buffer is released; no+ -- native storage or arena-backed values survive this operation.+ copyBuffer buffer = do+ size <- Buffer.cBufferSize buffer+ bytes <- Buffer.cBufferData buffer+ if bytes == nullPtr || size == 0 || toInteger size > toInteger (maxBound :: Int)+ then pure (Left (NativeContractFailure "script.applyParams"))+ else Right <$> ByteString.packCStringLen (castPtr bytes, fromIntegral size)++decodeBytes :: Decode.Decoder s ByteString+decodeBytes = do+ token <- Decode.peekTokenType+ if token == Decode.TypeBytesIndef+ then do+ Decode.decodeBytesIndef+ loop []+ else Decode.decodeBytes+ where+ loop accumulated = do+ ended <- Decode.decodeBreakOr+ if ended+ then pure (ByteString.concat (reverse accumulated))+ else do+ chunk <- Decode.decodeBytes+ loop (chunk : accumulated)
@@ -0,0 +1,77 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Inject partial signing with keys kept inside scoped closures. A signer+-- returns witnesses without attaching them or submitting the transaction.+-- Merge its result explicitly with 'Cometa.Transaction.addWitnesses'.+--+-- @+-- import qualified Cometa.Signer as Signer+-- import qualified Cometa.Transaction as Tx+--+-- signWith signer transaction = do+-- result <- Signer.signTransaction signer transaction+-- pure (result >>= (\witnesses -> Tx.addWitnesses witnesses transaction))+-- @+module Cometa.Signer+ ( Signer (..),+ ed25519,+ software,+ bip32,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error)+import qualified Cometa.KeyHandler.Software as Software+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Witnesses as Witnesses+import Data.List.NonEmpty (NonEmpty)++-- TYPES ----------------------------------------------------------------------++-- | An application-supplied partial signer. Captured scoped keys/handlers must+-- remain open throughout its use; escaped closures report the existing closed+-- key/handler error. No private-key export is required.+newtype Signer = Signer+ { -- | Sign the exact transaction body, returning only additional witnesses.+ -- Expected failures use Either; exceptions retain ordinary IO behavior.+ signTransaction :: Tx.Transaction -> IO (Either Error Witnesses.EncodedWitnesses)+ }++-- DEFINITIONS ----------------------------------------------------------------++-- | Capture an open normal or extended Ed25519 signing key. The result contains+-- one Shelley verification witness and does not mutate or attach it to input.+ed25519 :: Key.SigningKey -> Signer+ed25519 key = Signer $ \transaction -> do+ result <- Signing.verificationWitness key transaction+ pure $ do+ witness <- result+ witnesses <- Witnesses.mkWitnesses [witness] [] [] [] []+ pure (Witnesses.fromWitnesses witnesses)++-- | Capture an open Ed25519 software handler, retaining its secret scope rules.+software :: Software.Handler Software.Ed25519 -> Signer+software handler = Signer (Software.signTransaction handler)++-- | Capture an open BIP32 software handler and nonempty five-level derivation+-- paths. Existing path validation and role checks are reused without key export.+bip32 :: Software.Handler Software.Bip32 -> NonEmpty Path.DerivationPath -> Signer+bip32 handler paths = Signer (Software.signTransactionAt handler paths)
@@ -0,0 +1,110 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Convert between slots and Unix milliseconds within a period of constant+-- slot duration. A configuration applies from its reference slot onwards; it+-- does not describe earlier eras or predict future changes in slot duration.+--+-- @+-- import qualified Cometa.SlotConfig as Slots+--+-- firstMillisecond = Slots.slotToTime Slots.preview 100+-- enclosingSlot = firstMillisecond >>= Slots.timeToSlot Slots.preview+-- @+module Cometa.SlotConfig+ ( SlotConfig,+ mkSlotConfig,+ zeroTime,+ zeroSlot,+ slotLength,+ mainnet,+ preview,+ preprod,+ slotToTime,+ timeToSlot,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (InvalidSlotConfig))+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | A reference slot, its Unix start time, and a positive slot duration.+-- Equality compares these three values.+data SlotConfig = SlotConfig !Word64 !Word64 !Word64+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Construct a constant-duration schedule. A zero duration is rejected.+mkSlotConfig ::+ -- | Unix start time of the reference slot, in milliseconds.+ Word64 ->+ -- | Reference slot number.+ Word64 ->+ -- | Duration of one slot, in milliseconds; must be positive.+ Word64 ->+ Either Error SlotConfig+mkSlotConfig _ _ 0 = Left (InvalidSlotConfig "Slot duration must be positive")+mkSlotConfig time slot duration = Right (SlotConfig time slot duration)++-- | Unix start time of the reference slot, in milliseconds.+zeroTime :: SlotConfig -> Word64+zeroTime (SlotConfig time _ _) = time++-- | First slot described by this configuration.+zeroSlot :: SlotConfig -> Word64+zeroSlot (SlotConfig _ slot _) = slot++-- | Positive duration of each slot, in milliseconds.+slotLength :: SlotConfig -> Word64+slotLength (SlotConfig _ _ duration) = duration++-- | Mainnet's one-second schedule starting at slot 4,492,800.+-- Earlier Byron slots require a different configuration.+mainnet :: SlotConfig+mainnet = SlotConfig 1596059091000 4492800 1000++-- | Preview's one-second schedule starting at slot zero.+preview :: SlotConfig+preview = SlotConfig 1666656000000 0 1000++-- | Preprod's one-second schedule starting at slot 86,400.+preprod :: SlotConfig+preprod = SlotConfig 1655769600000 86400 1000++-- | Return the Unix start time of a slot, in milliseconds. Slots before the+-- reference slot and times greater than 2^64 - 1 are rejected.+slotToTime :: SlotConfig -> Word64 -> Either Error Word64+slotToTime config slot+ | slot < zeroSlot config = Left (InvalidSlotConfig "Slot precedes the reference slot")+ | otherwise = bounded (toInteger (zeroTime config) + (toInteger slot - toInteger (zeroSlot config)) * toInteger (slotLength config))++-- | Return the slot containing a Unix timestamp in milliseconds. A slot includes+-- its start instant and excludes the next slot's start. Times before the reference+-- time and resulting slots greater than 2^64 - 1 are rejected.+timeToSlot :: SlotConfig -> Word64 -> Either Error Word64+timeToSlot config time+ | time < zeroTime config = Left (InvalidSlotConfig "Time precedes the reference time")+ | otherwise = bounded (toInteger (zeroSlot config) + (toInteger time - toInteger (zeroTime config)) `div` toInteger (slotLength config))++bounded :: Integer -> Either Error Word64+bounded value+ | value > toInteger (maxBound :: Word64) = Left (InvalidSlotConfig "Conversion exceeds the unsigned 64-bit range")+ | otherwise = Right (fromInteger value)
@@ -0,0 +1,196 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Exact Dijkstra sub-transaction envelopes @[body,witnesses,auxiliary-data]@.+-- Their IDs hash only their own body. Editing an enclosing transaction does+-- not invalidate these independent signatures. Decoding does not establish+-- ledger validity or verify signatures and auxiliary-data commitments.+module Cometa.SubTransaction+ ( SubTransaction,+ fromBody,+ assemble,+ decodeCbor,+ encodeCbor,+ body,+ witnesses,+ auxiliaryData,+ transactionId,+ setBody,+ setBodySetEncoding,+ setAuxiliaryData,+ setWitnesses,+ addWitnesses,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import qualified Cometa.SubTransaction.Body as Body+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Witnesses as Witnesses+import Cometa.TransactionId (TransactionId)+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++-- | An immutable sub-transaction. Equality compares exact encoded bytes,+-- including its framing. 'Show' is diagnostic.+data SubTransaction+ = SubTransaction+ !Body.EncodedBody+ !Witnesses.EncodedWitnesses+ !(Maybe Auxiliary.EncodedAuxiliaryData)+ !ByteString+ !ByteString+ deriving (Show)++instance Eq SubTransaction where+ left == right = encodeCbor left == encodeCbor right++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble a definite three-field frame with empty witnesses and absent+-- auxiliary data. No balancing or ledger validation is performed.+fromBody :: Body.EncodedBody -> SubTransaction+fromBody encodedBody = assemble encodedBody (Witnesses.fromWitnesses Witnesses.empty) Nothing++-- | Assemble a definite three-field frame, retaining each supplied component's+-- exact bytes. Signature and auxiliary-data commitments are not checked.+assemble :: Body.EncodedBody -> Witnesses.EncodedWitnesses -> Maybe Auxiliary.EncodedAuxiliaryData -> SubTransaction+assemble encodedBody encodedWitnesses auxiliary =+ SubTransaction+ encodedBody+ encodedWitnesses+ auxiliary+ (ByteString.singleton 0x83)+ (maybe (ByteString.singleton 0xf6) Auxiliary.toCbor auxiliary)++-- | Decode exactly one three-field frame. Definite and indefinite framing and+-- all original child encodings are retained; malformed and trailing input fail.+decodeCbor :: ByteString -> Either Error SubTransaction+decodeCbor bytes = case R.deserialiseFromBytes parser (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidTransactionCbor (Text.pack (show failure)))+ Right (rest, result)+ | Lazy.null rest -> result+ | otherwise -> Left (InvalidTransactionCbor "Trailing sub-transaction CBOR")+ where+ parser = do+ size <- D.decodeListLenOrIndef+ unless (maybe True (== 3) size) (fail "Incorrect sub-transaction frame arity")+ (bodyBytes, start, _) <- item+ (witnessBytes, _, witnessEnd) <- item+ (auxiliaryBytes, _, _) <- item+ case size of+ Just _ -> pure ()+ Nothing -> D.decodeBreakOr >>= \ended -> unless ended (fail "Extra sub-transaction fields")+ pure $ do+ encodedBody <- Body.decodeCbor bodyBytes+ encodedWitnesses <- Witnesses.decodeCbor witnessBytes+ auxiliary <-+ if auxiliaryBytes == ByteString.singleton 0xf6+ then Right Nothing+ else Just <$> Auxiliary.decodeCbor auxiliaryBytes+ pure+ ( SubTransaction+ encodedBody+ encodedWitnesses+ auxiliary+ (ByteString.take start bytes)+ (ByteString.drop witnessEnd bytes)+ )+ item = do+ (_, start, end) <- D.decodeWithByteSpan T.decodeTerm+ pure+ ( ByteString.take (fromIntegral (end - start)) (ByteString.drop (fromIntegral start) bytes),+ fromIntegral start,+ fromIntegral end+ )++-- | Exact original bytes, with only edited components replaced.+encodeCbor :: SubTransaction -> ByteString+encodeCbor (SubTransaction encodedBody encodedWitnesses _ prefix suffix) =+ prefix <> Body.toCbor encodedBody <> Witnesses.toCbor encodedWitnesses <> suffix++-- | Body and exact hash-bearing encoding.+body :: SubTransaction -> Body.EncodedBody+body (SubTransaction value _ _ _ _) = value++-- | This sub-transaction's own witness set.+witnesses :: SubTransaction -> Witnesses.EncodedWitnesses+witnesses (SubTransaction _ value _ _ _) = value++-- | Optional exact auxiliary data.+auxiliaryData :: SubTransaction -> Maybe Auxiliary.EncodedAuxiliaryData+auxiliaryData (SubTransaction _ _ value _ _) = value++-- | BLAKE2b-256 of this sub-transaction's exact body encoding.+transactionId :: SubTransaction -> IO (Either Error TransactionId)+transactionId = Body.hash . body++-- | A semantically equal replacement is an exact no-op. A changed body clears+-- this sub-transaction's key signatures and retains its remaining witness bytes.+setBody :: Body.EncodedBody -> SubTransaction -> SubTransaction+setBody replacement transaction@(SubTransaction current encodedWitnesses auxiliary prefix suffix)+ | Body.toBody replacement == Body.toBody current = transaction+ | otherwise = SubTransaction replacement (Witnesses.removeKeyWitnesses encodedWitnesses) auxiliary prefix suffix++-- | Replace auxiliary data without changing this body or its signatures. The+-- body's auxiliary-data commitment must be updated separately with 'setBody'.+-- Equal auxiliary bytes are an exact no-op; original framing is retained.+setAuxiliaryData :: Maybe Auxiliary.EncodedAuxiliaryData -> SubTransaction -> SubTransaction+setAuxiliaryData replacement transaction@(SubTransaction encodedBody encodedWitnesses current prefix _)+ | replacement == current = transaction+ | otherwise =+ SubTransaction+ encodedBody+ encodedWitnesses+ replacement+ prefix+ (maybe (ByteString.singleton 0xf6) Auxiliary.toCbor replacement <> ending)+ where+ ending = if prefix == ByteString.singleton 0x9f then ByteString.singleton 0xff else ByteString.empty++-- | Replace witnesses without changing identity or framing. An equal+-- witness value is an exact no-op.+setWitnesses :: Witnesses.EncodedWitnesses -> SubTransaction -> SubTransaction+setWitnesses replacement transaction@(SubTransaction encodedBody current auxiliary prefix suffix)+ | Witnesses.toWitnesses replacement == Witnesses.toWitnesses current = transaction+ | otherwise = SubTransaction encodedBody replacement auxiliary prefix suffix++-- | Merge partial witnesses, failing on conflicting verification signatures.+addWitnesses :: Witnesses.EncodedWitnesses -> SubTransaction -> Either Error SubTransaction+addWitnesses additions transaction = do+ combined <- Witnesses.mergeEncoded (witnesses transaction) additions+ pure (setWitnesses combined transaction)++-- | Change one body's collection tag. Changed bytes remove this intent's key+-- and bootstrap signatures; unchanged tags and absent fields are exact no-ops.+-- Re-sign the intent and rebuild any enclosing transaction after a change.+setBodySetEncoding :: Body.SetField -> SetEncoding -> SubTransaction -> SubTransaction+setBodySetEncoding field requested transaction@(SubTransaction current encodedWitnesses auxiliary prefix suffix)+ | replacement == current = transaction+ | otherwise = SubTransaction replacement (Witnesses.removeKeyWitnesses encodedWitnesses) auxiliary prefix suffix+ where+ replacement = Body.withSetEncoding field requested current
@@ -0,0 +1,171 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Dijkstra subtransaction bodies. Their schema contains shared transaction+-- fields but excludes fees, legacy updates, collateral, nested subtransactions+-- and starting-account-balance requirements.+--+-- @+-- minimal = body [] []+-- @+module Cometa.SubTransaction.Body+ ( Body,+ body,+ fromFields,+ fields,+ encodeCbor,+ encodeCborWith,+ SetField (..),+ setEncoding,+ withSetEncoding,+ EncodedBody,+ decodeCbor,+ fromBody,+ toBody,+ toCbor,+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import qualified Cometa.Internal.SetEncoding as SetEncoding+import qualified Cometa.Internal.TransactionCbor as Cbor+import Cometa.Internal.TransactionFields (Fields)+import qualified Cometa.Internal.TransactionFields as Fields+import Cometa.Transaction.Input (Input)+import Cometa.Transaction.Output (Output)+import Cometa.TransactionId (TransactionId)+import qualified Cometa.TransactionId as Id+import Control.Monad (unless)+import Data.ByteString (ByteString)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Shared semantic fields with the subtransaction schema. Equality compares+-- fields, distinguishing absence, empty collections and embedded datum bytes.+newtype Body = Body Fields deriving (Eq, Show)++-- | Exact imported subtransaction-body encoding. Equality compares exact bytes.+data EncodedBody = EncodedBody !ByteString !Body !(Map.Map Word64 ByteString) deriving (Show)++instance Eq EncodedBody where+ left == right = toCbor left == toCbor right++-- | Set-valued fields in this body schema. Outputs and maps are not sets.+data SetField+ = -- | Spending inputs.+ Inputs+ | -- | Stake and governance certificates.+ Certificates+ | -- | Required signer or guard credentials.+ Guards+ | -- | Reference inputs.+ ReferenceInputs+ | -- | Governance proposals.+ Proposals+ deriving (Eq, Ord, Show, Enum, Bounded)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble required references and ordered outputs; all optional fields absent.+body :: [Input] -> [Output] -> Body+body inputs outputs = Body (Fields.fields inputs outputs)++-- | Assemble shared fields without introducing unsupported top-level fields.+fromFields :: Fields -> Body+fromFields = Body++-- | Inspect all shared semantic fields.+fields :: Body -> Fields+fields (Body value) = value++-- | Fresh definite body map in ascending numeric field order. Embedded datums+-- retain exact encoding; imported body identity is obtained through 'toCbor'.+encodeCbor :: Body -> Either Error ByteString+encodeCbor (Body value) = Fields.validateFields True value >> Right (Cbor.encode (E.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, payload) -> E.encodeWord64 key <> payload) (sortOn fst pairs)))+ where+ pairs = Fields.encodeFields value++-- | Validate context-specific fields and pair them with fresh bytes. Present+-- empty certificates, mint or guards and duplicate guard credentials return+-- 'InvalidTransactionField'.+fromBody :: Body -> Either Error EncodedBody+fromBody value = encodeCbor value >>= decodeCbor++-- | Inspect semantic fields without normalizing the exact body.+toBody :: EncodedBody -> Body+toBody (EncodedBody _ value _) = value++-- | Exact ledger subtransaction-body bytes.+toCbor :: EncodedBody -> ByteString+toCbor (EncodedBody bytes _ _) = bytes++-- | Decode the complete subtransaction schema. Top-level-only fields and unknown+-- keys are rejected rather than dropped. Original map, set and number encodings+-- are preserved. Missing required fields and malformed nested data return errors.+decodeCbor :: ByteString -> Either Error EncodedBody+decodeCbor bytes = do+ pairs <- Cbor.decode (Cbor.mapFields bytes) bytes+ unless (all (`elem` [0, 1, 3, 4, 5, 7, 8, 9, 11, 14, 15, 18, 19, 20, 21, 22, 24, 25, 26]) (Map.keys pairs)) (Left (InvalidTransactionField "Unsupported subtransaction body key"))+ value <- Fields.decodeFields pairs+ Fields.validateFields True value+ pure (EncodedBody bytes (Body value) pairs)++-- | Native BLAKE2b-256 of exact body bytes, with native errors retained.+hash :: EncodedBody -> IO (Either Error TransactionId)+hash value = do+ result <- Blake2b.compute 32 (toCbor value)+ pure (result >>= Id.fromBytes . Blake2b.toBytes)++-- | Encode fresh body fields with the requested set tags. Embedded values keep+-- their own encoding choices. Protocol validity is the caller's responsibility.+encodeCborWith :: SetEncoding -> Body -> Either Error ByteString+encodeCborWith requested value = do+ original <- fromBody value+ pure (toCbor (foldr (`withSetEncoding` requested) original [minBound .. maxBound]))++-- | Observe one field's set tag. An absent optional field returns 'Nothing'.+setEncoding :: SetField -> EncodedBody -> Maybe SetEncoding+setEncoding field (EncodedBody _ _ values) = SetEncoding.encoding <$> Map.lookup (setFieldKey field) values++-- | Change one present field's set tag. Absence and an unchanged tag preserve+-- the exact original body. A change rebuilds the outer map in numeric key order,+-- retaining all other field bytes and the selected array's contents. It can+-- change the body hash: signatures over the previous body must be renewed.+withSetEncoding :: SetField -> SetEncoding -> EncodedBody -> EncodedBody+withSetEncoding field requested original@(EncodedBody _ semantic values)+ | updated == values = original+ | otherwise = EncodedBody encoded semantic updated+ where+ updated = Map.adjust (SetEncoding.withEncoding requested) (setFieldKey field) values+ encoded = Cbor.encode (E.encodeMapLen (fromIntegral (Map.size updated)) <> foldMap (\(key, payload) -> E.encodeWord64 key <> Cbor.raw payload) (Map.toAscList updated))++-- | Ledger map key of a supported set-valued field.+setFieldKey :: SetField -> Word64+setFieldKey field = case field of+ Inputs -> 0+ Certificates -> 4+ Guards -> 14+ ReferenceInputs -> 18+ Proposals -> 20
@@ -0,0 +1,33 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Build a local Dijkstra sub-transaction intent from explicit resolved inputs+-- and outputs. The result can be inspected, signed and attached to an outer+-- transaction. No wallet selection, fee or change is added.+--+-- @+-- import qualified Cometa.SubTransaction.Builder as Builder+-- import qualified Cometa.SubTransaction.Plan as Plan+-- import qualified Cometa.Transaction.Fields as Fields+--+-- buildIntent params slots input output =+-- Builder.build (Builder.Config params slots Fields.Testnet)+-- (Plan.spend input <> Plan.payTo output)+-- @+module Cometa.SubTransaction.Builder (Config (..), build) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.SubTransactionBuilder (Config (..), build)
@@ -0,0 +1,113 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Locate objects in a subtransaction for deferred redeemers and script+-- arguments. Indices start at zero and can change when the body changes.+-- Missing objects return 'Nothing'. Nested levels remain independent.+--+-- @+-- import qualified Cometa.SubTransaction.Indices as Indices+--+-- spendingPosition reference transaction = Indices.findInput reference transaction+-- @+module Cometa.SubTransaction.Indices+ ( findInput,+ findReferenceInput,+ findOutput,+ findMintPolicy,+ findWithdrawal,+ findCertificate,+ findVote,+ findProposal,+ findRedeemer,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address (Address)+import Cometa.Address.Reward (RewardAddress)+import Cometa.Certificate (EncodedCertificate)+import Cometa.Error (Error)+import Cometa.Evaluation (RedeemerId)+import Cometa.Governance.Proposal (Proposal)+import Cometa.Governance.Voting (Voter)+import qualified Cometa.Internal.ContextualTransaction as Native+import qualified Cometa.Internal.TransactionIndices as Indices+import Cometa.PolicyId (PolicyId)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction.Fields as Fields+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Witnesses as Witnesses+import Data.ByteString (ByteString)+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++-- | First spending reference in hash-byte then numeric-index order. Duplicates+-- occupy separate positions.+findInput :: Input -> Sub.SubTransaction -> Maybe Word64+findInput reference = Indices.findInput reference . fields++-- | First reference input in the same order as 'findInput'.+findReferenceInput :: Input -> Sub.SubTransaction -> Maybe Word64+findReferenceInput reference = Indices.findReferenceInput reference . fields++-- | First output at the exact address containing at least the minimum lovelace.+-- Output creation order is retained; the minimum spans unsigned 64-bit values.+findOutput :: Address -> Word64 -> Sub.SubTransaction -> Maybe Word64+findOutput destination minimumLovelace = Indices.findOutput destination minimumLovelace . fields++-- | Policy position in ascending hash-byte order. Imported policies with only+-- zero quantities or an empty asset map still occupy positions.+findMintPolicy :: PolicyId -> Sub.SubTransaction -> Maybe Word64+findMintPolicy policy = Indices.findMintPolicy policy . bodyBytes++-- | Withdrawal position in ledger reward-account order: test networks before+-- mainnet, then script credentials before key credentials, then hash bytes.+-- All network tags other than 1 belong to the same test-network class.+findWithdrawal :: RewardAddress -> Sub.SubTransaction -> Maybe Word64+findWithdrawal account = Indices.findWithdrawal account . fields++-- | First certificate with the same native canonical encoding. Certificate+-- list order and duplicates count. Imported representation differences are+-- normalized by the native certificate codecs; no transaction bytes change.+findCertificate :: EncodedCertificate -> Sub.SubTransaction -> IO (Either Error (Maybe Word64))+findCertificate certificate = Native.findCertificate certificate . Indices.certificateBytes . bodyBytes++-- | Voter position in ledger role order: committee, DRep, stake pool. Within+-- each role script credentials precede key credentials, then hash bytes order+-- each kind. Multiple action votes by one voter occupy a single position.+findVote :: Voter -> Sub.SubTransaction -> Maybe Word64+findVote voter = Indices.findVote voter . fields++-- | First proposal with the same canonical encoding, including its deposit,+-- return account and anchor. Positions follow proposal insertion order, counting+-- actions without scripts. A proposing redeemer uses this same position.+findProposal :: Proposal -> Sub.SubTransaction -> Maybe Word64+findProposal proposal = Indices.findProposal proposal . fields++-- | Redeemer rank ordered by purpose then purpose index, independently of its+-- imported witness collection order. This is its position among all redeemers,+-- rather than its position in the body collection authorized by the script.+findRedeemer :: RedeemerId -> Sub.SubTransaction -> Maybe Word64+findRedeemer identifier = Indices.findRedeemer identifier . Witnesses.redeemers . Witnesses.toWitnesses . Sub.witnesses++fields :: Sub.SubTransaction -> Fields.Fields+fields = SubBody.fields . SubBody.toBody . Sub.body++bodyBytes :: Sub.SubTransaction -> ByteString+bodyBytes = SubBody.toCbor . Sub.body
@@ -0,0 +1,102 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Compose a sub-transaction intent with explicit resolved inputs. Building+-- preserves the specified inputs and outputs; it adds no fee, collateral or+-- change. Sign and attach the resulting sub-transaction separately.+--+-- @+-- import qualified Cometa.SubTransaction.Plan as Plan+--+-- payment input output = Plan.spend input <> Plan.payTo output+-- @+module Cometa.SubTransaction.Plan+ ( Plan,+ DeferredRedeemer,+ payTo,+ spend,+ spendWith,+ spendWithDeferredRedeemer,+ referenceInput,+ attachScript,+ mint,+ mintWithRedeemer,+ mintWithDeferredRedeemer,+ metadata,+ attachDatum,+ certificate,+ certificateWithRedeemer,+ certificateWithDeferredRedeemer,+ withdraw,+ withdrawWithRedeemer,+ withdrawWithDeferredRedeemer,+ requireSigner,+ validFrom,+ validUntil,+ requireTopLevelGuard,+ requireGuard,+ guardWithRedeemer,+ directDeposit,+ accountBalance,+ donate,+ propose,+ proposeWithRedeemer,+ proposeWithDeferredRedeemer,+ vote,+ voteWithRedeemer,+ voteWithDeferredRedeemer,+ resolvedInputs,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.SubTransactionPlan+ ( DeferredRedeemer,+ Plan,+ accountBalance,+ attachDatum,+ attachScript,+ certificate,+ certificateWithDeferredRedeemer,+ certificateWithRedeemer,+ directDeposit,+ donate,+ guardWithRedeemer,+ metadata,+ mint,+ mintWithDeferredRedeemer,+ mintWithRedeemer,+ payTo,+ propose,+ proposeWithDeferredRedeemer,+ proposeWithRedeemer,+ referenceInput,+ requireGuard,+ requireSigner,+ requireTopLevelGuard,+ resolvedInputs,+ spend,+ spendWith,+ spendWithDeferredRedeemer,+ validFrom,+ validUntil,+ vote,+ voteWithDeferredRedeemer,+ voteWithRedeemer,+ withdraw,+ withdrawWithDeferredRedeemer,+ withdrawWithRedeemer,+ )
@@ -0,0 +1,318 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Transactions retain exact body, witnesses and outer framing. Decoding does+-- not verify signatures, script execution, auxiliary-data hashes or ledger rules.+-- Witness updates preserve the bytes used for the transaction ID. A changed body+-- removes outer verification-key and bootstrap signatures; embedded transaction+-- witnesses remain part of their own unchanged bodies.+--+-- @+-- import qualified Cometa.Transaction as Tx+--+-- reload bytes = Tx.encodeCbor <$> Tx.decodeCbor bytes+-- @+module Cometa.Transaction+ ( Transaction,+ Frame (..),+ fromBody,+ assemble,+ decodeCbor,+ encodeCbor,+ body,+ witnesses,+ frame,+ scriptValidity,+ auxiliaryData,+ hasScriptData,+ transactionId,+ setBody,+ setBodySetEncoding,+ setFee,+ setScriptValidity,+ setAuxiliaryData,+ setWitnesses,+ addWitnesses,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Term as T+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Witnesses as Witnesses+import Cometa.TransactionId (TransactionId)+import Control.Monad (replicateM, unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import qualified Data.Text as Text+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Outer transaction field order. These layouts describe representation, not+-- validity in a particular ledger era.+data Frame+ = -- | @[body,witnesses,auxiliary-data-or-null]@; script validity is true.+ Historical+ | -- | @[body,witnesses,script-validity,auxiliary-data-or-null]@.+ Mempool+ | -- | @[body,witnesses,auxiliary-data-or-null,script-validity]@.+ Block+ deriving (Eq, Ord, Show)++-- | An immutable transaction. Equality compares exact encoded representation,+-- including nonminimal encodings and definite versus indefinite framing.+-- 'Show' is diagnostic; use 'encodeCbor' for storage.+data Transaction = Transaction+ { transactionBody :: !Body.EncodedBody,+ transactionWitnesses :: !Witnesses.EncodedWitnesses,+ transactionFrame :: !Frame,+ transactionValidity :: !Bool,+ transactionAuxiliary :: !(Maybe Auxiliary.EncodedAuxiliaryData),+ transactionPrefix :: !ByteString,+ transactionSuffix :: !ByteString+ }+ deriving (Show)++instance Eq Transaction where+ left == right = encodeCbor left == encodeCbor right++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble an unsigned transaction with a definite four-field mempool frame,+-- true script validity, empty witnesses and absent auxiliary data. This does not+-- balance the body or assert ledger validity.+fromBody :: Body.EncodedBody -> Transaction+fromBody encodedBody = assemble encodedBody (Witnesses.fromWitnesses Witnesses.empty) Nothing++-- | Assemble a fresh definite mempool frame with true script validity. The body,+-- witness set and optional auxiliary data retain their supplied exact bytes.+-- This does not check signatures or the body's auxiliary-data commitment.+assemble :: Body.EncodedBody -> Witnesses.EncodedWitnesses -> Maybe Auxiliary.EncodedAuxiliaryData -> Transaction+assemble encodedBody encodedWitnesses auxiliary =+ Transaction+ encodedBody+ encodedWitnesses+ Mempool+ True+ auxiliary+ (ByteString.singleton 0x84)+ (ByteString.singleton 0xf5 <> maybe (ByteString.singleton 0xf6) Auxiliary.toCbor auxiliary)++-- | Decode exactly one historical, mempool or block frame, accepting definite+-- and indefinite arrays. Preserve every byte. Malformed, trailing, unsupported+-- or duplicate-field encodings return a structured error. No native resources+-- or secret keys are acquired.+decodeCbor :: ByteString -> Either Error Transaction+decodeCbor bytes = case R.deserialiseFromBytes (decodeFrame bytes) (Lazy.fromStrict bytes) of+ Left failure -> Left (InvalidTransactionCbor (Text.pack (show failure)))+ Right (rest, result)+ | Lazy.null rest -> result+ | otherwise -> Left (InvalidTransactionCbor "Trailing transaction CBOR")++-- | Exact transaction encoding. Updates retain unchanged component bytes and+-- the original outer array header and ending, including indefinite framing.+encodeCbor :: Transaction -> ByteString+encodeCbor transaction =+ transactionPrefix transaction+ <> Body.toCbor (body transaction)+ <> Witnesses.toCbor (witnesses transaction)+ <> transactionSuffix transaction++-- | Body with its exact identity-bearing encoding.+body :: Transaction -> Body.EncodedBody+body = transactionBody++-- | Outer witness set with its exact encoding.+witnesses :: Transaction -> Witnesses.EncodedWitnesses+witnesses = transactionWitnesses++-- | Original outer field order.+frame :: Transaction -> Frame+frame = transactionFrame++-- | Claimed script validity. Historical frames implicitly claim true.+scriptValidity :: Transaction -> Bool+scriptValidity = transactionValidity++-- | Optional auxiliary data, preserving its original encoding.+auxiliaryData :: Transaction -> Maybe Auxiliary.EncodedAuxiliaryData+auxiliaryData = transactionAuxiliary++-- | Whether the outer witness set contains at least one datum or redeemer.+-- Script bytes alone do not count, and nested transactions are inspected+-- independently. This does not run or validate a script.+hasScriptData :: Transaction -> Bool+hasScriptData transaction =+ let values = Witnesses.toWitnesses (witnesses transaction)+ in not (null (Witnesses.datums values) && null (Witnesses.redeemers values))++-- | BLAKE2b-256 of the exact body bytes, independent of witnesses and framing.+-- Native hashing failures return 'NativeError'.+transactionId :: Transaction -> IO (Either Error TransactionId)+transactionId = Body.hash . body++-- | Replace the body. A semantically equal body is an exact no-op, retaining+-- existing signatures and encodings. A changed body uses the supplied encoding+-- and removes only the outer verification-key and bootstrap witnesses. Scripts,+-- datums, redeemers, auxiliary data and nested transaction witnesses are retained.+-- The caller must recheck fees, auxiliary-data commitments and ledger validity.+setBody :: Body.EncodedBody -> Transaction -> Transaction+setBody replacement transaction+ | Body.toBody replacement == Body.toBody (body transaction) = transaction+ | otherwise =+ transaction+ { transactionBody = replacement,+ transactionWitnesses = Witnesses.removeKeyWitnesses (witnesses transaction)+ }++-- | Change the fee in lovelace, removing outer key signatures when it changes.+-- An unchanged fee preserves the complete original transaction.+setFee :: Word64 -> Transaction -> Transaction+setFee lovelace transaction =+ setBody (Body.setFeeEncoded lovelace (body transaction)) transaction++-- | Change claimed script validity without changing the body hash or witnesses.+-- A same-value update is an exact no-op. Historical frames cannot encode false:+-- setting false promotes them to mempool order, retaining definite/indefinite+-- framing and every component byte. Other frames retain their original order.+setScriptValidity :: Bool -> Transaction -> Transaction+setScriptValidity valid transaction+ | valid == scriptValidity transaction = transaction+ | otherwise =+ transaction+ { transactionValidity = valid,+ transactionFrame = if frame transaction == Historical then Mempool else frame transaction,+ transactionPrefix = if frame transaction == Historical then promotePrefix prefix else prefix,+ transactionSuffix = case frame transaction of+ Historical -> boolean <> suffix+ Mempool -> boolean <> ByteString.drop 1 suffix+ Block -> maybe (ByteString.singleton 0xf6) Auxiliary.toCbor (auxiliaryData transaction) <> boolean <> ending+ }+ where+ prefix = transactionPrefix transaction+ suffix = transactionSuffix transaction+ boolean = ByteString.singleton (if valid then 0xf5 else 0xf4)+ ending = if prefix == ByteString.singleton 0x9f then ByteString.singleton 0xff else ByteString.empty+ promotePrefix original+ | original == ByteString.singleton 0x9f = original+ | ByteString.length original == 1 = ByteString.singleton 0x84+ | otherwise = case ByteString.unsnoc original of+ Nothing -> ByteString.singleton 0x84+ Just (initial, _) -> initial <> ByteString.singleton 4++-- | Replace auxiliary data without changing the body or its key signatures.+-- This does not update the body's auxiliary-data commitment: supply a matching+-- body separately using 'setBody'. Equal auxiliary bytes are an exact no-op.+setAuxiliaryData :: Maybe Auxiliary.EncodedAuxiliaryData -> Transaction -> Transaction+setAuxiliaryData replacement transaction+ | replacement == auxiliaryData transaction = transaction+ | otherwise =+ transaction+ { transactionAuxiliary = replacement,+ transactionSuffix = case frame transaction of+ Historical -> auxiliary <> ending+ Mempool -> boolean <> auxiliary <> ending+ Block -> auxiliary <> boolean <> ending+ }+ where+ auxiliary = maybe (ByteString.singleton 0xf6) Auxiliary.toCbor replacement+ boolean = ByteString.singleton (if scriptValidity transaction then 0xf5 else 0xf4)+ ending = if transactionPrefix transaction == ByteString.singleton 0x9f then ByteString.singleton 0xff else ByteString.empty++-- | Replace the outer witness set without changing the body, its hash or any+-- framing bytes. An equal witness value preserves the original encoding.+setWitnesses :: Witnesses.EncodedWitnesses -> Transaction -> Transaction+setWitnesses replacement transaction+ | Witnesses.toWitnesses replacement == Witnesses.toWitnesses (witnesses transaction) = transaction+ | otherwise = transaction {transactionWitnesses = replacement}++-- | Merge partial witnesses into the outer set. Conflicting signatures for the+-- same verification key fail. Unchanged body and nested witness bytes remain+-- exact; no signature verification or script evaluation occurs.+addWitnesses :: Witnesses.EncodedWitnesses -> Transaction -> Either Error Transaction+addWitnesses additions transaction = do+ combined <- Witnesses.mergeEncoded (witnesses transaction) additions+ pure (setWitnesses combined transaction)++-- The spans come from the original immutable input. Parsing a term only locates+-- its end; component decoders validate their schema against the exact slice.+decodeFrame :: ByteString -> D.Decoder s (Either Error Transaction)+decodeFrame bytes = do+ size <- D.decodeListLenOrIndef+ fields <- case size of+ Just count -> do+ unless (count == 3 || count == 4) (fail "Incorrect transaction frame arity")+ replicateM count item+ Nothing -> indefinite+ pure $ case fields of+ [(bodyBytes, start, _), (witnessBytes, _, witnessEnd), (third, _, _)] ->+ assembleDecoded Historical True bodyBytes witnessBytes third start witnessEnd+ [(bodyBytes, start, _), (witnessBytes, _, witnessEnd), (third, _, _), (fourth, _, _)]+ | third == boolBytes True || third == boolBytes False ->+ assembleDecoded Mempool (third == boolBytes True) bodyBytes witnessBytes fourth start witnessEnd+ | fourth == boolBytes True || fourth == boolBytes False ->+ assembleDecoded Block (fourth == boolBytes True) bodyBytes witnessBytes third start witnessEnd+ _ -> Left (InvalidTransactionCbor "Invalid transaction frame")+ where+ item = do+ (_, start, end) <- D.decodeWithByteSpan T.decodeTerm+ let value = ByteString.take (fromIntegral (end - start)) (ByteString.drop (fromIntegral start) bytes)+ pure (value, fromIntegral start, fromIntegral end)+ indefinite = do+ ended <- D.decodeBreakOr+ if ended+ then pure []+ else do+ first <- item+ remaining <- indefinite+ pure (first : remaining)+ assembleDecoded layout valid bodyBytes witnessBytes auxiliaryBytes start witnessEnd = do+ encodedBody <- Body.decodeCbor bodyBytes+ encodedWitnesses <- Witnesses.decodeCbor witnessBytes+ auxiliary <-+ if auxiliaryBytes == ByteString.singleton 0xf6+ then Right Nothing+ else Just <$> Auxiliary.decodeCbor auxiliaryBytes+ pure+ ( Transaction+ encodedBody+ encodedWitnesses+ layout+ valid+ auxiliary+ (ByteString.take start bytes)+ (ByteString.drop witnessEnd bytes)+ )+ boolBytes valid = ByteString.singleton (if valid then 0xf5 else 0xf4)++-- | Change a present body's collection tag, retaining unrelated field bytes.+-- An encoding change removes outer key/bootstrap signatures even when the body+-- has the same semantic values. Absent fields and unchanged tags are exact no-ops.+-- Recheck fees and protocol encoding requirements before signing again.+setBodySetEncoding :: Body.SetField -> SetEncoding -> Transaction -> Transaction+setBodySetEncoding field requested transaction+ | replacement == body transaction = transaction+ | otherwise = transaction {transactionBody = replacement, transactionWitnesses = Witnesses.removeKeyWitnesses (witnesses transaction)}+ where+ replacement = Body.withSetEncoding field requested (body transaction)
@@ -0,0 +1,48 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Discover the unique direct key authorities of a top-level transaction.+-- Resolve spending and collateral inputs before requesting hashes, then select+-- the corresponding signing keys in the application's wallet.+--+-- @+-- import qualified Cometa.Transaction.Authority as Authority+--+-- discover transaction resolved = Authority.requiredKeyHashes transaction resolved+-- @+module Cometa.Transaction.Authority (requiredKeyHashes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Crypto.Blake2b (Blake2bHash)+import Cometa.Error (Error)+import qualified Cometa.Internal.ContextualTransaction as Native+import Cometa.Transaction (Transaction)+import Cometa.Transaction.Utxo (Utxo)+import Data.Set (Set)++-- DEFINITIONS ----------------------------------------------------------------++-- | Unique 28-byte key hashes from top-level key guards, resolved spending and+-- collateral addresses, withdrawals, certificates and voters. The set has no+-- credential-role assignment. Every spending and collateral input must resolve;+-- duplicate resolution entries and missing references return an error. Extra+-- resolved outputs are allowed, and reference inputs need no resolution here.+--+-- Native scripts, script credentials, Byron bootstrap authorities and nested+-- transaction levels are excluded. This does not identify every key that could+-- satisfy arbitrary script logic, verify signatures, or validate ledger rules.+requiredKeyHashes :: Transaction -> [Utxo] -> IO (Either Error (Set Blake2bHash))+requiredKeyHashes = Native.requiredKeyHashes
@@ -0,0 +1,219 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TupleSections #-}++-- | Transaction metadata and auxiliary scripts. Fresh assembly uses the tagged+-- Alonzo map. Imported Shelley metadata, Shelley-MA arrays and tagged maps retain+-- their full exact bytes, which determine the auxiliary-data hash.+-- @fromAuxiliaryData empty@ assembles an empty tagged auxiliary map.+module Cometa.Transaction.AuxiliaryData+ ( AuxiliaryData,+ auxiliaryData,+ metadata,+ nativeScripts,+ plutusV1Scripts,+ plutusV2Scripts,+ plutusV3Scripts,+ plutusV4Scripts,+ empty,+ EncodedAuxiliaryData,+ encodeCbor,+ decodeCbor,+ fromAuxiliaryData,+ toAuxiliaryData,+ toCbor,+ AuxiliaryDataHash,+ hash,+ hashFromBytes,+ hashBytes,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.Metadata as Metadata+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Maybe (catMaybes)++-- TYPES ----------------------------------------------------------------------++-- | Optional field presence is preserved, including present empty lists.+-- Script lists retain order and duplicates. Metadata retains its exact nested CBOR.+data AuxiliaryData = AuxiliaryData+ { auxiliaryMetadata :: !(Maybe Metadata.EncodedMetadata),+ auxiliaryNativeScripts :: !(Maybe [Native.NativeScript]),+ auxiliaryPlutusV1Scripts :: !(Maybe [Plutus.PlutusScript]),+ auxiliaryPlutusV2Scripts :: !(Maybe [Plutus.PlutusScript]),+ auxiliaryPlutusV3Scripts :: !(Maybe [Plutus.PlutusScript]),+ auxiliaryPlutusV4Scripts :: !(Maybe [Plutus.PlutusScript])+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Optional metadata with its exact nested encoding.+metadata :: AuxiliaryData -> Maybe Metadata.EncodedMetadata+metadata = auxiliaryMetadata++-- | Optional ordered auxiliary native scripts, including duplicates.+nativeScripts :: AuxiliaryData -> Maybe [Native.NativeScript]+nativeScripts = auxiliaryNativeScripts++-- | Optional ordered auxiliary Plutus V1 scripts, including duplicates.+plutusV1Scripts :: AuxiliaryData -> Maybe [Plutus.PlutusScript]+plutusV1Scripts = auxiliaryPlutusV1Scripts++-- | Optional ordered auxiliary Plutus V2 scripts, including duplicates.+plutusV2Scripts :: AuxiliaryData -> Maybe [Plutus.PlutusScript]+plutusV2Scripts = auxiliaryPlutusV2Scripts++-- | Optional ordered auxiliary Plutus V3 scripts, including duplicates.+plutusV3Scripts :: AuxiliaryData -> Maybe [Plutus.PlutusScript]+plutusV3Scripts = auxiliaryPlutusV3Scripts++-- | Optional ordered auxiliary Plutus V4 scripts, including duplicates.+plutusV4Scripts :: AuxiliaryData -> Maybe [Plutus.PlutusScript]+plutusV4Scripts = auxiliaryPlutusV4Scripts++-- | Assemble metadata, optional native scripts and versioned Plutus scripts.+-- Plutus scripts are grouped by their validated version, retaining relative+-- order and duplicates within each version. Empty version groups are absent.+auxiliaryData :: Maybe Metadata.EncodedMetadata -> Maybe [Native.NativeScript] -> [Plutus.PlutusScript] -> AuxiliaryData+auxiliaryData meta natives scripts = AuxiliaryData meta natives (group Plutus.V1) (group Plutus.V2) (group Plutus.V3) (group Plutus.V4)+ where+ group version = case filter ((== version) . Plutus.version) scripts of+ [] -> Nothing+ values -> Just values++-- | All fields absent.+empty :: AuxiliaryData+empty = AuxiliaryData Nothing Nothing Nothing Nothing Nothing Nothing++-- | An auxiliary value and its full original bytes. Equality and ordering compare+-- bytes, so semantically equal encodings can have distinct hash identities.+data EncodedAuxiliaryData = EncodedAuxiliaryData !ByteString !AuxiliaryData deriving (Show)++instance Eq EncodedAuxiliaryData where+ a == b = toCbor a == toCbor b++instance Ord EncodedAuxiliaryData where+ compare a b = compare (toCbor a) (toCbor b)++-- | Fresh tagged map, preserving nested metadata and script encodings.+encodeCbor :: AuxiliaryData -> ByteString+encodeCbor value = C.encode (E.encodeTag 259 <> E.encodeMapLen (fromIntegral (length fields)) <> foldMap (uncurry (<>)) fields)+ where+ fields =+ catMaybes+ [ field 0 (C.raw . Metadata.toCbor <$> auxiliaryMetadata value),+ field 1 (listEncoding Native.encodeCbor <$> auxiliaryNativeScripts value),+ field 2 (listEncoding Plutus.encodeCbor <$> auxiliaryPlutusV1Scripts value),+ field 3 (listEncoding Plutus.encodeCbor <$> auxiliaryPlutusV2Scripts value),+ field 4 (listEncoding Plutus.encodeCbor <$> auxiliaryPlutusV3Scripts value),+ field 5 (listEncoding Plutus.encodeCbor <$> auxiliaryPlutusV4Scripts value)+ ]+ field key = fmap (E.encodeWord key,)++listEncoding :: (a -> ByteString) -> [a] -> E.Encoding+listEncoding encoder values = E.encodeListLen (fromIntegral (length values)) <> foldMap (C.raw . encoder) values++-- | Encode a newly assembled value and retain those bytes.+fromAuxiliaryData :: AuxiliaryData -> EncodedAuxiliaryData+fromAuxiliaryData value = EncodedAuxiliaryData (encodeCbor value) value++-- | Observe semantic fields.+toAuxiliaryData :: EncodedAuxiliaryData -> AuxiliaryData+toAuxiliaryData (EncodedAuxiliaryData _ value) = value++-- | Full original auxiliary CBOR, suitable for hashing.+toCbor :: EncodedAuxiliaryData -> ByteString+toCbor (EncodedAuxiliaryData bytes _) = bytes++-- | Decode historical metadata maps, metadata/script arrays, or tag-259 maps.+-- Unknown/duplicate fields, malformed scripts and trailing bytes fail.+decodeCbor :: ByteString -> Either Error EncodedAuxiliaryData+decodeCbor input = EncodedAuxiliaryData input <$> C.decodeAs InvalidAuxiliaryDataCbor parser input+ where+ parser = do+ token <- D.peekTokenType+ case token of+ D.TypeTag -> do+ tag <- D.decodeTag+ unless (tag == 259) (fail "Expected auxiliary tag 259")+ fields <- C.entries ((,) <$> D.decodeWord <*> C.slice input)+ unless (length fields == length (unique (map fst fields))) (fail "Duplicate auxiliary field")+ foldFields fields empty+ D.TypeMapLen -> historicalMetadata+ D.TypeMapLenIndef -> historicalMetadata+ _ -> do+ size <- D.decodeListLenOrIndef+ case size of+ Just 1 -> (\m -> empty {auxiliaryMetadata = Just m}) <$> C.nested input Metadata.decodeCbor+ Just 2 -> (AuxiliaryData . Just <$> C.nested input Metadata.decodeCbor) <*> (Just <$> C.list (C.nested input Native.decodeCbor)) <*> pure Nothing <*> pure Nothing <*> pure Nothing <*> pure Nothing+ Nothing -> do+ meta <- C.nested input Metadata.decodeCbor+ ended <- D.decodeBreakOr+ if ended+ then pure empty {auxiliaryMetadata = Just meta}+ else do+ natives <- C.list (C.nested input Native.decodeCbor)+ finished <- D.decodeBreakOr+ unless finished (fail "Extra historical auxiliary fields")+ pure empty {auxiliaryMetadata = Just meta, auxiliaryNativeScripts = Just natives}+ _ -> fail "Historical auxiliary array must contain one or two fields"+ historicalMetadata = (\m -> empty {auxiliaryMetadata = Just m}) <$> C.nested input Metadata.decodeCbor+ foldFields [] value = pure value+ foldFields ((key, bytes) : rest) value = do+ next <- case key of+ 0 -> (\m -> value {auxiliaryMetadata = Just m}) <$> parsed Metadata.decodeCbor bytes+ 1 -> (\s -> value {auxiliaryNativeScripts = Just s}) <$> parsed (scriptList Native.decodeCbor) bytes+ 2 -> (\s -> value {auxiliaryPlutusV1Scripts = Just s}) <$> parsed (scriptList (Plutus.decodeCbor Plutus.V1)) bytes+ 3 -> (\s -> value {auxiliaryPlutusV2Scripts = Just s}) <$> parsed (scriptList (Plutus.decodeCbor Plutus.V2)) bytes+ 4 -> (\s -> value {auxiliaryPlutusV3Scripts = Just s}) <$> parsed (scriptList (Plutus.decodeCbor Plutus.V3)) bytes+ 5 -> (\s -> value {auxiliaryPlutusV4Scripts = Just s}) <$> parsed (scriptList (Plutus.decodeCbor Plutus.V4)) bytes+ _ -> fail "Unknown auxiliary field"+ foldFields rest next+ parsed decoder = either (fail . show) pure . decoder+ scriptList decoder bytes = C.decodeAs InvalidAuxiliaryDataCbor (C.list (C.nested bytes decoder)) bytes+ unique [] = []+ unique (x : xs) = x : unique (filter (/= x) xs)++-- | A 32-byte Blake2b digest of full auxiliary CBOR.+newtype AuxiliaryDataHash = AuxiliaryDataHash ByteString deriving (Eq, Ord, Show)++-- | Validate a 32-byte auxiliary-data hash.+hashFromBytes :: ByteString -> Either Error AuxiliaryDataHash+hashFromBytes bytes+ | B.length bytes == 32 = Right (AuxiliaryDataHash bytes)+ | otherwise = Left (InvalidAuxiliaryDataCbor "Auxiliary-data hash must contain 32 bytes")++-- | Digest bytes.+hashBytes :: AuxiliaryDataHash -> ByteString+hashBytes (AuxiliaryDataHash bytes) = bytes++-- | Hash the full exact auxiliary encoding, including scripts and its envelope.+-- The native hashing boundary is explicit in IO.+hash :: EncodedAuxiliaryData -> IO (Either Error AuxiliaryDataHash)+hash value = fmap (AuxiliaryDataHash . Blake2b.toBytes) <$> Blake2b.compute 32 (toCbor value)
@@ -0,0 +1,22 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Complete an existing transaction using explicit wallet and ledger snapshots.+-- Balancing returns an unsigned copy; it never changes the supplied transaction.+module Cometa.Transaction.Balancing (balance, balanceWithRedeemers) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.TransactionBalancing (balance, balanceWithRedeemers)
@@ -0,0 +1,261 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Transaction bodies with typed semantic fields and exact imported identity.+-- Construct a minimal body, update its typed fields, then retain 'EncodedBody'+-- for hashing or signing. Reassembling semantic fields deliberately produces a+-- fresh encoding and can change a transaction identifier.+--+-- @+-- minimal = body [] [] 0+-- @+module Cometa.Transaction.Body+ ( Body (..),+ body,+ fee,+ setFee,+ setFeeEncoded,+ encodeCbor,+ encodeCborWith,+ SetField (..),+ setEncoding,+ inputsAreTagged,+ withSetEncoding,+ EncodedBody,+ decodeCbor,+ fromBody,+ toBody,+ toCbor,+ hash,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address.Reward (RewardAddress)+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Encoding.Set (SetEncoding (TaggedSet))+import Cometa.Error (Error (..))+import qualified Cometa.Internal.SetEncoding as SetEncoding+import qualified Cometa.Internal.TransactionCbor as Cbor+import Cometa.Internal.TransactionFields (BalanceInterval, Entries, Fields)+import qualified Cometa.Internal.TransactionFields as Fields+import Cometa.Protocol.ProposedUpdates (UpdateProposal)+import qualified Cometa.Protocol.ProposedUpdates as Updates+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction as Sub+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Input as Input+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import Cometa.TransactionId (TransactionId)+import qualified Cometa.TransactionId as Id+import Control.Monad (unless, when)+import Data.ByteString (ByteString)+import Data.List (sort, sortOn)+import qualified Data.Map.Strict as Map+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Semantic transaction-body data. Equality includes field presence, list order,+-- and exact encodings of embedded hash-bearing data. It does not compare the+-- imported containing-body encoding. No ledger-state validation is implied.+data Body = Body+ { -- | Shared spending, output, validity, certificate, asset and governance fields.+ bodyFields :: !Fields,+ -- | Transaction fee in lovelace, from zero through 2^64 - 1.+ bodyFee :: !Word64,+ -- | Legacy genesis-authorized protocol parameter update proposal.+ bodyUpdate :: !(Maybe UpdateProposal),+ -- | Inputs reserved as script-failure collateral; absence differs from empty.+ bodyCollateral :: !(Maybe [Input]),+ -- | Optional output returning excess collateral on script failure.+ bodyCollateralReturn :: !(Maybe Output),+ -- | Total collateral claimed, in lovelace; absence differs from zero.+ bodyTotalCollateral :: !(Maybe Word64),+ -- | Dijkstra subtransactions in serialized order, each retaining its exact+ -- body, witnesses and auxiliary-data representation.+ bodySubTransactions :: !(Maybe [SubTransaction]),+ -- | Dijkstra requirements on initial account balances before this transaction.+ bodyStartingAccountBalanceIntervals :: !(Maybe (Entries RewardAddress BalanceInterval))+ }+ deriving (Eq, Show)++-- | Exact transaction-body bytes paired with semantic data. Equality compares+-- bytes, so alternative integer widths, tags and map order remain distinguishable.+data EncodedBody = EncodedBody !ByteString !Body !(Map.Map Word64 ByteString) deriving (Show)++instance Eq EncodedBody where+ left == right = toCbor left == toCbor right++-- | Set-valued fields in this body schema. Outputs and maps are not sets.+data SetField+ = -- | Spending inputs.+ Inputs+ | -- | Stake and governance certificates.+ Certificates+ | -- | Required signer or guard credentials.+ Guards+ | -- | Reference inputs.+ ReferenceInputs+ | -- | Governance proposals.+ Proposals+ | -- | Collateral inputs.+ CollateralInputs+ | -- | Included subtransactions; their internal encodings are unchanged.+ SubTransactions+ deriving (Eq, Ord, Show, Enum, Bounded)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble required references, ordered outputs and fee with optional fields+-- absent. Empty input/output lists are representable but may fail ledger rules.+body :: [Input] -> [Output] -> Word64 -> Body+body inputs outputs amount = Body (Fields.fields inputs outputs) amount Nothing Nothing Nothing Nothing Nothing Nothing++-- | Fee measured in lovelace.+fee :: Body -> Word64+fee = bodyFee++-- | Set a fee in lovelace. Other semantic fields remain independent. Construct+-- a fresh 'EncodedBody' before signing this edited body.+setFee :: Word64 -> Body -> Body+setFee amount value = value {bodyFee = amount}++-- | Edit only a validated body's fee, retaining exact nested field bytes.+-- An unchanged fee returns the exact original body. A changed fee uses a fresh+-- definite outer map in numeric key order; other fields keep their original+-- encodings, including imported historical empty collections. The input snapshot+-- remains independent. Any signatures over the previous identifier need renewal.+setFeeEncoded :: Word64 -> EncodedBody -> EncodedBody+setFeeEncoded amount original@(EncodedBody _ semantic fields)+ | amount == fee semantic = original+ | otherwise = EncodedBody bytes (setFee amount semantic) updated+ where+ updated = Map.insert 2 (Cbor.encode (E.encodeWord64 amount)) fields+ bytes = Cbor.encode (E.encodeMapLen (fromIntegral (Map.size updated)) <> foldMap (\(key, payload) -> E.encodeWord64 key <> Cbor.raw payload) (Map.toAscList updated))++-- | Encode a fresh definite map in numeric field order, using shortest numbers+-- and tag 258 on sets. Present empty or duplicate guards return+-- 'InvalidTransactionField'. Embedded inline data and subtransactions retain exact+-- identity. Importing an existing signed body should use 'toCbor' instead.+encodeCbor :: Body -> Either Error ByteString+encodeCbor value = do+ Fields.validateFields False (bodyFields value)+ when (maybe False null (bodySubTransactions value)) (Left (InvalidTransactionField "Present subtransaction set must be nonempty"))+ Right (Cbor.encode (E.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, payload) -> E.encodeWord64 key <> payload) (sortOn fst pairs)))+ where+ pairs =+ Fields.encodeFields (bodyFields value)+ ++ [(2, E.encodeWord64 (bodyFee value))]+ ++ optional 6 (Cbor.raw . Updates.encodeProposal) (bodyUpdate value)+ ++ optional 13 inputSet (bodyCollateral value)+ ++ optional 16 (Cbor.raw . Output.encodeCbor) (bodyCollateralReturn value)+ ++ optional 17 E.encodeWord64 (bodyTotalCollateral value)+ ++ optional 23 subSet (bodySubTransactions value)+ ++ optional 27 Fields.encodeIntervals (bodyStartingAccountBalanceIntervals value)+ optional key encoder = maybe [] (\payload -> [(key, encoder payload)])+ inputSet values = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Input.encodeCbor) (sort values)+ subSet values = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap (Cbor.raw . Sub.encodeCbor) values++-- | Validate fresh assembly and pair semantic data with its encoding. Present+-- empty guards or repeated guard credentials return 'InvalidTransactionField'.+fromBody :: Body -> Either Error EncodedBody+fromBody value = encodeCbor value >>= decodeCbor++-- | Inspect semantic fields without changing the original body bytes.+toBody :: EncodedBody -> Body+toBody (EncodedBody _ value _) = value++-- | Exact imported or freshly encoded ledger transaction-body bytes.+toCbor :: EncodedBody -> ByteString+toCbor (EncodedBody bytes _ _) = bytes++-- | Decode all pinned native body fields, including typed Dijkstra fields 23-27.+-- Unknown keys, repeated keys, missing inputs/outputs/fee, malformed nested data,+-- and trailing bytes return a structured error. Definite and indefinite maps,+-- nonminimal numbers and optional set tags retain their original byte identity.+decodeCbor :: ByteString -> Either Error EncodedBody+decodeCbor bytes = do+ fields <- Cbor.decode (Cbor.mapFields bytes) bytes+ unless (all (`elem` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]) (Map.keys fields)) (Left (InvalidTransactionField "Unknown transaction body key"))+ common <- Fields.decodeFields fields+ amount <- required 2 (Cbor.decode D.decodeWord64) fields+ updates <- optional 6 (fmap Updates.toProposal . Updates.decodeProposal) fields+ collateral <- optional 13 inputDecoder fields+ collateralReturn <- optional 16 (fmap Output.toOutput . Output.decodeCbor) fields+ totalCollateral <- optional 17 (Cbor.decode D.decodeWord64) fields+ subs <- optional 23 subDecoder fields+ starting <- optional 27 Fields.decodeIntervals fields+ pure (EncodedBody bytes (Body common amount updates collateral collateralReturn totalCollateral subs starting) fields)+ where+ required key parser fields = maybe (Left (InvalidTransactionField "Missing fee")) parser (Map.lookup key fields)+ optional key parser fields = traverse parser (Map.lookup key fields)+ inputDecoder payload = sort <$> Cbor.decode (Cbor.setList (Cbor.nested payload Input.decodeCbor)) payload+ subDecoder payload = do+ values <- Cbor.decode (Cbor.setList (Cbor.nested payload Sub.decodeCbor)) payload+ when (null values) (Left (InvalidTransactionField "Present subtransaction set must be nonempty"))+ pure values++-- | Hash the exact body bytes with native BLAKE2b-256. This operation does not+-- normalize or rebuild the body. Native failures remain 'NativeError'.+hash :: EncodedBody -> IO (Either Error TransactionId)+hash value = do+ result <- Blake2b.compute 32 (toCbor value)+ pure (result >>= Id.fromBytes . Blake2b.toBytes)++-- | Encode fresh body fields with the requested set tags. Embedded values keep+-- their own encoding choices. Protocol validity is the caller's responsibility.+encodeCborWith :: SetEncoding -> Body -> Either Error ByteString+encodeCborWith requested value = do+ original <- fromBody value+ pure (toCbor (foldr (`withSetEncoding` requested) original [minBound .. maxBound]))++-- | Observe one field's set tag. An absent optional field returns 'Nothing'.+setEncoding :: SetField -> EncodedBody -> Maybe SetEncoding+setEncoding field (EncodedBody _ _ values) = SetEncoding.encoding <$> Map.lookup (setFieldKey field) values++-- | Whether the encoded spending-input collection carries set tag 258.+-- Other tagged collections do not affect this result; an absent input field+-- returns 'False'. This observes the exact body snapshot without re-encoding.+inputsAreTagged :: EncodedBody -> Bool+inputsAreTagged encoded = setEncoding Inputs encoded == Just TaggedSet++-- | Change one present field's set tag. Absence and an unchanged tag preserve+-- the exact original body. A change rebuilds the outer map in numeric key order,+-- retaining all other field bytes and the selected array's contents. It can+-- change the body hash: signatures over the previous body must be renewed.+withSetEncoding :: SetField -> SetEncoding -> EncodedBody -> EncodedBody+withSetEncoding field requested original@(EncodedBody _ semantic values)+ | updated == values = original+ | otherwise = EncodedBody encoded semantic updated+ where+ updated = Map.adjust (SetEncoding.withEncoding requested) (setFieldKey field) values+ encoded = Cbor.encode (E.encodeMapLen (fromIntegral (Map.size updated)) <> foldMap (\(key, payload) -> E.encodeWord64 key <> Cbor.raw payload) (Map.toAscList updated))++-- | Ledger map key of a supported set-valued field.+setFieldKey :: SetField -> Word64+setFieldKey field = case field of+ Inputs -> 0+ Certificates -> 4+ Guards -> 14+ ReferenceInputs -> 18+ Proposals -> 20+ CollateralInputs -> 13+ SubTransactions -> 23
@@ -0,0 +1,29 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Balance a complete pure transaction plan using explicit protocol and wallet+-- snapshots. Build returns a fresh unsigned transaction; signing and submission+-- are separate operations. Inject selection or evaluation with ordinary records.+--+-- @+-- buildPayment params slots change funds output =+-- build (defaultConfig params slots change) {availableUtxos = funds}+-- (Plan.payTo output)+-- @+module Cometa.Transaction.Builder (Config (..), defaultConfig, build) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.TransactionBuilder (Config (..), build, defaultConfig)
@@ -0,0 +1,209 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Standalone transaction building calculations. Obtain a protocol snapshot,+-- assemble outputs and witnesses, evaluate scripts, then calculate commitments+-- and fees explicitly. Calculations leave the supplied transaction unchanged.+--+-- @+-- import qualified Cometa.Transaction.Building as Building+--+-- priceOutput output = Building.minimumAda 4310 output+-- @+module Cometa.Transaction.Building+ ( coinSize,+ outputSize,+ scriptSize,+ transactionSize,+ totalExecutionUnits,+ minimumAda,+ baseFee,+ minimumFee,+ executionFee,+ referenceScriptFee,+ scriptDataHash,+ ImplicitCoin (..),+ implicitCoin,+ subTransactionImplicitCoin,+ imbalance,+ subTransactionImbalance,+ batchImbalance,+ isBalanced,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Write as Write+import Cometa.Error (Error (InvalidBuildingRequest))+import qualified Cometa.Internal.Balance as Balance+import Cometa.Internal.Building (ImplicitCoin (..))+import qualified Cometa.Internal.Building as Internal+import Cometa.Protocol.CostModels (CostModels)+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as ExUnits+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.Script.Plutus as PlutusScript+import Cometa.SubTransaction (SubTransaction)+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import Cometa.Transaction.Datum (Hash32)+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import Cometa.Transaction.Utxo (Utxo)+import Cometa.Transaction.Witnesses (EncodedWitnesses)+import Cometa.Value (Value)+import qualified Data.ByteString as ByteString+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++-- | Size in bytes of the shortest unsigned CBOR encoding of a lovelace amount.+-- Zero through 23 require one byte; every unsigned 64-bit amount is supported.+coinSize :: Word64 -> Int+coinSize = ByteString.length . Write.toStrictByteString . Encode.encodeWord64++-- | Size in bytes of this output's public CBOR encoding, including its value,+-- datum and reference script. Does not calculate the minimum required Ada.+outputSize :: Output -> Int+outputSize = ByteString.length . Output.encodeCbor++-- | Script size in bytes charged by reference-script pricing. Native scripts+-- use their exact CBOR; Plutus scripts use their compiled bytes without the+-- outer CBOR bytestring or the language-tag envelope.+scriptSize :: Script.Script -> Int+scriptSize script = case script of+ Script.Native native -> ByteString.length (NativeScript.encodeCbor native)+ Script.Plutus plutus -> ByteString.length (PlutusScript.toBytes plutus)++-- | Complete encoded transaction size in bytes, including the validity flag+-- when present, actual witnesses and auxiliary data. This is not the ledger+-- size used by 'baseFee', which excludes the validity flag.+transactionSize :: Transaction -> Int+transactionSize = ByteString.length . Tx.encodeCbor++-- | Sum declared memory units and CPU steps without executing scripts. Counts+-- every supplied redeemer, including repeated purpose/index pairs. Empty input+-- returns zero. Either total exceeding 2^64-1 returns 'Cometa.Error.InvalidExUnits'+-- rather than wrapping. Nested transaction redeemers must be supplied explicitly.+totalExecutionUnits :: [Redeemer.Redeemer] -> Either Error ExUnits.ExUnits+totalExecutionUnits redeemers =+ ExUnits.mkExUnits+ (sum (map (toInteger . ExUnits.memory . Redeemer.executionUnits) redeemers))+ (sum (map (toInteger . ExUnits.steps . Redeemer.executionUnits) redeemers))++-- | Minimum output coin in lovelace, accounting for the size of the resulting+-- coin encoding. The first argument is lovelace per UTxO byte. Zero is allowed;+-- amounts exceeding native 64-bit calculation bounds return a native error.+minimumAda :: Word64 -> Output -> IO (Either Error Word64)+minimumAda = Internal.minimumAda++-- | Linear fee in lovelace: constant plus coefficient times ledger transaction+-- size, excluding the script-validity flag. Arguments are the constant lovelace+-- charge, then lovelace per byte. Uses actual included witnesses and auxiliary+-- data; callers must account for any witnesses they intend to add. Overflow is+-- an error. No execution or reference script charge is included.+baseFee :: Word64 -> Word64 -> Transaction -> IO (Either Error Word64)+baseFee = Internal.baseFee++-- | Fee in lovelace for the complete supplied transaction, including execution+-- units of top-level and subtransaction redeemers and reference script prices.+-- Resolved UTxOs must be unique and cover exactly the union of spending and+-- reference inputs in all bodies. A reference script is charged once per UTxO+-- within each body, even if both spent and referenced there. The same UTxO+-- appearing in several bodies is priced for each body. Missing execution or reference prices and invalid coverage+-- return 'Cometa.Error.InvalidBuildingRequest'. Uses actual included witnesses;+-- adding signatures or changing budgets requires recalculation. No evaluation,+-- witness estimation, input resolution or fee installation is performed.+minimumFee :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Word64)+minimumFee = Internal.minimumFee++-- | Exact execution charge in lovelace for supplied prices and aggregate+-- budgets: round the sum of memory and CPU charges upward once. Does not price+-- reference scripts or execute scripts. Zero budgets cost zero. A result above+-- 2^64-1 returns 'Cometa.Error.InvalidBuildingRequest'. Aggregate transaction and+-- subtransaction redeemers with 'totalExecutionUnits' before pricing a batch.+executionFee :: Prices.ExUnitPrices -> ExUnits.ExUnits -> Either Error Word64+executionFee prices units =+ let charge =+ fromIntegral (ExUnits.memory units) * Rational.toRational (Prices.memoryPrice prices)+ + fromIntegral (ExUnits.steps units) * Rational.toRational (Prices.stepPrice prices)+ rounded = ceiling charge :: Integer+ in if rounded <= toInteger (maxBound :: Word64)+ then Right (fromInteger rounded)+ else Left (InvalidBuildingRequest "Execution fee exceeds the unsigned 64-bit range")++-- | Price reference scripts in exactly these unique resolved UTxOs, in lovelace.+-- Uses exact rational tier prices and floors the total once. Missing stride or+-- multiplier uses Conway values 25600 bytes and 6/5; supplied values use protocol+-- tiers. A reference byte price is required. Duplicate references are invalid.+referenceScriptFee :: Parameters -> [Utxo] -> IO (Either Error Word64)+referenceScriptFee = Internal.referenceScriptFee++-- | Script-data commitment for the exact redeemer and datum field encodings in+-- these witnesses. Supply only cost models for the languages used by the body:+-- every supplied language view contributes when redeemers are present. No+-- redeemers and no datums returns 'Nothing'; datum-only witnesses use empty+-- language views. Does not install the commitment in a body or evaluate scripts.+scriptDataHash :: CostModels -> EncodedWitnesses -> IO (Either Error (Maybe Hash32))+scriptDataHash = Internal.scriptDataHash++-- | Top-level body's withdrawals, paid deposits and reclaimed deposits. Nested+-- subtransactions are excluded. Each pool is charged once within this body;+-- already registered pools are also charged because no chain registration state+-- is supplied. Pool retirement refunds occur at epoch boundaries and contribute+-- zero here. This is an accounting component, not a ledger balance assertion.+-- Native unsigned 64-bit overflow is reported as an error.+implicitCoin :: Parameters -> Transaction -> IO (Either Error ImplicitCoin)+implicitCoin = Internal.implicitCoin++-- | The same accounting as 'implicitCoin' for one subtransaction body. Pool+-- deposits are charged once per pool within this body, independently of other+-- bodies in a batch; this does not compute the deduplicated batch balance.+subTransactionImplicitCoin :: Parameters -> SubTransaction -> IO (Either Error ImplicitCoin)+subTransactionImplicitCoin = Internal.subTransactionImplicitCoin++-- | Top-level consumed value minus produced value. Positive quantities are a+-- surplus; negative quantities are a deficit. Includes mint/burn, withdrawals,+-- refunds, deposits, fee, donation and direct deposits; excludes nested bodies.+-- Resolve every spending input exactly once. Extra resolved UTxOs are allowed;+-- reference and collateral inputs do not contribute. Signed 64-bit intermediate+-- overflow or missing/duplicate resolution returns 'Cometa.Error.InvalidBuildingRequest'.+imbalance :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Value)+imbalance = Balance.imbalance++-- | The same accounting for one subtransaction, which has no fee. A nonzero+-- result is normal for an intent awaiting matching in a batch.+subTransactionImbalance :: Parameters -> [Utxo] -> SubTransaction -> IO (Either Error Value)+subTransactionImbalance = Balance.subTransactionImbalance++-- | Whole-batch surplus or deficit, charging each registered pool's deposit+-- once across all bodies. Supply a unique resolved snapshot covering spending+-- inputs at every level. Positive and negative intermediate totals must each+-- fit signed 64-bit bounds. This checks value conservation, not ledger admission,+-- signatures, script success or availability of inputs on chain.+batchImbalance :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Value)+batchImbalance = Balance.batchImbalance++-- | Whether the complete batch has zero coin and asset imbalance. Does not+-- validate other ledger rules. Resolution and arithmetic errors remain explicit.+isBalanced :: Parameters -> [Utxo] -> Transaction -> IO (Either Error Bool)+isBalanced = Balance.isBalanced
@@ -0,0 +1,58 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Output datum alternatives. Inline data retains exact datum bytes because+-- re-encoding a datum can change its hash.+--+-- @+-- noDatum = NoDatum+-- @+module Cometa.Transaction.Datum (Datum (..), Hash32, hashFromBytes, hashBytes) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.PlutusData (EncodedPlutusData)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B++-- TYPES ----------------------------------------------------------------------++-- | An exact 32-byte datum, script-data or auxiliary-data digest. Equality and+-- ordering compare bytes; importing does not verify how the digest was obtained.+newtype Hash32 = Hash32 ByteString deriving (Eq, Ord, Show)++-- | Output datum choice. A hash carries no witness datum; inline data carries+-- the exact encoded datum, including arbitrary map order and duplicate keys.+data Datum+ = -- | No datum is attached to the output.+ NoDatum+ | -- | Hash identifying a datum supplied separately as a witness when needed.+ DatumHash !Hash32+ | -- | Exact datum bytes embedded directly in the output.+ InlineDatum !EncodedPlutusData+ deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate exactly 32 digest bytes; otherwise return 'InvalidTransactionHashLength'.+hashFromBytes :: ByteString -> Either Error Hash32+hashFromBytes bytes+ | B.length bytes == 32 = Right (Hash32 bytes)+ | otherwise = Left (InvalidTransactionHashLength (B.length bytes))++-- | Exact digest bytes, always length 32.+hashBytes :: Hash32 -> ByteString+hashBytes (Hash32 bytes) = bytes
@@ -0,0 +1,183 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Pure queries of the current builder draft for deferred redeemers. Compose+-- required indices, inspect selected inputs, then supply an explicit script-data+-- encoder to 'redeemer'. Queries run again whenever the builder invokes the+-- callback; positions are specific to that draft, not the final signed body.+--+-- @+-- import qualified Cometa.PlutusData as Data+-- import qualified Cometa.Transaction.Deferred as Deferred+--+-- spendingRedeemer reference =+-- Deferred.redeemer (Data.Integer . toInteger) (Deferred.inputIndex reference)+-- @+module Cometa.Transaction.Deferred+ ( Query,+ draft,+ selectedInputs,+ fromEither,+ run,+ inputIndex,+ referenceInputIndex,+ mintPolicyIndex,+ withdrawalIndex,+ voteIndex,+ proposalIndex,+ redeemerIndex,+ outputIndex,+ outputIndexWhere,+ redeemer,+ encodedRedeemer,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address.Reward (RewardAddress)+import Cometa.Error (Error (InvalidBuildingRequest))+import Cometa.Evaluation (RedeemerId)+import Cometa.Governance.Proposal (Proposal)+import Cometa.Governance.Voting (Voter)+import qualified Cometa.PlutusData as Data+import Cometa.PolicyId (PolicyId)+import Cometa.Transaction (Transaction)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as Indices+import Cometa.Transaction.Input (Input)+import Cometa.Transaction.Output (Output)+import Cometa.Transaction.Plan (DeferredRedeemer)+import Cometa.Transaction.Utxo (Utxo)+import Data.Text (Text)+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | A read-only draft query with explicit expected failure. 'Functor',+-- 'Applicative' and 'Monad' share the same immutable draft and selected-input+-- snapshot throughout a run and stop at the first 'Left'. No native or network+-- effects occur. The constructor is hidden; use the queries and 'fromEither'.+newtype Query a = Query (Transaction -> [Utxo] -> Either Error a)++instance Functor Query where+ fmap f (Query query) = Query (\transaction inputs -> fmap f (query transaction inputs))++instance Applicative Query where+ pure value = Query (\_ _ -> Right value)+ Query function <*> Query argument = Query $ \transaction inputs ->+ function transaction inputs <*> argument transaction inputs++instance Monad Query where+ Query query >>= next = Query $ \transaction inputs -> do+ value <- query transaction inputs+ run (next value) transaction inputs++-- DEFINITIONS ----------------------------------------------------------------++-- | The current callback draft. Inspect it with the ordinary pure transaction+-- observers. Subsequent balancing may change its body and indices.+draft :: Query Transaction+draft = Query (\transaction _ -> Right transaction)++-- | The exact selected-input list supplied to this callback, retaining order.+-- This is not a network query and need not include reference inputs. 'run' does+-- not validate or reorder an independently supplied snapshot.+selectedInputs :: Query [Utxo]+selectedInputs = Query (\_ inputs -> Right inputs)++-- | Lift existing pure validation. A 'Left' stops subsequent query steps.+fromEither :: Either Error a -> Query a+fromEither result = Query (\_ _ -> result)++-- | Evaluate against one draft and selected-input snapshot. Useful for testing+-- a query before installing it in a plan. Inputs remain unchanged.+run :: Query a -> Transaction -> [Utxo] -> Either Error a+run (Query query) = query++-- | Required spending-input position in hash-byte then numeric-index order.+-- Duplicates use their first position. Absence returns 'InvalidBuildingRequest'.+inputIndex :: Input -> Query Word64+inputIndex reference = required "Deferred spending input is missing" (Indices.findInput reference)++-- | Required reference-input position in the same order as 'inputIndex'.+-- Absence returns 'InvalidBuildingRequest'.+referenceInputIndex :: Input -> Query Word64+referenceInputIndex reference = required "Deferred reference input is missing" (Indices.findReferenceInput reference)++-- | Required mint-policy position in ascending policy-hash order. Empty and+-- zero-quantity imported policies count. Absence returns 'InvalidBuildingRequest'.+mintPolicyIndex :: PolicyId -> Query Word64+mintPolicyIndex policy = required "Deferred mint policy is missing" (Indices.findMintPolicy policy)++-- | Required withdrawal position in ledger reward-account order, as documented+-- by 'Indices.findWithdrawal'. Absence returns 'InvalidBuildingRequest'.+withdrawalIndex :: RewardAddress -> Query Word64+withdrawalIndex account = required "Deferred withdrawal is missing" (Indices.findWithdrawal account)++-- | Required voter position in ledger role and credential order, independent+-- of the number of action votes. Absence returns 'InvalidBuildingRequest'.+voteIndex :: Voter -> Query Word64+voteIndex voter = required "Deferred voter is missing" (Indices.findVote voter)++-- | Required proposal position in insertion order, comparing canonical+-- encodings and using the first duplicate. Absence returns 'InvalidBuildingRequest'.+proposalIndex :: Proposal -> Query Word64+proposalIndex proposal = required "Deferred proposal is missing" (Indices.findProposal proposal)++-- | Required rank among redeemers ordered by purpose and purpose index. This+-- is not the authorized body-item index. Absence returns 'InvalidBuildingRequest'.+redeemerIndex :: RedeemerId -> Query Word64+redeemerIndex identifier = required "Deferred redeemer is missing" (Indices.findRedeemer identifier)++required :: Text -> (Transaction -> Maybe Word64) -> Query Word64+required message lookupIndex = do+ transaction <- draft+ fromEither (maybe (Left (InvalidBuildingRequest message)) Right (lookupIndex transaction))++-- | Unique output with equal semantic fields, including exact inline datum+-- bytes. Creation order determines the index. Missing or multiple equal outputs+-- return 'InvalidBuildingRequest'; no first-match choice is made.+outputIndex :: Output -> Query Word64+outputIndex output = outputIndexWhere (== output)++-- | Unique output satisfying a pure predicate, in creation order. No match or+-- multiple matches return distinct 'InvalidBuildingRequest' diagnostics.+outputIndexWhere :: (Output -> Bool) -> Query Word64+outputIndexWhere matches = do+ transaction <- draft+ let outputs = Fields.fieldOutputs (Body.bodyFields (Body.toBody (Tx.body transaction)))+ positions = [index | (index, output) <- zip [0 ..] outputs, matches output]+ fromEither $ case positions of+ [] -> Left (InvalidBuildingRequest "Deferred output is missing")+ [index] -> Right index+ _ -> Left (InvalidBuildingRequest "Deferred output is ambiguous")++-- | Turn a query into the existing plan callback using an explicit application+-- data encoder. Encoding uses 'Data.fromData'; the query's first failure is+-- propagated unchanged. Repeated callbacks rerun the query against each draft.+redeemer :: (a -> Data.PlutusData) -> Query a -> DeferredRedeemer+redeemer encode query = encodedRedeemer (Data.fromData . encode <$> query)++-- | Turn exact validated script data into the existing plan callback without+-- re-encoding its CBOR. Compatible with top-level and subtransaction plan+-- callbacks; both receive the builder's 'Transaction' draft. Pure index queries+-- inspect the supplied draft's top-level body and do not descend into nested+-- subtransactions. Use a raw callback for other contextual policies.+encodedRedeemer :: Query Data.EncodedPlutusData -> DeferredRedeemer+encodedRedeemer = run
@@ -0,0 +1,48 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Typed fields common to transaction and Dijkstra subtransaction bodies.+--+-- @+-- minimalFields = fields [] []+-- @+module Cometa.Transaction.Fields+ ( Fields (..),+ fields,+ Mint,+ mkMint,+ mintValue,+ Entries,+ mkEntries,+ entries,+ BalanceInterval (..),+ BodyNetwork (..),+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.TransactionFields+ ( BalanceInterval (..),+ BodyNetwork (..),+ Entries,+ Fields (..),+ Mint,+ entries,+ fields,+ mintValue,+ mkEntries,+ mkMint,+ )
@@ -0,0 +1,113 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Locate objects in a top-level transaction for deferred redeemers and script+-- arguments. Indices start at zero and can change when the body changes.+-- Missing objects return 'Nothing'. Nested levels remain independent.+--+-- @+-- import qualified Cometa.Transaction.Indices as Indices+--+-- spendingPosition reference transaction = Indices.findInput reference transaction+-- @+module Cometa.Transaction.Indices+ ( findInput,+ findReferenceInput,+ findOutput,+ findMintPolicy,+ findWithdrawal,+ findCertificate,+ findVote,+ findProposal,+ findRedeemer,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address (Address)+import Cometa.Address.Reward (RewardAddress)+import Cometa.Certificate (EncodedCertificate)+import Cometa.Error (Error)+import Cometa.Evaluation (RedeemerId)+import Cometa.Governance.Proposal (Proposal)+import Cometa.Governance.Voting (Voter)+import qualified Cometa.Internal.ContextualTransaction as Native+import qualified Cometa.Internal.TransactionIndices as Indices+import Cometa.PolicyId (PolicyId)+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Witnesses as Witnesses+import Data.ByteString (ByteString)+import Data.Word (Word64)++-- DEFINITIONS ----------------------------------------------------------------++-- | First spending reference in hash-byte then numeric-index order. Duplicates+-- occupy separate positions.+findInput :: Input -> Tx.Transaction -> Maybe Word64+findInput reference = Indices.findInput reference . fields++-- | First reference input in the same order as 'findInput'.+findReferenceInput :: Input -> Tx.Transaction -> Maybe Word64+findReferenceInput reference = Indices.findReferenceInput reference . fields++-- | First output at the exact address containing at least the minimum lovelace.+-- Output creation order is retained; the minimum spans unsigned 64-bit values.+findOutput :: Address -> Word64 -> Tx.Transaction -> Maybe Word64+findOutput destination minimumLovelace = Indices.findOutput destination minimumLovelace . fields++-- | Policy position in ascending hash-byte order. Imported policies with only+-- zero quantities or an empty asset map still occupy positions.+findMintPolicy :: PolicyId -> Tx.Transaction -> Maybe Word64+findMintPolicy policy = Indices.findMintPolicy policy . bodyBytes++-- | Withdrawal position in ledger reward-account order: test networks before+-- mainnet, then script credentials before key credentials, then hash bytes.+-- All network tags other than 1 belong to the same test-network class.+findWithdrawal :: RewardAddress -> Tx.Transaction -> Maybe Word64+findWithdrawal account = Indices.findWithdrawal account . fields++-- | First certificate with the same native canonical encoding. Certificate+-- list order and duplicates count. Imported representation differences are+-- normalized by the native certificate codecs; no transaction bytes change.+findCertificate :: EncodedCertificate -> Tx.Transaction -> IO (Either Error (Maybe Word64))+findCertificate certificate = Native.findCertificate certificate . Indices.certificateBytes . bodyBytes++-- | Voter position in ledger role order: committee, DRep, stake pool. Within+-- each role script credentials precede key credentials, then hash bytes order+-- each kind. Multiple action votes by one voter occupy a single position.+findVote :: Voter -> Tx.Transaction -> Maybe Word64+findVote voter = Indices.findVote voter . fields++-- | First proposal with the same canonical encoding, including its deposit,+-- return account and anchor. Positions follow proposal insertion order, counting+-- actions without scripts. A proposing redeemer uses this same position.+findProposal :: Proposal -> Tx.Transaction -> Maybe Word64+findProposal proposal = Indices.findProposal proposal . fields++-- | Redeemer rank ordered by purpose then purpose index, independently of its+-- imported witness collection order. This is its position among all redeemers,+-- rather than its position in the body collection authorized by the script.+findRedeemer :: RedeemerId -> Tx.Transaction -> Maybe Word64+findRedeemer identifier = Indices.findRedeemer identifier . Witnesses.redeemers . Witnesses.toWitnesses . Tx.witnesses++fields :: Tx.Transaction -> Fields.Fields+fields = Body.bodyFields . Body.toBody . Tx.body++bodyBytes :: Tx.Transaction -> ByteString+bodyBytes = Body.toCbor . Tx.body
@@ -0,0 +1,67 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | References to consumed or observed transaction outputs.+--+-- @+-- firstOutput transactionId = input transactionId 0+-- @+module Cometa.Transaction.Input (Input, input, transactionId, index, encodeCbor, decodeCbor) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error)+import qualified Cometa.Internal.TransactionCbor as Cbor+import Cometa.TransactionId (TransactionId)+import qualified Cometa.TransactionId as Id+import Data.ByteString (ByteString)+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | Output identity. Ordering compares transaction hash bytes then numeric index.+-- An index occupies the native unsigned 64-bit range; assembly does not establish+-- that the referenced output exists or is spendable in a particular ledger era.+data Input = Input !TransactionId !Word64 deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Reference an output by transaction-body hash and zero-based output index.+input :: TransactionId -> Word64 -> Input+input = Input++-- | Hash of the transaction that created the output.+transactionId :: Input -> TransactionId+transactionId (Input value _) = value++-- | Zero-based output index, from zero through 2^64 - 1.+index :: Input -> Word64+index (Input _ value) = value++-- | Fresh two-element CBOR array with exact hash bytes and shortest index.+encodeCbor :: Input -> ByteString+encodeCbor (Input txId ix) = Cbor.encode (E.encodeListLen 2 <> E.encodeBytes (Id.toBytes txId) <> E.encodeWord64 ix)++-- | Decode one definite or indefinite pair, requiring a 32-byte hash and uint64+-- index. Malformed input, extra fields and trailing bytes return 'Cometa.Error.InvalidTransactionCbor'.+decodeCbor :: ByteString -> Either Error Input+decodeCbor = Cbor.decode (Cbor.array 2 parser)+ where+ parser = do+ bytes <- D.decodeBytes+ txId <- either (fail . show) pure (Id.fromBytes bytes)+ Input txId <$> D.decodeWord64
@@ -0,0 +1,68 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Inspect transaction fields as JSON domain values. These named operations+-- use the native CIP-116 representation, including its governance and nested+-- transaction fields. Large protocol integers use decimal strings; binary data+-- uses text encodings, and mapping fields may use ordered key/value arrays.+-- JSON object key order is not significant.+--+-- Inspection leaves transaction bytes, hashes and signatures unchanged. The+-- result describes fields; it is not a transaction serialization for signing,+-- an exact-CBOR interchange format, or a check of ledger validity. Use+-- 'Data.Aeson.encode' to render the returned value.+--+-- @+-- inspected <- Inspection.transaction transaction+-- -- fmap Data.Aeson.encode inspected+-- @+module Cometa.Transaction.Inspection+ ( transaction,+ subTransaction,+ body,+ subBody,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import qualified Cometa.Internal.Inspection as Inspection+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import Data.Aeson (Value)++-- DEFINITIONS ----------------------------------------------------------------++-- | Inspect the complete body, validity flag, witnesses and optional auxiliary+-- data. Native errors remain explicit; no network queries or signing occur.+transaction :: Tx.Transaction -> IO (Either Error Value)+transaction = Inspection.inspect "inspection.transaction" 0 . Tx.encodeCbor++-- | Inspect a subtransaction's body, witnesses and optional auxiliary data.+-- No fee or outer transaction validity flag is added to the result.+subTransaction :: Sub.SubTransaction -> IO (Either Error Value)+subTransaction = Inspection.inspect "inspection.subTransaction" 1 . Sub.encodeCbor++-- | Inspect an exact encoded top-level body, including any nested transactions.+body :: Body.EncodedBody -> IO (Either Error Value)+body = Inspection.inspect "inspection.body" 2 . Body.toCbor++-- | Inspect an exact encoded subtransaction body using its local field schema.+subBody :: SubBody.EncodedBody -> IO (Either Error Value)+subBody = Inspection.inspect "inspection.subBody" 3 . SubBody.toCbor
@@ -0,0 +1,189 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RankNTypes #-}++-- | Owned transaction outputs with validated quantities, explicit datum choice+-- and optional reference scripts. This module does not check minimum Ada or+-- ledger admission rules.+--+-- @+-- payment address = mkOutput address (Value.lovelace 2000000) Datum.NoDatum Nothing+-- @+module Cometa.Transaction.Output+ ( Output,+ mkOutput,+ address,+ value,+ datum,+ referenceScript,+ encodeCbor,+ EncodedOutput,+ decodeCbor,+ fromOutput,+ toOutput,+ toCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Address (Address)+import qualified Cometa.Address as Address+import Cometa.AssetId (AssetId (Ada))+import Cometa.Error (Error)+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionValue as V+import qualified Cometa.PlutusData as Data+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import Cometa.Transaction.Datum (Datum (..))+import qualified Cometa.Transaction.Datum as Datum+import Cometa.Value (Value)+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Data.ByteString (ByteString)+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++-- | A semantic output. Equality compares fields, including inline datum encoding.+-- Quantities are nonnegative and no greater than 2^63 - 1.+-- Inspecting an immutable output is pure.+data Output = Output !Address !Value !Datum !(Maybe Script) deriving (Eq, Show)++-- | Exact imported or freshly encoded output. Equality compares encoded bytes.+data EncodedOutput = EncodedOutput !ByteString !Output deriving (Show)++instance Eq EncodedOutput where+ left == right = toCbor left == toCbor right++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate every output quantity once. Negative quantities and quantities+-- greater than 2^63 - 1 return 'Cometa.Error.InvalidTransactionOutputValue'.+-- Address, datum and script values have already passed their own validation.+mkOutput :: Address -> Value -> Datum -> Maybe Script -> Either Error Output+mkOutput destination amount dat script = do+ V.validateOutput amount+ pure (Output destination amount dat script)++-- | Destination address. Reward addresses are representable without asserting+-- that a ledger accepts them as payment destinations.+address :: Output -> Address+address (Output result _ _ _) = result++-- | Nonnegative bundle; Ada quantities are lovelace.+value :: Output -> Value+value (Output _ result _ _) = result++-- | No datum, its hash, or exact inline data.+datum :: Output -> Datum+datum (Output _ _ result _) = result++-- | Optional reusable reference script, distinct from a spending witness.+referenceScript :: Output -> Maybe Script+referenceScript (Output _ _ _ result) = result++-- | Fresh Babbage-style map. Optional absent fields are omitted; inline data+-- and scripts are wrapped in tag 24 byte strings. Datum bytes remain exact.+encodeCbor :: Output -> ByteString+encodeCbor (Output destination amount dat script) = Cbor.encode (E.encodeMapLen (fromIntegral (length fields)) <> foldMap (\(key, payload) -> E.encodeWord key <> payload) fields)+ where+ assets = Value.toList (Value.difference amount (Value.lovelace (Value.quantity Ada amount)))+ coin = E.encodeInteger (Value.quantity Ada amount)+ amountEncoding = if null assets then coin else E.encodeListLen 2 <> coin <> V.encodeAssets amount+ fields = [(0, E.encodeBytes (Address.toBytes destination)), (1, amountEncoding)] ++ datumField ++ maybe [] (\s -> [(3, E.encodeTag 24 <> E.encodeBytes (Script.encodeCbor s))]) script+ datumField = case dat of+ NoDatum -> []+ DatumHash hash -> [(2, E.encodeListLen 2 <> E.encodeWord 0 <> E.encodeBytes (Datum.hashBytes hash))]+ InlineDatum payload -> [(2, E.encodeListLen 2 <> E.encodeWord 1 <> E.encodeTag 24 <> E.encodeBytes (Data.toCbor payload))]++-- | Pair semantic output with a fresh encoding.+fromOutput :: Output -> EncodedOutput+fromOutput output = EncodedOutput (encodeCbor output) output++-- | Inspect semantic output fields. Re-encoding may change imported legacy form.+toOutput :: EncodedOutput -> Output+toOutput (EncodedOutput _ output) = output++-- | Exact imported or freshly encoded bytes.+toCbor :: EncodedOutput -> ByteString+toCbor (EncodedOutput bytes _) = bytes++-- | Decode exactly one legacy array or Babbage map, rejecting unknown or duplicate+-- keys, malformed datum/script envelopes, invalid quantities and trailing bytes.+-- Legacy arrays contain address, value and optionally a datum hash. Original+-- bytes are retained independently of the semantic output.+decodeCbor :: ByteString -> Either Error EncodedOutput+decodeCbor bytes = EncodedOutput bytes <$> Cbor.decode parser bytes+ where+ parser = do+ token <- D.peekTokenType+ if token == D.TypeMapLen || token == D.TypeMapLenIndef then mapOutput else legacyOutput+ validate destination amount dat script = either (fail . show) pure (mkOutput destination amount dat script)+ addressParser = D.decodeBytes >>= either (fail . show) pure . Address.fromBytes+ valueParser = do+ token <- D.peekTokenType+ (coin, assets) <-+ if token == D.TypeUInt || token == D.TypeUInt64+ then (,) <$> D.decodeInteger <*> pure mempty+ else Cbor.array 2 ((,) <$> D.decodeInteger <*> V.decodeAssets)+ unless (coin >= 0 && coin <= toInteger (maxBound :: Int64)) (fail "Output coin exceeds nonnegative int64")+ pure (Value.lovelace coin <> assets)+ decodeField :: (forall s. D.Decoder s a) -> Word64 -> Map.Map Word64 ByteString -> D.Decoder t a+ decodeField parser' key fields = case Map.lookup key fields of+ Nothing -> fail "Missing required output field"+ Just payload -> either (fail . show) pure (Cbor.decode parser' payload)+ optionalField :: (forall s. D.Decoder s a) -> Word64 -> Map.Map Word64 ByteString -> D.Decoder t (Maybe a)+ optionalField parser' key fields = traverse (either (fail . show) pure . Cbor.decode parser') (Map.lookup key fields)+ mapOutput = do+ fields <- Cbor.mapFields bytes+ unless (all (`elem` [0, 1, 2, 3]) (Map.keys fields)) (fail "Unknown output field")+ destination <- decodeField addressParser 0 fields+ amount <- decodeField valueParser 1 fields+ dat <- fromMaybe NoDatum <$> optionalField datumParser 2 fields+ script <- optionalField scriptParser 3 fields+ validate destination amount dat script+ datumParser = Cbor.array 2 $ do+ kind <- D.decodeWord+ case kind of+ 0 -> DatumHash <$> (D.decodeBytes >>= either (fail . show) pure . Datum.hashFromBytes)+ 1 -> InlineDatum <$> (embedded >>= either (fail . show) pure . Data.decodeCbor)+ _ -> fail "Invalid datum alternative"+ scriptParser = embedded >>= either (fail . show) pure . Script.decodeCbor+ embedded = do+ tag <- D.decodeTag+ unless (tag == 24) (fail "Expected embedded CBOR tag24")+ D.decodeBytes+ legacyOutput = do+ count <- D.decodeListLenOrIndef+ unless (maybe True (`elem` [2, 3]) count) (fail "Invalid legacy output arity")+ destination <- addressParser+ amount <- valueParser+ hasDatum <- case count of+ Just 3 -> pure True+ Just _ -> pure False+ Nothing -> not <$> D.decodeBreakOr+ dat <- if hasDatum then DatumHash <$> (D.decodeBytes >>= either (fail . show) pure . Datum.hashFromBytes) else pure NoDatum+ case count of+ Nothing | hasDatum -> D.decodeBreakOr >>= \ended -> unless ended (fail "Extra legacy output field")+ _ -> pure ()+ validate destination amount dat Nothing
@@ -0,0 +1,103 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Compose transaction requirements as owned values, then pass the complete+-- plan to 'Cometa.Transaction.Builder.build'. Plans form an ordered monoid:+-- @payTo first <> payTo second@ preserves payment order, and @mempty@ adds no+-- requirements. Conflicts are reported when building.+--+-- @+-- payment output = payTo output <> validUntil 1000000+-- @+module Cometa.Transaction.Plan+ ( Plan,+ payTo,+ spend,+ spendWith,+ DeferredRedeemer,+ spendWithDeferredRedeemer,+ mintWithDeferredRedeemer,+ certificateWithDeferredRedeemer,+ withdrawWithDeferredRedeemer,+ referenceInput,+ attachScript,+ mint,+ mintWithRedeemer,+ metadata,+ attachDatum,+ certificate,+ certificateWithRedeemer,+ withdraw,+ withdrawWithRedeemer,+ requireSigner,+ validFrom,+ validUntil,+ requireGuard,+ guardWithRedeemer,+ directDeposit,+ accountBalance,+ startingAccountBalance,+ donate,+ currentTreasuryValue,+ propose,+ proposeWithRedeemer,+ proposeWithDeferredRedeemer,+ vote,+ voteWithRedeemer,+ voteWithDeferredRedeemer,+ attachSubTransaction,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Internal.TransactionPlan+ ( DeferredRedeemer,+ Plan,+ accountBalance,+ attachDatum,+ attachScript,+ attachSubTransaction,+ certificate,+ certificateWithDeferredRedeemer,+ certificateWithRedeemer,+ currentTreasuryValue,+ directDeposit,+ donate,+ guardWithRedeemer,+ metadata,+ mint,+ mintWithDeferredRedeemer,+ mintWithRedeemer,+ payTo,+ propose,+ proposeWithDeferredRedeemer,+ proposeWithRedeemer,+ referenceInput,+ requireGuard,+ requireSigner,+ spend,+ spendWith,+ spendWithDeferredRedeemer,+ startingAccountBalance,+ validFrom,+ validUntil,+ vote,+ voteWithDeferredRedeemer,+ voteWithRedeemer,+ withdraw,+ withdrawWithDeferredRedeemer,+ withdrawWithRedeemer,+ )
@@ -0,0 +1,123 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Indexed script arguments and execution budgets. Purpose and zero-based+-- index identify a redeemer; the index refers to the corresponding body field.+-- @Redeemer Spending 0 (PlutusData.fromData (PlutusData.Integer 42)) (ExUnits 10 20)@+-- assembles an argument and budget without running the script.+module Cometa.Transaction.Redeemer+ ( Purpose (..),+ Redeemer (..),+ encodeCbor,+ decodeCbor,+ encodeCollectionCbor,+ decodeCollectionCbor,+ mkCollection,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.PlutusData as PlutusData+import Cometa.Protocol.ExUnits (ExUnits)+import qualified Cometa.Protocol.ExUnits as ExUnits+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.List as List+import Data.Word (Word32)++-- TYPES ----------------------------------------------------------------------++-- | Ledger purpose tags zero through six. Guarding requires an era supporting+-- transaction guards; this standalone codec does not establish era acceptance.+data Purpose = Spending | Minting | Certifying | Rewarding | Voting | Proposing | Guarding+ deriving (Eq, Ord, Show, Enum, Bounded)++-- | Purpose, zero-based body-field index, exact script argument, and memory/CPU budget.+data Redeemer = Redeemer+ { -- | Body operation authorized by the script.+ purpose :: !Purpose,+ -- | Zero-based position in the corresponding body collection, at most 2^32-1.+ index :: !Word32,+ -- | Exact script argument encoding, preserved during witness edits.+ argument :: !PlutusData.EncodedPlutusData,+ -- | Memory units and CPU steps supplied by script evaluation.+ executionUnits :: !ExUnits+ }+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate unique purpose/index pairs and sort by purpose then index.+-- Duplicate identifiers are rejected even when their arguments agree.+mkCollection :: [Redeemer] -> Either Error [Redeemer]+mkCollection values =+ let sorted = List.sortOn identifier values+ in if any (\(a, b) -> identifier a == identifier b) (zip sorted (drop 1 sorted))+ then Left (InvalidRedeemerCbor "Duplicate redeemer purpose/index")+ else Right sorted++identifier :: Redeemer -> (Purpose, Word32)+identifier value = (purpose value, index value)++-- | Encode the historical four-element standalone redeemer form.+encodeCbor :: Redeemer -> ByteString+encodeCbor value = C.encode (E.encodeListLen 4 <> keyEncoding value <> valueEncoding value)++-- | Decode one standalone four-element form, retaining exact argument CBOR.+decodeCbor :: ByteString -> Either Error Redeemer+decodeCbor input = C.decodeAs InvalidRedeemerCbor (C.array 4 (decoder input)) input++-- | Encode a Conway-style map, sorted by purpose/index. Duplicate identifiers+-- fail explicitly; no map conversion silently overwrites an argument.+encodeCollectionCbor :: [Redeemer] -> Either Error ByteString+encodeCollectionCbor values = do+ sorted <- mkCollection values+ pure (C.encode (E.encodeMapLen (fromIntegral (length sorted)) <> foldMap entry sorted))+ where+ entry value = E.encodeListLen 2 <> keyEncoding value <> E.encodeListLen 2 <> valueEncoding value++-- | Accept the historical array or Conway map form. Imported collection order+-- normalizes by purpose/index; duplicate identifiers and indices above 2^32-1 fail.+decodeCollectionCbor :: ByteString -> Either Error [Redeemer]+decodeCollectionCbor input = C.decodeAs InvalidRedeemerCbor parser input >>= mkCollection+ where+ parser = do+ token <- D.peekTokenType+ if token == D.TypeMapLen || token == D.TypeMapLenIndef+ then C.entries $ do+ (tag, ix) <- C.array 2 ((,) <$> purposeDecoder <*> D.decodeWord32)+ C.array 2 (Redeemer tag ix <$> C.nested input PlutusData.decodeCbor <*> C.nested input ExUnits.decodeCbor)+ else C.list (C.array 4 (decoder input))++decoder :: ByteString -> D.Decoder s Redeemer+decoder input = Redeemer <$> purposeDecoder <*> D.decodeWord32 <*> C.nested input PlutusData.decodeCbor <*> C.nested input ExUnits.decodeCbor++purposeDecoder :: D.Decoder s Purpose+purposeDecoder = do+ tag <- D.decodeWord+ unless (tag <= 6) (fail "Unknown redeemer purpose")+ pure (toEnum (fromIntegral tag))++keyEncoding :: Redeemer -> E.Encoding+keyEncoding value = E.encodeWord (fromIntegral (fromEnum (purpose value))) <> E.encodeWord32 (index value)++valueEncoding :: Redeemer -> E.Encoding+valueEncoding value = C.raw (PlutusData.toCbor (argument value)) <> C.raw (ExUnits.encodeCbor (executionUnits value))
@@ -0,0 +1,70 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Produce and attach Ed25519 transaction witnesses using scoped signing keys.+-- Signatures cover the exact transaction-body hash; witnesses and outer framing+-- never enter the signed message. Operations preserve the source transaction.+module Cometa.Transaction.Signing+ ( verificationWitness,+ sign,+ subTransactionWitness,+ signSubTransaction,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import Control.Monad.Trans.Except (ExceptT (..), runExceptT)++-- DEFINITIONS ----------------------------------------------------------------++-- | Sign the exact body hash and pair it with the key's public key. The key+-- must remain open throughout the operation. No transaction bytes are changed.+verificationWitness :: Key.SigningKey -> Tx.Transaction -> IO (Either Error Witness.VerificationWitness)+verificationWitness key transaction = witnessForHash key (Tx.transactionId transaction)++-- | Add this key's witness, retaining existing partial signatures and exact body+-- bytes. Repeating the same signature is an exact no-op; a conflicting existing+-- signature for that public key fails. Closed keys and native failures fail.+sign :: Key.SigningKey -> Tx.Transaction -> IO (Either Error Tx.Transaction)+sign key transaction = runExceptT $ do+ witness <- ExceptT (verificationWitness key transaction)+ merged <- ExceptT (pure (Witnesses.addVerificationWitness witness (Tx.witnesses transaction)))+ pure (Tx.setWitnesses merged transaction)++-- | Sign a sub-transaction's own body hash, independent of its enclosing body.+subTransactionWitness :: Key.SigningKey -> Sub.SubTransaction -> IO (Either Error Witness.VerificationWitness)+subTransactionWitness key transaction = witnessForHash key (Sub.transactionId transaction)++-- | Add a signature to this sub-transaction while preserving its exact body.+signSubTransaction :: Key.SigningKey -> Sub.SubTransaction -> IO (Either Error Sub.SubTransaction)+signSubTransaction key transaction = runExceptT $ do+ witness <- ExceptT (subTransactionWitness key transaction)+ merged <- ExceptT (pure (Witnesses.addVerificationWitness witness (Sub.witnesses transaction)))+ pure (Sub.setWitnesses merged transaction)++witnessForHash :: Key.SigningKey -> IO (Either Error TxId.TransactionId) -> IO (Either Error Witness.VerificationWitness)+witnessForHash key hashAction = runExceptT $ do+ digest <- ExceptT hashAction+ public <- ExceptT (Key.publicKey key)+ signature <- ExceptT (Key.sign key (TxId.toBytes digest))+ pure (Witness.verificationWitness public signature)
@@ -0,0 +1,64 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | An unspent-output snapshot pairs a reference with its resolved output.+-- Construction does not query chain state or prove that the output is unspent.+--+-- @+-- resolved reference output = utxo reference output+-- @+module Cometa.Transaction.Utxo (Utxo, utxo, input, output, encodeCbor, decodeCbor) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import Cometa.Error (Error)+import qualified Cometa.Internal.TransactionCbor as Cbor+import Cometa.Transaction.Input (Input)+import qualified Cometa.Transaction.Input as Input+import Cometa.Transaction.Output (Output)+import qualified Cometa.Transaction.Output as Output+import Data.ByteString (ByteString)++-- TYPES ----------------------------------------------------------------------++-- | Owned resolved reference and semantic output. Equality compares both fields.+data Utxo = Utxo !Input !Output deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble a resolved reference and its output without chain-state validation.+utxo :: Input -> Output -> Utxo+utxo = Utxo++-- | Reference identifying the resolved output.+input :: Utxo -> Input+input (Utxo result _) = result++-- | Resolved semantic output; inspecting it has no chain or native effects.+output :: Utxo -> Output+output (Utxo _ result) = result++-- | Fresh native UTxO pair @[input, output]@. This is a snapshot interchange+-- encoding, not an on-chain transaction-body field.+encodeCbor :: Utxo -> ByteString+encodeCbor (Utxo reference resolved) = Cbor.encode (E.encodeListLen 2 <> Cbor.raw (Input.encodeCbor reference) <> Cbor.raw (Output.encodeCbor resolved))++-- | Decode a complete definite or indefinite pair through the public input and+-- output schemas. Malformed data and trailing bytes return structured errors.+-- This snapshot API inspects semantic outputs; use an enclosing exact transaction+-- or 'Output.EncodedOutput' when preserving signed-body identity is required.+decodeCbor :: ByteString -> Either Error Utxo+decodeCbor bytes = Cbor.decode (Cbor.array 2 (Utxo <$> Cbor.nested bytes Input.decodeCbor <*> (Output.toOutput <$> Cbor.nested bytes Output.decodeCbor))) bytes
@@ -0,0 +1,121 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Verification-key signatures and Byron bootstrap witnesses. Construction+-- assembles previously validated keys and signatures; it does not verify them.+-- @verificationWitness key signature@ assembles a Shelley witness.+module Cometa.Transaction.Witness+ ( VerificationWitness,+ verificationWitness,+ publicKey,+ signature,+ BootstrapWitness,+ mkBootstrapWitness,+ bootstrapPublicKey,+ bootstrapSignature,+ chainCode,+ attributes,+ encodeCbor,+ decodeCbor,+ encodeBootstrapCbor,+ decodeBootstrapCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Crypto.Ed25519.PublicKey (PublicKey)+import qualified Cometa.Crypto.Ed25519.PublicKey as Key+import Cometa.Crypto.Ed25519.Signature (Signature)+import qualified Cometa.Crypto.Ed25519.Signature as Sig+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as C+import Data.ByteString (ByteString)+import qualified Data.ByteString as B++-- TYPES ----------------------------------------------------------------------++-- | A verification key and its signature of a transaction body hash.+data VerificationWitness = VerificationWitness !PublicKey !Signature deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Assemble a key witness. Cryptographic verification is a separate effect.+verificationWitness :: PublicKey -> Signature -> VerificationWitness+verificationWitness = VerificationWitness++-- | The signing verification key.+publicKey :: VerificationWitness -> PublicKey+publicKey (VerificationWitness key _) = key++-- | Signature bytes validated for Ed25519 length.+signature :: VerificationWitness -> Signature+signature (VerificationWitness _ sig) = sig++-- | A Byron witness with a 32-byte derivation chain code and opaque serialized+-- address attributes. Equality compares all fields.+data BootstrapWitness = BootstrapWitness !PublicKey !Signature !ByteString !ByteString deriving (Eq, Ord, Show)++-- | Assemble a bootstrap witness; the chain code must contain exactly 32 bytes.+-- Attributes are the serialized Byron address attributes, retained verbatim.+mkBootstrapWitness :: PublicKey -> Signature -> ByteString -> ByteString -> Either Error BootstrapWitness+mkBootstrapWitness key sig chain attrs+ | B.length chain /= 32 = Left (InvalidBootstrapChainCodeLength (B.length chain))+ | otherwise = Right (BootstrapWitness key sig chain attrs)++-- | Bootstrap signing key.+bootstrapPublicKey :: BootstrapWitness -> PublicKey+bootstrapPublicKey (BootstrapWitness key _ _ _) = key++-- | Bootstrap signature.+bootstrapSignature :: BootstrapWitness -> Signature+bootstrapSignature (BootstrapWitness _ sig _ _) = sig++-- | Exactly 32 chain-code bytes.+chainCode :: BootstrapWitness -> ByteString+chainCode (BootstrapWitness _ _ chain _) = chain++-- | Opaque serialized Byron address attributes.+attributes :: BootstrapWitness -> ByteString+attributes (BootstrapWitness _ _ _ attrs) = attrs++-- | Encode the two-element key/signature array.+encodeCbor :: VerificationWitness -> ByteString+encodeCbor (VerificationWitness key sig) = C.encode (E.encodeListLen 2 <> E.encodeBytes (Key.toBytes key) <> E.encodeBytes (Sig.toBytes sig))++-- | Decode one key/signature array, validating lengths and rejecting trailing bytes.+decodeCbor :: ByteString -> Either Error VerificationWitness+decodeCbor = C.decodeAs InvalidWitnessCbor (C.array 2 (VerificationWitness <$> keyDecoder <*> signatureDecoder))++-- | Encode the four-element bootstrap array.+encodeBootstrapCbor :: BootstrapWitness -> ByteString+encodeBootstrapCbor (BootstrapWitness key sig chain attrs) = C.encode (E.encodeListLen 4 <> E.encodeBytes (Key.toBytes key) <> E.encodeBytes (Sig.toBytes sig) <> E.encodeBytes chain <> E.encodeBytes attrs)++-- | Decode a bootstrap array, validating lengths and rejecting trailing bytes.+decodeBootstrapCbor :: ByteString -> Either Error BootstrapWitness+decodeBootstrapCbor = C.decodeAs InvalidWitnessCbor $ C.array 4 $ do+ key <- keyDecoder+ sig <- signatureDecoder+ chain <- D.decodeBytes+ attrs <- D.decodeBytes+ either (fail . show) pure (mkBootstrapWitness key sig chain attrs)++keyDecoder :: D.Decoder s PublicKey+keyDecoder = D.decodeBytes >>= either (fail . show) pure . Key.fromBytes++signatureDecoder :: D.Decoder s Signature+signatureDecoder = D.decodeBytes >>= either (fail . show) pure . Sig.fromBytes
@@ -0,0 +1,308 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Typed transaction witnesses with exact nested script/data encodings.+-- Collection order and imported duplicates are observable. Merging adds distinct+-- witnesses and rejects conflicting signatures or redeemer arguments.+-- @fromWitnesses empty@ creates an empty witness map for an unsigned transaction.+module Cometa.Transaction.Witnesses+ ( Witnesses,+ empty,+ mkWitnesses,+ verificationWitnesses,+ bootstrapWitnesses,+ scripts,+ datums,+ redeemers,+ merge,+ EncodedWitnesses,+ encodeCbor,+ encodeCborWith,+ SetField (..),+ setEncoding,+ withSetEncoding,+ decodeCbor,+ fromWitnesses,+ toWitnesses,+ toCbor,+ mergeEncoded,+ addVerificationWitness,+ removeKeyWitnesses,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.Encoding.Set (SetEncoding)+import Cometa.Error (Error (..))+import qualified Cometa.Internal.SetEncoding as SetEncoding+import qualified Cometa.Internal.TransactionCbor as C+import qualified Cometa.PlutusData as Data+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Witness as Witness+import Control.Monad (foldM, unless)+import Data.ByteString (ByteString)+import qualified Data.List as List++-- TYPES ----------------------------------------------------------------------++-- | Immutable semantic values plus exact field encodings. Equality compares+-- field bytes; inspection exposes individual typed collections.+data Witnesses = Witnesses+ { witnessVerificationWitnesses :: ![Witness.VerificationWitness],+ witnessBootstrapWitnesses :: ![Witness.BootstrapWitness],+ witnessScripts :: ![Script.Script],+ witnessDatums :: ![Data.EncodedPlutusData],+ witnessRedeemers :: ![Redeemer.Redeemer],+ fields :: ![(Word, ByteString)]+ }+ deriving (Show)++instance Eq Witnesses where+ a == b = fields a == fields b++-- | Set-valued witness fields. Redeemers have a separate collection format.+data SetField+ = -- | Verification-key witnesses.+ VerificationKeys+ | -- | Native scripts.+ NativeScripts+ | -- | Byron bootstrap witnesses.+ BootstrapWitnesses+ | -- | Plutus V1 scripts.+ PlutusV1Scripts+ | -- | Witness datums.+ Datums+ | -- | Plutus V2 scripts.+ PlutusV2Scripts+ | -- | Plutus V3 scripts.+ PlutusV3Scripts+ | -- | Plutus V4 scripts.+ PlutusV4Scripts+ deriving (Eq, Ord, Show, Enum, Bounded)++-- DEFINITIONS ----------------------------------------------------------------++-- | Ordered Shelley key witnesses, including imported duplicates.+verificationWitnesses :: Witnesses -> [Witness.VerificationWitness]+verificationWitnesses = witnessVerificationWitnesses++-- | Ordered Byron bootstrap witnesses, including imported duplicates.+bootstrapWitnesses :: Witnesses -> [Witness.BootstrapWitness]+bootstrapWitnesses = witnessBootstrapWitnesses++-- | Scripts grouped by serialized language field; relative order and duplicates+-- within each language are preserved.+scripts :: Witnesses -> [Script.Script]+scripts = witnessScripts++-- | Ordered exact datum encodings, including duplicates.+datums :: Witnesses -> [Data.EncodedPlutusData]+datums = witnessDatums++-- | Redeemers sorted by purpose and zero-based body index.+redeemers :: Witnesses -> [Redeemer.Redeemer]+redeemers = witnessRedeemers++-- | All collections absent.+empty :: Witnesses+empty = Witnesses [] [] [] [] [] []++-- | Assemble ordered collections. Redeemers are sorted by purpose/index and+-- duplicate identifiers fail. Other collection order and duplicates are retained.+mkWitnesses :: [Witness.VerificationWitness] -> [Witness.BootstrapWitness] -> [Script.Script] -> [Data.EncodedPlutusData] -> [Redeemer.Redeemer] -> Either Error Witnesses+mkWitnesses keys boots scriptValues dataValues redeemerValues = do+ redeemerBytes <- Redeemer.encodeCollectionCbor redeemerValues+ let nativeValues = [n | Script.Native n <- scriptValues]+ plutusValues version = [p | Script.Plutus p <- scriptValues, Plutus.version p == version]+ entries =+ concat+ [ entry 0 Witness.encodeCbor keys,+ entry 1 Native.encodeCbor nativeValues,+ entry 2 Witness.encodeBootstrapCbor boots,+ entry 3 Plutus.encodeCbor (plutusValues Plutus.V1),+ entry 4 Data.toCbor dataValues,+ [(5, redeemerBytes) | not (null redeemerValues)],+ entry 6 Plutus.encodeCbor (plutusValues Plutus.V2),+ entry 7 Plutus.encodeCbor (plutusValues Plutus.V3),+ entry 8 Plutus.encodeCbor (plutusValues Plutus.V4)+ ]+ toWitnesses <$> decodeCbor (encodeFields entries)+ where+ entry _ _ [] = []+ entry key encoder values = [(key, encodeSet encoder values)]++encodeSet :: (a -> ByteString) -> [a] -> ByteString+encodeSet encoder values = C.encode (E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap (C.raw . encoder) values)++-- | Exact imported witness envelope. Equality compares full bytes.+data EncodedWitnesses = EncodedWitnesses !ByteString !Witnesses deriving (Show)++instance Eq EncodedWitnesses where+ a == b = toCbor a == toCbor b++instance Ord EncodedWitnesses where+ compare a b = compare (toCbor a) (toCbor b)++-- | Encode a definite map while retaining each exact stored field value.+encodeCbor :: Witnesses -> ByteString+encodeCbor = encodeFields . fields++encodeFields :: [(Word, ByteString)] -> ByteString+encodeFields values = C.encode (E.encodeMapLen (fromIntegral (length values)) <> foldMap (\(key, bytes) -> E.encodeWord key <> C.raw bytes) values)++-- | Retain an encoding of assembled witness data.+fromWitnesses :: Witnesses -> EncodedWitnesses+fromWitnesses value = EncodedWitnesses (encodeCbor value) value++-- | Observe typed witness collections.+toWitnesses :: EncodedWitnesses -> Witnesses+toWitnesses (EncodedWitnesses _ value) = value++-- | Full original witness-map bytes.+toCbor :: EncodedWitnesses -> ByteString+toCbor (EncodedWitnesses bytes _) = bytes++-- | Decode fields zero through eight, including Plutus V4. Unknown/duplicate+-- fields, invalid element lengths, duplicate redeemer identifiers and trailing+-- bytes fail. Tagged and untagged collections are accepted.+decodeCbor :: ByteString -> Either Error EncodedWitnesses+decodeCbor input = do+ values <- C.decodeAs InvalidWitnessCbor (C.entries ((,) <$> D.decodeWord <*> C.slice input)) input+ unless (length values == length (List.nub (map fst values))) (Left (InvalidWitnessCbor "Duplicate witness field"))+ decoded <- foldM parseField empty values+ pure (EncodedWitnesses input decoded {fields = values})+ where+ parseField value (key, bytes) = case key of+ 0 -> (\xs -> value {witnessVerificationWitnesses = xs}) <$> set Witness.decodeCbor bytes+ 1 -> (\xs -> value {witnessScripts = witnessScripts value ++ map Script.Native xs}) <$> set Native.decodeCbor bytes+ 2 -> (\xs -> value {witnessBootstrapWitnesses = xs}) <$> set Witness.decodeBootstrapCbor bytes+ 3 -> plutus value Plutus.V1 bytes+ 4 -> (\xs -> value {witnessDatums = xs}) <$> set Data.decodeCbor bytes+ 5 -> (\xs -> value {witnessRedeemers = xs}) <$> Redeemer.decodeCollectionCbor bytes+ 6 -> plutus value Plutus.V2 bytes+ 7 -> plutus value Plutus.V3 bytes+ 8 -> plutus value Plutus.V4 bytes+ _ -> Left (InvalidWitnessCbor "Unknown witness field")+ plutus value version bytes = (\xs -> value {witnessScripts = witnessScripts value ++ map Script.Plutus xs}) <$> set (Plutus.decodeCbor version) bytes+ set decoder bytes = C.decodeAs InvalidWitnessCbor (C.setList (C.nested bytes decoder)) bytes++-- | Merge without overwriting existing signatures or redeemer budgets/arguments.+-- Identical additions are idempotent. Distinct additions follow existing elements;+-- untouched field encodings are preserved, including empty and historical forms.+-- Key/bootstrap equality compares their validated fields; script and datum+-- equality includes exact payload encodings, as does the redeemer argument.+merge :: Witnesses -> Witnesses -> Either Error Witnesses+merge left right = do+ keys <- mergeBy Witness.publicKey (witnessVerificationWitnesses left) (witnessVerificationWitnesses right)+ boots <- mergeBy Witness.bootstrapPublicKey (witnessBootstrapWitnesses left) (witnessBootstrapWitnesses right)+ rs <- mergeBy (\r -> (Redeemer.purpose r, Redeemer.index r)) (witnessRedeemers left) (witnessRedeemers right)+ fresh <- mkWitnesses keys boots (witnessScripts left `union` witnessScripts right) (witnessDatums left `union` witnessDatums right) rs+ let combined = map (retain fresh) (fields left) ++ [(key, bytes) | (key, bytes) <- fields fresh, key `notElem` map fst (fields left)]+ toWitnesses <$> decodeCbor (encodeFields combined)+ where+ retain fresh (key, original)+ | unchanged fresh key = (key, original)+ | otherwise = case lookup key (fields fresh) of+ Just updated -> (key, updated)+ Nothing -> (key, original)+ unchanged fresh key = case key of+ 0 -> witnessVerificationWitnesses left == witnessVerificationWitnesses fresh+ 2 -> witnessBootstrapWitnesses left == witnessBootstrapWitnesses fresh+ 4 -> witnessDatums left == witnessDatums fresh+ 5 -> witnessRedeemers left == witnessRedeemers fresh+ _ -> scriptsAt key left == scriptsAt key fresh+ scriptsAt key value = filter (belongs key) (witnessScripts value)+ belongs key value = case value of+ Script.Native _ -> key == 1+ Script.Plutus script ->+ key == case Plutus.version script of+ Plutus.V1 -> 3+ Plutus.V2 -> 6+ Plutus.V3 -> 7+ Plutus.V4 -> 8++mergeBy :: (Eq key, Eq value) => (value -> key) -> [value] -> [value] -> Either Error [value]+mergeBy project = foldM insert+ where+ insert values value = case filter ((== project value) . project) values of+ [] -> Right (values ++ [value])+ matches+ | all (== value) matches -> Right values+ | otherwise -> Left (WitnessConflict "Conflicting witness identity")++union :: (Eq a) => [a] -> [a] -> [a]+union = foldl (\values value -> if value `elem` values then values else values ++ [value])++-- | Merge exact envelopes. An addition with no semantic or representation change+-- returns the original envelope verbatim.+mergeEncoded :: EncodedWitnesses -> EncodedWitnesses -> Either Error EncodedWitnesses+mergeEncoded left right = do+ merged <- merge (toWitnesses left) (toWitnesses right)+ pure (if merged == toWitnesses left then left else fromWitnesses merged)++-- | Add a Shelley witness, rejecting a different signature for an existing key.+addVerificationWitness :: Witness.VerificationWitness -> EncodedWitnesses -> Either Error EncodedWitnesses+addVerificationWitness witness value = do+ addition <- mkWitnesses [witness] [] [] [] []+ mergeEncoded value (fromWitnesses addition)++-- | Remove Shelley and bootstrap signatures, retaining all other exact fields.+-- An envelope with no signatures is returned verbatim.+removeKeyWitnesses :: EncodedWitnesses -> EncodedWitnesses+removeKeyWitnesses encoded =+ let value = toWitnesses encoded+ retained = filter (\(key, _) -> key /= 0 && key /= 2) (fields value)+ in if length retained == length (fields value)+ then encoded+ else fromWitnesses value {witnessVerificationWitnesses = [], witnessBootstrapWitnesses = [], fields = retained}++-- | Encode with the requested tag on each present witness set. Nested datum and+-- script bytes remain unchanged; no absent collection is introduced.+encodeCborWith :: SetEncoding -> Witnesses -> ByteString+encodeCborWith requested value = toCbor (foldr (`withSetEncoding` requested) (fromWitnesses value) [minBound .. maxBound])++-- | Observe a witness collection's set tag; absent collections return 'Nothing'.+setEncoding :: SetField -> EncodedWitnesses -> Maybe SetEncoding+setEncoding field (EncodedWitnesses _ value) = SetEncoding.encoding <$> lookup (setFieldKey field) (fields value)++-- | Change only a present witness collection's set tag. Unchanged tags and absent+-- fields preserve the original envelope. Changes use a definite outer map while+-- retaining field order and exact nested bytes. Changing datum-set bytes can+-- require a new script-data hash and renewed transaction signatures.+withSetEncoding :: SetField -> SetEncoding -> EncodedWitnesses -> EncodedWitnesses+withSetEncoding field requested original@(EncodedWitnesses _ value)+ | updated == fields value = original+ | otherwise = EncodedWitnesses (encodeFields updated) value {fields = updated}+ where+ updated = [(key, if key == setFieldKey field then SetEncoding.withEncoding requested bytes else bytes) | (key, bytes) <- fields value]++-- | Ledger map key of a supported set-valued witness field.+setFieldKey :: SetField -> Word+setFieldKey field = case field of+ VerificationKeys -> 0+ NativeScripts -> 1+ BootstrapWitnesses -> 2+ PlutusV1Scripts -> 3+ Datums -> 4+ PlutusV2Scripts -> 6+ PlutusV3Scripts -> 7+ PlutusV4Scripts -> 8
@@ -0,0 +1,68 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Transaction identifiers are exact 32-byte transaction-body hashes.+-- Importing an identifier does not hash or verify a transaction.+--+-- @+-- import qualified Cometa.TransactionId as TransactionId+-- import qualified Data.ByteString as ByteString+--+-- example = TransactionId.fromBytes (ByteString.replicate 32 0)+-- @+module Cometa.TransactionId+ ( TransactionId,+ fromBytes,+ toBytes,+ fromHex,+ toHex,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++-- | A transaction-body hash. Equality and ordering compare exact bytes+-- lexicographically. 'Show' is diagnostic, not an interchange format.+newtype TransactionId = TransactionId ByteString deriving (Eq, Ord, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Import exactly 32 bytes. Other lengths return 'InvalidTransactionIdLength'+-- with the actual byte count.+fromBytes :: ByteString -> Either Error TransactionId+fromBytes bytes+ | ByteString.length bytes == 32 = Right (TransactionId bytes)+ | otherwise = Left (InvalidTransactionIdLength (ByteString.length bytes))++-- | Exact transaction hash bytes.+toBytes :: TransactionId -> ByteString+toBytes (TransactionId bytes) = bytes++-- | Import 64 ASCII hexadecimal digits, accepting either case. Invalid syntax+-- returns 'InvalidHex'; another decoded length returns 'InvalidTransactionIdLength'.+fromHex :: Text -> Either Error TransactionId+fromHex text = maybe (Left InvalidHex) fromBytes (Hex.decodeHex text)++-- | Lowercase hexadecimal without a prefix, always 64 digits.+toHex :: TransactionId -> Text+toHex = Hex.encodeHex . toBytes
@@ -0,0 +1,88 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Exact proportions from zero through one, inclusive.+-- Pairs retain their numerator and denominator; comparison is numeric.+--+-- @mkUnitInterval 2 3@ validates a two-thirds voting threshold.+module Cometa.UnitInterval+ ( UnitInterval,+ mkUnitInterval,+ fromDouble,+ toDouble,+ numerator,+ denominator,+ toRational,+ asNonNegativeRational,+ encodeCbor,+ decodeCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.ProtocolValues (NonNegativeRational, UnitInterval, mkUnitInterval)+import qualified Cometa.Internal.ProtocolValues as Internal+import Data.ByteString (ByteString)+import Data.Word (Word64)+import Prelude hiding (toRational)++-- DEFINITIONS ----------------------------------------------------------------++-- | Convert a finite number in @[0,1]@ using the native decimal-floor rule:+-- reduce @floor(value * 10^15) / 10^15@. This may round down and is not the+-- exact binary rational representation of the Double. NaN, infinities and values+-- outside the interval return 'InvalidUnitIntervalDouble'. Negative zero is zero.+fromDouble :: Double -> Either Error UnitInterval+fromDouble value+ | isNaN value || isInfinite value || value < 0 || value > 1 = Left InvalidUnitIntervalDouble+ | otherwise =+ let n = floor (value * 1000000000000000)+ d = 1000000000000000+ divisor = gcd n d+ in mkUnitInterval (n `quot` divisor) (d `quot` divisor)++-- | Approximate the fraction by converting its numerator and denominator+-- separately to Double and dividing, matching the native conversion. This can+-- differ from rounding an exact Rational once.+toDouble :: UnitInterval -> Double+toDouble value = fromIntegral (numerator value) / fromIntegral (denominator value)++-- | Original unsigned numerator.+numerator :: UnitInterval -> Word64+numerator = Internal.rationalNumerator . Internal.unitIntervalRational++-- | Original positive unsigned denominator.+denominator :: UnitInterval -> Word64+denominator = Internal.rationalDenominator . Internal.unitIntervalRational++-- | Exact numeric proportion.+toRational :: UnitInterval -> Rational+toRational = Internal.rationalValue . Internal.unitIntervalRational++-- | Forget the upper bound while retaining the original fraction pair.+asNonNegativeRational :: UnitInterval -> NonNegativeRational+asNonNegativeRational = Internal.unitIntervalRational++-- | Encode a definite-length ledger CBOR value with shortest integer encodings.+encodeCbor :: UnitInterval -> ByteString+encodeCbor = Internal.encodeBytes Internal.encodeUnitInterval++-- | Decode exactly one ledger CBOR value. Invalid fields or trailing data return+-- 'Cometa.Error.InvalidProtocolCbor'. Nonminimal integers and indefinite arrays+-- are accepted; output encoding uses definite arrays and shortest integers.+decodeCbor :: ByteString -> Either Error UnitInterval+decodeCbor = Internal.decodeBytes Internal.decodeUnitInterval
@@ -0,0 +1,248 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Immutable signed asset bundles with arbitrary-precision quantities.+-- Duplicate assets add, zero quantities disappear, and missing assets have+-- quantity zero. Signed deltas compose without overflow or clamping.+--+-- @+-- import qualified Cometa.AssetId as AssetId+-- import qualified Cometa.Value as Value+--+-- remaining :: Value.Value -> Value.Value -> Integer+-- remaining available required =+-- Value.quantity AssetId.Ada (Value.difference available required)+-- @+module Cometa.Value+ ( Value,++ -- * Construction+ singleton,+ lovelace,+ fromList,++ -- * Inspection+ toList,+ quantity,+ isZero,+ isNonNegative,+ assetCount,+ intersection,++ -- * Arithmetic+ negate,+ difference,+ scale,+ positivePart,+ negativePart,++ -- * Serialization+ encodeCbor,+ decodeCbor,+ encodeMintCbor,+ decodeMintCbor,+ )+where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as Name+import Cometa.Error (Error (..))+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.PolicyId as Policy+import Control.Monad (unless)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sortOn)+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Prelude hiding (negate)++-- TYPES ----------------------------------------------------------------------++-- | A finite bundle of signed asset quantities. Ada quantities count+-- lovelace; native quantities count units of the corresponding asset.+-- Equality compares quantities, ignoring absent zero entries. 'Show' is+-- diagnostic output. Signed values need not be valid transaction outputs or+-- mint quantities; those uses impose additional constraints.+newtype Value = Value (Map AssetId Integer) deriving (Eq, Show)++-- | Pointwise addition with zero results removed. Associative and commutative.+instance Semigroup Value where+ Value left <> Value right = normalized (Map.unionWith (+) left right)++-- | The empty bundle is the identity for addition.+instance Monoid Value where+ mempty = Value Map.empty++-- DEFINITIONS ----------------------------------------------------------------++-- | One asset quantity. Zero produces 'mempty'; negative quantities are retained.+singleton :: AssetId -> Integer -> Value+singleton asset amount = normalized (Map.singleton asset amount)++-- | An Ada quantity measured in lovelace. Zero produces 'mempty'; negative+-- amounts represent signed Ada deltas.+lovelace :: Integer -> Value+lovelace = singleton Ada++-- | Assemble entries by adding duplicate assets and removing zero totals.+-- Input order does not affect the resulting value.+fromList :: [(AssetId, Integer)] -> Value+fromList = normalized . Map.fromListWith (+)++-- | Nonzero entries in ascending 'AssetId' order: Ada, then policy/name bytes+-- lexicographically. This is not insertion order or CBOR map ordering.+toList :: Value -> [(AssetId, Integer)]+toList (Value amounts) = Map.toAscList amounts++-- | Quantity of the requested asset, or zero when absent.+quantity :: AssetId -> Value -> Integer+quantity asset (Value amounts) = Map.findWithDefault 0 asset amounts++-- | Negate every quantity exactly. The sum of a value and its negation is zero.+negate :: Value -> Value+negate = scale (-1)++-- | Left value minus right value, retaining negative results.+difference :: Value -> Value -> Value+difference left right = left <> negate right++-- | Multiply every quantity by an arbitrary signed scalar. Scaling by zero+-- yields 'mempty'; no quantity limit is imposed.+scale :: Integer -> Value -> Value+scale factor (Value amounts) = normalized (Map.map (factor *) amounts)++-- | Whether all quantities are zero, equivalently whether the bundle is empty.+isZero :: Value -> Bool+isZero (Value amounts) = Map.null amounts++-- | Whether every quantity is nonnegative. True for the empty bundle. This+-- inspection does not check quantity limits, minimum Ada or other output requirements.+isNonNegative :: Value -> Bool+isNonNegative (Value amounts) = all (>= 0) amounts++normalized :: Map AssetId Integer -> Value+normalized = Value . Map.filter (/= 0)++-- | Encode a standalone native value as an unsigned Ada integer, or+-- @[Ada, {policy: {name: signed quantity}}]@ when native assets are present.+-- Ada must be in 0 through 2^63-1; native quantities must fit signed 64 bits.+-- Invalid quantities return 'InvalidValueQuantity' before encoding. These are+-- serialization bounds, not transaction output validation: negative native+-- quantities are retained. Maps use canonical byte-length/lexicographic order.+-- This is fresh semantic encoding; zero entries have already been removed.+encodeCbor :: Value -> Either Error ByteString+encodeCbor value = do+ mapM_ validate (toList value)+ pure (Cbor.encode encoding)+ where+ coin = quantity Ada value+ validate (asset, amount)+ | amount > toInteger (maxBound :: Int64) = Left (InvalidValueQuantity amount)+ | amount < (if asset == Ada then 0 else toInteger (minBound :: Int64)) = Left (InvalidValueQuantity amount)+ | otherwise = Right ()+ encoding+ | assetCount value == (if coin == 0 then 0 else 1) = E.encodeInteger coin+ | otherwise = E.encodeListLen 2 <> E.encodeInteger coin <> assetsEncoding value++-- | Decode exactly one complete standalone value. Definite or indefinite arrays+-- and maps and nonminimal integers are accepted. Duplicate policies or names,+-- invalid identifiers, out-of-range quantities, wrong schemas and trailing bytes+-- return 'InvalidValueCbor'. Zero entries and empty policy maps normalize away;+-- original bytes are not retained. Ada is limited to 0 through 2^63-1.+decodeCbor :: ByteString -> Either Error Value+decodeCbor = Cbor.decodeAs InvalidValueCbor decoder+ where+ decoder = do+ token <- D.peekTokenType+ case token of+ D.TypeUInt -> lovelace <$> coinDecoder+ D.TypeUInt64 -> lovelace <$> coinDecoder+ _ -> Cbor.array 2 ((<>) . lovelace <$> coinDecoder <*> assetsDecoder)+ coinDecoder = do+ amount <- toInteger <$> D.decodeWord64+ unless (amount <= toInteger (maxBound :: Int64)) (fail "Ada exceeds signed native coin range")+ pure amount++-- | Number of distinct nonzero assets, including Ada when its quantity is+-- nonzero. Negative amounts count as present, just as positive amounts do.+assetCount :: Value -> Int+assetCount (Value amounts) = Map.size amounts++-- | Left-biased intersection: retain the left quantities for assets with+-- nonzero quantities in both bundles, regardless of sign. This includes signed+-- Ada; it does not clamp amounts or take a minimum. Results use normal asset+-- ordering. Useful for restricting a requested bundle to available asset kinds.+intersection :: Value -> Value -> Value+intersection (Value left) (Value right) = Value (Map.intersection left right)++-- | Retain strictly positive quantities, including Ada. The sum of+-- 'positivePart' and 'negativePart' recovers the original signed value.+positivePart :: Value -> Value+positivePart (Value amounts) = Value (Map.filter (> 0) amounts)++-- | Retain strictly negative quantities, including Ada, without negating them.+negativePart :: Value -> Value+negativePart (Value amounts) = Value (Map.filter (< 0) amounts)++-- | Encode a mint/burn bundle as @{policy: {name: signed quantity}}@ CBOR.+-- Native quantities must fit signed 64 bits, otherwise 'InvalidValueQuantity'.+-- Any nonzero Ada returns 'InvalidValueCbor': Ada cannot be minted. Empty+-- bundles encode an empty map. This does not validate policies or witnesses+-- against a transaction; identifiers are already validated by their types.+encodeMintCbor :: Value -> Either Error ByteString+encodeMintCbor value+ | quantity Ada value /= 0 = Left (InvalidValueCbor "Mint cannot contain Ada")+ | otherwise = do+ mapM_ valid (toList value)+ pure (Cbor.encode (assetsEncoding value))+ where+ valid (_, amount)+ | amount < toInteger (minBound :: Int64) || amount > toInteger (maxBound :: Int64) = Left (InvalidValueQuantity amount)+ | otherwise = Right ()++-- | Decode exactly one complete standalone mint/burn map. Policy and name+-- lengths, signed 64-bit quantities and duplicate keys are checked. Invalid+-- encodings or trailing bytes return 'InvalidValueCbor'. Definite/indefinite+-- maps are accepted; zero entries and empty policy maps normalize away.+decodeMintCbor :: ByteString -> Either Error Value+decodeMintCbor = Cbor.decodeAs InvalidValueCbor assetsDecoder++assetsEncoding :: Value -> E.Encoding+assetsEncoding value = E.encodeMapLen (fromIntegral (Map.size policies)) <> foldMap encodePolicy (Map.toAscList policies)+ where+ policies = Map.fromListWith (++) [(policy, [(name, amount)]) | (Native policy name, amount) <- toList value]+ encodePolicy (policy, assets) = E.encodeBytes (Policy.toBytes policy) <> E.encodeMapLen (fromIntegral (length assets)) <> foldMap encodeAsset (sortOn (\(name, _) -> (B.length (Name.toBytes name), Name.toBytes name)) assets)+ encodeAsset (name, amount) = E.encodeBytes (Name.toBytes name) <> E.encodeInteger amount++assetsDecoder :: D.Decoder s Value+assetsDecoder = do+ policies <- Cbor.entries $ do+ policy <- D.decodeBytes >>= either (fail . show) pure . Policy.fromBytes+ assets <- Cbor.entries $ do+ name <- D.decodeBytes >>= either (fail . show) pure . Name.fromBytes+ amount <- toInteger <$> D.decodeInt64+ pure (name, amount)+ unless (Set.size (Set.fromList (map fst assets)) == length assets) (fail "Duplicate asset name")+ pure (policy, assets)+ unless (Set.size (Set.fromList (map fst policies)) == length policies) (fail "Duplicate policy")+ pure (fromList [(Native policy name, amount) | (policy, assets) <- policies, (name, amount) <- assets])
@@ -0,0 +1,101 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Immutable advanced value snapshots retaining native stored-state details.+-- Ordinary "Cometa.Value" is a normalized quantity bundle; this module keeps+-- explicit zero assets, repeated names and empty policy groups. These snapshots+-- are not transaction outputs and do not establish ledger validity.+--+-- @+-- import qualified Cometa.Value.Raw as Raw+--+-- emptySnapshot = Raw.mkSnapshot 0 []+-- @+module Cometa.Value.Raw+ ( Snapshot,+ mkSnapshot,+ coin,+ assets,+ fromValue,+ toValue,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Cometa.AssetId (AssetId (Ada, Native))+import Cometa.AssetName (AssetName)+import qualified Cometa.AssetName as Name+import Cometa.Error (Error (InvalidValueQuantity))+import Cometa.PolicyId (PolicyId)+import qualified Cometa.Value as Value+import Control.Monad (unless)+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map++-- TYPES ----------------------------------------------------------------------++-- | Signed coin plus raw native-asset associations. Equality compares every+-- stored entry, including zero quantities, repeated names and empty groups.+-- Values are Haskell-owned immutable snapshots; retaining one preserves it when+-- another snapshot is assembled or converted. No cloning allocation is needed.+data Snapshot = Snapshot !Integer ![(PolicyId, [(AssetName, Integer)])]+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++-- | Validate signed 64-bit coin and asset quantities, returning+-- 'InvalidValueQuantity' on overflow. Policies sort by hash bytes; repeated+-- policy keys use the last supplied group. Names sort stably by byte length,+-- then bytes, retaining repeated names in their supplied tie order. Explicit+-- zeros and empty groups remain. The signed coin is raw accounting state;+-- negative coin is not a valid transaction-output amount.+mkSnapshot :: Integer -> [(PolicyId, [(AssetName, Integer)])] -> Either Error Snapshot+mkSnapshot lovelace groups = do+ bounded lovelace+ mapM_ (mapM_ (bounded . snd) . snd) groups+ pure (Snapshot lovelace [(policy, sortOn nameKey names) | (policy, names) <- Map.toAscList (Map.fromList groups)])+ where+ nameKey (name, _) = let bytes = Name.toBytes name in (B.length bytes, bytes)++-- | Signed coin quantity in lovelace, within the native signed 64-bit range.+coin :: Snapshot -> Integer+coin (Snapshot result _) = result++-- | Stored policy/name associations in the order documented by 'mkSnapshot'.+-- The returned lists retain zero quantities, repeated names and empty groups.+assets :: Snapshot -> [(PolicyId, [(AssetName, Integer)])]+assets (Snapshot _ result) = result++-- | Snapshot a normalized bundle, checking native signed 64-bit bounds. Input+-- normalization has already removed zero entries and combined repeated assets;+-- this operation cannot recover that discarded representation information.+fromValue :: Value.Value -> Either Error Snapshot+fromValue value = mkSnapshot (Value.quantity Ada value) (Map.toAscList groups)+ where+ groups = Map.fromListWith (<>) [(policy, [(name, quantity)]) | (Native policy name, quantity) <- Value.toList value]++-- | Explicitly normalize a raw snapshot into an ordinary bundle. This is lossy:+-- repeated names are added, zeros and empty groups disappear. The summed result+-- may exceed native bounds, which ordinary value encoders validate separately.+-- For any successfully snapshotted bundle, @fmap toValue (fromValue value) ==+-- Right value@. The reverse composition need not preserve a raw snapshot.+toValue :: Snapshot -> Value.Value+toValue (Snapshot lovelace groups) = Value.fromList ((Ada, lovelace) : [(Native policy name, quantity) | (policy, names) <- groups, (name, quantity) <- names])++bounded :: Integer -> Either Error ()+bounded quantity = unless (quantity >= toInteger (minBound :: Int64) && quantity <= toInteger (maxBound :: Int64)) (Left (InvalidValueQuantity quantity))
@@ -0,0 +1,265 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Original properties for fee and pool-accounting gaps. Independent numeric+-- expectations come from generated descriptions, not native fee/accounting+-- results. Source revision/path/license review: Fixtures/ACCOUNTING_RELIABILITY.md.+module AccountingReliability (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.PublicKey as Key+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import Cometa.Error (Error)+import qualified Cometa.Metadata as Metadata+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Value+import Control.Monad (forM)+import qualified Data.ByteString as B+import Data.Ratio ((%))+import qualified Data.Set as Set+import qualified Data.Text as T+import Data.Word (Word64, Word8)+import qualified Fixtures.ProtocolParameters as ProtocolFixture+import Hedgehog (Gen, Property, PropertyT, classify, evalEither, evalIO, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++data PoolEvent = Register Word8 | Retire Word8 deriving (Eq, Show)++type Budget = (Word64, Word64)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Independent accounting reliability"+ [ testProperty "linear fees use the three-part ledger envelope across witness width boundaries" propLinearFee,+ testProperty "reference pricing follows marginal byte rates and ignores script partitioning" propReferenceTiers,+ testProperty "native batch execution charges aggregate all intents before rounding once" propExecutionRounding,+ testProperty "split half-unit execution charges round once in the complete native fee" halfUnitRegression,+ testProperty "pool updates and retirements preserve operator deposit identity across many intents" propPoolUpdates+ ]++address :: Either Error Address.Address+address = do+ key <- Credential.keyHashFromBytes (B.replicate 28 9)+ pure (Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key)))++propLinearFee :: Property+propLinearFee = property $ do+ witnessCount <- forAll (Gen.element [0, 1, 2, 22, 23, 24, 25])+ textSize <- forAll (Gen.element [0, 1, 23, 24, 63, 64])+ auxiliaryPresent <- forAll Gen.bool+ coefficient <- forAll (Gen.integral (Range.linear 0 1000))+ constant <- forAll (Gen.integral (Range.linear 0 1000000))+ bodyFee <- forAll (Gen.element [0, 23, 24, 255, 256, 65535, 65536])+ keys <- evalEither $ traverse keyWitness [1 .. witnessCount]+ witnesses <- Witnesses.fromWitnesses <$> evalEither (Witnesses.mkWitnesses keys [] [] [] [])+ text <- evalEither (Metadata.mkText (T.replicate textSize "x"))+ metadata <- evalEither (Metadata.decodeCbor (Metadata.encodeCbor (Metadata.singleton 1 text)))+ let auxiliary = if auxiliaryPresent then Just (Auxiliary.fromAuxiliaryData (Auxiliary.auxiliaryData (Just metadata) Nothing [])) else Nothing+ encoded <- evalEither (Body.fromBody (Body.body [] [] bodyFee))+ let transaction = Tx.assemble encoded witnesses auxiliary+ -- Ledger Alonzo size uses [body,witnesses,auxiliary-or-null]. The list+ -- header is one byte. No full-transaction size or native fee helper is+ -- consulted, and the mempool validity byte never enters this equation.+ ledgerBytes = 1 + B.length (Body.toCbor encoded) + B.length (Witnesses.toCbor witnesses) + maybe 1 (B.length . Auxiliary.toCbor) auxiliary+ expected = toInteger constant + toInteger coefficient * toInteger ledgerBytes+ original = Tx.encodeCbor transaction+ classify "witness collection header grows" (witnessCount >= 24)+ classify "auxiliary field absent" (not auxiliaryPresent)+ actual <- evalIO (Building.baseFee constant coefficient transaction) >>= evalEither+ toInteger actual === expected+ falseFee <- evalIO (Building.baseFee constant coefficient (Tx.setScriptValidity False transaction)) >>= evalEither+ falseFee === actual+ Tx.encodeCbor transaction === original+ where+ keyWitness index = Witness.verificationWitness <$> Key.fromBytes (B.replicate 32 index) <*> Signature.fromBytes (B.replicate 64 index)++propReferenceTiers :: Property+propReferenceTiers = property $ do+ stride <- forAll (Gen.element [1, 2, 5, 23, 24, 64])+ total <- forAll (Gen.element [0, 1, stride - 1, stride, stride + 1, 2 * stride - 1, 2 * stride, 2 * stride + 1, 6 * stride])+ cuts <- forAll (Gen.list (Range.linear 0 3) (Gen.int (Range.linear 0 total)))+ priceNumerator <- forAll (Gen.integral (Range.linear 0 10000))+ priceDenominator <- forAll (Gen.integral (Range.linear 1 19))+ (multiplierNumerator, multiplierDenominator) <- forAll (Gen.element [(1, 2), (1, 1), (3, 2), (6, 5)])+ raw <- evalEither ProtocolFixture.parameters+ strideValue <- evalEither (Parameters.mkReferenceScriptCostStride (toInteger stride))+ price <- evalEither (Rational.mkNonNegativeRational priceNumerator priceDenominator)+ multiplier <- evalEither (Rational.mkNonNegativeRational multiplierNumerator multiplierDenominator)+ destination <- evalEither address+ let points = Set.toAscList (Set.fromList (0 : total : cuts))+ parts = zipWith (-) (drop 1 points) points+ prices = (priceNumerator % priceDenominator, multiplierNumerator % multiplierDenominator)+ -- Assign each byte its independent marginal tier index, then floor the+ -- rational total once. This does not reproduce the production mixed-+ -- number recurrence, coarsening path or fixed-width arithmetic.+ (perByte, growth) = prices+ exact = sum [perByte * growth ^ (byte `quot` stride) | byte <- [0 .. total - 1]]+ expected = floor exact :: Integer+ parameters = raw {Parameters.parameterRefScriptCostPerByte = Just price, Parameters.parameterRefScriptCostStride = Just strideValue, Parameters.parameterRefScriptCostMultiplier = Just multiplier}+ split <- evalEither (traverse (uncurry (referenceUtxo destination)) (zip [1 ..] parts))+ single <- evalEither (if total == 0 then Right [] else (: []) <$> referenceUtxo destination 99 total)+ classify "zero scripts" (total == 0)+ classify "exact tier boundary" (total > 0 && total `rem` stride == 0)+ classify "decreasing marginal prices" (multiplierNumerator < multiplierDenominator)+ classify "partitioned reference payload" (length parts > 1)+ splitFee <- evalIO (Building.referenceScriptFee parameters split) >>= evalEither+ singleFee <- evalIO (Building.referenceScriptFee parameters single) >>= evalEither+ toInteger splitFee === expected+ toInteger singleFee === expected++referenceUtxo :: Address.Address -> Word8 -> Int -> Either Error Utxo.Utxo+referenceUtxo destination salt count = do+ script <- Script.Plutus <$> Plutus.fromBytes Plutus.V2 (B.replicate count salt)+ output <- Output.mkOutput destination (Value.lovelace 2000000) Datum.NoDatum (Just script)+ identifier <- Id.fromBytes (B.replicate 32 salt)+ pure (Utxo.utxo (Input.input identifier 0) output)++budget :: Gen Budget+budget = (,) <$> Gen.integral (Range.linear 0 1000) <*> Gen.integral (Range.linear 0 1000)++propExecutionRounding :: Property+propExecutionRounding = property $ do+ groups <- forAll (Gen.list (Range.linear 1 5) (Gen.list (Range.linear 0 4) budget))+ memoryNumerator <- forAll (Gen.integral (Range.linear 0 13))+ memoryDenominator <- forAll (Gen.integral (Range.linear 1 17))+ stepNumerator <- forAll (Gen.integral (Range.linear 0 13))+ stepDenominator <- forAll (Gen.integral (Range.linear 1 17))+ checkExecution groups (memoryNumerator, memoryDenominator) (stepNumerator, stepDenominator)++halfUnitRegression :: Property+halfUnitRegression = withTests 1 . property $ checkExecution [[(1, 0)], [(1, 0)], [(1, 0)], [(1, 0)]] (1, 2) (0, 1)++checkExecution :: [[Budget]] -> (Integer, Integer) -> (Integer, Integer) -> PropertyT IO ()+checkExecution groups memoryRate stepRate = do+ raw <- evalEither ProtocolFixture.parameters+ memoryPrice <- evalEither (uncurry Rational.mkNonNegativeRational memoryRate)+ stepPrice <- evalEither (uncurry Rational.mkNonNegativeRational stepRate)+ zero <- evalEither (Rational.mkNonNegativeRational 0 1)+ let charge values = sum [fromIntegral memory * uncurry (%) memoryRate + fromIntegral steps * uncurry (%) stepRate | (memory, steps) <- values]+ expected = ceiling (charge (concat groups)) :: Integer+ separatelyRounded = sum [ceiling (charge values) :: Integer | values <- groups]+ parameters = raw {Parameters.parameterMinFeeA = 0, Parameters.parameterMinFeeB = 0, Parameters.parameterExecutionCosts = Just (Prices.ExUnitPrices memoryPrice stepPrice), Parameters.parameterRefScriptCostPerByte = Just zero}+ (outerBudgets, localBudgets) = case groups of [] -> ([], []); first : rest -> (first, rest)+ outerWitnesses <- evalEither (budgetWitnesses outerBudgets)+ locals <- evalEither $ traverse (uncurry localTransaction) (zip [1 ..] localBudgets)+ encoded <- evalEither (Body.fromBody ((Body.body [] [] 0) {Body.bodySubTransactions = if null locals then Nothing else Just locals}))+ let transaction = Tx.assemble encoded outerWitnesses Nothing+ original = Tx.encodeCbor transaction+ classify "separate intent rounding would overcharge" (separatelyRounded > expected)+ classify "several nested intent budgets" (length localBudgets >= 2)+ actual <- evalIO (Building.minimumFee parameters [] transaction) >>= evalEither+ toInteger actual === expected+ Tx.encodeCbor transaction === original++budgetWitnesses :: [Budget] -> Either Error Witnesses.EncodedWitnesses+budgetWitnesses values = Witnesses.fromWitnesses <$> Witnesses.mkWitnesses [] [] [] [] [Redeemer.Redeemer Redeemer.Spending index argument (Ex.ExUnits memory steps) | (index, (memory, steps)) <- zip [0 ..] values]+ where+ argument = Data.fromData (Data.Integer 0)++localTransaction :: Word64 -> [Budget] -> Either Error Sub.SubTransaction+localTransaction index values = do+ encoded <- SubBody.fromBody (SubBody.fromFields ((Fields.fields [] []) {Fields.fieldInvalidBefore = Just index}))+ witnesses <- budgetWitnesses values+ pure (Sub.assemble encoded witnesses Nothing)++propPoolUpdates :: Property+propPoolUpdates = property $ do+ groups <- forAll (Gen.list (Range.linear 2 5) (Gen.list (Range.linear 0 8) poolEvent))+ let registrations = [key | events <- groups, Register key <- events]+ globalKeys = Set.fromList registrations+ safeDeposit = (2 ^ (63 :: Int) - 1) `quot` max 1 (toInteger (length registrations))+ deposit <- forAll (Gen.element [0, 1, 23, 24, 65536, safeDeposit])+ raw <- evalEither ProtocolFixture.parameters+ let parameters = raw {Parameters.parameterPoolDeposit = fromInteger deposit}+ bodyFields <- evalEither $ traverse (uncurry poolFields) (zip [0 ..] groups)+ let (outerFields, localFields) = case bodyFields of [] -> (Fields.fields [] [], []); first : rest -> (first, rest)+ locals <- evalEither (traverse (fmap Sub.fromBody . SubBody.fromBody . SubBody.fromFields) localFields)+ encoded <- evalEither (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = outerFields, Body.bodySubTransactions = Just locals}))+ let transaction = Tx.fromBody encoded+ expectedBatch = negate (toInteger (Set.size globalKeys) * deposit)+ original = Tx.encodeCbor transaction+ classify "same operator updated across bodies" (length registrations > Set.size globalKeys)+ classify "retirement interleaved with registration" (any (any isRetirement) groups && not (null registrations))+ classify "large signed-safe deposit" (deposit > 2 ^ (32 :: Int))+ actual <- evalIO (Building.batchImbalance parameters [] transaction) >>= evalEither+ Value.quantity Asset.Ada actual === expectedBatch+ Value.toList actual === [(Asset.Ada, expectedBatch) | expectedBatch /= 0]+ top <- evalIO (Building.implicitCoin parameters transaction) >>= evalEither+ let outerEvents = case groups of [] -> []; first : _ -> first+ Building.deposits top === fromInteger (toInteger (Set.size (Set.fromList [key | Register key <- outerEvents])) * deposit)+ Building.reclaimedDeposits top === 0+ Tx.encodeCbor transaction === original+ where+ isRetirement (Retire _) = True+ isRetirement _ = False++poolEvent :: Gen PoolEvent+poolEvent = Gen.choice [Register <$> Gen.element [1, 2, 3, 4], Retire <$> Gen.element [1, 2, 3, 4]]++poolFields :: Word64 -> [PoolEvent] -> Either Error Fields.Fields+poolFields bodyIndex events = do+ stake <- Credential.keyHashFromBytes (B.replicate 28 12)+ let reward = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ certificates <- forM (zip [0 ..] events) $ \(position, event) -> case event of+ Register key -> do+ operator <- Credential.keyHashFromBytes (B.replicate 28 key)+ vrf <- Pool.vrfKeyHashFromBytes (B.replicate 32 key)+ margin <- Unit.mkUnitInterval 0 1+ -- Alter non-identity fields: repeated registrations must not become+ -- byte-identical certificates whose collection handling masks the test.+ pure (Certificate.PoolRegistration (Pool.PoolParameters operator vrf Nothing (bodyIndex * 100 + position) position margin reward Set.empty [] Nothing))+ Retire key -> Certificate.PoolRetirement <$> Credential.keyHashFromBytes (B.replicate 28 key) <*> pure 42+ pure ((Fields.fields [] []) {Fields.fieldInvalidBefore = Just bodyIndex, Fields.fieldCertificates = if null certificates then Nothing else Just (Certificates.fromList certificates)})
@@ -0,0 +1,267 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Identical public API fixtures across bindings, with explicit failure cases.+module AdditionalProviders (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.Protocol.ExUnits as Units+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import qualified Cometa.Provider.Hydra as PublicHydra+import qualified Cometa.Provider.Internal.Codec as C+import qualified Cometa.Provider.Internal.Hydra as Hydra+import qualified Cometa.Provider.Internal.Remote as Remote+import qualified Cometa.Provider.Koios as Koios+import qualified Cometa.Provider.Kupmios as Kupmios+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TxId+import Control.Concurrent (threadDelay)+import Control.Monad (forM_, unless)+import Data.Aeson (Value (..), eitherDecodeStrict', encode, object, toJSON, (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KM+import Data.Aeson.Types (withText)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as Lazy+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Maybe (isJust)+import Data.Text (Text)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++must :: (Show e) => Either e a -> IO a+must = either (\e -> assertFailure (show e) >> fail "fixture") pure++fixture :: FilePath -> IO Value+fixture name = B.readFile ("test/fixtures/providers/" <> name <> ".json") >>= must . eitherDecodeStrict'++field :: Text -> Value -> IO Value+field key = must . C.parse (C.field key)++reply :: Int -> Value -> Http.Response+reply status value = Http.Response status (Lazy.toStrict (encode value)) Nothing++rpc :: Value -> Value+rpc value = object ["jsonrpc" .= ("2.0" :: Text), "id" .= ("cometa" :: Text), "result" .= value]++sampleTx :: IO Tx.Transaction+sampleTx = maybe (fail "hex fixture") (must . Tx.decodeCbor) (Hex.decodeHex "84a3008001800200a0f5f6")++scripted :: Text -> [Http.Response] -> (Provider.Provider -> IO ()) -> IO ()+scripted backend responses action = do+ pending <- newIORef responses+ let config = (Config.defaultConfig Config.Preprod Nothing) {Config.pollIntervalMillis = 1}+ send _ = do+ result <-+ atomicModifyIORef'+ pending+ ( \case+ [] -> ([], Nothing)+ y : ys -> (ys, Just y)+ )+ maybe (assertFailure "Unexpected request" >> pure (Left Http.ConnectionFailure)) (pure . Right) result+ transport = Http.Transport send (pure (Right ()))+ provider = case backend of+ "Koios" -> Remote.provider Remote.Koios config transport transport+ "Kupmios" -> Remote.provider Remote.Kupmios config transport transport+ _ -> Hydra.provider config transport+ action provider+ remaining <- readIORef pending+ unless (null remaining) (assertFailure "Unused expected requests")++tests :: TestTree+tests =+ testGroup+ "Additional providers"+ [ testGroup+ "shared contracts"+ [ testGroup+ (show backend)+ [ testCase "complete protocol snapshot" (parameters backend),+ testCase "HTTP errors propagate" (httpErrors backend),+ testCase "zero timeout makes no request" (zeroTimeout backend),+ testCase "submission validates response" (submission backend),+ testCase "unexpected budgets fail" (evaluation backend),+ testCase "complete, missing and duplicate budgets" (evaluationCoverage backend)+ ]+ | backend <- ["Koios", "Kupmios", "Hydra"]+ ],+ testCase "Koios live UTxOs retain reference scripts" koiosOutputs,+ testCase "Koios rejects duplicate and spent results" koiosDuplicates,+ testCase "Hydra upstream outputs preserve native and Plutus scripts" hydraOutputs,+ testCase "Hydra rejects missing inline datum bytes" hydraMissingDatum,+ testCase "Hydra snapshot records establish L2 confirmation" hydraConfirmation,+ testCase "Hydra deposits are not treated as L2 confirmations" hydraDeposit,+ testCase "public scopes reject escaped providers" scopes,+ testCase "credentials reject header injection without printable secrets" credentials+ ]++parameters :: Text -> Assertion+parameters backend = do+ source <- fixture (if backend == "Hydra" then "hydra-parameters" else "ogmios-parameters")+ response <- if backend == "Hydra" then pure source else rpc <$> field "result" source+ scripted backend [reply 200 response] $ \provider -> do+ result <- Provider.protocolParameters provider >>= must+ P.parameterAdaPerUtxoByte result @?= Just 4310+ P.parameterProtocolVersion result @?= Version.ProtocolVersion 11 0+ P.parameterMinFeeA result @?= if backend == "Hydra" then 0 else 44+ fmap P.referenceScriptCostStride (P.parameterRefScriptCostStride result) @?= Just 25600+ assertBool "governance retained" (isJust (P.parameterDrepVotingThresholds result))++httpErrors :: Text -> Assertion+httpErrors backend = forM_ [401, 403, 429, 500] $ \status ->+ scripted backend [reply status (String "credential-secret")] $ \p -> do+ result <- Provider.protocolParameters p+ case result of+ Left (ProviderHttpError _ actual) -> actual @?= status+ _ -> assertFailure "HTTP status was swallowed"++zeroTimeout :: Text -> Assertion+zeroTimeout backend = do+ tx <- sampleTx >>= Tx.transactionId >>= must+ scripted backend [] $ \p -> Provider.awaitTransaction p tx 0 >>= (@?= Right False)++submission :: Text -> Assertion+submission backend = do+ transaction <- sampleTx+ actual <- Tx.transactionId transaction >>= must+ if backend == "Hydra"+ then do+ scripted backend [reply 202 (object ["tag" .= ("SubmitTxSubmitted" :: Text)])] $ \p -> Provider.submitTransaction p transaction >>= (@?= Right actual)+ scripted backend [reply 200 (object ["tag" .= ("SubmitTxSubmitted" :: Text)])] $ \p -> Provider.submitTransaction p transaction >>= rejected+ else do+ wrong <- must (TxId.fromBytes (B.replicate 32 1))+ scripted backend [reply 200 (rpc (object ["transaction" .= object ["id" .= TxId.toHex wrong]]))] $ \p -> Provider.submitTransaction p transaction >>= rejected++evaluation :: Text -> Assertion+evaluation backend = do+ transaction <- sampleTx+ let result = rpc (toJSON [object ["validator" .= object ["purpose" .= ("spend" :: Text), "index" .= (0 :: Int)], "budget" .= object ["memory" .= (1 :: Int), "cpu" .= (2 :: Int)]]])+ scripted backend [reply 200 result | backend /= "Hydra"] $ \p -> Provider.evaluateTransaction p transaction [] >>= rejected++koiosOutputs :: Assertion+koiosOutputs = do+ source <- fixture "koios-utxos"+ rows <- must (C.parse C.list source)+ case rows of+ [] -> assertFailure "missing fixture outputs"+ first : _ -> do+ text <- field "address" first >>= must . C.parse (withText "address" pure)+ address <- must (Address.fromText text)+ scripted "Koios" [reply 200 source] $ \p -> do+ result <- Provider.utxosAt p address >>= must+ length result @?= length rows+ length [() | u <- result, isJust (Output.referenceScript (Utxo.output u))] @?= 3++koiosDuplicates :: Assertion+koiosDuplicates = do+ source <- fixture "koios-utxos"+ rows <- must (C.parse C.list source)+ case rows of+ [] -> assertFailure "missing fixture"+ first : _ -> do+ address <- field "address" first >>= must . C.parse (withText "address" (C.checked . Address.fromText))+ scripted "Koios" [reply 200 (toJSON [first, first])] $ \p -> Provider.utxosAt p address >>= rejected+ let spent = case first of+ Object o -> Object (KM.insert "is_spent" (Bool True) o)+ _ -> first+ scripted "Koios" [reply 200 (toJSON [spent])] $ \p -> Provider.utxosAt p address >>= (@?= Right [])++hydraOutputs :: Assertion+hydraOutputs = do+ source <- fixture "hydra-utxos"+ case source of+ Object rows -> forM_ (KM.toList rows) $ \(_, row) -> do+ address <- field "address" row >>= must . C.parse (withText "address" (C.checked . Address.fromText))+ scripted "Hydra" [reply 200 source] $ \p -> do+ outputs <- Provider.utxosAt p address >>= must+ length outputs @?= 1+ forM_ outputs $ \u -> assertBool "reference script retained" (isJust (Output.referenceScript (Utxo.output u)))+ _ -> assertFailure "invalid fixture"++hydraConfirmation :: Assertion+hydraConfirmation = do+ tx <- sampleTx+ hash <- Tx.transactionId tx >>= must+ let response = object ["tag" .= ("ConfirmedSnapshot" :: Text), "snapshot" .= object ["number" .= (1 :: Int), "confirmed" .= [object ["cborHex" .= Hex.encodeHex (Tx.encodeCbor tx), "txId" .= TxId.toHex hash]]]]+ scripted "Hydra" [reply 200 response] $ \p -> Provider.awaitTransaction p hash 1000 >>= (@?= Right True)++hydraDeposit :: Assertion+hydraDeposit = do+ tx <- sampleTx >>= Tx.transactionId >>= must+ let response = object ["tag" .= ("InitialSnapshot" :: Text), "initialUTxO" .= object [Key.fromText (TxId.toHex tx <> "#0") .= object []]]+ -- A single poll occupies the entire short deadline without a second request.+ pending <- newIORef (0 :: Int)+ let transport = Http.Transport (\_ -> atomicModifyIORef' pending (\x -> (x + 1, ())) >> threadDelay 2000 >> pure (Right (reply 200 response))) (pure (Right ()))+ p = Hydra.provider (Config.defaultConfig Config.Preprod Nothing) transport+ Provider.awaitTransaction p tx 1 >>= (@?= Right False)++scopes :: Assertion+scopes = do+ a <- Koios.withProvider (Koios.defaultConfig Koios.Preprod Nothing) (pure . Right) >>= must+ b <- Kupmios.withProvider (Kupmios.defaultConfig Kupmios.Preprod "http://localhost:1" "http://localhost:2") (pure . Right) >>= must+ c <- PublicHydra.withProvider (PublicHydra.defaultConfig PublicHydra.Preprod "http://localhost:1") (pure . Right) >>= must+ forM_ [a, b, c] $ \p -> Provider.resolveInputs p [] >>= (@?= Left RuntimeClosed)++credentials :: Assertion+credentials = do+ case Koios.mkApiKey "valid.jwt-token_123" of+ Left _ -> assertFailure "valid credential rejected"+ Right _ -> pure ()+ case Koios.mkApiKey "key\r\nOther: value" of+ Left _ -> pure ()+ Right _ -> assertFailure "header injection accepted"++rejected :: Either e a -> Assertion+rejected (Left _) = pure ()+rejected (Right _) = assertFailure "Expected rejection"++evaluationCoverage :: Text -> Assertion+evaluationCoverage "Hydra" = pure ()+evaluationCoverage backend = do+ transaction <- maybe (fail "fixture hex") (must . Tx.decodeCbor) (Hex.decodeHex "84a3008001800200a1058184000000820000f5f6")+ let budget = object ["validator" .= object ["purpose" .= ("spend" :: Text), "index" .= (0 :: Int)], "budget" .= object ["memory" .= (17 :: Int), "cpu" .= (29 :: Int)]]+ scripted backend [reply 200 (rpc (toJSON [budget]))] $ \p -> do+ result <- Provider.evaluateTransaction p transaction [] >>= must+ map snd (Evaluation.budgets result) @?= [Units.ExUnits 17 29]+ forM_ [[], [budget, budget]] $ \values ->+ scripted backend [reply 200 (rpc (toJSON values))] $ \p -> Provider.evaluateTransaction p transaction [] >>= rejected++hydraMissingDatum :: Assertion+hydraMissingDatum = do+ source <- fixture "hydra-utxos"+ case source of+ Object rows -> forM_ (KM.toList rows) $ \(key, row) -> case row of+ Object fields -> do+ address <- field "address" row >>= must . C.parse (withText "address" (C.checked . Address.fromText))+ let malformed = Object (KM.insert "inlineDatumRaw" Null (KM.insert "inlineDatumhash" (String "1111111111111111111111111111111111111111111111111111111111111111") fields))+ scripted "Hydra" [reply 200 (Object (KM.singleton key malformed))] $ \provider -> Provider.utxosAt provider address >>= rejected+ _ -> assertFailure "invalid output fixture"+ _ -> assertFailure "invalid fixture"
@@ -0,0 +1,322 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module Address (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import Cometa.Credential (Credential (..))+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import Cometa.Error (Error (..))+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (evaluate)+import Control.Monad (forM_, replicateM_)+import Data.Bits (shiftL)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word8)+import qualified Fixtures.Address as Fixtures+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++-- Test-only sum permits shared vector/property loops without erasing the public+-- distinction between transaction destinations and reward accounts.+data TestAddress = PaymentAddress Shelley.Address | RewardAccount Reward.RewardAddress+ deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Shelley addresses"+ [ testCase "network and hash validation bounds" checkBounds,+ testCase "CIP-19 all supported forms on mainnet and testnet" checkVectors,+ testCase "all network tags agree with native credential construction" checkNative,+ testCase "exact lengths and unsupported headers" checkBytes,+ testCase "payment addresses and reward accounts have disjoint decoders" checkFamilies,+ testCase "Bech32 casing checksum and lexical rejection" checkText,+ testCase "valid checksums cannot disguise header or trailing payload" checkStrictText,+ testCase "fixed prefixes and strict bit padding" checkPadding,+ testCase "public key credential hashes agree and survive cleanup" checkPublicKey,+ testCase "owned values survive GC and failures" checkLifetime,+ testCase "pure codec shared evaluation is deterministic" checkDeterminism,+ testProperty "owned construction and byte/text roundtrips" propRoundTrip+ ]++checkBounds :: IO ()+checkBounds = do+ forM_ [-2, -1, 16, 18446744073709551616] $ \value -> Shelley.mkNetworkId value @?= Left (InvalidNetworkId value)+ Shelley.mkNetworkId 0 @?= Right (minBound :: Shelley.NetworkId)+ Shelley.mkNetworkId 15 @?= Right (maxBound :: Shelley.NetworkId)+ forM_ [0, 1, 27, 29, 57] $ \size -> do+ let bytes = ByteString.replicate size 0+ (Credential.keyHashFromBytes bytes :: Either Error (Credential.KeyHash Credential.Payment)) @?= Left (InvalidCredentialHashLength size)+ Credential.scriptHashFromBytes bytes @?= Left (InvalidCredentialHashLength size)++checkVectors :: IO ()+checkVectors = forM_ Fixtures.vectors $ \(network, tag, text) -> do+ address <- fixture network tag+ toText address @?= text+ fromText text @?= Right address+ fromText (Text.toUpper text) @?= Right address+ fromBytes (toBytes address) @?= Right address+ fmap credentialBytes (paymentCredential address) @?= expectedPayment tag+ fmap credentialBytes (stakeCredential address) @?= expectedStake tag++checkNative :: IO ()+checkNative = forM_ [0 .. 15] $ \network -> forM_ [0, 1, 2, 3, 6, 7, 14, 15] $ \tag -> do+ address <- fixture network tag+ -- Oracle reconstructs native credentials and an address from separate fields.+ withBytes (toBytes address) $ \input size ->+ withBytes (Text.encodeUtf8 (toText address)) $ \text textSize ->+ cNativeAgreement input size text textSize >>= (@?= 1)+ let encoded = toText address+ let prefix = (if tag >= 14 then "stake" else "addr") <> (if network == 1 then "1" else "_test1")+ Text.isPrefixOf prefix encoded @?= True+ fromText encoded @?= Right address++checkBytes :: IO ()+checkBytes = do+ fromBytes ByteString.empty @?= Left InvalidShelleyAddress+ forM_ [0, 1, 2, 3, 6, 7, 14, 15] $ \tag -> do+ address <- fixture 1 tag+ let bytes = toBytes address+ fromBytes (ByteString.take (ByteString.length bytes - 1) bytes) @?= Left InvalidShelleyAddress+ fromBytes (bytes <> "\NUL") @?= Left InvalidShelleyAddress+ forM_ [8, 9, 10, 11, 12, 13] $ \tag ->+ fromBytes (ByteString.singleton (tag `shiftL` 4) <> ByteString.replicate 56 0) @?= Left (UnsupportedAddressType tag)++checkText :: IO ()+checkText = do+ address <- fixture 1 0+ let text = toText address+ forM_ ["", " " <> text, text <> "\NUL", text <> "\n", "中文", Text.replicate 121 "x", "A" <> Text.drop 1 text] $ \bad ->+ do+ let result = fromText bad+ result @?= Left InvalidShelleyAddressText+ let corrupted = Text.dropEnd 1 text <> "q"+ result = fromText corrupted+ case result of+ Left InvalidShelleyAddressText -> pure ()+ _ -> assertFailure ("Expected checksum failure, got " <> show result)++checkStrictText :: IO ()+checkStrictText = do+ address <- fixture 1 0+ forM_ ["stake", "addr_test", "addr_extra"] $ \hrp -> do+ text <- customText hrp (toBytes address)+ fromText text @?= Left InvalidShelleyAddressText+ text <- customText "addr" (toBytes address <> "\NUL")+ fromText text @?= Left InvalidShelleyAddress+ testAddress <- fixture 0 6+ wrongNetwork <- customText "addr" (toBytes testAddress)+ fromText wrongNetwork @?= Left InvalidShelleyAddressText+ pointer <- customText "addr" (ByteString.singleton 0x41 <> ByteString.replicate 28 0 <> ByteString.pack [0, 0, 0])+ key <- requireRight (Credential.keyHashFromBytes (ByteString.replicate 28 0))+ fromText pointer @?= Right (PaymentAddress (Shelley.pointer Shelley.mainnet (KeyCredential key) (Shelley.StakePointer 0 0 0)))++checkPublicKey :: IO ()+checkPublicKey = do+ key <- requireRight (PublicKey.fromBytes (ByteString.replicate 32 7))+ payment <- Credential.fromPublicKey key >>= requireRight+ stake <- Credential.fromPublicKey key >>= requireRight+ digest <- PublicKey.hash key >>= requireRight+ performGC+ let address = PaymentAddress (Shelley.base Shelley.testnet payment stake)+ fmap credentialBytes (paymentCredential address) @?= Just (Blake2b.toBytes digest)+ fmap credentialBytes (stakeCredential address) @?= Just (Blake2b.toBytes digest)++checkLifetime :: IO ()+checkLifetime = do+ original <- fixture 1 3+ let text = toText original+ copied <- requireRight (fromText text)+ replicateM_ 100 $ do+ fromText "bad1address" @?= Left InvalidShelleyAddressText+ toText copied @?= text+ performGC+ copied @?= original+ fromBytes (toBytes copied) @?= Right original++checkDeterminism :: IO ()+checkDeterminism = do+ address <- fixture 1 0+ let shared = toText address+ done <- newEmptyMVar+ replicateM_ 4 $ forkFinally (evaluate shared) (putMVar done)+ replicateM_ 4 $ do+ result <- takeMVar done+ case result of+ Left exception -> assertFailure (show exception)+ Right encoded -> encoded @?= toText address+ performGC+ let encoded = shared+ fromText encoded @?= Right address++propRoundTrip :: Property+propRoundTrip = property $ do+ network <- forAll (Gen.integral (Range.linear 0 15)) >>= evalEither . Shelley.mkNetworkId+ tag <- forAll (Gen.element [0, 1, 2, 3, 6, 7, 14, 15])+ payment <- forAll (Gen.bytes (Range.singleton 28))+ stake <- forAll (Gen.bytes (Range.singleton 28))+ address <- evalEither (assemble network tag payment stake)+ fromBytes (toBytes address) === Right address+ let encoded = toText address+ decoded <- evalEither (fromText encoded)+ decoded === address++fixture :: Integer -> Int -> IO TestAddress+fixture network tag = do+ networkTag <- requireRight (Shelley.mkNetworkId network)+ payment <- hex "9493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e"+ stake <- hex "337b62cfff6403a06a3acbc34f8c46003c69fe79a3628cefa9c47251"+ script <- hex "c37b1b5dc0669f1d3c61a6fddb2e8fde96be87b881c60bce8e8d542f"+ requireRight (assemble networkTag tag (if odd tag then script else payment) (if tag `elem` [2, 3, 15] then script else stake))++assemble :: Shelley.NetworkId -> Int -> ByteString -> ByteString -> Either Error TestAddress+assemble network tag payment stake = case tag of+ value | value <= 3 -> PaymentAddress <$> (Shelley.base network <$> credential (odd tag) payment <*> credential (tag >= 2) stake)+ value | value == 6 || value == 7 -> PaymentAddress . Shelley.enterprise network <$> credential (odd tag) payment+ value | value == 14 || value == 15 -> RewardAccount . Reward.fromCredential network <$> credential (odd tag) stake+ _ -> Left InvalidShelleyAddress+ where+ credential script bytes+ | script = ScriptCredential <$> Credential.scriptHashFromBytes bytes+ | otherwise = KeyCredential <$> Credential.keyHashFromBytes bytes++expectedPayment :: Int -> Maybe ByteString+expectedPayment tag+ | tag >= 14 = Nothing+ | odd tag = Just scriptBytes+ | otherwise = Just paymentBytes++expectedStake :: Int -> Maybe ByteString+expectedStake tag+ | tag == 6 || tag == 7 = Nothing+ | tag `elem` [2, 3, 15] = Just scriptBytes+ | otherwise = Just stakeBytes++-- Exact credential bytes from the native CIP-19 fixture.+paymentBytes, stakeBytes, scriptBytes :: ByteString+paymentBytes = ByteString.pack [0x94, 0x93, 0x31, 0x5c, 0xd9, 0x2e, 0xb5, 0xd8, 0xc4, 0x30, 0x4e, 0x67, 0xb7, 0xe1, 0x6a, 0xe3, 0x6d, 0x61, 0xd3, 0x45, 0x02, 0x69, 0x46, 0x57, 0x81, 0x1a, 0x2c, 0x8e]+stakeBytes = ByteString.pack [0x33, 0x7b, 0x62, 0xcf, 0xff, 0x64, 0x03, 0xa0, 0x6a, 0x3a, 0xcb, 0xc3, 0x4f, 0x8c, 0x46, 0x00, 0x3c, 0x69, 0xfe, 0x79, 0xa3, 0x62, 0x8c, 0xef, 0xa9, 0xc4, 0x72, 0x51]+scriptBytes = ByteString.pack [0xc3, 0x7b, 0x1b, 0x5d, 0xc0, 0x66, 0x9f, 0x1d, 0x3c, 0x61, 0xa6, 0xfd, 0xdb, 0x2e, 0x8f, 0xde, 0x96, 0xbe, 0x87, 0xb8, 0x81, 0xc6, 0x0b, 0xce, 0x8e, 0x8d, 0x54, 0x2f]++credentialBytes :: Credential purpose -> ByteString+credentialBytes credential = case credential of+ KeyCredential hash -> Credential.keyHashBytes hash+ ScriptCredential hash -> Credential.scriptHashBytes hash++hex :: Text.Text -> IO ByteString+hex = fmap Blake2b.toBytes . requireRight . Blake2b.fromHex++requireRight :: (Show err) => Either err value -> IO value+requireRight = either (fail . show) pure++withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO value) -> IO value+withBytes bytes action = ByteString.useAsCStringLen bytes $ \(pointer, size) -> action (castPtr pointer) (fromIntegral size)++customText :: ByteString -> ByteString -> IO Text.Text+customText hrp bytes = ByteString.useAsCString hrp $ \prefix -> withBytes bytes $ \input size ->+ allocaBytes 160 $ \output -> do+ cBech32 prefix input size output 160 >>= (@?= 0)+ Text.decodeUtf8 <$> ByteString.packCString (castPtr output)++toBytes :: TestAddress -> ByteString+toBytes address = case address of+ PaymentAddress value -> Shelley.toBytes value+ RewardAccount value -> Reward.toBytes value++fromBytes :: ByteString -> Either Error TestAddress+fromBytes bytes = case Shelley.fromBytes bytes of+ Left (UnsupportedAddressType tag) | tag == 14 || tag == 15 -> RewardAccount <$> Reward.fromBytes bytes+ result -> PaymentAddress <$> result++toText :: TestAddress -> Text.Text+toText address = case address of+ PaymentAddress value -> Shelley.toText value+ RewardAccount value -> Reward.toText value++fromText :: Text.Text -> Either Error TestAddress+fromText text = case Shelley.fromText text of+ Left (UnsupportedAddressType tag) | tag == 14 || tag == 15 -> RewardAccount <$> Reward.fromText text+ result -> PaymentAddress <$> result++paymentCredential :: TestAddress -> Maybe (Credential Credential.Payment)+paymentCredential address = case address of+ PaymentAddress value -> Just (Shelley.paymentCredential value)+ RewardAccount _ -> Nothing++stakeCredential :: TestAddress -> Maybe (Credential Credential.Stake)+stakeCredential address = case address of+ PaymentAddress value -> Shelley.stakeCredential value+ RewardAccount value -> Just (Reward.credential value)++checkFamilies :: IO ()+checkFamilies = do+ forM_ [0, 1, 2, 3, 6, 7] $ \tag -> do+ address <- fixture 1 tag+ Reward.fromBytes (toBytes address) @?= Left (UnsupportedAddressType (fromIntegral tag))+ let text = toText address+ Reward.fromText text @?= Left (UnsupportedAddressType (fromIntegral tag))+ forM_ [14, 15] $ \tag -> do+ address <- fixture 1 tag+ Shelley.fromBytes (toBytes address) @?= Left (UnsupportedAddressType (fromIntegral tag))+ let text = toText address+ Shelley.fromText text @?= Left (UnsupportedAddressType (fromIntegral tag))++checkPadding :: IO ()+checkPadding = do+ forM_ ["addr", "addr_test", "stake", "stake_test"] $ \prefix ->+ fmap Bech32.humanReadablePartToText (Bech32.humanReadablePartFromText prefix) @?= Right prefix+ address <- fixture 1 6+ prefix <- requireRight (Bech32.humanReadablePartFromText "addr")+ let words5 = Bech32.dataPartToWords (Bech32.dataPartFromBytes (toBytes address))+ excessive = Bech32.encodeLenient prefix (Bech32.dataPartFromWords (words5 <> [minBound, minBound]))+ fromText excessive @?= Left InvalidShelleyAddressText+ case reverse words5 of+ [] -> assertFailure "Fixture did not produce data words"+ _ : rest -> do+ let nonzero = Bech32.encodeLenient prefix (Bech32.dataPartFromWords (reverse (maxBound : rest)))+ fromText nonzero @?= Left InvalidShelleyAddressText+ fromText (Bech32.encodeLenient prefix (Bech32.dataPartFromBytes ByteString.empty)) @?= Left InvalidShelleyAddress++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_address_agreement"+ cNativeAgreement :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CInt++foreign import ccall safe "cometa_test_address_bech32"+ cBech32 :: Ptr a -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CUInt
@@ -0,0 +1,131 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module AssetId (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.AssetId as AssetId+import qualified Cometa.AssetName as AssetName+import Cometa.Error (Error (..))+import qualified Cometa.PolicyId as PolicyId+import Control.Monad (forM_)+import qualified Data.ByteString as ByteString+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word8)+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Native asset identity codecs and fingerprints"+ [ testCase "binary and hex length boundaries" checkBounds,+ testCase "Ada is distinct from an empty native name" checkAda,+ testCase "native codec correspondence at every allowed name length" checkNative,+ testCase "CIP-14 official fingerprints" checkFingerprints,+ testProperty "exact native byte and hex round trips" propRoundTrip+ ]++checkBounds :: IO ()+checkBounds = do+ forM_ [0, 1, 27, 61, 64] $ \size -> do+ AssetId.fromBytes (ByteString.replicate size 0) @?= Left (InvalidAssetIdLength size)+ AssetId.fromHex (Text.replicate size "00") @?= Left (InvalidAssetIdLength size)+ forM_ ["a", "gg", "0x00", " 00", "12", "00\n"] $ \text ->+ AssetId.fromHex text @?= Left InvalidHex+ forM_ [28, 60] $ \size -> do+ asset <- expectRight (AssetId.fromHex (Text.replicate size "Ab"))+ AssetId.toHex asset @?= Right (Text.replicate size "ab")+ AssetId.toBytes asset @?= Right (ByteString.replicate size 171)++checkAda :: IO ()+checkAda = do+ assertUnsupported (AssetId.toBytes AssetId.Ada)+ assertUnsupported (AssetId.toHex AssetId.Ada)+ AssetId.fingerprint AssetId.Ada >>= assertUnsupported+ policy <- expectRight (PolicyId.fromBytes (ByteString.replicate 28 0))+ let native = AssetId.Native policy AssetName.empty+ AssetId.fromBytes (ByteString.replicate 28 0) @?= Right native+ (native == AssetId.Ada) @?= False++checkNative :: IO ()+checkNative = forM_ [0 .. 32] $ \nameSize -> do+ let bytes = ByteString.pack ([0 .. 27] <> take nameSize (cycle [0, 255, 128, 65]))+ asset <- expectRight (AssetId.fromBytes bytes)+ text <- expectRight (AssetId.toHex asset)+ ByteString.useAsCStringLen bytes $ \(raw, size) ->+ ByteString.useAsCStringLen (ByteString.pack (map (fromIntegral . fromEnum) (Text.unpack text))) $ \(hex, hexSize) -> do+ result <- cAgreement (castPtr raw) (fromIntegral size) (castPtr hex) (fromIntegral hexSize)+ result @?= 1++checkFingerprints :: IO ()+checkFingerprints = forM_ fingerprintVectors $ \(policy, name, expected) -> do+ asset <- expectRight (AssetId.fromHex (policy <> name))+ AssetId.fingerprint asset >>= (@?= Right expected)++-- Official CIP-0014 vectors, Matthias Benkort and Rodney Lorrimar, CC-BY-4.0.+-- https://github.com/cardano-foundation/CIPs/blob/86b89208d3b2aabb5dcc5b778dfbe09096b4e114/CIP-0014/README.md+-- Values are decoded from hex before hashing; no UTF-8 asset-name conversion.+fingerprintVectors :: [(Text, Text, Text)]+fingerprintVectors =+ [ ("7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373", "", "asset1rjklcrnsdzqp65wjgrg55sy9723kw09mlgvlc3"),+ ("7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc37e", "", "asset1nl0puwxmhas8fawxp8nx4e2q3wekg969n2auw3"),+ ("1e349c9bdea19fd6c147626a5260bc44b71635f398b67c59881df209", "", "asset1uyuxku60yqe57nusqzjx38aan3f2wq6s93f6ea"),+ ("7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373", "504154415445", "asset13n25uv0yaf5kus35fm2k86cqy60z58d9xmde92"),+ ("1e349c9bdea19fd6c147626a5260bc44b71635f398b67c59881df209", "504154415445", "asset1hv4p5tv2a837mzqrst04d0dcptdjmluqvdx9k3"),+ ("1e349c9bdea19fd6c147626a5260bc44b71635f398b67c59881df209", "7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373", "asset1aqrdypg669jgazruv5ah07nuyqe0wxjhe2el6f"),+ ("7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373", "1e349c9bdea19fd6c147626a5260bc44b71635f398b67c59881df209", "asset17jd78wukhtrnmjh3fngzasxm8rck0l2r4hhyyt"),+ ("7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373", "0000000000000000000000000000000000000000000000000000000000000000", "asset1pkpwyknlvul7az0xx8czhl60pyel45rpje4z8w")+ ]++propRoundTrip :: Property+propRoundTrip = property $ do+ policyBytes <- forAll (Gen.bytes (Range.singleton 28))+ nameBytes <- forAll (Gen.bytes (Range.linear 0 32))+ policy <- evalEither (PolicyId.fromBytes policyBytes)+ name <- evalEither (AssetName.fromBytes nameBytes)+ let asset = AssetId.Native policy name+ bytes = policyBytes <> nameBytes+ AssetId.toBytes asset === Right bytes+ AssetId.fromBytes bytes === Right asset+ text <- evalEither (AssetId.toHex asset)+ AssetId.fromHex text === Right asset+ AssetId.fromHex (Text.toUpper text) === Right asset++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Left failure -> assertFailure (show failure) >> fail "unexpected Left"+ Right value -> pure value++assertUnsupported :: (Show value) => Either Error value -> IO ()+assertUnsupported (Left (UnsupportedOperation _)) = pure ()+assertUnsupported result = assertFailure ("expected UnsupportedOperation, got " <> show result)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_asset_id_codecs"+ cAgreement :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,281 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Actual hash matching and purpose selection for outer language views.+module BalancingScriptLanguages (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (InvalidBuildingRequest))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.BalancingScripts as Languages+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.NetworkId as Network+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.UnitInterval as Interval+import qualified Cometa.Value as Value+import Control.Monad (forM_)+import qualified Data.ByteString as B+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import qualified Fixtures.ProtocolParameters as Fixture+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Balancing script language views"+ [ testCase "every certificate alternative uses its authorizing credential" certificates,+ testCase "governance, voters and guards select actual purposes" governance,+ testCase "original empty and zero mint policies still need scripts" mintPolicies,+ testCase "relevant references and nested witnesses supply outer purposes" sources,+ testCase "missing scripts, models and resolutions remain typed failures" missing+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++key :: IO (Credential.KeyHash purpose)+key = must (Credential.keyHashFromBytes (B.replicate 28 7))++data Fixtures = Fixtures+ { parameters :: Parameters.Parameters,+ wanted :: Script.Script,+ unused :: Script.Script,+ wantedHash :: Credential.ScriptHash+ }++fixtures :: IO Fixtures+fixtures = do+ configured <- must Fixture.parameters+ requiredScript <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V2 (B.pack [1, 2]))+ unusedScript <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V1 (B.pack [3, 4]))+ requiredHash <- Script.hash requiredScript >>= must+ models <- traverse (\language -> must (Models.mkCostModel language [1])) [0, 1, 255]+ pure (Fixtures (configured {Parameters.parameterCostModels = Just (Models.fromList models)}) requiredScript unusedScript requiredHash)++transaction :: Fields.Fields -> [Script.Script] -> [Sub.SubTransaction] -> IO Tx.Transaction+transaction fields scripts nested = do+ body <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = fields, Body.bodySubTransactions = if null nested then Nothing else Just nested}))+ witnesses <- must (Witnesses.mkWitnesses [] [] scripts [] [])+ pure (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing)++check :: Fixtures -> [Utxo.Utxo] -> Tx.Transaction -> [Int] -> IO ()+check fixture resolved tx expected = do+ baseline <- Runtime.liveContexts+ result <- Languages.usedCostModels (parameters fixture) resolved tx >>= must+ map (fromIntegral . Models.languageId) (Models.toList result) @?= expected+ Runtime.liveContexts >>= (@?= baseline)++checkFields :: Fixtures -> Fields.Fields -> [Int] -> IO ()+checkFields fixture fields expected = do+ tx <- transaction fields [unused fixture, wanted fixture] []+ check fixture [] tx expected++certificates :: IO ()+certificates = do+ fixture <- fixtures+ stakeKey <- key+ poolKey <- key+ coldKey <- key+ hotKey <- key+ genesisKey <- key+ delegateKey <- key+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 8))+ margin <- must (Interval.mkUnitInterval 1 2)+ let credential :: Credential.Credential purpose+ credential = Credential.ScriptCredential (wantedHash fixture)+ account = Reward.fromCredential Network.testnet (Credential.KeyCredential stakeKey)+ pool = Pool.PoolParameters poolKey vrf Nothing 0 0 margin account Set.empty [] Nothing+ drep = DRep.DRepCredential credential+ cases =+ [ (Certificate.StakeRegistration credential, []),+ (Certificate.StakeDeregistration credential, [1]),+ (Certificate.StakeDelegation credential poolKey, [1]),+ (Certificate.PoolRegistration pool, []),+ (Certificate.PoolRetirement poolKey 0, []),+ (Certificate.GenesisKeyDelegation genesisKey delegateKey vrf, []),+ (Certificate.MoveInstantaneousRewards (Certificate.ToStakeCredentials Certificate.Reserves (Map.singleton credential 1)), []),+ (Certificate.Registration credential 0, [1]),+ (Certificate.Unregistration credential 0, [1]),+ (Certificate.VoteDelegation credential drep, [1]),+ (Certificate.StakeVoteDelegation credential poolKey drep, [1]),+ (Certificate.StakeRegistrationDelegation credential poolKey 0, [1]),+ (Certificate.VoteRegistrationDelegation credential drep 0, [1]),+ (Certificate.StakeVoteRegistrationDelegation credential poolKey drep 0, [1]),+ (Certificate.AuthorizeCommitteeHot credential (Credential.KeyCredential hotKey), [1]),+ (Certificate.ResignCommitteeCold credential Nothing, [1]),+ (Certificate.RegisterDRep credential 0 Nothing, [1]),+ (Certificate.UnregisterDRep credential 0, [1]),+ (Certificate.UpdateDRep credential Nothing, [1]),+ (Certificate.AuthorizeCommitteeHot (Credential.KeyCredential coldKey) credential, []),+ (Certificate.VoteDelegation (Credential.KeyCredential stakeKey) drep, [])+ ]+ forM_ cases $ \(certificate, expected) -> checkFields fixture ((Fields.fields [] []) {Fields.fieldCertificates = Just (Certificates.fromList [certificate])}) expected++governance :: IO ()+governance = do+ fixture <- fixtures+ stakeKey <- key+ drepKey <- key+ committeeKey <- key+ poolKey <- key+ url <- must (Anchor.mkUrl "https://example.com/anchor")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 9))+ txid <- must (TxId.fromBytes (B.replicate 32 10))+ quorum <- must (Interval.mkUnitInterval 1 2)+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stakeKey)+ scriptAccount = Reward.fromCredential Network.testnet (Credential.ScriptCredential (wantedHash fixture))+ anchor = Anchor.Anchor url digest+ withdrawals <- must (Action.withdrawalsFromList [(account, 0)])+ let actions =+ [ (Action.ParameterChange Nothing Update.empty (Just (wantedHash fixture)), [1]),+ (Action.ParameterChange Nothing Update.empty Nothing, []),+ (Action.HardForkInitiation Nothing (Version.ProtocolVersion 12 0), []),+ (Action.TreasuryWithdrawals withdrawals (Just (wantedHash fixture)), [1]),+ (Action.TreasuryWithdrawals withdrawals Nothing, []),+ (Action.NoConfidence Nothing, []),+ (Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers quorum, []),+ (Action.NewConstitution Nothing (Constitution.Constitution anchor (Just (wantedHash fixture))), []),+ (Action.InfoAction, [])+ ]+ forM_ actions $ \(action, expected) ->+ checkFields fixture ((Fields.fields [] []) {Fields.fieldProposalProcedures = Just (Proposal.fromList [Proposal.Proposal 0 account action anchor])}) expected+ let voters =+ [ (Voting.CommitteeVoter (Credential.ScriptCredential (wantedHash fixture)), [1]),+ (Voting.CommitteeVoter (Credential.KeyCredential committeeKey), []),+ (Voting.DRepVoter (Credential.ScriptCredential (wantedHash fixture)), [1]),+ (Voting.DRepVoter (Credential.KeyCredential drepKey), []),+ (Voting.StakePoolVoter poolKey, [])+ ]+ forM_ voters $ \(voter, expected) ->+ checkFields fixture ((Fields.fields [] []) {Fields.fieldVotingProcedures = Just (Voting.singleton voter (ActionId.ActionId txid 0) (Voting.VotingProcedure Voting.Yes Nothing))}) expected+ rewards <- must (Fields.mkEntries [(scriptAccount, 0)])+ checkFields fixture ((Fields.fields [] []) {Fields.fieldWithdrawals = Just rewards}) [1]+ checkFields fixture ((Fields.fields [] []) {Fields.fieldGuards = Just [Credential.ScriptCredential (wantedHash fixture)]}) [1]+ guardKey <- key+ checkFields fixture ((Fields.fields [] []) {Fields.fieldGuards = Just [Credential.KeyCredential guardKey]}) []+ accountGuards <- must (Fields.mkEntries [(Credential.ScriptCredential (wantedHash fixture), Nothing)])+ checkFields fixture ((Fields.fields [] []) {Fields.fieldRequiredTopLevelGuards = Just accountGuards}) []++mintPolicies :: IO ()+mintPolicies = do+ fixture <- fixtures+ forM_ [E.encodeMapLen 0, E.encodeMapLen 1 <> E.encodeBytes B.empty <> E.encodeWord 0] $ \assets -> do+ -- Import exact mint map keys instead of semantic Value (which erases zeros).+ let encoded = Cbor.encode (E.encodeMapLen 4 <> E.encodeWord 0 <> E.encodeListLen 0 <> E.encodeWord 1 <> E.encodeListLen 0 <> E.encodeWord 2 <> E.encodeWord 0 <> E.encodeWord 9 <> E.encodeMapLen 1 <> E.encodeBytes (Credential.scriptHashBytes (wantedHash fixture)) <> assets)+ body <- must (Body.decodeCbor encoded)+ witnesses <- must (Witnesses.mkWitnesses [] [] [unused fixture, wanted fixture] [] [])+ check fixture [] (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing) [1]++sources :: IO ()+sources = do+ fixture <- fixtures+ txid <- must (TxId.fromBytes (B.replicate 32 11))+ paymentKey <- key+ let keyAddress = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential paymentKey))+ scriptAddress = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.ScriptCredential (wantedHash fixture)))+ spend = Input.input txid 0+ reference = Input.input txid 1+ nestedReference = Input.input txid 2+ locked <- must (Output.mkOutput scriptAddress (Value.lovelace 2000000) Datum.NoDatum Nothing)+ supplied <- must (Output.mkOutput keyAddress (Value.lovelace 2000000) Datum.NoDatum (Just (wanted fixture)))+ unusedScriptOutput <- must (Output.mkOutput keyAddress (Value.lovelace 2000000) Datum.NoDatum (Just (unused fixture)))+ let spent = Utxo.utxo spend locked+ ref = Utxo.utxo reference supplied+ nestedRef = Utxo.utxo nestedReference supplied+ fields = (Fields.fields [spend] []) {Fields.fieldReferenceInputs = Just [reference]}+ tx <- transaction fields [unused fixture] []+ check fixture [spent, ref] tx [1]+ -- A reference script on a spent output is also available.+ spentWithScript <- must (Output.mkOutput scriptAddress (Value.lovelace 2000000) Datum.NoDatum (Just (wanted fixture)))+ spendTx <- transaction (Fields.fields [spend] []) [unused fixture] []+ check fixture [Utxo.utxo spend spentWithScript] spendTx [1]+ -- A script in an unrelated resolved snapshot cannot satisfy a required hash.+ Languages.usedCostModels (parameters fixture) [spent, ref] spendTx >>= (@?= Left (InvalidBuildingRequest "A required body script is missing"))+ -- CIP-172 adds created outputs only from protocol 12.+ createdTx <- transaction (Fields.fields [spend] [supplied]) [] []+ let dijkstra = fixture {parameters = (parameters fixture) {Parameters.parameterProtocolVersion = Version.ProtocolVersion 12 0}}+ earlier = (parameters fixture) {Parameters.parameterProtocolVersion = Version.ProtocolVersion 11 0}+ check dijkstra [spent] createdTx [1]+ Languages.usedCostModels earlier [spent] createdTx >>= (@?= Left (InvalidBuildingRequest "A required body script is missing"))+ collateralBody <- must (Body.fromBody ((Body.body [spend] [] 0) {Body.bodyCollateralReturn = Just supplied}))+ check dijkstra [spent] (Tx.fromBody collateralBody) [1]+ createdSubBody <- must (SubBody.fromBody (SubBody.body [] [supplied]))+ createdSubTx <- transaction (Fields.fields [spend] []) [] [Sub.fromBody createdSubBody]+ check dijkstra [spent] createdSubTx [1]+ subBody <- must (SubBody.fromBody (SubBody.body [] []))+ subWitnesses <- must (Witnesses.mkWitnesses [] [] [wanted fixture] [] [])+ let nested = Sub.assemble subBody (Witnesses.fromWitnesses subWitnesses) Nothing+ nestedTx <- transaction (Fields.fields [spend] []) [unused fixture] [nested]+ check fixture [spent] nestedTx [1]+ nestedRefBody <- must (SubBody.fromBody (SubBody.fromFields ((Fields.fields [] []) {Fields.fieldReferenceInputs = Just [nestedReference]})))+ nestedRefTx <- transaction (Fields.fields [spend] []) [unused fixture] [Sub.fromBody nestedRefBody]+ check fixture [spent, nestedRef] nestedRefTx [1]+ -- A provided but unneeded reference language does not enter the language view.+ unusedRefTx <- transaction ((Fields.fields [spend] []) {Fields.fieldReferenceInputs = Just [reference]}) [wanted fixture] []+ check fixture [spent, Utxo.utxo reference unusedScriptOutput] unusedRefTx [1]+ nativeHash <- Script.hash (Script.Native (Native.invalidBefore 0)) >>= must+ nativeTx <- transaction ((Fields.fields [] []) {Fields.fieldGuards = Just [Credential.ScriptCredential nativeHash]}) [Script.Native (Native.invalidBefore 0), unused fixture] []+ check fixture [] nativeTx []++missing :: IO ()+missing = do+ fixture <- fixtures+ let fields = (Fields.fields [] []) {Fields.fieldGuards = Just [Credential.ScriptCredential (wantedHash fixture)]}+ absent <- transaction fields [unused fixture] []+ Languages.usedCostModels (parameters fixture) [] absent >>= (@?= Left (InvalidBuildingRequest "A required body script is missing"))+ tx <- transaction fields [wanted fixture] []+ Languages.usedCostModels ((parameters fixture) {Parameters.parameterCostModels = Just Models.empty}) [] tx >>= (@?= Left (InvalidBuildingRequest "A required script language has no cost model"))+ txid <- must (TxId.fromBytes (B.replicate 32 12))+ unresolved <- transaction (Fields.fields [Input.input txid 0] []) [] []+ Languages.usedCostModels (parameters fixture) [] unresolved >>= (@?= Left (InvalidBuildingRequest "A script-resolution input is missing"))
@@ -0,0 +1,401 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Public BIP32 known answers, derivation laws and scoped secret lifetimes.+module Bip32 (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PrivateKey as Private+import qualified Cometa.Crypto.Bip32.PublicKey as Public+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as EdPublic+import qualified Cometa.Crypto.Ed25519.SigningKey as Signing+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Bip32PrivateKey as Core+import qualified Cometa.Internal.FFI.Bip32 as Native+import qualified Cometa.Internal.Hex as Hex+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, bracket, fromException, mask_, throwIO, try)+import Control.Monad (replicateM_, void, when, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word32)+import qualified Fixtures.Bip32 as Fixture+import Foreign.C.Types (CSize (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, nullPtr)+import Foreign.Storable (poke)+import Hedgehog (Property, evalEither, evalIO, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "BIP32"+ [ testCase "native hardened and soft derivation known answers" checkKnownAnswers,+ testCase "root derivation agrees with native and independent PBKDF2 oracles" checkEntropy,+ testCase "public projection, chain code and independent hash" checkProjection,+ testCase "public and private byte/hex bounds" checkBounds,+ testCase "malformed hexadecimal never invokes a secret continuation" checkHex,+ testCase "entropy validation accepts every BIP39 size and rejects other lengths" checkEntropyBounds,+ testCase "harden sets high bit idempotently at boundary values" checkHarden,+ testCase "public derivation rejects every hardened boundary" checkHardenedPublic,+ testCase "invalid curve points and scalars fail without invalidating scope" checkInvalidMaterial,+ testCase "closed and escaped keys reject all operations" checkClosedScope,+ testCase "callback failure closes an escaped handle" checkFailure,+ testCase "exception closes an escaped handle" checkException,+ testCase "cancellation closes an escaped handle" checkCancellation,+ testCase "clone and empty-path clone survive closing their source" checkClone,+ testCase "derived and signing scopes own independent keys" checkIndependentScopes,+ testCase "public snapshots survive churn, close and GC" checkSnapshot,+ testCase "throwing derivation input leaves source operations usable" checkPathException,+ testCase "converted signing scope closes after failure, exception and cancellation" checkSigningCleanup,+ testCase "concurrent derivation and close preserve independent ownership" checkDeriveCloseRace,+ testCase "native scope consumes exactly one retained reference on every exit" checkNativeRelease,+ testProperty "public bytes and hex round trip" propPublicRoundTrip,+ testProperty "soft private derivation and public derivation commute" propCommutation,+ testProperty "private path concatenation and sequential derivation agree" propComposition+ ]++checkKnownAnswers :: IO ()+checkKnownAnswers = do+ hard <- require $ Private.withKeyHex Fixture.privateHex $ \root ->+ Private.withDerived root (map Private.harden [1852, 1815, 0]) Private.exportHex+ hard @?= Fixture.hardChildHex+ soft <- require $ Private.withKeyHex Fixture.softRootHex $ \root ->+ Private.withDerived root [1852, 1815, 0] Private.exportHex+ soft @?= Fixture.softChildHex+ public <- requirePure (Public.fromHex Fixture.softPublicHex)+ child <- require (Public.derive public [1852, 1815, 0])+ Public.toHex child @?= Fixture.softPublicChildHex+ Public.derive public [] >>= (@?= Right public)++checkEntropy :: IO ()+checkEntropy = do+ entropy <- hexBytes Fixture.entropyHex+ Private.withEntropy "some_password_@#$%^&" entropy Private.exportHex >>= (@?= Right Fixture.entropyRootHex)+ Private.withEntropy ByteString.empty (ByteString.replicate 16 0) Private.exportHex >>= (@?= Right Fixture.emptyPasswordRootHex)+ Private.withEntropy "a\0b" (ByteString.pack [0 .. 31]) Private.exportHex >>= (@?= Right Fixture.nulPasswordRootHex)++checkProjection :: IO ()+checkProjection = do+ public <- require $ Private.withKeyHex Fixture.privateHex $ \root -> do+ Private.byteLength root >>= (@?= Right 96)+ Private.hexLength root >>= (@?= Right 192)+ Private.exportHex root >>= (@?= Right Fixture.privateHex)+ _ <- require $ Private.withSigningKey root $ \key -> do+ Signing.exportHex key >>= (@?= Right (Text.take 128 Fixture.privateHex))+ signature <- require (Signing.sign key "message\0")+ edPublic <- require (Signing.publicKey key)+ EdPublic.verify edPublic "message\0" signature >>= (@?= Right True)+ pure (Right ())+ Private.publicKey root+ Public.toHex public @?= Fixture.publicHex+ Public.byteLength public @?= 64+ Public.hexLength public @?= 128+ EdPublic.toHex (Public.toEd25519 public) @?= Text.take 64 Fixture.publicHex+ Text.drop 64 (Public.toHex public) @?= Text.drop 128 Fixture.privateHex+ digest <- require (Public.hash public)+ Blake2b.toHex digest @?= Fixture.publicHashHex++checkBounds :: IO ()+checkBounds = do+ mapM_ (\size -> Public.fromBytes (ByteString.replicate size 0) @?= Left (InvalidBip32PublicKeyLength size)) [0, 1, 32, 63, 65, 96]+ mapM_ (\size -> Private.withKey (ByteString.replicate size 0) forbidden >>= (@?= Left (InvalidBip32PrivateKeyLength size))) [0, 1, 64, 95, 97, 192]+ Public.fromHex "00" @?= Left (InvalidBip32PublicKeyLength 1)+ Private.withKeyHex "00" forbidden >>= (@?= Left (InvalidBip32PrivateKeyLength 1))++checkHex :: IO ()+checkHex = do+ mapM_+ ( \input -> do+ Public.fromHex input @?= Left InvalidHex+ Private.withKeyHex input forbidden >>= (@?= Left InvalidHex)+ )+ ["", "0", "gg", " 00", "0x00", "12"]+ Private.withKeyHex (Text.toUpper Fixture.privateHex) Private.exportHex >>= (@?= Right Fixture.privateHex)+ fmap Public.toHex (Public.fromHex (Text.toUpper Fixture.publicHex)) @?= Right Fixture.publicHex++checkEntropyBounds :: IO ()+checkEntropyBounds = do+ mapM_ (\size -> Private.withEntropy "" (ByteString.replicate size 0) forbidden >>= (@?= Left (InvalidBip39EntropyLength size))) [0, 1, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 64]+ mapM_ (\size -> Private.withEntropy "" (ByteString.replicate size 0) Private.byteLength >>= (@?= Right 96)) [16, 20, 24, 28, 32]++checkHarden :: IO ()+checkHarden =+ mapM_+ ( \index -> do+ let hardened = Private.harden index+ assertBool "high bit set" (hardened >= 0x80000000)+ Private.harden hardened @?= hardened+ )+ [0, 1, 0x7fffffff, 0x80000000, maxBound]++checkHardenedPublic :: IO ()+checkHardenedPublic = do+ public <- requirePure (Public.fromHex Fixture.publicHex)+ mapM_ (\index -> Public.derive public [0, index] >>= (@?= Left (HardenedPublicDerivation index))) [0x80000000, 0x80000001, maxBound]++checkInvalidMaterial :: IO ()+checkInvalidMaterial = do+ public <- requirePure (Public.fromBytes (ByteString.replicate 64 2))+ Public.derive public [0] >>= (@?= Left (NativeError "bip32.publicKey.derive" Code.GenericFailure "Generic error"))+ Private.withKey+ (ByteString.replicate 96 0)+ ( \key -> do+ Private.publicKey key >>= (@?= Left (NativeError "bip32.publicKey" Code.GenericFailure "Generic error"))+ Private.byteLength key+ )+ >>= (@?= Right 96)++checkClosedScope :: IO ()+checkClosedScope = do+ key <- require $ Private.withKeyHex Fixture.privateHex (pure . Right)+ checkClosed key++checkClosed :: Private.PrivateKey -> IO ()+checkClosed key = do+ Private.close key+ Private.close key+ Private.byteLength key >>= (@?= Left Bip32PrivateKeyClosed)+ Private.hexLength key >>= (@?= Left Bip32PrivateKeyClosed)+ Private.exportBytes key >>= (@?= Left Bip32PrivateKeyClosed)+ Private.exportHex key >>= (@?= Left Bip32PrivateKeyClosed)+ Private.publicKey key >>= (@?= Left Bip32PrivateKeyClosed)+ Private.withClone key forbidden >>= (@?= Left Bip32PrivateKeyClosed)+ Private.withDerived key [0] forbidden >>= (@?= Left Bip32PrivateKeyClosed)+ Private.withSigningKey key (const (assertFailure "closed conversion callback" >> pure (Right ()))) >>= (@?= Left Bip32PrivateKeyClosed)++checkFailure :: IO ()+checkFailure = do+ escaped <- newIORef Nothing+ Private.withKeyHex Fixture.privateHex (\key -> writeIORef escaped (Just key) >> pure (Left InvalidHex :: Either Error ())) >>= (@?= Left InvalidHex)+ readIORef escaped >>= maybe (assertFailure "missing handle") checkClosed++checkException :: IO ()+checkException = do+ escaped <- newIORef Nothing+ result <- try (Private.withKeyHex Fixture.privateHex (\key -> writeIORef escaped (Just key) >> throwIO ThreadKilled)) :: IO (Either SomeException (Either Error ()))+ case result of+ Left exception -> fromException exception @?= Just ThreadKilled+ Right _ -> assertFailure "exception swallowed"+ readIORef escaped >>= maybe (assertFailure "missing handle") checkClosed++checkCancellation :: IO ()+checkCancellation = do+ ready <- newEmptyMVar+ done <- newEmptyMVar+ blocker <- newEmptyMVar+ worker <- forkFinally (Private.withKeyHex Fixture.privateHex (\key -> putMVar ready key >> takeMVar blocker)) (putMVar done)+ key <- takeMVar ready+ outcome <- timeout 10000000 (killThread worker >> takeMVar done)+ case outcome of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "cancellation did not propagate"+ checkClosed key++checkClone :: IO ()+checkClone = mapM_ check [Private.withClone, (`Private.withDerived` [])]+ where+ check clone =+ Private.withKeyHex+ Fixture.privateHex+ ( \source -> clone source $ \copy -> do+ Private.close source+ Private.exportHex copy+ )+ >>= (@?= Right Fixture.privateHex)++checkIndependentScopes :: IO ()+checkIndependentScopes = do+ Private.withKeyHex+ Fixture.privateHex+ ( \source -> Private.withDerived source [0] $ \child -> do+ Private.close source+ Private.byteLength child+ )+ >>= (@?= Right 96)+ signing <- require $ Private.withKeyHex Fixture.privateHex $ \source ->+ Private.withSigningKey source $ \key -> do+ Private.close source+ Signing.byteLength key >>= (@?= Right 64)+ pure (Right key)+ Signing.byteLength signing >>= (@?= Left SigningKeyClosed)++checkSnapshot :: IO ()+checkSnapshot = do+ public <- require (Private.withKeyHex Fixture.privateHex Private.publicKey)+ replicateM_ 100 (void (Private.withKeyHex Fixture.privateHex Private.publicKey))+ performGC+ Public.toHex public @?= Fixture.publicHex++checkPathException :: IO ()+checkPathException = do+ result <- timeout 1000000 $ Private.withKeyHex Fixture.privateHex $ \key -> do+ attempted <- try (Private.withDerived key [throwInput] forbidden) :: IO (Either SomeException (Either Error ()))+ case attempted of+ Left _ -> Private.byteLength key+ Right _ -> assertFailure "path exception swallowed" >> pure (Right 0)+ result @?= Just (Right 96)+ where+ throwInput :: Word32+ throwInput = Prelude.error "test-only path evaluation failure"++checkSigningCleanup :: IO ()+checkSigningCleanup = do+ escaped <- newIORef Nothing+ Private.withKeyHex+ Fixture.privateHex+ ( \root ->+ Private.withSigningKey root (\key -> writeIORef escaped (Just key) >> pure (Left InvalidHex :: Either Error ()))+ )+ >>= (@?= Left InvalidHex)+ checkEscapedSigning escaped+ exception <- try $ Private.withKeyHex Fixture.privateHex $ \root ->+ Private.withSigningKey root $ \key -> writeIORef escaped (Just key) >> throwIO ThreadKilled+ case (exception :: Either SomeException (Either Error ())) of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right _ -> assertFailure "conversion callback exception swallowed"+ checkEscapedSigning escaped+ ready <- newEmptyMVar+ done <- newEmptyMVar+ blocker <- newEmptyMVar+ worker <-+ forkFinally+ ( Private.withKeyHex Fixture.privateHex $ \root ->+ Private.withSigningKey root $ \key -> writeIORef escaped (Just key) >> putMVar ready () >> takeMVar blocker+ )+ (putMVar done)+ takeMVar ready+ outcome <- timeout 10000000 (killThread worker >> takeMVar done)+ case outcome of+ Just (Left cause) -> fromException cause @?= Just ThreadKilled+ _ -> assertFailure "conversion callback cancellation did not propagate"+ checkEscapedSigning escaped+ where+ checkEscapedSigning escaped =+ readIORef escaped+ >>= maybe+ (assertFailure "missing signing handle")+ (Signing.byteLength >=> (@?= Left SigningKeyClosed))++checkDeriveCloseRace :: IO ()+checkDeriveCloseRace = replicateM_ 25 $ do+ result <- Private.withKeyHex Fixture.privateHex $ \root -> do+ started <- newEmptyMVar+ done <- newEmptyMVar+ _ <- forkFinally (putMVar started () >> Private.withDerived root [0, 1, 2] Private.byteLength) (putMVar done)+ takeMVar started+ Private.close root+ outcome <- timeout 10000000 (takeMVar done)+ case outcome of+ Just (Right (Right size)) -> size @?= 96+ Just (Right (Left failure)) -> failure @?= Bip32PrivateKeyClosed+ Just (Left cause) -> assertFailure (show (cause :: SomeException))+ Nothing -> assertFailure "derivation/close race did not finish"+ Private.byteLength root+ result @?= Left Bip32PrivateKeyClosed++-- Retain a second reference to prove the scoped local obligation is consumed+-- exactly once even when the native unref leaves its local slot non-NULL.+checkNativeRelease :: IO ()+checkNativeRelease = mapM_ check [False, True]+ where+ check failAction = bracket (newIORef nullPtr) release $ \owner -> do+ bytes <- hexBytes Fixture.privateHex+ result <-+ try+ ( Core.withBytesKey bytes $ \key -> do+ _ <- require $ Core.withKey key $ \pointer -> mask_ $ nativeRef pointer >> writeIORef owner pointer >> pure (Right ())+ when failAction (throwIO ThreadKilled)+ ) ::+ IO (Either SomeException (Either Core.Failure ()))+ case result of+ Left exception -> fromException exception @?= Just ThreadKilled+ Right value -> value @?= Right ()+ pointer <- readIORef owner+ nativeRefcount pointer >>= (@?= 1)+ release owner = readIORef owner >>= \pointer -> alloca $ \slot -> poke slot pointer >> Native.cUnref slot++propPublicRoundTrip :: Property+propPublicRoundTrip = withTests 300 $ property $ do+ bytes <- forAll (Gen.bytes (Range.singleton 64))+ key <- evalEither (Public.fromBytes bytes)+ otherBytes <- forAll (Gen.bytes (Range.singleton 64))+ otherKey <- evalEither (Public.fromBytes otherBytes)+ compare key otherKey === compare bytes otherBytes+ Public.toBytes key === bytes+ Public.fromHex (Public.toHex key) === Right key+ Public.fromHex (Text.toUpper (Public.toHex key)) === Right key++propCommutation :: Property+propCommutation = withTests 300 $ property $ do+ path <- forAll (Gen.list (Range.linear 0 6) (Gen.word32 (Range.linear 0 0x7fffffff)))+ pair <- evalIO $ Private.withKeyHex Fixture.softRootHex $ \key -> do+ public <- require (Private.publicKey key)+ childPublic <- Private.withDerived key path Private.publicKey+ publicChild <- Public.derive public path+ pure ((,) <$> childPublic <*> publicChild)+ (privatePublic, publicPrivate) <- evalEither pair+ privatePublic === publicPrivate++propComposition :: Property+propComposition = withTests 300 $ property $ do+ first <- forAll (Gen.list (Range.linear 0 4) (Gen.word32 Range.constantBounded))+ second <- forAll (Gen.list (Range.linear 0 4) (Gen.word32 Range.constantBounded))+ pair <- evalIO $ Private.withKeyHex Fixture.privateHex $ \key -> do+ direct <- Private.withDerived key (first ++ second) Private.exportHex+ sequential <- Private.withDerived key first $ \child -> Private.withDerived child second Private.exportHex+ pure ((,) <$> direct <*> sequential)+ (direct, sequential) <- evalEither pair+ -- Never render either secret in property diagnostics.+ (direct == sequential) === True++forbidden :: Private.PrivateKey -> IO (Either Error ())+forbidden _ = assertFailure "invalid input invoked continuation" >> pure (Right ())++require :: (Show err) => IO (Either err value) -> IO value+require action = action >>= requirePure++requirePure :: (Show err) => Either err value -> IO value+requirePure result = case result of+ Left failure -> assertFailure (show failure) >> fail "unexpected failure"+ Right value -> pure value++hexBytes :: Text -> IO ByteString+hexBytes input = maybe (fail "invalid test hex") pure (Hex.decodeHex input)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cardano_bip32_private_key_ref"+ nativeRef :: Ptr Native.NativeKey -> IO ()++foreign import ccall unsafe "cardano_bip32_private_key_refcount"+ nativeRefcount :: Ptr Native.NativeKey -> IO CSize
@@ -0,0 +1,179 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Bip39 (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PrivateKey as PrivateKey+import qualified Cometa.Crypto.Bip39 as Bip39+import Cometa.Error (Error (..))+import qualified Cometa.Internal.FFI.Bip39 as Native+import Cometa.Internal.Hex (decodeHex)+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar, yield)+import Control.Exception (AsyncException (ThreadKilled), evaluate, fromException)+import Control.Monad (forM_, replicateM)+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import Data.Word (Word8)+import Fixtures.Bip39 (vectors)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (peekArray, pokeArray)+import Hedgehog (Property, evalEither, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "BIP39"+ [ testCase "native corpus and independent 160/224-bit checksum vectors" checkVectors,+ testCase "entropy lengths are validated" $ forM_ [0, 1, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33] $ \n -> do+ let result = Bip39.fromEntropy (ByteString.replicate n 0)+ expectError (InvalidBip39EntropyLength n) result,+ testCase "word counts are validated" $ forM_ [0, 1, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25] $ \n ->+ expectError (InvalidBip39WordCount n) (Bip39.fromWords (replicate n "abandon")),+ testCase "unknown dictionary word" $ expectError UnknownBip39Word (Bip39.fromWords ("notaword" : replicate 11 "abandon")),+ testCase "checksum failure" $ expectError InvalidBip39Checksum (Bip39.fromWords (replicate 12 "abandon")),+ testCase "NUL upper case non-ASCII and embedded whitespace rejected" $ forM_ ["abandon\0", "Abandon", "ábaco", "abandon about", "", "\xfffd"] $ \word ->+ expectError (InvalidBip39Word 1) (Bip39.fromWords (word : replicate 11 "abandon")),+ testCase "invalid word reports one-based position without secret" $+ expectError (InvalidBip39Word 12) (Bip39.fromWords (replicate 11 "abandon" ++ ["ABOUT"])),+ testCase "Unicode whitespace normalizes to single spaces" $ do+ let result = Bip39.fromText (" \t" <> Text.intercalate "\x2003\n" (replicate 11 "abandon" ++ ["about"]) <> "\r ")+ fmap Bip39.exportText result @?= Right zeroPhrase,+ testCase "public native wipe clears only the requested buffer extent" checkWipe,+ testCase "snapshots survive GC and repeated failure" checkSnapshots,+ testCase "concurrent evaluation and shared thunk" checkConcurrent,+ testCase "cancellation smoke leaves later conversions usable" checkCancellation,+ testCase "exported entropy feeds scoped BIP32 root" checkRoot,+ testProperty "entropy and mnemonic round trips for every standard size" propRoundTrip+ ]++zeroPhrase :: Text.Text+zeroPhrase = Text.unwords (replicate 11 "abandon" ++ ["about"])++expectError :: Error -> Either Error a -> IO ()+expectError expected result = case result of+ Left err -> err @?= expected+ Right _ -> assertFailure "Expected validation failure"++checkVectors :: IO ()+checkVectors = forM_ vectors $ \(hex, phrase) -> case decodeHex hex of+ Nothing -> assertFailure "Malformed test entropy"+ Just entropy -> do+ let generated = Bip39.fromEntropy entropy+ fmap Bip39.exportText generated @?= Right phrase+ let parsed = Bip39.fromText phrase+ case parsed of+ Left err -> assertFailure (show err)+ Right mnemonic -> do+ Bip39.wordCount mnemonic @?= length (Text.words phrase)+ Bip39.exportEntropy mnemonic @?= Right entropy++checkSnapshots :: IO ()+checkSnapshots = do+ original <- evaluate (Bip39.fromText zeroPhrase)+ forM_ [1 .. 100] $ \n -> do+ checkRoundTrip n+ expectError UnknownBip39Word (Bip39.fromWords (Text.replicate n "x" : replicate 11 "abandon"))+ performGC+ fmap Bip39.exportText original @?= Right zeroPhrase++-- Distinct inputs resist loop floating; GC runs between conversion and export.+checkRoundTrip :: Int -> IO ()+checkRoundTrip n = do+ let entropy = ByteString.pack (take (16 + 4 * (n `mod` 5)) (cycle [fromIntegral n, 73, 255]))+ case Bip39.fromEntropy entropy of+ Left err -> assertFailure (show err)+ Right mnemonic -> do+ _ <- evaluate (Bip39.wordCount mnemonic)+ performGC+ Bip39.exportEntropy mnemonic @?= Right entropy++checkConcurrent :: IO ()+checkConcurrent = do+ let shared = Bip39.fromEntropy (ByteString.replicate 32 0)+ slots <- replicateM 8 newEmptyMVar+ forM_ (zip [1 ..] slots) $ \(worker, slot) -> do+ _ <-+ forkFinally+ ( do+ fmap Bip39.wordCount shared @?= Right 24+ forM_ [1 .. 10] (checkRoundTrip . (+ (worker * 10)))+ )+ (putMVar slot)+ pure ()+ result <- timeout 10000000 (mapM takeMVar slots)+ case result of+ Nothing -> assertFailure "Concurrent evaluation timed out"+ Just results -> mapM_ (either (assertFailure . show) pure) results++-- Scheduling smoke test: it cannot ensure delivery during a tiny native call.+checkCancellation :: IO ()+checkCancellation = do+ started <- newEmptyMVar+ done <- newEmptyMVar+ worker <-+ forkFinally+ (putMVar started () >> mapM_ (\n -> checkRoundTrip n >> yield) [0 ..])+ (putMVar done)+ takeMVar started+ result <- timeout 10000000 (killThread worker >> takeMVar done)+ case result of+ Just (Left err) -> fromException err @?= Just ThreadKilled+ _ -> assertFailure "Cancellation failed"+ let parsed = Bip39.fromText zeroPhrase+ fmap Bip39.wordCount parsed @?= Right 12+ checkRoundTrip 127++checkRoot :: IO ()+checkRoot = do+ let parsed = Bip39.fromText zeroPhrase+ case parsed of+ Left err -> assertFailure (show err)+ Right mnemonic -> do+ let entropy = Bip39.exportEntropy mnemonic+ case entropy of+ Left err -> assertFailure (show err)+ Right bytes -> do+ result <- PrivateKey.withEntropy ByteString.empty bytes (\_ -> pure (Right ()))+ result @?= Right ()++propRoundTrip :: Property+propRoundTrip = withTests 300 $ property $ do+ size <- forAll (Gen.element [16, 20, 24, 28, 32])+ entropy <- forAll (Gen.bytes (Range.singleton size))+ mnemonic <- evalEither (Bip39.fromEntropy entropy)+ Bip39.wordCount mnemonic === size * 3 `div` 4+ let restored = Bip39.exportEntropy mnemonic+ restored === Right entropy+ parsed <- evalEither (Bip39.fromText (Bip39.exportText mnemonic))+ Bip39.exportText parsed === Bip39.exportText mnemonic++checkWipe :: IO ()+checkWipe = allocaBytes 40 $ \buffer -> do+ pokeArray buffer (replicate 40 (255 :: Word8))+ Native.cClear buffer 32+ bytes <- peekArray 40 buffer+ bytes @?= replicate 32 0 ++ replicate 8 255
@@ -0,0 +1,701 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module BlockfrostHttp (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import Cometa.Error (Error (..))+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost as Blockfrost+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Connection as Connection+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import qualified Cometa.Provider.Kupmios as Kupmios+import Control.Concurrent (forkFinally, killThread, threadDelay, yield)+import Control.Concurrent.MVar (modifyMVar_, newEmptyMVar, newMVar, putMVar, readMVar, takeMVar, tryPutMVar, tryTakeMVar)+import Control.Concurrent.STM (STM, atomically, check, newTVarIO, readTVar, readTVarIO, writeTVar)+import Control.Exception (AsyncException (ThreadKilled), IOException, SomeException, bracket, bracketOnError, catch, finally, fromException, mask, onException, throwIO, try)+import Control.Monad (forM_, void, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as C+import qualified Data.ByteString.Lazy as Lazy+import Data.Char (toLower)+import Data.Either (isLeft)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.List (find)+import Data.Maybe (isNothing)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import qualified Data.X509.CertificateStore as Certificates+import qualified Data.X509.Memory as Certificates+import qualified Network.HTTP.Client as Client+import qualified Network.HTTP.Types.URI as URI+import qualified Network.Socket as Socket+import qualified Network.Socket.ByteString as Socket+import qualified Network.TLS as Tls+import qualified Network.TLS.Extra.Cipher as Cipher+import System.Environment (lookupEnv)+import System.IO (hPutStrLn, stderr)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- TYPES ----------------------------------------------------------------------++data WireRequest = WireRequest+ { requestLine :: !ByteString,+ requestHeaders :: ![ByteString],+ requestBody :: !ByteString+ }+ deriving (Show)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Blockfrost HTTP transport"+ [ testCase "opaque credentials and bounded schedules reject unsafe input" configuration,+ testCase "fixture cleanup joins an idle listener without a client" fixtureCleanup,+ testCase "fixture cleanup joins an incomplete request and blocked handler" fixtureConnections,+ testCase "fixture cleanup preserves continuation exceptions" fixtureException,+ testCase "fixture cleanup deadline reports failure while cleanup retains ownership" fixtureDeadline,+ testCase "public provider uses custom base paths with optional credentials" customEndpoints,+ testCase "custom endpoint queries survive pagination and selected network magic" endpointQueries,+ testCase "invalid URLs fail before callback without echoing secrets" invalidEndpoints,+ testCase "IPv6 and explicit ports validate without live requests" endpointSyntax,+ testCase "path/query encoding, credential header and exact CBOR body" wire,+ testCase "Kupmios sends bare status flags over HTTP" kupmiosFlags,+ testCase "HTTP failures retain status without redirects or retries" statuses,+ testCase "whole-request timeout and body-size limits release response scope" limits,+ testCase "asynchronous cancellation propagates and later requests recover" cancellation,+ testCase "TLS validates trusted roots and rejects untrusted or mismatched hosts" tlsValidation,+ testCase "TLS blocked-read cancellation propagates and later requests recover" tlsCancellation,+ testCase "TLS cancellation joins blocked writes without a close-notify write" tlsWriteCancellation,+ testCase "TLS handshake timeout cancels its socket operations" tlsHandshakeTimeout,+ testCase "TLS CONNECT proxy retains target hostname verification" tlsProxy,+ testCase "refused local connections obey request deadlines and close their scope" refusedConnection,+ testCase "escaped transports close and scope teardown joins active sends" lifetime+ ]++config :: IO Config.Config+config = Config.defaultConfig Config.Preview . Just <$> require (Config.mkProjectId "fixture-project-id")++request :: Http.Request+request = Http.Request Http.Get ["health"] [] B.empty B.empty Nothing++configuration :: IO ()+configuration = do+ forM_ ["", "secret\r\nproject_id: leaked", "secret value"] $ \value ->+ assertBool "invalid credential rejected" (isLeft (Config.mkProjectId value))+ configured <- config+ forM_ [0, -1, 60001, maxBound] $ \duration -> do+ assertBool "invalid HTTP timeout" (isLeft (Config.validateConfig configured {Config.responseTimeoutMillis = duration}))+ assertBool "invalid poll interval" (isLeft (Config.validateConfig configured {Config.pollIntervalMillis = duration}))++-- Exercise custom HTTP through the public provider, with the same validation,+-- scope, URL joining and authentication path used by applications.+customEndpoints :: IO ()+customEndpoints = do+ credential <- require (Blockfrost.mkProjectId "fixture-project-id")+ destination <- require (Address.fromBytes (B.cons 0x60 (B.replicate 28 1)))+ forM_ [Nothing, Just credential] $ \project ->+ forM_ ["", "/", "///"] $ \trailing -> do+ received <- newEmptyMVar+ withServer (\incoming -> putMVar received incoming >> pure (response 200 "[]" [])) $ \base -> do+ let configured = (Blockfrost.defaultConfig Blockfrost.Mainnet project) {Blockfrost.endpoint = Text.pack base <> "/custom%20prefix" <> trailing}+ outcome <- Blockfrost.withProvider configured $ \provider -> do+ Provider.networkMagic provider @?= 764824073+ Provider.utxosAt provider destination+ fmap length outcome @?= Right 0+ actual <- takeMVar received+ let (actualPath, _) = B.break (== 63) (B.takeWhile (/= 32) (B.drop 4 (requestLine actual)))+ let separator = Text.encodeUtf8 (if Text.null trailing then "/" else trailing)+ actualPath @?= "/api/v0/custom%20prefix" <> separator <> "addresses/" <> Text.encodeUtf8 (Address.toText destination) <> "/utxos"+ let authorization = filter (\header -> "project_id:" `B.isPrefixOf` lower header) (requestHeaders actual)+ authorization @?= case project of Nothing -> []; Just _ -> ["project_id: fixture-project-id"]+ where+ lower = C.map toLower++endpointQueries :: IO ()+endpointQueries = do+ destination <- require (Address.fromBytes (B.cons 0x60 (B.replicate 28 1)))+ forM_ [(Blockfrost.Mainnet, 764824073), (Blockfrost.Preprod, 1), (Blockfrost.Preview, 2)] $ \(selected, magic) -> do+ received <- newEmptyMVar+ withServer (\incoming -> putMVar received incoming >> pure (response 200 "[]" [])) $ \base -> do+ let configured = (Blockfrost.defaultConfig selected Nothing) {Blockfrost.endpoint = Text.pack base <> "/proxy/?tenant=space%20value&auth=fixture-route-key&count=7&page=999&order=desc"}+ outcome <- Blockfrost.withProvider configured $ \provider -> do+ Provider.networkMagic provider @?= magic+ Provider.utxosAt provider destination+ fmap length outcome @?= Right 0+ actual <- takeMVar received+ let target = B.takeWhile (/= 32) (B.drop 4 (requestLine actual))+ (_, suffix) = B.break (== 63) target+ parameters = URI.parseQuery suffix+ lookup "tenant" parameters @?= Just (Just "space value")+ lookup "auth" parameters @?= Just (Just "fixture-route-key")+ forM_ [("count", "100"), ("page", "1"), ("order", "asc")] $ \(key, value) -> do+ filter ((== key) . fst) parameters @?= [(key, Just value)]+ assertBool "optional project header omitted" (not (any ("project_id:" `B.isPrefixOf`) (requestHeaders actual)))++invalidEndpoints :: IO ()+invalidEndpoints = do+ forM_+ [ "",+ "/relative/api",+ "ftp://host/api?auth=fixture-secret",+ "https://",+ "https:///missing-host",+ "http://host:0/api",+ "http://host:/api",+ "http://host:65536/api",+ "http://host:18446744073709551617/api",+ "http://host:999999999999999999999999999999999999999/api",+ "http://host:-1/api",+ "http://host:not-a-port/api",+ "http://user:fixture-secret@host/api",+ "http://@host/api",+ "https://host/api#fixture-secret",+ "http://host/has space",+ "http://host/\r\nproject_id: fixture-secret",+ "http://::1:3000/api"+ ]+ $ \endpoint -> do+ called <- newIORef False+ let configured = (Blockfrost.defaultConfig Blockfrost.Preview Nothing) {Blockfrost.endpoint = endpoint}+ outcome <- Blockfrost.withProvider configured (\_ -> writeIORef called True >> pure (Right ()))+ case outcome of+ Left (InvalidProviderConfiguration detail) -> assertBool "diagnostic excludes URL/credentials" (not ("fixture-secret" `Text.isInfixOf` detail))+ other -> assertFailure (show other)+ readIORef called >>= (@?= False)++endpointSyntax :: IO ()+endpointSyntax = do+ forM_+ [ "http://localhost:1/api",+ "HTTP://localhost:00080/api",+ "https://localhost:65535/api/",+ "http://[::1]:3000/api/v0",+ "https://[2001:db8::1]:8443/custom%20prefix?tenant=fixture",+ "http://127.0.0.1/api/v0?route=fixture"+ ]+ $ \endpoint ->+ Config.validateConfig (Blockfrost.defaultConfig Blockfrost.Preprod Nothing) {Blockfrost.endpoint = endpoint} @?= Right ()++wire :: IO ()+wire = do+ received <- newEmptyMVar+ configured <- config+ withServer (\incoming -> putMVar received incoming >> pure (response 200 "ok" [])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport -> do+ result <- Http.send transport request {Http.method = Http.Post, Http.path = ["tx", "part/with ?"], Http.query = [("page", Just "2"), ("asset", Just "space value"), ("unspent", Nothing), ("asset_name", Just "")], Http.body = B.pack [0, 255, 128], Http.contentType = "application/cbor"}+ fmap Http.status result @?= Right 200+ actual <- takeMVar received+ requestLine actual @?= "POST /api/v0/tx/part%2Fwith%20%3F?page=2&asset=space%20value&unspent&asset_name= HTTP/1.1"+ assertBool "project credential sent only as header" ("project_id: fixture-project-id" `elem` requestHeaders actual)+ assertBool "content type" ("Content-Type: application/cbor" `elem` requestHeaders actual)+ requestBody actual @?= B.pack [0, 255, 128]++kupmiosFlags :: IO ()+kupmiosFlags = do+ received <- newEmptyMVar+ let addressText = "addr_test1qrwyxh7zvw8kdp9ar70klytasryj4ejz5j3n5sfw29j8nejzg53k4wq9vaswlnhthl6har9tygqc9037xepeu5s2v32qn6lwrx"+ address <- either (fail . show) pure (Address.fromText addressText)+ withServer (\incoming -> putMVar received incoming >> pure (response 200 "[]" [])) $ \endpoint -> do+ let settings = Kupmios.defaultConfig Kupmios.Preprod (Text.pack endpoint <> "?unspent=wrong&tenant=fixture") "http://localhost:1"+ result <- Kupmios.withProvider settings (\provider -> fmap (fmap length) (Provider.utxosAt provider address))+ result @?= Right 0+ actual <- takeMVar received+ requestLine actual @?= "GET /api/v0/matches/" <> Text.encodeUtf8 addressText <> "?tenant=fixture&unspent HTTP/1.1"++statuses :: IO ()+statuses = do+ configured <- config+ calls <- newMVar (0 :: Int)+ withServer (\_ -> modifyMVar_ calls (pure . (+ 1)) >> pure (response 429 "credential-echo-must-not-be-diagnostic" [("Retry-After", "2"), ("Location", "/other")])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport -> do+ result <- Http.send transport request+ fmap (\reply -> (Http.status reply, Http.retryAfter reply)) result @?= Right (429, Just "2")+ readMVar calls >>= (@?= 1)+ redirectCalls <- newMVar (0 :: Int)+ withServer (\_ -> modifyMVar_ redirectCalls (pure . (+ 1)) >> pure (response 302 B.empty [("Location", "/other")])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport -> do+ Http.send transport request >>= (@?= Right 302) . fmap Http.status+ readMVar redirectCalls >>= (@?= 1)+ submissionCalls <- newMVar (0 :: Int)+ withServer (\_ -> modifyMVar_ submissionCalls (pure . (+ 1)) >> pure "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\n") $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport -> do+ result <- Http.send transport request {Http.method = Http.Post, Http.path = ["tx", "submit"], Http.body = "exact-transaction", Http.contentType = "application/cbor"}+ result @?= Left Http.ConnectionFailure+ assertBool "transport diagnostics cannot echo credential or body" (not ("fixture-project-id" `C.isInfixOf` C.pack (show result)) && not ("exact-transaction" `C.isInfixOf` C.pack (show result)))+ readMVar submissionCalls >>= (@?= 1)++limits :: IO ()+limits = do+ configured <- config+ withServer (\_ -> threadDelay 150000 >> pure (response 200 "late" [])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint, Config.responseTimeoutMillis = 25} $ \transport ->+ Http.send transport request {Http.requestTimeoutMillis = Just 1000} >>= (@?= Left Http.Timeout)+ withServer (\_ -> threadDelay 150000 >> pure (response 200 "late" [])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport ->+ Http.send transport request {Http.requestTimeoutMillis = Just 25} >>= (@?= Left Http.Timeout)+ withServer (\_ -> pure (response 200 (B.replicate (Http.maximumResponseBytes + 1) 120) [])) $ \endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport ->+ Http.send transport request >>= (@?= Left Http.ResponseTooLarge)++cancellation :: IO ()+cancellation = cancellationScenario withServer $ \configured endpoint ->+ Http.withTransport configured {Config.endpoint = Text.pack endpoint}++tlsCancellation :: IO ()+tlsCancellation = do+ let settings = Connection.managerSettingsWithStore fixtureRoots+ cancellationScenario withTlsServer $ \configured endpoint ->+ Http.withEndpointSettings (pure settings) configured (tlsEndpoint endpoint)++cancellationScenario :: ((WireRequest -> IO ByteString) -> (String -> IO ()) -> IO ()) -> (Config.Config -> String -> (Http.Transport -> IO ()) -> IO ()) -> IO ()+cancellationScenario server transportScope = do+ configured <- config+ started <- newEmptyMVar+ gate <- newEmptyMVar+ let handler incoming =+ if requestLine incoming == "GET /api/v0/blocked HTTP/1.1"+ then putMVar started () >> takeMVar gate >> pure (response 200 "late" [])+ else pure (response 200 "recovered" [])+ server handler $ \endpoint -> cleanupWithin $+ transportScope configured endpoint $ \transport -> do+ finished <- newEmptyMVar+ worker <- forkFinally (Http.send transport request {Http.path = ["blocked"]}) (putMVar finished)+ ( do+ within (takeMVar started)+ traceFixture "cancellation requesting ThreadKilled while response is withheld"+ killThread worker+ outcome <- within (takeMVar finished)+ case outcome of+ Left failure -> fromException failure @?= Just ThreadKilled+ Right _ -> assertFailure "asynchronous cancellation became an expected HTTP failure"+ traceFixture "cancellation joined; sending recovery request on same transport"+ Http.send transport request >>= (@?= Right 200) . fmap Http.status+ )+ `finally` void (tryPutMVar gate ())++tlsValidation :: IO ()+tlsValidation = do+ configured <- config+ let trusted = Connection.managerSettingsWithStore fixtureRoots+ untrusted = Connection.managerSettingsWithStore (Certificates.makeCertificateStore [])+ forM_ [(trusted, False, Right 200), (untrusted, False, Left Http.ConnectionFailure), (trusted, True, Left Http.ConnectionFailure)] $ \(settings, wrongHost, expected) ->+ withTlsServer (\_ -> pure (response 200 "trusted" [])) $ \endpoint -> do+ let target = if wrongHost then "https://127.0.0.1:" <> drop (length ("https://localhost:" :: String)) (tlsEndpoint endpoint) else tlsEndpoint endpoint+ cleanupWithin $ Http.withEndpointSettings (pure settings) configured target $ \transport ->+ Http.send transport request >>= (@?= expected) . fmap Http.status++tlsWriteCancellation :: IO ()+tlsWriteCancellation = do+ configured <- config+ started <- newEmptyMVar+ gate <- newEmptyMVar+ let peer socket _ = withTlsContext socket $ \_ -> putMVar started () >> takeMVar gate+ withSocketServer (pure ()) peer $ \endpoint -> cleanupWithin $+ Http.withEndpointSettings (pure (Connection.managerSettingsWithStore fixtureRoots)) configured (tlsEndpoint endpoint) $ \transport -> do+ finished <- newEmptyMVar+ worker <- forkFinally (Http.send transport request {Http.method = Http.Post, Http.body = B.replicate (8 * 1024 * 1024) 7}) (putMVar finished)+ within (takeMVar started)+ -- The peer has completed TLS but does not consume any HTTP/application+ -- bytes. A payload larger than normal TCP buffers exercises backend writes.+ threadDelay 50000+ killThread worker+ outcome <- within (takeMVar finished)+ case outcome of+ Left failure -> fromException failure @?= Just ThreadKilled+ Right result -> assertFailure ("blocked TLS write returned before cancellation: " <> show result)++tlsHandshakeTimeout :: IO ()+tlsHandshakeTimeout = do+ configured <- config+ gate <- newEmptyMVar+ -- A TCP peer accepts the connection but never sends any TLS handshake bytes.+ withSocketServer (pure ()) (\_ _ -> takeMVar gate) $ \endpoint ->+ cleanupWithin $ Http.withEndpointSettings (pure (Connection.managerSettingsWithStore fixtureRoots)) configured {Config.responseTimeoutMillis = 50} (tlsEndpoint endpoint) $ \transport ->+ Http.send transport request >>= (@?= Left Http.Timeout)++tlsProxy :: IO ()+tlsProxy = do+ configured <- config+ connected <- newEmptyMVar+ withSocketServer (pure ()) (proxyConnection connected) $ \endpoint -> do+ port <- endpointPort endpoint+ let settings = Client.managerSetSecureProxy (Client.useProxy (Client.Proxy "127.0.0.1" (fromIntegral port))) (Connection.managerSettingsWithStore fixtureRoots)+ cleanupWithin $ Http.withEndpointSettings (pure settings) configured "https://localhost:443/api/v0" $ \transport ->+ Http.send transport request >>= (@?= Right 200) . fmap Http.status+ within (takeMVar connected) >>= (@?= "CONNECT localhost:443 HTTP/1.1")+ where+ proxyConnection connected socket cancelled = do+ connectRequest <- receive socket cancelled+ putMVar connected (requestLine connectRequest)+ Socket.sendAll socket "HTTP/1.1 200 Connection established\r\n\r\n"+ serveTls (\_ -> pure (response 200 "proxied" [])) socket cancelled++refusedConnection :: IO ()+refusedConnection = Socket.withSocketsDo $ do+ configured <- config+ address <- bracket (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol) Socket.close $ \socket -> do+ Socket.bind socket (Socket.SockAddrInet 0 (Socket.tupleToHostAddress (127, 0, 0, 1)))+ Socket.getSocketName socket+ case address of+ Socket.SockAddrInet port _ -> do+ escaped <- newEmptyMVar+ -- Windows can retry loopback SYNs for about two seconds before reporting+ -- refusal. Bound the request explicitly: either refusal or its earlier+ -- deadline is correct, while the unchanged fixture deadline still detects+ -- a connect/cancellation operation that fails to join.+ cleanupWithin $ Http.withTransport configured {Config.endpoint = Text.pack ("http://127.0.0.1:" <> show port <> "/api/v0"), Config.responseTimeoutMillis = 250} $ \transport -> do+ outcome <- Http.send transport request+ assertBool "refused connection neither failed nor reached its request deadline" (outcome == Left Http.ConnectionFailure || outcome == Left Http.Timeout)+ Http.checkOpen transport >>= (@?= Right ())+ putMVar escaped transport+ transport <- within (takeMVar escaped)+ Http.checkOpen transport >>= (@?= Left Http.Closed)+ _ -> assertFailure "unexpected refused fixture socket family"++tlsEndpoint :: String -> String+tlsEndpoint endpoint = "https://localhost:" <> drop (length ("http://127.0.0.1:" :: String)) endpoint++fixtureRoots :: Certificates.CertificateStore+fixtureRoots = Certificates.makeCertificateStore (Certificates.readSignedObjectFromMemory fixtureCertificate)++withTlsServer :: (WireRequest -> IO ByteString) -> (String -> IO a) -> IO a+withTlsServer handler = withSocketServer (pure ()) (serveTls handler)++serveTls :: (WireRequest -> IO ByteString) -> Socket.Socket -> STM () -> IO ()+serveTls handler socket _ = withTlsContext socket $ \context -> do+ incoming <- receiveWith (Tls.recvData context)+ reply <- handler incoming+ Tls.sendData context (Lazy.fromStrict reply)++withTlsContext :: Socket.Socket -> (Tls.Context -> IO a) -> IO a+withTlsContext socket action = do+ credential <- require (Tls.credentialLoadX509FromMemory fixtureCertificate fixturePrivateKey)+ backend <- Connection.socketBackend socket+ let defaults = Tls.defaultParamsServer+ parameters =+ defaults+ { Tls.serverShared = (Tls.serverShared defaults) {Tls.sharedCredentials = Tls.Credentials [credential]},+ Tls.serverSupported = Tls.defaultSupported {Tls.supportedCiphers = Cipher.ciphersuite_default}+ }+ bracket (Tls.contextNew backend parameters) Tls.contextClose $ \context -> do+ Tls.handshake context+ action context++lifetime :: IO ()+lifetime = do+ traceFixture "lifetime entered test action"+ configured <- config+ started <- newEmptyMVar+ gate <- newEmptyMVar+ finished <- newEmptyMVar+ escaped <- newEmptyMVar+ workerResult <- newEmptyMVar+ let handler _ = putMVar started () >> takeMVar gate >> pure (response 200 "done" [])+ traceFixture "lifetime entering server acquisition"+ withServer handler $ \endpoint -> do+ traceFixture "lifetime starting owner and send"+ owner <-+ forkFinally+ ( Http.withTransport configured {Config.endpoint = Text.pack endpoint} $ \transport -> do+ putMVar escaped transport+ _ <- forkFinally (Http.send transport request) (putMVar workerResult)+ within (readMVar started)+ traceFixture "lifetime owner leaving transport callback"+ )+ (putMVar finished)+ ( do+ transport <- within (takeMVar escaped)+ traceFixture "lifetime waiting for handler entry"+ within (readMVar started)+ -- Scope exit has invalidated new work, but must wait for the old response.+ traceFixture "lifetime waiting for scope closure"+ within (waitClosed transport)+ traceFixture "lifetime scope closed; checking active send remains joined"+ tryTakeMVar finished >>= assertBool "scope joins in-flight send" . isNothing+ Http.send transport request >>= (@?= Left Http.Closed)+ traceFixture "lifetime releasing response gate"+ putMVar gate ()+ traceFixture "lifetime waiting for send result"+ outcome <- within (takeMVar workerResult)+ either (assertFailure . show) (\result -> fmap Http.status result @?= Right 200) outcome+ traceFixture "lifetime waiting for owner exit"+ within (readMVar finished) >>= either (assertFailure . show) pure+ closedAgain <- Http.checkOpen transport+ closedAgain @?= Left Http.Closed+ Http.send transport request >>= (@?= Left Http.Closed)+ )+ `finally` do+ traceFixture "lifetime finalizer releasing gate and joining owner cancellation"+ void (tryPutMVar gate ())+ cleanupWithin (killThread owner >> readMVar finished >> pure ())+ traceFixture "lifetime leaving server scope"++waitClosed :: Http.Transport -> IO ()+waitClosed transport = do+ state <- Http.checkOpen transport+ case state of+ Left Http.Closed -> pure ()+ Left failure -> assertFailure (show failure)+ Right () -> yield >> waitClosed transport++-- The stop signal must work both before accept starts and while it is blocked.+-- A real loopback connection wakes Windows' safe blocking accept; neither closing+-- a socket from another thread nor throwing an async exception establishes this.+fixtureCleanup :: IO ()+fixtureCleanup = forM_ [1 .. 20 :: Int] $ \iteration -> do+ called <- newIORef False+ withServer (\_ -> writeIORef called True >> pure B.empty) $ \_ ->+ when (even iteration) (threadDelay 1000)+ readIORef called >>= (@?= False)++fixtureConnections :: IO ()+fixtureConnections = Socket.withSocketsDo $ do+ entered <- newEmptyMVar+ received <- newEmptyMVar+ gate <- newEmptyMVar+ let handler _ = putMVar entered () >> takeMVar gate >> pure B.empty+ -- Keep the peer alive beyond fixture exit: cleanup must release a worker in+ -- recv itself, rather than depending on a well-behaved client sending EOF.+ traceFixture "incomplete client starting"+ bracket (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol) Socket.close $ \peer ->+ withServerReady (putMVar received ()) handler $ \endpoint -> do+ port <- endpointPort endpoint+ Socket.connect peer (Socket.SockAddrInet port (Socket.tupleToHostAddress (127, 0, 0, 1)))+ Socket.sendAll peer "GET /unfinished HTTP/1.1\r\n"+ within (takeMVar received)+ traceFixture "incomplete client cleanup joined; blocked handler starting"+ -- Wait for the handler itself, rather than racing HTTP request startup against+ -- a short client timeout. The peer remains open while fixture exit cancels a+ -- worker that has finished socket input and is blocked in Haskell code.+ bracket (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol) Socket.close $ \peer ->+ withServer handler $ \endpoint -> do+ port <- endpointPort endpoint+ Socket.connect peer (Socket.SockAddrInet port (Socket.tupleToHostAddress (127, 0, 0, 1)))+ Socket.sendAll peer "GET /blocked HTTP/1.1\r\nHost: fixture\r\n\r\n"+ within (takeMVar entered)+ traceFixture "blocked handler cleanup joined"++fixtureException :: IO ()+fixtureException = do+ outcome <- (withServer (\_ -> pure B.empty) (\_ -> ioError (userError "fixture continuation failed")) >> pure False) `catch` expected+ assertBool "continuation exception survives joined fixture cleanup" outcome+ where+ expected :: IOException -> IO Bool+ expected failure = pure ("fixture continuation failed" `Text.isInfixOf` Text.pack (show failure))++fixtureDeadline :: IO ()+fixtureDeadline = do+ gate <- newEmptyMVar+ finished <- newEmptyMVar+ ( do+ outcome <- within (try (cleanupWithinMicros 10000 (takeMVar gate `finally` putMVar finished ())) :: IO (Either SomeException ()))+ case outcome of+ Left failure -> assertBool "cleanup timeout is a visible failure" ("fixture cleanup timed out" `Text.isInfixOf` Text.pack (show failure))+ Right () -> assertFailure "cleanup timeout became success"+ tryTakeMVar finished >>= assertBool "unfinished cleanup retains ownership" . isNothing+ )+ `finally` (putMVar gate () >> within (takeMVar finished))++endpointPort :: String -> IO Socket.PortNumber+endpointPort endpoint = case reads (takeWhile (/= '/') (drop (length ("http://127.0.0.1:" :: String)) endpoint)) of+ [(port, "")] -> pure port+ _ -> assertFailure "invalid local fixture endpoint" >> fail "fixture endpoint"++-- A local HTTP fixture owns its listener, accept worker and every connection+-- worker. No public endpoint is contacted, and only a fixed fake project ID is used.+withServer :: (WireRequest -> IO ByteString) -> (String -> IO a) -> IO a+withServer = withServerReady (pure ())++withServerReady :: IO () -> (WireRequest -> IO ByteString) -> (String -> IO a) -> IO a+withServerReady connectionReady handler = withSocketServer connectionReady serve+ where+ serve connection cancelled = do+ incoming <- receive connection cancelled+ bytes <- handler incoming+ outcome <- Socket.sendAllWith connection bytes cancelled+ either (const (throwIO ThreadKilled)) pure outcome++withSocketServer :: IO () -> (Socket.Socket -> STM () -> IO ()) -> (String -> IO a) -> IO a+withSocketServer connectionReady serve action = Socket.withSocketsDo $ mask $ \restore -> do+ traceFixture "server acquiring listener"+ listener <- open+ traceFixture "server querying listener address"+ address <- Socket.getSocketName listener `onException` Socket.close listener+ port <- case address of+ Socket.SockAddrInet value _ -> pure value+ _ -> Socket.close listener >> assertFailure "unexpected fixture socket family" >> fail "fixture"+ workers <- newMVar []+ stopping <- newTVarIO False+ accepted <- newEmptyMVar+ bracket+ (forkFinally (restore (acceptLoop listener workers stopping)) (putMVar accepted) `onException` Socket.close listener)+ (const (cleanupWithin (stop listener address workers stopping accepted)))+ ( \_ -> do+ traceFixture "server entering client action"+ restore (action ("http://127.0.0.1:" <> show port <> "/api/v0"))+ )+ where+ open = bracketOnError createSocket Socket.close $ \listener -> do+ traceFixture "server setting listener reuse option"+ Socket.setSocketOption listener Socket.ReuseAddr 1+ traceFixture "server binding listener"+ Socket.bind listener (Socket.SockAddrInet 0 (Socket.tupleToHostAddress (127, 0, 0, 1)))+ traceFixture "server listening"+ Socket.listen listener 8+ pure listener+ createSocket = do+ traceFixture "server creating socket"+ Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol+ acceptLoop listener workers stopping = mask $ \restore -> do+ (connection, _) <- Socket.accept listener+ shouldStop <- readTVarIO stopping+ if shouldStop+ then Socket.close connection+ else do+ finished <- newEmptyMVar+ let cancelled = check =<< readTVar stopping+ worker <-+ forkFinally+ (restore (connectionReady >> serve connection cancelled))+ (const (Socket.close connection `finally` putMVar finished ()))+ `onException` Socket.close connection+ modifyMVar_ workers (pure . ((worker, finished) :))+ restore (acceptLoop listener workers stopping)+ stop listener address workers stopping accepted = do+ atomically (writeTVar stopping True)+ -- Do not close the listener concurrently with accept. In network-3.2.12.0+ -- withFdSocket takes no lock, and Winsock does not promise that closesocket+ -- cancels a synchronous accept. Wake it normally, join, then close.+ ( do+ bracket (Socket.socket Socket.AF_INET Socket.Stream Socket.defaultProtocol) Socket.close $ \wake ->+ Socket.connect wake address+ outcome <- readMVar accepted+ Socket.close listener+ either throwIO pure outcome+ )+ `finally` do+ connections <- readMVar workers+ forM_ connections $ \(worker, finished) -> killThread worker >> readMVar finished++-- timeout cannot interrupt a safe blocking foreign call, and killThread waits+-- synchronously for delivery. Give the cleanup worker ownership until it joins;+-- the test thread waits only on an interruptible MVar, so a failed shutdown is a+-- bounded test failure rather than a six-hour CI hang. Successful cleanup joins+-- every worker and closes every socket before returning.+cleanupWithin :: IO () -> IO ()+cleanupWithin = cleanupWithinMicros 2000000++cleanupWithinMicros :: Int -> IO () -> IO ()+cleanupWithinMicros deadline action = do+ finished <- newEmptyMVar+ _ <- forkFinally action (putMVar finished)+ outcome <- timeout deadline (takeMVar finished)+ case outcome of+ Nothing -> assertFailure "local HTTP fixture cleanup timed out"+ Just result -> either throwIO pure result++receive :: Socket.Socket -> STM () -> IO WireRequest+receive connection cancelled = receiveWith $ do+ outcome <- Socket.recvWith connection 4096 cancelled+ either (const (throwIO ThreadKilled)) pure outcome++receiveWith :: IO ByteString -> IO WireRequest+receiveWith receiveChunk = do+ (headers, rest) <- headerBytes B.empty+ let lines' = C.split '\n' (B.filter (/= 13) headers)+ line = case lines' of [] -> B.empty; value : _ -> value+ fields = drop 1 lines'+ lengthHeader = find ("Content-Length:" `B.isPrefixOf`) fields+ size = case lengthHeader >>= C.readInt . C.dropWhile (== ' ') . B.drop 15 of Just (value, _) -> value; Nothing -> 0+ bytes <- remainingBytes size rest+ pure (WireRequest line fields bytes)+ where+ headerBytes accumulated = do+ let (prefix, suffix) = B.breakSubstring "\r\n\r\n" accumulated+ if not (B.null suffix)+ then pure (prefix, B.drop 4 suffix)+ else do+ chunk <- receiveChunk+ if B.null chunk || B.length accumulated > 65536 then fail "incomplete fixture headers" else headerBytes (accumulated <> chunk)+ remainingBytes size accumulated+ | B.length accumulated >= size = pure (B.take size accumulated)+ | otherwise = do+ chunk <- receiveChunk+ if B.null chunk then fail "incomplete fixture body" else remainingBytes size (accumulated <> chunk)++response :: Int -> ByteString -> [(ByteString, ByteString)] -> ByteString+response code bytes headers =+ "HTTP/1.1 "+ <> C.pack (show code)+ <> " Fixture\r\nContent-Length: "+ <> C.pack (show (B.length bytes))+ <> "\r\nConnection: close\r\n"+ <> B.concat [key <> ": " <> value <> "\r\n" | (key, value) <- headers]+ <> "\r\n"+ <> bytes++require :: (Show failure) => Either failure value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "invalid fixture") pure++within :: IO a -> IO a+within action = do+ result <- timeout 2000000 action+ maybe (assertFailure "local HTTP fixture timed out" >> fail "fixture timeout") pure result++-- Enabled only for CI diagnosis: each phase is flushed through stderr even when+-- a Windows foreign call or an uninterruptible owner prevents test completion.+traceFixture :: String -> IO ()+traceFixture phase = do+ enabled <- lookupEnv "COMETA_HTTP_FIXTURE_TRACE"+ when (enabled == Just "1") (hPutStrLn stderr ("HTTP fixture: " <> phase))++-- Newly authored localhost-only TLS fixture. These PUBLIC test credentials have+-- no wallet or production use. Certificate validity is 2020-2120 and SAN contains+-- localhost only, so a 127.0.0.1 endpoint must fail hostname verification.+fixtureCertificate :: ByteString+fixtureCertificate =+ C.unlines+ [ "-----BEGIN CERTIFICATE-----",+ "MIIBhjCCASygAwIBAgIBATAKBggqhkjOPQQDAjAUMRIwEAYDVQQDDAlsb2NhbGhv",+ "c3QwIBcNMjAwMTAxMDAwMDAwWhgPMjEyMDAxMDEwMDAwMDBaMBQxEjAQBgNVBAMM",+ "CWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIbSghSljv2c93Tj",+ "CkxU2qvUzPch2gZDuuPriZMMv1e6uoOCZqCE6+VC2TfDGegPQFZq6SsXtrUdJruP",+ "u17S3bejbTBrMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgKEMBMGA1Ud",+ "JQQMMAoGCCsGAQUFBwMBMBQGA1UdEQQNMAuCCWxvY2FsaG9zdDAdBgNVHQ4EFgQU",+ "Atnqaqx2desr7wObh/tm/LyDWyAwCgYIKoZIzj0EAwIDSAAwRQIgRyVixABHThhu",+ "jzjA1TqXWdfnYZmhmm4AqNH8QVmBMy4CIQCCi1wVU6EeyQcxLIAEiov5w0yz8Jd3",+ "wgDMGpEmTZedZg==",+ "-----END CERTIFICATE-----"+ ]++fixturePrivateKey :: ByteString+fixturePrivateKey =+ C.unlines+ [ "-----BEGIN EC PRIVATE KEY-----",+ "MHcCAQEEIKxMaeDo1qhVDq1GdXY1GAOUsRd6Ngx3drYGjpxtPyFFoAoGCCqGSM49",+ "AwEHoUQDQgAEhtKCFKWO/Zz3dOMKTFTaq9TM9yHaBkO64+uJkwy/V7q6g4JmoITr",+ "5ULZN8MZ6A9AVmrpKxe2tR0mu4+7XtLdtw==",+ "-----END EC PRIVATE KEY-----"+ ]
@@ -0,0 +1,237 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | New deterministic codec fixtures; no live account or funded transaction.+module BlockfrostJson (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.AssetId as AssetId+import qualified Cometa.AssetName as Name+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Provider.Blockfrost.Internal.Json as Json+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Monad (forM_)+import Data.Aeson (Value (..), object, toJSON, (.=))+import qualified Data.Aeson.Key+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.Aeson.Types+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Scientific (scientific)+import qualified Data.Text as Text+import Data.Word (Word64)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Blockfrost JSON codecs"+ [ testCase "quantity and scientific integer bounds remain exact" integers,+ testCase "asset units roundtrip and reject invalid policy/name bytes" assets,+ testCase "UTxO amounts and inline datum bytes retain typed values" utxos,+ testCase "nullable fields are required and duplicate semantic assets fail" invalidRows,+ testCase "native JSON timelocks and threshold children map precisely" nativeScripts,+ testCase "historical output addresses require identity and unique indices" historical,+ testCase "evaluation budgets cover exactly four supported purposes" budgets,+ testCase "Ogmios v6 payload retains CBOR, datum choice and reference script" payload,+ testCase "Ada-only supplemental evaluation values retain the v6 structure" adaOnlyPayload+ ]++parse :: (Value -> Data.Aeson.Types.Parser a) -> Value -> Either Error a+parse = Json.parseValue "fixture"++integers :: IO ()+integers = do+ parse Json.parseNatural (Number 9007199254740993) @?= Right 9007199254740993+ parse Json.parseNatural (Number 18446744073709551615) @?= Right (maxBound :: Word64)+ Json.parseValue "fixture" (\_ -> Json.parseQuantity "18446744073709551615") Null @?= Right (maxBound :: Word64)+ forM_ [Number (-1), Number 0.5, Number 18446744073709551616, Number (scientific 1 1000000), Number (scientific 1 minBound), Number (scientific 10 maxBound)] $ \value ->+ assertBool "invalid number" (isLeft (parse Json.parseNatural value))+ forM_ ["-1", "+1", "1.1", "18446744073709551616", "123456789012345678901", ""] $ \quantity ->+ assertBool "invalid decimal string" (isLeft (Json.parseValue "fixture" (\_ -> Json.parseQuantity quantity) Null))++assets :: IO ()+assets = do+ policy <- require (Policy.fromBytes (B.replicate 28 1))+ name <- require (Name.fromBytes (B.pack [0, 255]))+ forM_ [AssetId.Ada, AssetId.Native policy Name.empty, AssetId.Native policy name] $ \asset ->+ Json.parseValue "fixture" (\_ -> Json.parseAsset (Json.assetText asset)) Null @?= Right asset+ forM_ ["LOVELACE", Text.replicate 55 "0", Text.replicate 56 "z", Text.replicate 56 "0" <> "f", Text.replicate 56 "0" <> Text.replicate 66 "a"] $ \unit ->+ assertBool "invalid asset" (isLeft (Json.parseValue "fixture" (\_ -> Json.parseAsset unit) Null))++fixtureAddress :: IO Address.Address+fixtureAddress = require (Address.fromBytes (B.cons 0x60 (B.replicate 28 1)))++rowValue :: IO Value+rowValue = do+ address <- fixtureAddress+ pure $+ object+ [ "tx_hash" .= Text.replicate 64 "0",+ "output_index" .= (0 :: Int),+ "address" .= Address.toText address,+ "amount" .= [object ["unit" .= String "lovelace", "quantity" .= String "9007199254740993"]],+ "data_hash" .= Null,+ "inline_datum" .= Null,+ "reference_script_hash" .= Null+ ]++replace :: Data.Aeson.Key.Key -> Value -> Value -> Value+replace key replacement (Object fields) = Object (KeyMap.insert key replacement fields)+replace _ _ original = original++utxos :: IO ()+utxos = do+ base <- rowValue+ let inline = replace "inline_datum" (String "1818") (replace "data_hash" (String (Text.replicate 64 "1")) base)+ decoded <- require (parse Json.rows (toJSON [inline]))+ case decoded of+ [entry] -> do+ Input.index (Json.rowInput entry) @?= 0+ Amount.quantity AssetId.Ada (Json.rowValue entry) @?= 9007199254740993+ case Json.rowDatum entry of+ Datum.InlineDatum value -> Data.toCbor value @?= B.pack [0x18, 0x18]+ other -> assertFailure (show other)+ fmap Datum.hashBytes (Json.rowDatumHash entry) @?= Just (B.replicate 32 0x11)+ _ -> assertFailure "wrong row count"++invalidRows :: IO ()+invalidRows = do+ base <- rowValue+ forM_ ["data_hash", "inline_datum", "reference_script_hash"] $ \key -> case base of+ Object fields -> assertBool "documented nullable field is required" (isLeft (parse Json.rows (toJSON [Object (KeyMap.delete key fields)])))+ _ -> assertFailure "invalid object fixture"+ let duplicate = replace "amount" (toJSON [object ["unit" .= String "lovelace", "quantity" .= String "1"], object ["unit" .= String "lovelace", "quantity" .= String "2"]]) base+ noAda = replace "amount" (toJSON ([] :: [Value])) base+ overflowing = replace "amount" (toJSON [object ["unit" .= String "lovelace", "quantity" .= String "9223372036854775808"]]) base+ forM_ [duplicate, noAda, overflowing, replace "inline_datum" (String "ff") base, replace "reference_script_hash" (String "00") base] $ \value ->+ assertBool "invalid row" (isLeft (parse Json.rows (toJSON [value])))++nativeScripts :: IO ()+nativeScripts = do+ key <- require (Credential.keyHashFromBytes (B.replicate 28 1))+ let sig = object ["type" .= String "sig", "keyHash" .= Hex.encodeHex (B.replicate 28 1)]+ samples =+ [ (sig, Native.signature key),+ (object ["type" .= String "before", "slot" .= (12 :: Int)], Native.invalidAfter 12),+ (object ["type" .= String "after", "slot" .= (34 :: Int)], Native.invalidBefore 34),+ (object ["type" .= String "all", "scripts" .= [sig]], Native.allOf [Native.signature key]),+ (object ["type" .= String "any", "scripts" .= [sig]], Native.anyOf [Native.signature key]),+ (object ["type" .= String "atLeast", "required" .= (1 :: Int), "scripts" .= [sig]], Native.atLeast 1 [Native.signature key])+ ]+ forM_ samples $ \(value, expected) ->+ fmap Native.encodeCbor (parse Json.nativeScript value) @?= Right (Native.encodeCbor expected)+ assertBool "unsupported native type" (isLeft (parse Json.nativeScript (object ["type" .= String "requireGuard"])))++historical :: IO ()+historical = do+ txId <- require (TxId.fromBytes (B.replicate 32 0))+ address <- fixtureAddress+ let item = object ["address" .= Address.toText address, "output_index" .= (1 :: Int)]+ value = object ["hash" .= TxId.toHex txId, "outputs" .= [item]]+ parse (Json.transactionAddresses txId) value @?= Right [(Input.input txId 1, address)]+ assertBool "duplicate output index" (isLeft (parse (Json.transactionAddresses txId) (replace "outputs" (toJSON [item, item]) value)))+ assertBool "wrong transaction hash" (isLeft (parse (Json.transactionAddresses txId) (replace "hash" (String (Text.replicate 64 "1")) value)))++transaction :: [Redeemer.Purpose] -> IO Tx.Transaction+transaction purposes = do+ body <- require (Body.fromBody (Body.body [] [] 0))+ let argument = Data.fromData (Data.Integer 0)+ values = [Redeemer.Redeemer purpose 0 argument (ExUnits 0 0) | purpose <- purposes]+ witnesses <- require (Witnesses.mkWitnesses [] [] [] [] values)+ pure (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing)++budgets :: IO ()+budgets = do+ tx <- transaction [Redeemer.Spending, Redeemer.Minting, Redeemer.Certifying, Redeemer.Rewarding, Redeemer.Voting, Redeemer.Proposing]+ let result = object [key .= object ["memory" .= (100 + n :: Int), "steps" .= (1000 + n :: Int)] | (key, n) <- zip ["spend:0", "mint:0", "certificate:0", "withdrawal:0", "vote:0", "propose:0"] [0 ..]]+ envelope entries = object ["result" .= object ["EvaluationResult" .= entries]]+ decoded <- require (Json.decodeBudgets tx (envelope result))+ map snd (Evaluation.budgets decoded) @?= [ExUnits 100 1000, ExUnits 101 1001, ExUnits 102 1002, ExUnits 103 1003, ExUnits 104 1004, ExUnits 105 1005]+ forM_ [object [], object ["spend:4294967296" .= object ["memory" .= (1 :: Int), "steps" .= (1 :: Int)]], object ["vote:0" .= object ["memory" .= (1 :: Int), "steps" .= (1 :: Int)]]] $ \value ->+ assertBool "incomplete/unsupported budget set" (isLeft (Json.decodeBudgets tx (envelope value)))++payload :: IO ()+payload = do+ tx <- transaction []+ txId <- require (TxId.fromBytes (B.replicate 32 0))+ address <- fixtureAddress+ policy <- require (Policy.fromBytes (B.replicate 28 1))+ name <- require (Name.fromBytes (B.singleton 255))+ script <- require (Plutus.fromBytes Plutus.V2 (B.pack [0x45, 1, 0, 0, 0x24, 0x99]))+ hashed <- require (Datum.hashFromBytes (B.replicate 32 2))+ let amount = Amount.lovelace 42 <> Amount.singleton (AssetId.Native policy name) 7+ inline = Data.fromData (Data.Integer 24)+ output <- require (Output.mkOutput address amount (Datum.InlineDatum inline) (Just (Script.Plutus script)))+ hashedOutput <- require (Output.mkOutput address (Amount.lovelace 9) (Datum.DatumHash hashed) Nothing)+ let resolved = [Utxo.utxo (Input.input txId 1) output, Utxo.utxo (Input.input txId 2) hashedOutput]+ reference =+ [ object ["id" .= TxId.toHex txId, "index" .= (1 :: Int)],+ object ["address" .= Address.toText address, "value" .= object ["ada" .= object ["lovelace" .= (42 :: Int)], Data.Aeson.Key.fromText (Policy.toHex policy) .= object ["ff" .= (7 :: Int)]], "datum" .= Hex.encodeHex (Data.toCbor inline), "script" .= object ["language" .= String "plutus:v2", "cbor" .= String "450100002499"]]+ ]+ hashReference =+ [ object ["id" .= TxId.toHex txId, "index" .= (2 :: Int)],+ object ["address" .= Address.toText address, "value" .= object ["ada" .= object ["lovelace" .= (9 :: Int)]], "datumHash" .= Hex.encodeHex (B.replicate 32 2)]+ ]+ Json.evaluationPayload tx resolved @?= Right (object ["cbor" .= Hex.encodeHex (Tx.encodeCbor tx), "additionalUtxo" .= (reference <> hashReference)])+ assertBool "duplicate resolution" (isLeft (Json.evaluationPayload tx (resolved ++ resolved)))+ governanceTx <- transaction [Redeemer.Voting]+ _ <- require (Json.evaluationPayload governanceTx [])+ forM_ [Plutus.V3, Plutus.V4] $ \version -> do+ newer <- require (Plutus.fromBytes version (Plutus.toBytes script))+ witnesses <- require (Witnesses.mkWitnesses [] [] [Script.Plutus newer] [] [])+ _ <- require (Json.evaluationPayload (Tx.setWitnesses (Witnesses.fromWitnesses witnesses) tx) [])+ pure ()++require :: (Show failure) => Either failure value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "invalid JSON fixture") pure++-- Ada-only supplemental values retain the v6 ada/lovelace structure.+adaOnlyPayload :: IO ()+adaOnlyPayload = do+ tx <- transaction []+ identifier <- require (TxId.fromBytes (B.replicate 32 0xab))+ address <- fixtureAddress+ output <- require (Output.mkOutput address (Amount.lovelace 10000000) Datum.NoDatum Nothing)+ let supplemental = Utxo.utxo (Input.input identifier 0) output+ expected =+ [ object ["id" .= TxId.toHex identifier, "index" .= (0 :: Int)],+ object ["address" .= Address.toText address, "value" .= object ["ada" .= object ["lovelace" .= (10000000 :: Int)]]]+ ]+ Json.evaluationPayload tx [supplemental] @?= Right (object ["cbor" .= Hex.encodeHex (Tx.encodeCbor tx), "additionalUtxo" .= expected])
@@ -0,0 +1,240 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module BlockfrostProtocol (tests) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.DRepVotingThresholds (DRepVotingThresholds (..))+import Cometa.Protocol.ExUnitPrices (ExUnitPrices (..))+import qualified Cometa.Protocol.ExUnits as Units+import qualified Cometa.Protocol.Parameters as P+import Cometa.Protocol.PoolVotingThresholds (PoolVotingThresholds (..))+import qualified Cometa.Protocol.Rational as Fraction+import qualified Cometa.Protocol.Version as Version+import Cometa.Provider.Blockfrost.Internal.Protocol (decodeProtocolParameters)+import qualified Cometa.UnitInterval as Interval+import Control.Monad (forM_)+import Data.Aeson (Value (..), object, (.=))+import Data.Aeson.Key (Key)+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.ByteString as B+import Data.Int (Int64)+import Data.Ratio ((%))+import Data.Scientific (scientific)+import qualified Data.Text as Text+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Blockfrost protocol snapshots"+ [ testCase "exact prices and unbounded pledge influence" exactPrices,+ testCase "all required base snapshot fields map independently" baseMapping,+ testCase "all Conway groups retain distinct positions and units" conwayMapping,+ testCase "nonce absence, neutral and hash remain distinct" nonceVariants,+ testCase "cost coefficients and monetary integer boundaries" boundaries,+ testCase "partial Conway groups and invalid domains fail" conwayFailures,+ testCase "preserve availability and neutral nonce" availability,+ testCase "Alonzo word charge is not a byte charge" alonzoUnits,+ testCase "cost models preserve ordered signed coefficients" models,+ testCase "reject partial execution-price group" $+ rejected (replace "price_mem" (Number 1) fixture),+ testCase "reject overflowing monetary value" $+ rejected (replace "key_deposit" (String "18446744073709551616") fixture),+ testCase "reject negative unsigned parameter" $+ rejected (replace "min_fee_a" (Number (-1)) fixture),+ testCase "reject fractional integer parameter" $+ rejected (replace "min_fee_a" (Number 0.5) fixture),+ testCase "reject pathological numeric exponent before expansion" $+ rejected (replace "a0" (Number (scientific 1 1000000)) fixture),+ testCase "reject minimum Int exponent without overflow" $+ rejected (replace "a0" (Number (scientific 1 minBound)) fixture),+ testCase "reject incomplete voting thresholds" $+ rejected (replace "pvt_motion_no_confidence" (Number 0.5) fixture),+ testCase "reject unknown language rather than discard its model" $+ rejected (replace "cost_models_raw" (object ["PlutusV99" .= ([1] :: [Int])]) fixture)+ ]++fixture :: Value+fixture =+ object+ [ "min_fee_a" .= (44 :: Int),+ "min_fee_b" .= (155381 :: Int),+ "max_block_size" .= (90112 :: Int),+ "max_tx_size" .= (16384 :: Int),+ "max_block_header_size" .= (1100 :: Int),+ "key_deposit" .= String "2000000",+ "pool_deposit" .= String "500000000",+ "e_max" .= (18 :: Int),+ "n_opt" .= (500 :: Int),+ "a0" .= Number 2.5,+ "rho" .= Number 0.003,+ "tau" .= Number 0.2,+ "protocol_major_ver" .= (10 :: Int),+ "protocol_minor_ver" .= (0 :: Int),+ "min_pool_cost" .= String "170000000",+ "coins_per_utxo_size" .= String "4310",+ "extra_entropy" .= Null+ ]++replace :: Key -> Value -> Value -> Value+replace key value (Object fields) = Object (KeyMap.insert key value fields)+replace _ _ value = value++rejected :: Value -> IO ()+rejected value = decodeProtocolParameters value @?= Left (InvalidProviderResponse "provider.protocolParameters")++parsed :: Value -> (P.Parameters -> IO ()) -> IO ()+parsed value action = either (assertFailure . show) action (decodeProtocolParameters value)++exactPrices :: IO ()+exactPrices = parsed snapshot $ \parameters -> do+ Fraction.toRational (P.parameterPoolPledgeInfluence parameters) @?= 5 % 2+ Interval.toRational (P.parameterExpansionRate parameters) @?= 3 % 1000+ case P.parameterExecutionCosts parameters of+ Nothing -> assertFailure "Missing execution prices"+ Just prices -> do+ Fraction.toRational (memoryPrice prices) @?= 577 % 10000+ Fraction.toRational (stepPrice prices) @?= 721 % 10000000+ where+ snapshot = replace "price_mem" (Number 0.0577) (replace "price_step" (Number 0.0000721) fixture)++availability :: IO ()+availability = parsed fixture $ \parameters -> do+ P.parameterCostModels parameters @?= Nothing+ P.parameterExtraEntropy parameters @?= Just P.neutralNonce+ P.parameterAdaPerUtxoByte parameters @?= Just 4310+ P.parameterMaxRefScriptSizePerTx parameters @?= Nothing+ P.parameterMaxPledgeLeverage parameters @?= Nothing++alonzoUnits :: IO ()+alonzoUnits = parsed (replace "protocol_major_ver" (Number 5) fixture) $ \parameters ->+ P.parameterAdaPerUtxoByte parameters @?= Nothing++models :: IO ()+models = parsed snapshot $ \parameters ->+ fmap (map Models.costs . Models.toList) (P.parameterCostModels parameters) @?= Just [[-1, 2, 3], [7, 8]]+ where+ snapshot = replace "cost_models_raw" (object ["PlutusV1" .= ([-1, 2, 3] :: [Int]), "PlutusV3" .= ([7, 8] :: [Int])]) fixture++remove :: Key -> Value -> Value+remove key (Object fields) = Object (KeyMap.delete key fields)+remove _ value = value++baseMapping :: IO ()+baseMapping = parsed fixture $ \parameters -> do+ P.parameterMinFeeA parameters @?= 44+ P.parameterMinFeeB parameters @?= 155381+ P.parameterMaxBlockBodySize parameters @?= 90112+ P.parameterMaxTxSize parameters @?= 16384+ P.parameterMaxBlockHeaderSize parameters @?= 1100+ P.parameterKeyDeposit parameters @?= 2000000+ P.parameterPoolDeposit parameters @?= 500000000+ P.parameterMaxEpoch parameters @?= 18+ P.parameterDesiredPoolCount parameters @?= 500+ P.parameterProtocolVersion parameters @?= Version.ProtocolVersion 10 0+ P.parameterMinPoolCost parameters @?= 170000000+ P.parameterDecentralization parameters @?= Nothing++poolKeys :: [Key]+poolKeys = ["pvt_motion_no_confidence", "pvt_committee_normal", "pvt_committee_no_confidence", "pvt_hard_fork_initiation", "pvt_p_p_security_group"]++drepKeys :: [Key]+drepKeys = ["dvt_motion_no_confidence", "dvt_committee_normal", "dvt_committee_no_confidence", "dvt_update_to_constitution", "dvt_hard_fork_initiation", "dvt_p_p_network_group", "dvt_p_p_economic_group", "dvt_p_p_technical_group", "dvt_p_p_gov_group", "dvt_treasury_withdrawal"]++conway :: Value+conway =+ foldr (uncurry replace) fixture $+ zip poolKeys [Number (scientific n (-2)) | n <- [1 .. 5]]+ ++ zip drepKeys [Number (scientific n (-2)) | n <- [11 .. 20]]+ ++ [ ("max_tx_ex_mem", String "123"),+ ("max_tx_ex_steps", String "456"),+ ("max_block_ex_mem", String "789"),+ ("max_block_ex_steps", String "101112"),+ ("max_val_size", Number 5000),+ ("collateral_percent", Number 150),+ ("max_collateral_inputs", Number 3),+ ("committee_min_size", Number 7),+ ("committee_max_term_length", Number 19),+ ("gov_action_lifetime", Number 23),+ ("gov_action_deposit", String "100000007"),+ ("drep_deposit", String "500000011"),+ ("drep_activity", Number 31),+ ("min_fee_ref_script_cost_per_byte", Number 1.5),+ ("decentralisation_param", Number 0.25)+ ]++conwayMapping :: IO ()+conwayMapping = parsed conway $ \parameters -> do+ let pool = fmap (\(PoolVotingThresholds a b c d e) -> map Interval.toRational [a, b, c, d, e]) (P.parameterPoolVotingThresholds parameters)+ drep = fmap (\(DRepVotingThresholds a b c d e f g h i j) -> map Interval.toRational [a, b, c, d, e, f, g, h, i, j]) (P.parameterDrepVotingThresholds parameters)+ pool @?= Just [n % 100 | n <- [1 .. 5]]+ drep @?= Just [n % 100 | n <- [11 .. 20]]+ P.parameterMaxTxExUnits parameters @?= Just (Units.ExUnits 123 456)+ P.parameterMaxBlockExUnits parameters @?= Just (Units.ExUnits 789 101112)+ P.parameterMaxValueSize parameters @?= Just 5000+ P.parameterCollateralPercentage parameters @?= Just 150+ P.parameterMaxCollateralInputs parameters @?= Just 3+ P.parameterMinCommitteeSize parameters @?= Just 7+ P.parameterCommitteeTermLimit parameters @?= Just 19+ P.parameterGovernanceActionValidityPeriod parameters @?= Just 23+ P.parameterGovernanceActionDeposit parameters @?= Just 100000007+ P.parameterDrepDeposit parameters @?= Just 500000011+ P.parameterDrepInactivityPeriod parameters @?= Just 31+ fmap Fraction.toRational (P.parameterRefScriptCostPerByte parameters) @?= Just (3 % 2)+ fmap Interval.toRational (P.parameterDecentralization parameters) @?= Just (1 % 4)++nonceVariants :: IO ()+nonceVariants = do+ parsed (remove "extra_entropy" fixture) $ \parameters -> P.parameterExtraEntropy parameters @?= Nothing+ parsed fixture $ \parameters -> P.parameterExtraEntropy parameters @?= Just P.neutralNonce+ hashed <- either (\failure -> assertFailure (show failure) >> fail "invalid nonce fixture") pure (P.mkNonce (B.replicate 32 0xab))+ parsed (replace "extra_entropy" (String (Text.replicate 32 "AB")) fixture) $ \parameters ->+ P.parameterExtraEntropy parameters @?= Just hashed+ parsed (foldr (`replace` Null) fixture (poolKeys ++ drepKeys ++ ["cost_models_raw", "price_mem", "price_step", "max_tx_ex_mem", "max_tx_ex_steps", "max_block_ex_mem", "max_block_ex_steps"])) $ \parameters -> do+ P.parameterPoolVotingThresholds parameters @?= Nothing+ P.parameterDrepVotingThresholds parameters @?= Nothing+ P.parameterCostModels parameters @?= Nothing+ P.parameterExecutionCosts parameters @?= Nothing+ P.parameterMaxTxExUnits parameters @?= Nothing+ P.parameterMaxBlockExUnits parameters @?= Nothing++boundaries :: IO ()+boundaries = do+ let signed = [minBound, maxBound] :: [Int64]+ boundaryModels = object [key .= signed | key <- ["PlutusV1", "PlutusV2", "PlutusV3", "PlutusV4"]]+ parsed (replace "cost_models_raw" boundaryModels fixture) $ \parameters ->+ fmap (map Models.costs . Models.toList) (P.parameterCostModels parameters) @?= Just (replicate 4 signed)+ parsed (replace "key_deposit" (String "18446744073709551615") fixture) $ \parameters ->+ P.parameterKeyDeposit parameters @?= maxBound+ forM_ [Number 0.5, String "9223372036854775808", String "-9223372036854775809"] $ \cost ->+ rejected (replace "cost_models_raw" (object ["PlutusV1" .= [cost]]) fixture)+ rejected (replace "cost_models_raw" (object ["PlutusV1" .= replicate 2049 (0 :: Int)]) fixture)+ parsed (replace "cost_models_raw" (object ["PlutusV1" .= replicate 2048 (0 :: Int)]) fixture) $ \parameters ->+ fmap (map (length . Models.costs) . Models.toList) (P.parameterCostModels parameters) @?= Just [2048]++conwayFailures :: IO ()+conwayFailures = do+ forM_ (poolKeys ++ drepKeys ++ ["max_tx_ex_mem", "max_tx_ex_steps", "max_block_ex_mem", "max_block_ex_steps"]) $ \key ->+ rejected (replace key Null conway)+ forM_ [("pvt_committee_normal", Number 1.01), ("dvt_committee_normal", Number (-0.01)), ("min_fee_ref_script_cost_per_byte", Number (-1)), ("drep_deposit", String "18446744073709551616"), ("extra_entropy", String "zz"), ("max_tx_ex_mem", Number 0.5)] $ \(key, value) ->+ rejected (replace key value conway)
@@ -0,0 +1,333 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Scripted official endpoint fixtures; no credentials or network access.+module BlockfrostProvider (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Provider as Provider+import qualified Cometa.Provider.Blockfrost as Blockfrost+import qualified Cometa.Provider.Blockfrost.Internal.Config as Config+import qualified Cometa.Provider.Blockfrost.Internal.Http as Http+import Cometa.Provider.Blockfrost.Internal.Provider (providerWithTransport)+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Amount+import Control.Concurrent (threadDelay)+import Control.Monad (forM_, unless, (>=>))+import Data.Aeson (Value (..), encode, object, toJSON, (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as Lazy+import Data.IORef (atomicModifyIORef', newIORef, readIORef)+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, assertFailure, testCase, (@?=))++-- TYPES ----------------------------------------------------------------------++data Step = Step (Http.Request -> Assertion) (Either Http.HttpFailure Http.Response)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Blockfrost provider queries"+ [ testCase "all address pages preserve order and exact pagination parameters" pagination,+ testCase "duplicate pages and mismatched address snapshots fail" invalidPages,+ testCase "missing results and status failures have endpoint-specific meanings" statuses,+ testCase "native assets and lovelace use the appropriate endpoints" assets,+ testCase "NFT lookup rejects ambiguous quantity and multiple outputs" nfts,+ testCase "resolution excludes historical spent outputs and preserves request order" resolution,+ testCase "datum lookup verifies exact CBOR against its hash" datums,+ testCase "reference scripts are cached per query and their hashes verified" scripts,+ testCase "submission sends exact CBOR once and validates the accepted hash" submission,+ testCase "remote evaluation sends v6 additional inputs and exact budgets" evaluation,+ testCase "confirmation uses identities, monotonic deadlines and cancellation" confirmation,+ testCase "escaped providers reject even empty operations" closed+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++configuration :: IO Config.Config+configuration = Config.defaultConfig Config.Preview . Just <$> must (Config.mkProjectId "preview-fixture-not-a-real-project")++address :: IO Address.Address+address = do+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ pure (Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key)))++identifier :: IO TxId.TransactionId+identifier = must (TxId.fromBytes (B.replicate 32 8))++row :: Address.Address -> TxId.TransactionId -> Word64 -> Value+row destination tx index =+ object+ [ "address" .= Address.toText destination,+ "tx_hash" .= TxId.toHex tx,+ "output_index" .= index,+ "amount" .= [object ["unit" .= ("lovelace" :: Text), "quantity" .= ("2000000" :: Text)]],+ "data_hash" .= Null,+ "inline_datum" .= Null,+ "reference_script_hash" .= Null+ ]++set :: Text -> Value -> Value -> Value+set key value (Object fields) = Object (KeyMap.insert (Key.fromText key) value fields)+set _ _ value = value++reply :: Int -> Value -> Either Http.HttpFailure Http.Response+reply status value = Right (Http.Response status (Lazy.toStrict (encode value)) Nothing)++get :: [Text] -> Http.Request -> Assertion+get path request = do+ Http.method request @?= Http.Get+ Http.path request @?= path+ Http.body request @?= B.empty++scripted :: [Step] -> (Provider.Provider -> IO ()) -> IO ()+scripted responses action = do+ baseConfig <- configuration+ let config = baseConfig {Config.pollIntervalMillis = 1}+ pending <- newIORef responses+ let send request = do+ next <- atomicModifyIORef' pending $ \case [] -> ([], Nothing); step : rest -> (rest, Just step)+ case next of+ Nothing -> assertFailure "Unexpected additional HTTP request" >> pure (Left Http.ConnectionFailure)+ Just (Step check response) -> check request >> pure response+ transport = Http.Transport send (pure (Right ()))+ action (providerWithTransport config transport)+ remaining <- readIORef pending+ unless (null remaining) (assertFailure "Expected HTTP requests were not made")++pagination :: IO ()+pagination = do+ destination <- address+ tx <- identifier+ let path = ["addresses", Address.toText destination, "utxos"]+ check page request = do+ get path request+ Http.query request @?= [("count", Just "100"), ("page", Just page), ("order", Just "asc")]+ scripted [Step (check "1") (reply 200 (toJSONRows [row destination tx index | index <- [0 .. 99]])), Step (check "2") (reply 200 (toJSONRows [row destination tx 100]))] $ \provider -> do+ found <- Provider.utxosAt provider destination >>= must+ map (Input.index . Utxo.input) found @?= [0 .. 100]++toJSONRows :: [Value] -> Value+toJSONRows = toJSON++invalidPages :: IO ()+invalidPages = do+ destination <- address+ tx <- identifier+ let first = toJSONRows [row destination tx index | index <- [0 .. 99]]+ expected = Left (InvalidProviderResponse "blockfrost.utxosAt")+ scripted [Step (const (pure ())) (reply 200 first), Step (const (pure ())) (reply 200 first)] $ \provider -> Provider.utxosAt provider destination >>= (@?= expected)+ wrongKey <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ let wrong = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential wrongKey))+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [row wrong tx 0]))] $ \provider -> Provider.utxosAt provider destination >>= (@?= expected)++statuses :: IO ()+statuses = do+ destination <- address+ tx <- identifier+ hash <- must (Datum.hashFromBytes (B.replicate 32 0))+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ scripted (replicate 4 (Step (const (pure ())) (reply 404 Null))) $ \provider -> do+ Provider.utxosAt provider destination >>= (@?= Right [])+ Provider.resolveDatum provider hash >>= (@?= Right Nothing)+ Provider.rewardBalance provider account >>= (@?= Right 0)+ Provider.resolveInputs provider [Input.input tx 0] >>= (@?= Right [])+ scripted [Step (const (pure ())) (reply 200 (object ["stake_address" .= Text.toUpper (Reward.toText account), "withdrawable_amount" .= ("20" :: Text)]))] $ \provider -> Provider.rewardBalance provider account >>= (@?= Right 20)+ forM_ [400, 403, 418, 425, 429, 500] $ \status ->+ scripted [Step (const (pure ())) (reply status (object ["message" .= ("redacted fixture" :: Text)]))] $ \provider ->+ Provider.utxosAt provider destination >>= (@?= Left (ProviderHttpError "blockfrost.utxosAt" status))+ scripted [Step (const (pure ())) (reply 404 Null)] (Provider.protocolParameters >=> (@?= Left (ProviderHttpError "blockfrost.protocolParameters" 404)))+ scripted [Step (const (pure ())) (Right (Http.Response 200 "not json" Nothing))] $ \provider -> Provider.utxosAt provider destination >>= (@?= Left (InvalidProviderResponse "blockfrost.utxosAt"))++asset :: IO AssetId+asset = Native <$> must (Policy.fromBytes (B.replicate 28 1)) <*> pure AssetName.empty++assetRow :: Address.Address -> TxId.TransactionId -> Word64 -> AssetId -> Text -> Value+assetRow destination tx index token quantity =+ set "amount" (toJSON [object ["unit" .= ("lovelace" :: Text), "quantity" .= ("2000000" :: Text)], object ["unit" .= unit, "quantity" .= quantity]]) (row destination tx index)+ where+ unit = case token of Ada -> "lovelace"; Native policy name -> Policy.toHex policy <> AssetName.toHex name++assets :: IO ()+assets = do+ destination <- address+ tx <- identifier+ token <- asset+ let path = ["addresses", Address.toText destination, "utxos"]+ unit = case token of Ada -> "lovelace"; Native policy name -> Policy.toHex policy <> AssetName.toHex name+ scripted [Step (get path) (reply 200 (toJSONRows [row destination tx 0])), Step (get (path <> [unit])) (reply 200 (toJSONRows [assetRow destination tx 0 token "1"]))] $ \provider -> do+ ada <- Provider.utxosWithAsset provider destination Ada >>= must+ length ada @?= 1+ native <- Provider.utxosWithAsset provider destination token >>= must+ map (Amount.quantity token . Output.value . Utxo.output) native @?= [1]++nfts :: IO ()+nfts = do+ destination <- address+ tx <- identifier+ token <- asset+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [assetRow destination tx 0 token "1"]))] $ \provider -> do+ found <- Provider.utxoWithAsset provider token >>= must+ fmap (Amount.quantity token . Output.value . Utxo.output) found @?= Just 1+ forM_ [[assetRow destination tx 0 token "2"], [assetRow destination tx 0 token "1", assetRow destination tx 1 token "1"]] $ \values ->+ scripted [Step (const (pure ())) (reply 200 (toJSONRows values))] $ \provider -> Provider.utxoWithAsset provider token >>= (@?= Left (InvalidProviderResponse "blockfrost.utxoWithAsset"))+ scripted [Step (const (pure ())) (reply 404 Null)] $ \provider -> Provider.utxoWithAsset provider token >>= (@?= Right Nothing)++resolution :: IO ()+resolution = do+ destination <- address+ tx <- identifier+ missing <- must (TxId.fromBytes (B.replicate 32 9))+ let historical = object ["hash" .= TxId.toHex tx, "inputs" .= ([] :: [Value]), "outputs" .= [row destination tx 0, row destination tx 1]]+ scripted [Step (get ["txs", TxId.toHex tx, "utxos"]) (reply 200 historical), Step (get ["txs", TxId.toHex missing, "utxos"]) (reply 404 Null), Step (get ["addresses", Address.toText destination, "utxos"]) (reply 200 (toJSONRows [row destination tx 1]))] $ \provider -> do+ found <- Provider.resolveInputs provider [Input.input tx 1, Input.input tx 0, Input.input tx 1, Input.input missing 0] >>= must+ map Utxo.input found @?= [Input.input tx 1]+ let consumed = object ["hash" .= TxId.toHex tx, "inputs" .= ([] :: [Value]), "outputs" .= [set "consumed_by_tx" (String (TxId.toHex missing)) (row destination tx 0), row destination tx 1]]+ scripted [Step (const (pure ())) (reply 200 consumed), Step (const (pure ())) (reply 200 (toJSONRows [row destination tx 0, row destination tx 1]))] $ \provider -> do+ found <- Provider.resolveInputs provider [Input.input tx 0, Input.input tx 1] >>= must+ map Utxo.input found @?= [Input.input tx 1]++datums :: IO ()+datums = do+ let encoded = Data.fromData (Data.Integer 42)+ digest <- Data.hash encoded >>= must+ hash <- must (Datum.hashFromBytes (Blake2b.toBytes digest))+ let payload = object ["cbor" .= Hex.encodeHex (Data.toCbor encoded)]+ scripted [Step (get ["scripts", "datum", Hex.encodeHex (Datum.hashBytes hash), "cbor"]) (reply 200 payload)] $ \provider -> Provider.resolveDatum provider hash >>= (@?= Right (Just encoded))+ wrong <- must (Datum.hashFromBytes (B.replicate 32 0))+ scripted [Step (const (pure ())) (reply 200 payload)] $ \provider -> Provider.resolveDatum provider wrong >>= (@?= Left (InvalidProviderResponse "blockfrost.resolveDatum"))+ destination <- address+ tx <- identifier+ let inline = set "inline_datum" (String (Hex.encodeHex (Data.toCbor encoded))) (set "data_hash" (String (Hex.encodeHex (Datum.hashBytes wrong))) (row destination tx 0))+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [inline]))] $ \provider -> Provider.utxosAt provider destination >>= (@?= Left (InvalidProviderResponse "blockfrost.utxosAt"))++scripts :: IO ()+scripts = do+ destination <- address+ tx <- identifier+ let script = Script.Native (Native.allOf [])+ hash <- Script.hash script >>= must+ let hashText = Hex.encodeHex (Credential.scriptHashBytes hash)+ referenced index = set "reference_script_hash" (String hashText) (row destination tx index)+ metadata = object ["script_hash" .= hashText, "type" .= ("timelock" :: Text), "serialised_size" .= Null]+ content = object ["json" .= object ["type" .= ("all" :: Text), "scripts" .= ([] :: [Value])]]+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [referenced 0, referenced 1])), Step (get ["scripts", hashText]) (reply 200 metadata), Step (get ["scripts", hashText, "json"]) (reply 200 content)] $ \provider -> do+ found <- Provider.utxosAt provider destination >>= must+ map (Output.referenceScript . Utxo.output) found @?= [Just script, Just script]+ let wrong = object ["json" .= object ["type" .= ("any" :: Text), "scripts" .= ([] :: [Value])]]+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [referenced 0])), Step (const (pure ())) (reply 200 metadata), Step (const (pure ())) (reply 200 wrong)] $ \provider -> Provider.utxosAt provider destination >>= (@?= Left (InvalidProviderResponse "blockfrost.utxosAt"))+ plutus <- must (Plutus.fromBytes Plutus.V2 (B.pack [0x44, 1, 2, 3, 4]))+ plutusHash <- Plutus.hash plutus >>= must+ let plutusText = Hex.encodeHex (Credential.scriptHashBytes plutusHash)+ locked = set "reference_script_hash" (String plutusText) (row destination tx 0)+ scripted [Step (const (pure ())) (reply 200 (toJSONRows [locked])), Step (const (pure ())) (reply 200 (object ["script_hash" .= plutusText, "type" .= ("plutusV2" :: Text)])), Step (const (pure ())) (reply 200 (object ["cbor" .= Hex.encodeHex (Plutus.toBytes plutus)]))] $ \provider -> do+ found <- Provider.utxosAt provider destination >>= must+ map (Output.referenceScript . Utxo.output) found @?= [Just (Script.Plutus plutus)]++transaction :: IO Tx.Transaction+transaction = do+ body <- must (Body.fromBody (Body.body [] [] 0))+ pure (Tx.assemble body (Witnesses.fromWitnesses Witnesses.empty) Nothing)++submission :: IO ()+submission = do+ tx <- transaction+ expected <- Tx.transactionId tx >>= must+ let check request = do+ Http.method request @?= Http.Post+ Http.path request @?= ["tx", "submit"]+ Http.contentType request @?= "application/cbor"+ Http.body request @?= Tx.encodeCbor tx+ scripted [Step check (reply 200 (String (TxId.toHex expected)))] $ \provider -> Provider.submitTransaction provider tx >>= (@?= Right expected)+ wrong <- identifier+ scripted [Step check (reply 200 (String (TxId.toHex wrong)))] $ \provider -> Provider.submitTransaction provider tx >>= (@?= Left (InvalidProviderResponse "blockfrost.submitTransaction"))+ scripted [Step check (reply 503 Null)] $ \provider -> Provider.submitTransaction provider tx >>= (@?= Left (ProviderHttpError "blockfrost.submitTransaction" 503))++evaluation :: IO ()+evaluation = do+ plain <- transaction+ let argument = Data.fromData (Data.Constr 0 [])+ witnesses <- must (Witnesses.mkWitnesses [] [] [] [] [Redeemer.Redeemer Redeemer.Minting 0 argument (ExUnits 0 0)])+ let tx = Tx.assemble (Tx.body plain) (Witnesses.fromWitnesses witnesses) Nothing+ response = object ["result" .= object ["EvaluationResult" .= object ["mint:0" .= object ["memory" .= (10 :: Int), "steps" .= (20 :: Int)]]]]+ check request = do+ Http.method request @?= Http.Post+ Http.query request @?= [("version", Just "6")]+ Http.contentType request @?= "application/json"+ expected <- must (Evaluation.mkBudgets [(Evaluation.RedeemerId Redeemer.Minting 0, ExUnits 10 20)])+ scripted [Step check (reply 200 response)] $ \provider -> Provider.evaluateTransaction provider tx [] >>= (@?= Right expected)+ scripted [Step check (reply 200 (object ["result" .= object ["EvaluationFailure" .= object []]]))] $ \provider -> Provider.evaluateTransaction provider tx [] >>= (@?= Left (InvalidEvaluationResult "Blockfrost script evaluation failed"))++confirmation :: IO ()+confirmation = do+ tx <- must (TxId.fromBytes (B.replicate 32 0xab))+ let success = object ["hash" .= Text.toUpper (TxId.toHex tx), "block" .= Text.replicate 64 "0", "block_height" .= (1 :: Int)]+ scripted [Step (get ["txs", TxId.toHex tx]) (reply 404 Null), Step (get ["txs", TxId.toHex tx]) (reply 200 success)] $ \provider -> Provider.awaitTransaction provider tx 1000 >>= (@?= Right True)+ scripted [] $ \provider -> Provider.awaitTransaction provider tx 0 >>= (@?= Right False)+ scripted [Step (const (pure ())) (reply 200 (set "hash" (String (Text.replicate 64 "0")) success))] $ \provider -> Provider.awaitTransaction provider tx 1000 >>= (@?= Left (InvalidProviderResponse "blockfrost.awaitTransaction"))+ config <- configuration+ let pending = providerWithTransport config {Config.pollIntervalMillis = 1} (Http.Transport (\_ -> pure (Right (Http.Response 404 "null" Nothing))) (pure (Right ())))+ Provider.awaitTransaction pending tx 3 >>= (@?= Right False)+ let failed = providerWithTransport config (Http.Transport (\_ -> pure (Left Http.Timeout)) (pure (Right ())))+ Provider.awaitTransaction failed tx 1000 >>= (@?= Left (ProviderTransportError "blockfrost.awaitTransaction" "timeout"))+ let slow = providerWithTransport config (Http.Transport (\_ -> threadDelay 1000000 >> pure (Left Http.Timeout)) (pure (Right ())))+ timeout 10000 (Provider.awaitTransaction slow tx 1000) >>= (@?= Nothing)++closed :: IO ()+closed = do+ config <- configuration+ escaped <- Blockfrost.withProvider config (pure . Right) >>= must+ tx <- identifier+ Provider.resolveInputs escaped [] >>= (@?= Left RuntimeClosed)+ Provider.awaitTransaction escaped tx 0 >>= (@?= Left RuntimeClosed)
@@ -0,0 +1,340 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Ownership evidence against the actual pinned cardano-c provider callback.+-- The suite is sequential because it checks process-wide native allocation and+-- unwind counters; independent providers are explicitly overlapped below.+module Callback (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Callback as Bridge+import qualified Cometa.Internal.FFI.Provider as FFI+import qualified Cometa.Internal.Provider as Provider+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar, tryReadMVar)+import Control.Exception (AsyncException (ThreadKilled), Exception, MaskingState (MaskedInterruptible, Unmasked), SomeException, bracket, fromException, getMaskingState, mask_, throw, throwIO, toException, try, uninterruptibleMask_)+import Control.Monad (replicateM_)+import qualified Data.ByteString as ByteString+import Data.IORef (IORef, mkWeakIORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (isJust, isNothing)+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (castPtr)+import Foreign.StablePtr (freeStablePtr, newStablePtr)+import Foreign.Storable (peek)+import System.Mem (performGC)+import System.Mem.Weak (Weak, deRefWeak)+import System.Timeout (timeout)+import Test.Tasty (TestTree)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- TYPES ----------------------------------------------------------------------++-- Distinct from expected native failures, so exception identity is observable.+data CallbackException = CallbackException deriving (Eq, Show)++instance Exception CallbackException++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests = testCase "native provider callback ownership, exceptions and cancellation" $ do+ baseline <- Provider.liveCallbackContexts+ checkRegistrationRelease+ checkCopiedArguments baseline+ checkRetainedHandle baseline+ checkFailureRecovery+ checkExceptionalResults+ checkPendingCancellation+ checkCancellation baseline+ checkDelayedCancellation baseline+ checkFastCancellationRaces+ checkCallerMasking+ checkConcurrencyAndClose baseline+ checkReentry+ checkRepeatedFailures+ performGC+ Provider.liveCallbackContexts >>= (@?= baseline)++checkCopiedArguments :: Int -> IO ()+checkCopiedArguments baseline = do+ copied <- newIORef ByteString.empty+ Provider.withProvider+ ( \hash milliseconds -> do+ writeIORef copied hash+ hash @?= transactionId+ performGC+ pure (Right (milliseconds == maxBound))+ )+ $ \provider -> do+ performGC+ Provider.confirmTransaction provider transactionId 0 >>= (@?= Right False)+ Provider.confirmTransaction provider transactionId maxBound >>= (@?= Right True)+ Provider.confirmTransaction provider ByteString.empty 0 >>= (@?= Left (Provider.InvalidTransactionIdLength 0))+ replicateM_ 50 $ Provider.confirmTransaction provider transactionId 1 >>= (@?= Right False)++ performGC+ readIORef copied >>= (@?= transactionId)+ Provider.liveCallbackContexts >>= (@?= baseline)++checkRetainedHandle :: Int -> IO ()+checkRetainedHandle baseline = do+ escaped <- Provider.withProvider (\_ _ -> pure (Right True)) $ \original -> do+ Provider.withRetainedProvider original $ \retained -> do+ closeTwice original+ performGC+ Provider.liveCallbackContexts >>= (@?= baseline + 1)+ Provider.confirmTransaction original transactionId 0 >>= (@?= Left Provider.ProviderClosed)+ Provider.confirmTransaction retained transactionId 0 >>= (@?= Right True)+ pure original+ Provider.confirmTransaction escaped transactionId 0 >>= (@?= Left Provider.ProviderClosed)+ Provider.liveCallbackContexts >>= (@?= baseline)++checkFailureRecovery :: IO ()+checkFailureRecovery = do+ count <- newIORef (0 :: Int)+ Provider.withProvider+ ( \_ _ -> do+ previous <- readIORef count+ writeIORef count (previous + 1)+ pure (if previous == 0 then Left "declined" else Right True)+ )+ $ \provider -> do+ Provider.confirmTransaction provider transactionId 0+ >>= (@?= Left (Provider.ProviderNativeFailure (Code.toNumber Code.GenericFailure) "declined"))+ Provider.confirmTransaction provider transactionId 0 >>= (@?= Right True)++checkExceptionalResults :: IO ()+checkExceptionalResults =+ mapM_+ checkThrown+ [ \_ _ -> throwIO CallbackException,+ \_ _ -> pure (Right (throw CallbackException)),+ \_ _ -> pure (Left (throw CallbackException)),+ \_ _ -> pure (throw CallbackException)+ ]++checkRepeatedFailures :: IO ()+checkRepeatedFailures =+ replicateM_ 50 $ do+ Provider.withProvider (\_ _ -> pure (Left "expected failure")) $ \provider -> do+ result <- Provider.confirmTransaction provider transactionId 0+ result @?= Left (Provider.ProviderNativeFailure (Code.toNumber Code.GenericFailure) "expected failure")+ checkThrown (\_ _ -> throwIO CallbackException)++-- Callback exceptions may reach Haskell only after the C call has unwound.+checkThrown :: Provider.ConfirmationHandler -> IO ()+checkThrown handler = do+ before <- Provider.completedNativeCalls+ Provider.withProvider handler $ \provider -> do+ result <- try (Provider.confirmTransaction provider transactionId 0)+ result @?= Left CallbackException+ -- This counter is incremented in C after the real provider call and hash+ -- destructor. An exception escaping through the ABI cannot satisfy it.+ Provider.completedNativeCalls >>= (@?= before + 1)++-- The marker is reachable only through the handler after this helper returns.+-- A leaked StablePtr keeps it alive even after the native context counter falls.+checkRegistrationRelease :: IO ()+checkRegistrationRelease = do+ finalized <- newEmptyMVar+ (closed, weak) <- withMarkedProvider (putMVar finalized ()) $ \provider marker -> do+ performGC+ deRefWeak marker >>= assertBool "native registration roots captured state" . isJust+ Provider.confirmTransaction provider transactionId 0 >>= (@?= Right True)+ pure (provider, marker)+ performGC+ Provider.confirmTransaction closed transactionId 0 >>= (@?= Left Provider.ProviderClosed)+ waitFor "callback registration finalization" (takeMVar finalized)+ deRefWeak weak >>= assertBool "final native release frees the StablePtr root" . isNothing++-- Cancellation of a blocked handler must join native work before propagating.+checkCancellation :: Int -> IO ()+checkCancellation baseline = do+ entered <- newEmptyMVar+ blocked <- newEmptyMVar+ finished <- newEmptyMVar+ before <- Provider.completedNativeCalls+ Provider.withProvider+ (\_ _ -> putMVar entered () >> takeMVar blocked >> pure (Right True))+ $ \provider -> do+ worker <- forkFinally (Provider.confirmTransaction provider transactionId 0) (putMVar finished)+ waitFor "callback entry" (takeMVar entered)+ outcome <- waitFor "cancellation unwind" (killThread worker >> takeMVar finished)+ case outcome of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right value -> assertFailure ("cancelled callback returned " ++ show value)+ Provider.completedNativeCalls >>= (@?= before + 1)+ Provider.liveCallbackContexts >>= (@?= baseline + 1)+ Provider.liveCallbackContexts >>= (@?= baseline)++-- Independent providers isolate exceptions; closing a busy handle leaves its+-- operation reference alive until the callback has finished.+checkConcurrencyAndClose :: Int -> IO ()+checkConcurrencyAndClose baseline = do+ entered <- newEmptyMVar+ resume <- newEmptyMVar+ finished <- newEmptyMVar+ failSecond <- newIORef True+ Provider.withProvider+ (\_ _ -> putMVar entered () >> takeMVar resume >> pure (Right True))+ $ \first ->+ Provider.withProvider+ ( \_ _ -> do+ failNow <- readIORef failSecond+ if failNow then throwIO CallbackException else pure (Right False)+ )+ $ \second -> do+ _ <- forkFinally (Provider.confirmTransaction first transactionId 0) (putMVar finished)+ waitFor "concurrent callback entry" (takeMVar entered)+ isolated <- try (Provider.confirmTransaction second transactionId 0)+ isolated @?= Left CallbackException+ writeIORef failSecond False+ Provider.confirmTransaction second transactionId 0 >>= (@?= Right False)+ Provider.confirmTransaction first transactionId 0 >>= (@?= Left Provider.ProviderBusy)+ closeTwice first+ Provider.liveCallbackContexts >>= (@?= baseline + 2)+ Provider.confirmTransaction first transactionId 0 >>= (@?= Left Provider.ProviderClosed)+ putMVar resume ()+ outcome <- waitFor "closed provider operation" (takeMVar finished)+ case outcome of+ Left cause -> assertFailure (show (cause :: SomeException))+ Right value -> value @?= Right True+ Provider.liveCallbackContexts >>= (@?= baseline + 1)+ Provider.liveCallbackContexts >>= (@?= baseline)++-- Recursive use of the same provider rejects overlap rather than deadlocking.+checkReentry :: IO ()+checkReentry = do+ owner <- newIORef Nothing+ Provider.withProvider+ ( \_ _ -> do+ current <- readIORef owner+ case current of+ Nothing -> assertFailure "missing test owner"+ Just provider -> Provider.confirmTransaction provider transactionId 0 >>= (@?= Left Provider.ProviderBusy)+ pure (Right True)+ )+ $ \provider -> do+ writeIORef owner (Just provider)+ result <- waitFor "reentrant operation rejection" (Provider.confirmTransaction provider transactionId 0)+ assertBool "outer callback succeeds after rejected reentry" (result == Right True)+ -- Do not keep the closed handle in a test-owned reference unnecessarily.+ writeIORef owner Nothing++-- Deterministic unit coverage of cancellation arriving before native dispatch.+-- The normal path above exercises the same trampoline through real cardano-c.+checkPendingCancellation :: IO ()+checkPendingCancellation = do+ calls <- newIORef (0 :: Int)+ control <- Bridge.newCallbackControl+ Bridge.beginCallbackOperation control Unmasked+ Bridge.cancelCallbackOperation control (toException ThreadKilled)+ let state = Bridge.newCallbackState (\_ _ -> modifyIORef' calls (+ 1) >> pure (Right True)) control+ bracket (newStablePtr state) freeStablePtr $ \stable ->+ ByteString.useAsCStringLen transactionId $ \(hash, size) ->+ alloca $ \confirmed ->+ allocaBytes 1024 $ \diagnostic -> do+ replicateM_ 2 $ do+ code <- Bridge.confirmationCallback stable (castPtr hash) (fromIntegral size) 0 confirmed diagnostic 1024+ code @?= FFI.failure+ peek confirmed >>= (@?= 0)+ readIORef calls >>= (@?= 0)+ result <- try (Bridge.rethrowCallbackException control)+ result @?= Left ThreadKilled+ Bridge.finishCallbackOperation control++-- A handler masking cancellation keeps native ownership until explicitly resumed.+checkDelayedCancellation :: Int -> IO ()+checkDelayedCancellation baseline = do+ entered <- newEmptyMVar+ resume <- newEmptyMVar+ finished <- newEmptyMVar+ before <- Provider.completedNativeCalls+ Provider.withProvider+ (\_ _ -> uninterruptibleMask_ (putMVar entered () >> takeMVar resume >> pure (Right True)))+ $ \provider -> do+ worker <- forkFinally (Provider.confirmTransaction provider transactionId 0) (putMVar finished)+ waitFor "masked callback entry" (takeMVar entered)+ -- Delivery to the initiating caller occurs now. Its cleanup must retain+ -- native state until the deliberately masked handler is released below.+ waitFor "masked callback cancellation request" (killThread worker)+ tryReadMVar finished >>= assertBool "caller still awaits native unwind" . isNothing+ Provider.completedNativeCalls >>= (@?= before)+ closeTwice provider+ Provider.liveCallbackContexts >>= (@?= baseline + 1)+ putMVar resume ()+ outcome <- waitFor "masked callback safe unwind" (takeMVar finished)+ case outcome of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right value -> assertFailure ("masked cancellation returned " ++ show value)+ Provider.completedNativeCalls >>= (@?= before + 1)+ Provider.liveCallbackContexts >>= (@?= baseline)++-- Either result may win the race, but the next operation must start cleanly.+checkFastCancellationRaces :: IO ()+checkFastCancellationRaces =+ Provider.withProvider (\_ _ -> pure (Right True)) $ \provider ->+ replicateM_ 50 $ do+ finished <- newEmptyMVar+ worker <- forkFinally (Provider.confirmTransaction provider transactionId 0) (putMVar finished)+ outcome <- waitFor "fast callback cancellation race" (killThread worker >> takeMVar finished)+ case outcome of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right value -> value @?= Right True+ -- The next operation has a fresh error/cancellation cell and a released+ -- gate whether the previous cancellation won before or after dispatch.+ Provider.confirmTransaction provider transactionId 0 >>= (@?= Right True)++-- Worker dispatch preserves the initiating caller's masking state.+checkCallerMasking :: IO ()+checkCallerMasking = do+ expected <- newIORef Unmasked+ Provider.withProvider+ ( \_ _ -> do+ actual <- getMaskingState+ readIORef expected >>= (@?= actual)+ pure (Right True)+ )+ $ \provider -> do+ Provider.confirmTransaction provider transactionId 0 >>= (@?= Right True)+ writeIORef expected MaskedInterruptible+ mask_ (Provider.confirmTransaction provider transactionId 0) >>= (@?= Right True)++-- Deterministic 32-byte input, independent of the provider under test.+transactionId :: ByteString.ByteString+transactionId = ByteString.pack [0 .. 31]++-- Exercise handle idempotence even when native ownership is shared.+closeTwice :: Provider.Provider -> IO ()+closeTwice provider = Provider.closeProvider provider >> Provider.closeProvider provider++-- Bound synchronization waits so a broken lifecycle yields a test failure.+waitFor :: String -> IO a -> IO a+waitFor label action = do+ result <- timeout 10000000 action+ case result of+ Nothing -> assertFailure (label ++ " timed out") >> fail label+ Just value -> pure value++-- Capture the marker only in the native-rooted handler after construction.+withMarkedProvider :: IO () -> (Provider.Provider -> Weak (IORef Int) -> IO a) -> IO a+withMarkedProvider finalizer action = do+ marker <- newIORef (0 :: Int)+ weak <- mkWeakIORef marker finalizer+ Provider.withProvider+ (\_ _ -> modifyIORef' marker (+ 1) >> pure (Right True))+ (`action` weak)
@@ -0,0 +1,295 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Scalar marshaling and exact encoded-item laws. Handwritten CBOR examples+-- follow RFC 8949 major-type encodings; native transaction corpus provenance is+-- recorded separately in test/Fixtures/TRANSACTIONS.md.+module Cbor (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Error (Error (..))+import Control.Monad (forM_, replicateM_, (>=>))+import Data.Bifunctor (bimap)+import qualified Data.ByteString as ByteString+import Data.Either (isLeft)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Hedgehog (Property, evalEither, evalIO, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "CBOR foundation"+ [ testCase "floating-point widths and IEEE special values are preserved" checkFloatingPoint,+ testCase "simple values and undefined remain distinct" checkSimpleValues,+ testCase "scalar failures release readers and permit recovery" checkScalarCleanup,+ testCase "integer boundaries have independent expected encodings" checkIntegerVectors,+ testCase "out-of-range integers are rejected without truncation" checkIntegerBounds,+ testCase "byte, text and Boolean values have expected encodings" checkScalarVectors,+ testCase "nested nonminimal and indefinite items preserve exact bytes" checkRawItems,+ testCase "malformed, truncated and trailing input is rejected" checkInvalidItems,+ testCase "text decoding rejects invalid UTF-8" checkInvalidUtf8,+ testCase "scalar decoders reject a different major type" checkWrongTypes,+ testCase "arrays preserve child encodings and order" checkArrays,+ testCase "maps preserve duplicate keys and order" checkMaps,+ testCase "absent, null, empty and zero map values remain distinct" checkPresence,+ testCase "copied scalar and collection snapshots survive cleanup and GC" checkSnapshots,+ testProperty "primitive integers round trip" propInteger,+ testProperty "arbitrary bytes round trip" propBytes,+ testProperty "Unicode text round trips" propText,+ testProperty "Booleans round trip" propBool,+ testProperty "array children retain their encoded bytes" propArray,+ testProperty "ordered duplicate map entries round trip" propMap+ ]++checkIntegerVectors :: IO ()+checkIntegerVectors = mapM_ check integerVectors+ where+ check (number, expected) = do+ encoded <- requireRight (Cbor.encodeInteger number)+ Cbor.toHex encoded @?= expected+ Cbor.decodeInteger encoded >>= (@?= Right number)+ parsed <- requireRight (Cbor.fromHex expected)+ Cbor.decodeInteger parsed >>= (@?= Right number)++checkIntegerBounds :: IO ()+checkIntegerBounds = mapM_ check [negate (2 ^ (64 :: Int)) - 1, 2 ^ (64 :: Int), negate (2 ^ (256 :: Int)), 2 ^ (256 :: Int)]+ where+ check number = Cbor.encodeInteger number >>= (@?= Left (InvalidCborInteger number))++checkScalarVectors :: IO ()+checkScalarVectors = do+ empty <- requireRight (Cbor.encodeByteString ByteString.empty)+ Cbor.toHex empty @?= "40"+ bytes <- requireRight (Cbor.encodeByteString (ByteString.pack [0, 1, 2, 255]))+ Cbor.toHex bytes @?= "44000102ff"+ text <- requireRight (Cbor.encodeText "λ😀")+ Cbor.toHex text @?= "66cebbf09f9880"+ Cbor.decodeText text >>= (@?= Right "λ😀")+ embeddedNull <- requireRight (Cbor.encodeText "a\NULb")+ Cbor.toHex embeddedNull @?= "63610062"+ Cbor.decodeText embeddedNull >>= (@?= Right "a\NULb")+ blank <- requireRight (Cbor.encodeText "")+ Cbor.toHex blank @?= "60"+ false <- requireRight (Cbor.encodeBool False)+ true <- requireRight (Cbor.encodeBool True)+ map Cbor.toHex [false, true] @?= ["f4", "f5"]++checkRawItems :: IO ()+checkRawItems = mapM_ check rawItems+ where+ check encoded = do+ value <- requireRight (Cbor.fromHex encoded)+ Cbor.toHex value @?= encoded+ Cbor.fromBytes (Cbor.toBytes value) >>= (@?= Right value)++checkInvalidItems :: IO ()+checkInvalidItems = mapM_ check ["", "ff", "18", "81", "9f00", "bf0001", "5f6100ff", "a100", "0000", "00ff", "f600"]+ where+ check encoded = do+ result <- Cbor.fromHex encoded+ assertBool ("accepted malformed or trailing CBOR: " <> Text.unpack encoded) (isLeft result)++checkInvalidUtf8 :: IO ()+checkInvalidUtf8 = do+ mapM_ check ["61ff", "62c080", "63eda080", "64f4908080", "7f61c361a9ff"]+ validChunks <- requireRight (Cbor.fromHex "7f62c3a962cebbff")+ Cbor.decodeText validChunks >>= (@?= Right "éλ")+ emptyChunks <- requireRight (Cbor.fromHex "7fff")+ Cbor.decodeText emptyChunks >>= (@?= Right "")+ -- Raw items preserve accepted structure. Text validation belongs to decodeText,+ -- including when malformed text is encountered inside an array.+ nested <- requireRight (Cbor.fromHex "8161ff")+ items <- requireRight (Cbor.decodeArray nested)+ mapM_ (Cbor.decodeText >=> (@?= Left InvalidCborUtf8)) items+ where+ check encoded = do+ item <- requireRight (Cbor.fromHex encoded)+ Cbor.decodeText item >>= (@?= Left InvalidCborUtf8)++checkWrongTypes :: IO ()+checkWrongTypes = do+ nullValue <- requireRight (Cbor.fromHex "f6")+ Cbor.decodeInteger nullValue >>= assertBool "null decoded as integer" . isLeft+ Cbor.decodeByteString nullValue >>= assertBool "null decoded as bytes" . isLeft+ Cbor.decodeText nullValue >>= assertBool "null decoded as text" . isLeft+ Cbor.decodeBool nullValue >>= assertBool "null decoded as Boolean" . isLeft+ Cbor.decodeArray nullValue >>= assertBool "null decoded as array" . isLeft+ Cbor.decodeMap nullValue >>= assertBool "null decoded as map" . isLeft++checkArrays :: IO ()+checkArrays = do+ original <- requireRight (Cbor.fromHex "9f18175f41014102ffff")+ children <- requireRight (Cbor.decodeArray original)+ map Cbor.toHex children @?= ["1817", "5f41014102ff"]+ encoded <- requireRight (Cbor.encodeArray children)+ Cbor.toHex encoded @?= "8218175f41014102ff"+ empty <- requireRight (Cbor.encodeArray [])+ Cbor.toHex empty @?= "80"++checkMaps :: IO ()+checkMaps = do+ original <- requireRight (Cbor.fromHex "bf1801616118016162ff")+ entries <- requireRight (Cbor.decodeMap original)+ map (bimap Cbor.toHex Cbor.toHex) entries @?= [("1801", "6161"), ("1801", "6162")]+ encoded <- requireRight (Cbor.encodeMap entries)+ Cbor.toHex encoded @?= "a21801616118016162"++checkPresence :: IO ()+checkPresence = do+ values <- mapM (requireRight . Cbor.fromHex) ["a0", "a100f6", "a10080", "a10000"]+ entries <- mapM (requireRight . Cbor.decodeMap) values+ map (map (bimap Cbor.toHex Cbor.toHex)) entries+ @?= [[], [("00", "f6")], [("00", "80")], [("00", "00")]]+ mapM_ (\(original, pairs) -> Cbor.encodeMap pairs >>= (@?= Right original)) (zip values entries)++checkSnapshots :: IO ()+checkSnapshots = do+ original <- requireRight (Cbor.encodeText "retained λ😀")+ container <- requireRight (Cbor.encodeArray [original, original])+ children <- requireRight (Cbor.decodeArray container)+ replicateM_ 100 $ do+ _ <- requireRight (Cbor.encodeByteString (ByteString.replicate 256 42))+ _ <- requireRight (Cbor.fromHex "a2016161016162")+ pure ()+ performGC+ mapM_ (Cbor.decodeText >=> (@?= Right "retained λ😀")) children+ Cbor.decodeText original >>= (@?= Right "retained λ😀")++propInteger :: Property+propInteger = withTests 300 $ property $ do+ number <- forAll (Gen.integral (Range.linear (negate (2 ^ (64 :: Int))) (2 ^ (64 :: Int) - 1)))+ encoded <- evalIO (Cbor.encodeInteger number) >>= evalEither+ decoded <- evalIO (Cbor.decodeInteger encoded) >>= evalEither+ decoded === number++propBytes :: Property+propBytes = withTests 300 $ property $ do+ bytes <- forAll (Gen.bytes (Range.linear 0 1024))+ encoded <- evalIO (Cbor.encodeByteString bytes) >>= evalEither+ decoded <- evalIO (Cbor.decodeByteString encoded) >>= evalEither+ decoded === bytes++propText :: Property+propText = withTests 300 $ property $ do+ text <- forAll (Gen.text (Range.linear 0 256) Gen.unicode)+ encoded <- evalIO (Cbor.encodeText text) >>= evalEither+ decoded <- evalIO (Cbor.decodeText encoded) >>= evalEither+ decoded === text+ ByteString.length (Text.encodeUtf8 decoded) === ByteString.length (Text.encodeUtf8 text)++propBool :: Property+propBool = withTests 300 $ property $ do+ value <- forAll Gen.bool+ encoded <- evalIO (Cbor.encodeBool value) >>= evalEither+ decoded <- evalIO (Cbor.decodeBool encoded) >>= evalEither+ decoded === value++propArray :: Property+propArray = withTests 300 $ property $ do+ values <- forAll (Gen.list (Range.linear 0 40) (Gen.integral (Range.linear (-1000000) 1000000)))+ children <- mapM (\value -> evalIO (Cbor.encodeInteger value) >>= evalEither) values+ encoded <- evalIO (Cbor.encodeArray children) >>= evalEither+ decoded <- evalIO (Cbor.decodeArray encoded) >>= evalEither+ map Cbor.toBytes decoded === map Cbor.toBytes children++propMap :: Property+propMap = withTests 300 $ property $ do+ -- A tiny key domain deliberately produces duplicates, without sorting them.+ values <- forAll (Gen.list (Range.linear 0 40) ((,) <$> Gen.int (Range.linear 0 3) <*> Gen.bytes (Range.linear 0 32)))+ entries <- mapM encodeEntry values+ encoded <- evalIO (Cbor.encodeMap entries) >>= evalEither+ decoded <- evalIO (Cbor.decodeMap encoded) >>= evalEither+ map encodedPair decoded === map encodedPair entries+ where+ encodeEntry (key, value) = do+ first <- evalIO (Cbor.encodeInteger (toInteger key)) >>= evalEither+ second <- evalIO (Cbor.encodeByteString value) >>= evalEither+ pure (first, second)+ encodedPair (key, value) = (Cbor.toBytes key, Cbor.toBytes value)++requireRight :: (Show failure) => IO (Either failure value) -> IO value+requireRight action = do+ result <- action+ case result of+ Right value -> pure value+ Left failure -> assertFailure (show failure) >> fail "fixture operation failed"++integerVectors :: [(Integer, Text)]+integerVectors = [(0, "00"), (23, "17"), (24, "1818"), (255, "18ff"), (256, "190100"), (65535, "19ffff"), (65536, "1a00010000"), (2 ^ (32 :: Int), "1b0000000100000000"), (2 ^ (64 :: Int) - 1, "1bffffffffffffffff"), (-1, "20"), (-24, "37"), (-25, "3818"), (negate (2 ^ (64 :: Int)), "3bffffffffffffffff")]++rawItems :: [Text]+rawItems = ["1817", "5f41014102ff", "7f61616162ff", "9f00f68101ff", "bf016161016162ff", "d86400", "c249010000000000000000", "a201f60100"]++-- | Independent RFC 8949 encodings cover each width and sign boundary.+checkFloatingPoint :: IO ()+checkFloatingPoint = do+ forM_ [("f93c00", 1), ("f9c000", -2), ("f90001", 2 ** (-24)), ("f97bff", 65504), ("fa3fc00000", 1.5), ("fb3ff8000000000000", 1.5)] $ \(bytes, expected) -> do+ item <- requireRight (Cbor.fromHex bytes)+ Cbor.decodeDouble item >>= (@?= Right expected)+ Cbor.toHex item @?= bytes+ forM_ ["f98000", "fa80000000", "fb8000000000000000"] $ \bytes -> do+ item <- requireRight (Cbor.fromHex bytes)+ actual <- requireRight (Cbor.decodeDouble item)+ assertBool "negative zero sign lost" (isNegativeZero actual)+ forM_ [("f97c00", False), ("f9fc00", True), ("fa7f800000", False), ("fbfff0000000000000", True)] $ \(bytes, negative) -> do+ item <- requireRight (Cbor.fromHex bytes)+ actual <- requireRight (Cbor.decodeDouble item)+ assertBool "infinity lost" (isInfinite actual)+ (actual < 0) @?= negative+ forM_ ["f97e00", "fa7fc00000", "fb7ff8000000000000"] $ \bytes -> do+ item <- requireRight (Cbor.fromHex bytes)+ requireRight (Cbor.decodeDouble item) >>= assertBool "NaN lost" . isNaN++-- | Enumerate the byte-valued native simple domain, including nonminimal forms.+checkSimpleValues :: IO ()+checkSimpleValues = do+ forM_ [0 .. 255] $ \number -> do+ let bytes = ByteString.pack [248, number]+ item <- requireRight (Cbor.fromBytes bytes)+ Cbor.decodeSimple item >>= (@?= Right number)+ Cbor.toBytes item @?= bytes+ forM_ [0 .. 23] $ \number -> do+ item <- requireRight (Cbor.fromBytes (ByteString.singleton (224 + number)))+ Cbor.decodeSimple item >>= (@?= Right number)+ item <- requireRight Cbor.encodeUndefined+ Cbor.toHex item @?= "f7"+ Cbor.decodeSimple item >>= (@?= Right 23)+ Cbor.decodeBool item >>= assertBool "undefined decoded as Boolean" . isLeft+ values <- mapM (requireRight . Cbor.fromHex) ["f4", "f5", "f6", "f7"]+ mapM (requireRight . Cbor.decodeSimple) values >>= (@?= [20, 21, 22, 23])++checkScalarCleanup :: IO ()+checkScalarCleanup = replicateM_ 40 $ do+ wrong <- requireRight (Cbor.encodeInteger 1)+ Cbor.decodeDouble wrong >>= assertBool "integer coerced into Double" . isLeft+ Cbor.decodeSimple wrong >>= assertBool "integer decoded as simple" . isLeft+ float <- requireRight (Cbor.fromHex "f93c00")+ Cbor.decodeSimple float >>= assertBool "float decoded as simple" . isLeft+ forM_ ["f9", "f900", "fa0000", "fb00000000", "f8", "f701"] (Cbor.fromHex >=> (assertBool "invalid complete item accepted" . isLeft))+ item <- requireRight Cbor.encodeUndefined+ Cbor.decodeSimple item >>= (@?= Right 23)
@@ -0,0 +1,269 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Certificate schema, constructor boundaries and native reconstruction tests.+module Certificates (tests, sampleCertificates) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Error (Error)+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.NetworkId as Network+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.UnitInterval as UnitInterval+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Either (isLeft)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import qualified Data.Text as Text+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Certificates"+ [ testCase "all certificate alternatives and uint64 boundaries reconstruct natively" checkAlternatives,+ testCase "pinned native certificate corpus reconstructs semantic public data" checkPinned,+ testCase "exact envelopes preserve nonminimal and indefinite encodings" checkExact,+ testCase "malformed schemas, duplicate rewards and signed MIR amounts fail" checkInvalid,+ testCase "collection order, duplicates and optional set tag are preserved" checkCollections,+ testCase "repeated native reconstruction releases retained fields" checkRepeated,+ testProperty "all generated typed certificates round trip and reconstruct natively" propRoundTrip+ ]++sampleCertificates :: Word8 -> Word64 -> Either Error [Certificate.Certificate]+sampleCertificates seed amount = do+ stakeKey <- key seed+ poolKey <- key (seed + 1)+ drepKey <- key (seed + 2)+ coldKey <- key (seed + 3)+ hotKey <- key (seed + 4)+ genesisKey <- key (seed + 5)+ delegateKey <- key (seed + 6)+ script <- Credential.scriptHashFromBytes (ByteString.replicate 28 (seed + 7))+ vrf <- Pool.vrfKeyHashFromBytes (ByteString.replicate 32 seed)+ margin <- UnitInterval.mkUnitInterval 1 5+ location <- Anchor.mkUrl "https://example.com/certificate.json"+ digest <- Anchor.dataHashFromBytes (ByteString.replicate 32 (seed + 8))+ let stake = Credential.KeyCredential stakeKey+ drepCredential = Credential.KeyCredential drepKey+ cold = Credential.KeyCredential coldKey+ hot = Credential.KeyCredential hotKey+ target = DRep.DRepCredential drepCredential+ anchor = Just (Anchor.Anchor location digest)+ parameters = Pool.PoolParameters poolKey vrf Nothing amount amount margin (Reward.fromCredential Network.testnet stake) (Set.singleton stakeKey) [] Nothing+ pure+ [ Certificate.StakeRegistration stake,+ Certificate.StakeDeregistration stake,+ Certificate.StakeDelegation stake poolKey,+ Certificate.PoolRegistration parameters,+ Certificate.PoolRetirement poolKey amount,+ Certificate.GenesisKeyDelegation genesisKey delegateKey vrf,+ Certificate.MoveInstantaneousRewards (Certificate.ToOtherPot Certificate.Reserves amount),+ Certificate.MoveInstantaneousRewards (Certificate.ToOtherPot Certificate.Treasury amount),+ Certificate.MoveInstantaneousRewards (Certificate.ToStakeCredentials Certificate.Reserves (Map.fromList [(stake, amount), (Credential.ScriptCredential script, amount)])),+ Certificate.MoveInstantaneousRewards (Certificate.ToStakeCredentials Certificate.Treasury Map.empty),+ Certificate.Registration stake amount,+ Certificate.Unregistration stake amount,+ Certificate.VoteDelegation stake target,+ Certificate.VoteDelegation (Credential.ScriptCredential script) DRep.AlwaysAbstain,+ Certificate.VoteDelegation stake DRep.AlwaysNoConfidence,+ Certificate.StakeVoteDelegation stake poolKey target,+ Certificate.StakeRegistrationDelegation stake poolKey amount,+ Certificate.VoteRegistrationDelegation stake target amount,+ Certificate.StakeVoteRegistrationDelegation stake poolKey target amount,+ Certificate.AuthorizeCommitteeHot cold hot,+ Certificate.AuthorizeCommitteeHot (Credential.ScriptCredential script) (Credential.ScriptCredential script),+ Certificate.ResignCommitteeCold cold Nothing,+ Certificate.ResignCommitteeCold cold anchor,+ Certificate.RegisterDRep drepCredential amount Nothing,+ Certificate.RegisterDRep (Credential.ScriptCredential script) amount anchor,+ Certificate.UnregisterDRep drepCredential amount,+ Certificate.UpdateDRep drepCredential Nothing,+ Certificate.UpdateDRep drepCredential anchor+ ]++key :: Word8 -> Either Error (Credential.KeyHash purpose)+key = Credential.keyHashFromBytes . ByteString.replicate 28++checkAlternatives :: IO ()+checkAlternatives = forM_ [0, 23, 24, 255, 256, 65535, 65536, 4294967295, 4294967296, maxBound] $ \amount -> do+ values <- expectRight (sampleCertificates 11 amount)+ forM_ values checkCertificate++checkCertificate :: Certificate.Certificate -> IO ()+checkCertificate value = do+ let encoded = Certificate.encodeCbor value+ reloaded <- expectRight (Certificate.decodeCbor encoded)+ Certificate.toCertificate reloaded @?= value+ Certificate.toCbor reloaded @?= encoded+ Certificate.toCertificate (Certificate.fromCertificate value) @?= value+ nativeAgreement 0 encoded++checkPinned :: IO ()+checkPinned = forM_ pinnedVectors $ \(_, fixture) -> do+ encoded <- bytes fixture+ reloaded <- expectRight (Certificate.decodeCbor encoded)+ let value = Certificate.toCertificate reloaded+ checkCertificate value+ -- Null BLS placeholders are semantic omission and re-encode without the slot.+ Certificate.toCbor reloaded @?= encoded++checkExact :: IO ()+checkExact = do+ authority <- expectRight (key 0)+ let value = Certificate.Registration (Credential.KeyCredential authority) 0+ canonical = Certificate.encodeCbor value+ nonminimal = ByteString.pack [0x9f, 0x18, 7] <> ByteString.take (ByteString.length canonical - 3) (ByteString.drop 2 canonical) <> ByteString.pack [0x18, 0, 0xff]+ -- Build indefinite form directly so its accepted structure is explicit.+ imported = ByteString.pack [0x9f, 0x18, 7] <> ByteString.take 32 (ByteString.drop 2 canonical) <> ByteString.pack [0x18, 0, 0xff]+ nonminimal @?= imported+ reloaded <- expectRight (Certificate.decodeCbor imported)+ Certificate.toCertificate reloaded @?= value+ Certificate.toCbor reloaded @?= imported+ Certificate.encodeCbor (Certificate.toCertificate reloaded) @?= canonical+ assertBool "byte-sensitive exact envelopes" (reloaded /= Certificate.fromCertificate value)++checkInvalid :: IO ()+checkInvalid = do+ authority <- expectRight (key 0)+ let stake = Credential.KeyCredential authority+ credential = Encode.encodeListLen 2 <> Encode.encodeWord 0 <> Encode.encodeBytes (Credential.keyHashBytes authority)+ duplicateMir = Encode.encodeListLen 2 <> Encode.encodeWord 6 <> Encode.encodeListLen 2 <> Encode.encodeWord 0 <> Encode.encodeMapLen 2 <> credential <> Encode.encodeWord 1 <> credential <> Encode.encodeWord 2+ signedMir = Encode.encodeListLen 2 <> Encode.encodeWord 6 <> Encode.encodeListLen 2 <> Encode.encodeWord 0 <> Encode.encodeMapLen 1 <> credential <> Encode.encodeInteger (-1)+ overflow = Encode.encodeListLen 3 <> Encode.encodeWord 7 <> credential <> Encode.encodeInteger (2 ^ (64 :: Int))+ forM_ ["", "80", "8100", "8200", "820013", "82138200581c", "82008202581c", "83078200581b00000000000000000000000000000000000000000000000000000000"] $ \fixture -> do+ malformed <- bytes fixture+ assertBool "invalid certificate schema" (isLeft (Certificate.decodeCbor malformed))+ forM_ [duplicateMir, signedMir, overflow] $ \malformed -> assertBool "invalid rewards or bound" (isLeft (Certificate.decodeCbor (Write.toStrictByteString malformed)))+ let valid = Certificate.encodeCbor (Certificate.StakeRegistration stake)+ assertBool "trailing data" (isLeft (Certificate.decodeCbor (valid <> "\NUL")))+ assertBool "wrong collection tag" (isLeft (Certificates.decodeCbor (ByteString.pack [0xd9, 1, 3, 0x80])))++checkCollections :: IO ()+checkCollections = do+ values <- expectRight (sampleCertificates 9 1000)+ let ordered = values <> take 2 values+ collection = Certificates.fromList ordered+ encoded = Certificates.encodeCbor collection+ untagged = ByteString.drop 3 encoded+ reloaded <- expectRight (Certificates.decodeCbor encoded)+ Certificates.toList (Certificates.toCertificates reloaded) @?= ordered+ Certificates.toCbor reloaded @?= encoded+ Certificates.toCertificates (Certificates.fromCertificates collection) @?= collection+ untaggedValue <- expectRight (Certificates.decodeCbor untagged)+ Certificates.toCertificates untaggedValue @?= collection+ Certificates.toCbor untaggedValue @?= untagged+ nativeAgreement 1 encoded+ nativeAgreement 1 (Certificates.encodeCbor Certificates.empty)++checkRepeated :: IO ()+checkRepeated = do+ values <- expectRight (sampleCertificates 8 maxBound)+ replicateM_ 20 (forM_ values (nativeAgreement 0 . Certificate.encodeCbor))++propRoundTrip :: Property+propRoundTrip = property $ do+ seed <- forAll (Gen.word8 Range.constantBounded)+ amount <- forAll (Gen.word64 Range.constantBounded)+ values <- evalEither (sampleCertificates seed amount)+ forM_ values $ \value -> do+ let encoded = Certificate.encodeCbor value+ reloaded <- evalEither (Certificate.decodeCbor encoded)+ Certificate.toCertificate reloaded === value+ evalIO (nativeAgreement 0 encoded)+ let collection = Certificates.fromList values+ reloaded <- evalEither (Certificates.decodeCbor (Certificates.encodeCbor collection))+ Certificates.toCertificates reloaded === collection+ evalIO (nativeAgreement 1 (Certificates.encodeCbor collection))++nativeAgreement :: CUInt -> ByteString -> IO ()+nativeAgreement mode encoded = ByteString.useAsCStringLen encoded $ \(input, size) -> do+ agrees <- cAgreement mode (castPtr input) (fromIntegral size)+ agrees @?= 1++bytes :: String -> IO ByteString+bytes encoded = case Hex.decodeHex (Text.pack encoded) of+ Nothing -> assertFailure "invalid fixture hexadecimal" >> fail "unreachable assertion"+ Just value -> pure value++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Left failure -> assertFailure (show failure) >> fail "unreachable assertion"+ Right value -> pure value++-- Pinned Apache-2.0 cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/certs/*.cpp constants, retaining source filename and constant name.+-- Native constructor/getter agreement is checked after public semantic decoding;+-- generated public constructors above independently exercise field marshaling.+pinnedVectors :: [(String, String)]+pinnedVectors =+ [ ("auth_committee_hot_cert.cpp/CBOR", "830e8200581c000000000000000000000000000000000000000000000000000000008200581c00000000000000000000000000000000000000000000000000000000"),+ ("genesis_key_delegation_cert.cpp/CBOR", "8405581c00010001000100010001000100010001000100010001000100010001581c0002000200020002000200020002000200020002000200020002000258200003000300030003000300030003000300030003000300030003000300030003"),+ ("mir_cert.cpp/CBOR_USE_RESERVES_TO_POT", "820682001a000f4240"),+ ("mir_cert.cpp/CBOR_USE_TREASURY_TO_POT", "820682011a000f4240"),+ ("mir_cert.cpp/CBOR_USE_RESERVES_TO_CREDS", "82068200a18200581c0101010101010101010101010101010101010101010101010101010100"),+ ("mir_cert.cpp/CBOR_USE_TREASURY_TO_CREDS", "82068201a18200581c0101010101010101010101010101010101010101010101010101010100"),+ ("pool_registration_cert.cpp/CBOR", "8a03581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db01927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"),+ ("pool_registration_cert.cpp/CBOR_WITH_BLS_KEY", "8b03581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0825860000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f5830606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f1927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"),+ ("pool_registration_cert.cpp/CBOR_WITH_NULL_BLS_KEY", "8b03581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0f61927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"),+ ("pool_retirement_cert.cpp/CBOR", "8304581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef921903e8"),+ ("register_drep_cert.cpp/CBOR", "84108200581c0000000000000000000000000000000000000000000000000000000000f6"),+ ("register_drep_cert.cpp/CBOR_WITH_ANCHOR", "84108200581c0000000000000000000000000000000000000000000000000000000000827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"),+ ("registration_cert.cpp/CBOR", "83078200581c0000000000000000000000000000000000000000000000000000000000"),+ ("registration_cert.cpp/CBOR_WITH_NONZERO_DEPOSIT", "83078200581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f1a001e8480"),+ ("resign_committee_cold_cert.cpp/CBOR", "830f8200581c00000000000000000000000000000000000000000000000000000000f6"),+ ("resign_committee_cold_cert.cpp/CBOR_WITH_ANCHOR", "830f8200581c00000000000000000000000000000000000000000000000000000000827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"),+ ("stake_delegation_cert.cpp/CBOR", "83028200581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef92"),+ ("stake_deregistration_cert.cpp/CBOR", "82018200581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f"),+ ("stake_registration_cert.cpp/CBOR", "82008200581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f"),+ ("stake_registration_delegation_cert.cpp/CBOR", "840b8200581c00000000000000000000000000000000000000000000000000000000581c0000000000000000000000000000000000000000000000000000000000"),+ ("stake_vote_delegation_cert.cpp/CBOR", "840a8200581c00000000000000000000000000000000000000000000000000000000581c000000000000000000000000000000000000000000000000000000008200581c00000000000000000000000000000000000000000000000000000000"),+ ("stake_vote_registration_delegation_cert.cpp/CBOR", "850d8200581c00000000000000000000000000000000000000000000000000000000581c000000000000000000000000000000000000000000000000000000008200581c0000000000000000000000000000000000000000000000000000000000"),+ ("unregister_drep_cert.cpp/CBOR", "83118200581c0000000000000000000000000000000000000000000000000000000000"),+ ("unregistration_cert.cpp/CBOR", "83088200581c0000000000000000000000000000000000000000000000000000000000"),+ ("unregistration_cert.cpp/CBOR_WITH_NONZERO_DEPOSIT", "83088200581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f1a001e8480"),+ ("update_drep_cert.cpp/CBOR", "83128200581c00000000000000000000000000000000000000000000000000000000f6"),+ ("update_drep_cert.cpp/CBOR_WITH_ANCHOR", "83128200581c00000000000000000000000000000000000000000000000000000000827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"),+ ("vote_delegation_cert.cpp/CBOR", "83098200581c000000000000000000000000000000000000000000000000000000008200581c00000000000000000000000000000000000000000000000000000000"),+ ("vote_registration_delegation_cert.cpp/CBOR", "840c8200581c000000000000000000000000000000000000000000000000000000008200581c0000000000000000000000000000000000000000000000000000000000")+ ]++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_certificates_agree"+ cAgreement :: CUInt -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,191 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Apache-2.0 native vectors from cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/message_signing/cip8.cpp. COSE fields and Sig_structure are also+-- decoded/reconstructed through public CBOR values and cryptographically checked.+module Cip8 (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as Public+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Message.Cip8 as Cip8+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, try)+import Control.Monad (forM_, replicateM_, (>=>))+import qualified Data.ByteString as B+import Data.Text (Text)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "CIP8"+ [ testCase "address and key-hash native vectors and independent verification" vectors,+ testCase "binary payload, direct signing and empty AAD" binary,+ testCase "normal seed keys sign without checking address control" normalKey,+ testCase "bindings do not validate control of the signing key" mismatched,+ testCase "empty payload and closed key fail without poisoning a live key" failures,+ testCase "owned results, repeated calls and independent concurrent scopes" lifetime+ ]++privateKey :: Text+privateKey = "d06d3744d9089b21b1fbb736a45d359ed5d5b4028800e70aa1a2968183cb68528ef06f1c2b289a85e09738d528869dd1f69f436ada4b471b12e950a2b9e780b6"++address :: IO Address.Address+address = require (Address.fromText "addr_test1qqja52pwpq7v7amg34r6x9dpp5le04n6cmqf2zpnurt2lm48wgx7j5cur9w0zxv7ky333eef3akg092hhcmp3teeth3qktnslv")++hashBinding :: B.ByteString -> IO Cip8.Binding+hashBinding bytes = Cip8.keyHashBinding <$> require (Credential.keyHashFromBytes bytes :: Either Error (Credential.KeyHash Credential.DRep))++withKey :: (Key.SigningKey -> IO ()) -> IO ()+withKey action = Key.withExtendedKeyHex privateKey (\key -> action key >> pure (Right ())) >>= require++vectors :: IO ()+vectors = withKey $ \key -> do+ addr <- address+ hash <- Cbor.fromHex "581c25da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afee" >>= require >>= Cbor.decodeByteString >>= require+ binding <- hashBinding hash+ forM_ [(Cip8.addressBinding addr, Address.toBytes addr, addressSign, addressKey), (binding, hash, hashSign, hashKey)] $ \(bound, bytes, expectedSign, expectedKey) -> do+ signed <- Cip8.sign key bound (B.pack [0xab, 0xc1, 0x23]) >>= require+ Cbor.fromBytes (Cip8.coseSign1 signed) >>= require >>= (\cbor -> Cbor.toHex cbor @?= expectedSign)+ Cbor.fromBytes (Cip8.coseKey signed) >>= require >>= (\cbor -> Cbor.toHex cbor @?= expectedKey)+ verify key bytes (B.pack [0xab, 0xc1, 0x23]) signed++binary :: IO ()+binary = withKey $ \key -> do+ addr <- address+ let payload = B.pack [0, 255, 128, 0, 1, 0]+ signed <- Cip8.sign key (Cip8.addressBinding addr) payload >>= require+ verify key (Address.toBytes addr) payload signed++normalKey :: IO ()+normalKey = do+ addr <- address+ Key.withNormalKey+ (B.replicate 32 7)+ ( \key -> do+ public <- Key.publicKey key >>= require+ digest <- Public.hash public >>= require+ assertBool "address payment credential must differ from signing key" (Blake2b.toBytes digest /= B.take 28 (B.drop 1 (Address.toBytes addr)))+ signed <- Cip8.sign key (Cip8.addressBinding addr) "normal key" >>= require+ verify key (Address.toBytes addr) "normal key" signed+ pure (Right ())+ )+ >>= require++mismatched :: IO ()+mismatched = withKey $ \key -> do+ let bytes = B.replicate 28 0+ binding <- hashBinding bytes+ signed <- Cip8.sign key binding "mismatched binding" >>= require+ verify key bytes "mismatched binding" signed++failures :: IO ()+failures = do+ addr <- address+ let binding = Cip8.addressBinding addr+ withKey $ \key -> do+ empty <- Cip8.sign key binding B.empty+ case empty of+ Left (NativeError "cip8.sign" Code.InvalidArgument _) -> pure ()+ _ -> assertFailure "empty payload should fail with InvalidArgument"+ lazy <- try (Cip8.sign key binding (error "lazy payload")) :: IO (Either SomeException (Either Error Cip8.SignedMessage))+ assertBool "lazy payload must throw" (either (const True) (const False) lazy)+ _ <- Cip8.sign key binding "usable afterward" >>= require+ pure ()+ closed <- Key.withExtendedKeyHex privateKey (pure . Right) >>= require+ Cip8.sign closed binding "closed" >>= (@?= Left SigningKeyClosed)++lifetime :: IO ()+lifetime = do+ addr <- address+ let binding = Cip8.addressBinding addr+ operation = Key.withExtendedKeyHex privateKey $ \key -> Cip8.sign key binding "retained"+ retained <- operation >>= require+ replicateM_ 30 (operation >>= require >>= (@?= retained))+ withKey $ \key -> verify key (Address.toBytes addr) "retained" retained+ completions <- mapM (const newEmptyMVar) [1 :: Int .. 8]+ forM_ completions $ \done -> do+ _ <- forkFinally operation (putMVar done)+ pure ()+ forM_ completions $ \done -> do+ result <- takeMVar done+ either (assertFailure . show) (require >=> (@?= retained)) result++verify :: Key.SigningKey -> B.ByteString -> B.ByteString -> Cip8.SignedMessage -> IO ()+verify key binding payload signed = do+ signFields <- Cbor.fromBytes (Cip8.coseSign1 signed) >>= require >>= Cbor.decodeArray >>= require+ case signFields of+ [protected, unprotected, encodedPayload, encodedSignature] -> do+ Cbor.decodeByteString encodedPayload >>= require >>= (@?= payload)+ protectedBytes <- Cbor.decodeByteString protected >>= require+ headers <- Cbor.fromBytes protectedBytes >>= require >>= Cbor.decodeMap >>= require+ algorithm <- intField 1 headers+ Cbor.decodeInteger algorithm >>= require >>= (@?= (-8))+ bound <- textField "address" headers+ Cbor.decodeByteString bound >>= require >>= (@?= binding)+ annotations <- Cbor.decodeMap unprotected >>= require+ hashed <- textField "hashed" annotations+ Cbor.decodeBool hashed >>= require >>= (@?= False)+ keyFields <- Cbor.fromBytes (Cip8.coseKey signed) >>= require >>= Cbor.decodeMap >>= require+ forM_ [(1, 1), (3, -8), (-1, 6)] $ \(label, expected) -> intField label keyFields >>= Cbor.decodeInteger >>= require >>= (@?= expected)+ publicBytes <- intField (-2) keyFields >>= Cbor.decodeByteString >>= require+ public <- Key.publicKey key >>= require+ publicBytes @?= Public.toBytes public+ intField 2 keyFields >>= Cbor.decodeByteString >>= require >>= (@?= binding)+ signature <- Cbor.decodeByteString encodedSignature >>= require >>= (require . Signature.fromBytes)+ context <- Cbor.encodeText "Signature1" >>= require+ emptyAad <- Cbor.encodeByteString B.empty >>= require+ preimage <- Cbor.encodeArray [context, protected, emptyAad, encodedPayload] >>= require+ Public.verify public (Cbor.toBytes preimage) signature >>= (@?= Right True)+ wrongAad <- Cbor.encodeByteString "different AAD" >>= require+ wrongStructure <- Cbor.encodeArray [context, protected, wrongAad, encodedPayload] >>= require+ Public.verify public (Cbor.toBytes wrongStructure) signature >>= (@?= Right False)+ Public.verify public payload signature >>= (@?= Right False)+ _ -> assertFailure "COSE_Sign1 must contain exactly four fields"++intField :: Integer -> [(Cbor.Cbor, Cbor.Cbor)] -> IO Cbor.Cbor+intField label fields = Cbor.encodeInteger label >>= require >>= (\encoded -> maybe (assertFailure "missing integer header" >> fail "missing") pure (lookup encoded fields))++textField :: Text -> [(Cbor.Cbor, Cbor.Cbor)] -> IO Cbor.Cbor+textField label fields = Cbor.encodeText label >>= require >>= (\encoded -> maybe (assertFailure "missing text header" >> fail "missing") pure (lookup encoded fields))++require :: (Show failure) => Either failure value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "unexpected failure") pure++addressSign :: Text+addressSign = "845882a301270458390025da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afeea7720de9531c195cf1199eb12318e7298f6c879557be3618af395de2676164647265737358390025da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afeea7720de9531c195cf1199eb12318e7298f6c879557be3618af395de2a166686173686564f443abc1235840cf4f8356899ef40f4c21869b50a3d5dc95414a8d3c1aae088b7518a65069cdf841331877c16f11f6a88bbfe402e8fbb338a5646ff2d931d5e955c6717cf1c404"++addressKey :: Text+addressKey = "a501010258390025da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afeea7720de9531c195cf1199eb12318e7298f6c879557be3618af395de20327200621582088cb67866b59520bffcfe9c421ef5d9e0db88815637796f597d3305126c8c78c"++hashSign :: Text+hashSign = "845829a201276761646472657373581c25da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afeea166686173686564f443abc1235840a079c58895a1da28dc4c696321b0d1649590acc9813a43aa0a0e172705326665aec54fbc0ce6dc2a6c1972f25d1c8ee8f36b169709afdebf057e929afc900306"++hashKey :: Text+hashKey = "a5010102581c25da282e083ccf77688d47a315a10d3f97d67ac6c0950833e0d6afee0327200621582088cb67866b59520bffcfe9c421ef5d9e0db88815637796f597d3305126c8c78c"
@@ -0,0 +1,265 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Native contract sources: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1+-- coin_selector.c, large_first_coin_selector.c, utxo_list.c and fee.c;+-- Apache-2.0. Cases use fresh typed public values and actual native dispatch.+module CoinSelection (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.CoinSelection as Selection+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.CoinSelection as Wire+import qualified Cometa.Internal.CoinSelection.Native as Native+import qualified Cometa.Internal.FFI.CoinSelection as FFI+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.NetworkId as Network+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, displayException, finally, throwIO, try)+import Control.Monad (forM_, replicateM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (newIORef, readIORef, writeIORef)+import Data.List (isInfixOf)+import qualified Fixtures.ProtocolParameters as Fixture+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Coin selection"+ [ testCase "direct checked selection and actual native callback agree" checkDispatch,+ testCase "preselected may be outside or identically overlap available" checkOverlap,+ testCase "request reference conflicts and target/parameter boundaries fail early" checkRequests,+ testCase "full selection accounting rejects dropped mandatory and changed snapshots" checkLaws,+ testCase "change minimum Ada uses actual native output sizing" checkMinimum,+ testCase "exact expected callback errors recover on the same runtime" checkErrors,+ testCase "exceptions and lazy callback results unwind all native owners" checkExceptions,+ testCase "malformed three-output replies release each partial output" checkPartial,+ testCase "retained runtime alias and repeated callbacks survive GC" checkRetained,+ testCase "reentrant selection fails fast with shared busy error" checkReentry,+ testCase "cancellation joins callback finalizer and releases registrations" checkCancellation,+ testProperty "generated full selections satisfy native dispatch and balance laws" propSelection+ ]++must :: (Show e) => Either e a -> IO a+must value = case value of+ Left failure -> assertFailure (show failure) >> fail "Invalid fixture"+ Right result -> pure result++fixture :: IO (Selection.SelectionRequest, Selection.Selection)+fixture = do+ params <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ txId <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ resolved ix amount = do+ out <- Output.mkOutput destination (Value.lovelace amount) Datum.NoDatum Nothing+ pure (Utxo.utxo (Input.input txId ix) out)+ mandatory <- must (resolved 0 3000000)+ candidate <- must (resolved 1 7000000)+ spare <- must (resolved 2 2000000)+ hint <- must (Output.mkOutput destination (Value.lovelace 1000000) Datum.NoDatum Nothing)+ change <- must (Output.mkOutput destination (Value.lovelace 4000000) Datum.NoDatum Nothing)+ request <- must (Selection.mkSelectionRequest (Selection.SelectionOptions [mandatory] [candidate, spare] (Value.lovelace 6000000) (Just [hint]) destination params))+ pure (request, Selection.Selection [mandatory, candidate] [spare] [change])++options :: Selection.SelectionRequest -> Selection.SelectionOptions+options request = Selection.SelectionOptions (Selection.preselected request) (Selection.available request) (Selection.target request) (Selection.outputHints request) (Selection.changeAddress request) (Selection.parameters request)++fixed :: Selection.Selection -> Selection.Selector+fixed result = Selection.Selector (\_ -> pure (Right result))++checkDispatch :: IO ()+checkDispatch = do+ (request, result) <- fixture+ let selector = Selection.Selector $ \observed -> do+ observed @?= request+ pure (Right result)+ Selection.select selector request >>= (@?= Right result)+ Native.invoke selector request >>= (@?= Right result)+ Wire.decodeRequest (Wire.encodeRequest request) @?= Right request+ Wire.decodeSelection (Wire.encodeSelection result) @?= Right result++checkOverlap :: IO ()+checkOverlap = do+ (request, result) <- fixture+ let raw = options request+ overlap <- must (Selection.mkSelectionRequest (raw {Selection.selectionAvailable = Selection.preselected request ++ Selection.available request}))+ Native.invoke (fixed result) overlap >>= (@?= Right result)+ Selection.validateSelection request result @?= Right ()+ Selection.validateSelection overlap result @?= Right ()++checkRequests :: IO ()+checkRequests = do+ (request, _) <- fixture+ let raw = options request+ mandatory = Selection.preselected request+ candidates = Selection.available request+ invalid = [raw {Selection.selectionPreselected = mandatory ++ mandatory}, raw {Selection.selectionAvailable = candidates ++ candidates}, raw {Selection.selectionTarget = Value.lovelace (negate (2 ^ (63 :: Int)) - 1)}, raw {Selection.selectionTarget = Value.lovelace (2 ^ (63 :: Int))}, raw {Selection.selectionParameters = (Selection.parameters request) {Parameters.parameterAdaPerUtxoByte = Nothing}}]+ forM_ invalid $ \value -> assertBool "invalid request accepted" (isLeft (Selection.mkSelectionRequest value))+ case mandatory of+ [original] -> do+ out <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 1) Datum.NoDatum Nothing)+ let conflicting = Utxo.utxo (Utxo.input original) out+ assertBool "conflicting overlap" (isLeft (Selection.mkSelectionRequest (raw {Selection.selectionAvailable = conflicting : candidates})))+ _ -> assertFailure "Unexpected mandatory fixture"++checkLaws :: IO ()+checkLaws = do+ (request, result) <- fixture+ let chosen = Selection.selected result+ invalid = [result {Selection.selected = chosen ++ chosen}, result {Selection.selected = drop 1 chosen}, result {Selection.remaining = []}, result {Selection.change = []}]+ forM_ invalid $ \value -> do+ assertBool "invalid pure law accepted" (isLeft (Selection.validateSelection request value))+ answer <- Native.invoke (fixed value) request+ assertBool "invalid callback result accepted" (isLeft answer)+ case chosen of+ first : rest -> do+ out <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 3000001) Datum.NoDatum Nothing)+ let changed = Utxo.utxo (Utxo.input first) out+ assertBool "changed input snapshot" (isLeft (Selection.validateSelection request (result {Selection.selected = changed : rest})))+ _ -> assertFailure "Missing selected fixture"++checkMinimum :: IO ()+checkMinimum = do+ (request, result) <- fixture+ tiny <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 1) Datum.NoDatum Nothing)+ tinyRequest <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionTarget = Value.lovelace 9999999}))+ let tinyResult = result {Selection.change = [tiny]}+ Selection.validateSelection tinyRequest tinyResult @?= Right ()+ Selection.select (fixed tinyResult) tinyRequest >>= \answer -> assertBool "underfunded change accepted" (isLeft answer)+ Native.invoke (fixed tinyResult) tinyRequest >>= \answer -> assertBool "native callback underfunded change accepted" (isLeft answer)+ zeroCost <- must (Selection.mkSelectionRequest ((options tinyRequest) {Selection.selectionParameters = (Selection.parameters request) {Parameters.parameterAdaPerUtxoByte = Just 0}}))+ Selection.select (fixed tinyResult) zeroCost >>= (@?= Right tinyResult)++checkErrors :: IO ()+checkErrors = do+ (request, result) <- fixture+ first <- newIORef True+ let failure = InvalidSelection "deterministic selector failure"+ selector = Selection.Selector $ \_ -> do+ failNow <- readIORef first+ writeIORef first False+ pure (if failNow then Left failure else Right result)+ answer <- Native.withSelector selector $ \runtime -> do+ Native.invokeWith runtime request >>= (@?= Left failure)+ Native.invokeWith runtime request+ answer @?= Right result++checkExceptions :: IO ()+checkExceptions = do+ (request, _) <- fixture+ baseline <- Runtime.liveContexts+ let thrown = Selection.Selector (\_ -> throwIO (userError "selector exploded"))+ lazy = Selection.Selector (\_ -> pure (Right (Selection.Selection [error "lazy selector output"] [] [])))+ forM_ [(thrown, "selector exploded"), (lazy, "lazy selector output")] $ \(selector, message) -> do+ result <- try (Native.invoke selector request) :: IO (Either SomeException (Either Error Selection.Selection))+ case result of+ Left failure -> assertBool "exception message lost" (message `isInfixOf` displayException failure)+ Right _ -> assertFailure "Callback exception did not propagate"+ Runtime.liveContexts >>= (@?= baseline)++checkPartial :: IO ()+checkPartial = do+ (request, _) <- fixture+ baseline <- Runtime.liveContexts+ -- First list allocated before second fails; both lists allocated before third+ -- fails; then a complete result with extra trailing bytes. Each must unwind.+ forM_ [B.pack [0x83, 0x80, 0xf6, 0x80], B.pack [0x83, 0x80, 0x80, 0xf6], B.pack [0x83, 0x80, 0x80, 0x80, 0]] $ \reply -> do+ answer <- Runtime.withRuntime (\_ _ -> pure (Right reply)) $ \runtime -> Runtime.withOperation runtime $ \context ->+ Runtime.withBytes (Wire.encodeRequest request) $ \bytes size -> Runtime.withOwnedBuffer "test.selector.partial" (FFI.cSelect context bytes size)+ assertBool "malformed reply accepted" (isLeft answer)+ Runtime.liveContexts >>= (@?= baseline)++checkRetained :: IO ()+checkRetained = do+ (request, result) <- fixture+ baseline <- Runtime.liveContexts+ answer <- Native.withSelector (fixed result) $ \original -> Runtime.withRetained original $ \alias -> do+ Runtime.close original >>= must+ replicateM_ 32 $ do+ performGC+ Native.invokeWith alias request >>= (@?= Right result)+ pure (Right result)+ answer @?= Right result+ Runtime.liveContexts >>= (@?= baseline)++checkReentry :: IO ()+checkReentry = do+ (request, result) <- fixture+ slot <- newEmptyMVar+ let selector = Selection.Selector $ \_ -> do+ runtime <- takeMVar slot+ putMVar slot runtime+ Native.invokeWith runtime request >>= (@?= Left RuntimeBusy)+ pure (Right result)+ answer <- Native.withSelector selector $ \runtime -> putMVar slot runtime >> Native.invokeWith runtime request+ answer @?= Right result++checkCancellation :: IO ()+checkCancellation = do+ (request, _) <- fixture+ baseline <- Runtime.liveContexts+ entered <- newEmptyMVar+ blocker <- newEmptyMVar+ finalized <- newEmptyMVar+ finished <- newEmptyMVar+ let selector = Selection.Selector $ \_ -> (putMVar entered () >> takeMVar blocker) `finally` putMVar finalized ()+ worker <- forkFinally (Native.invoke selector request) (putMVar finished)+ takeMVar entered+ killThread worker+ joined <- timeout 5000000 (takeMVar finished)+ case joined of+ Just (Left _) -> pure ()+ _ -> assertFailure "Cancellation did not join native selector unwind"+ timeout 5000000 (takeMVar finalized) >>= (@?= Just ())+ Runtime.liveContexts >>= (@?= baseline)++propSelection :: Property+propSelection = property $ do+ amount <- forAll (Gen.integral (Range.linear 1 100000000))+ (request, result) <- evalIO fixture+ case Selection.selected result of+ first : _ -> do+ output <- evalEither (Output.mkOutput (Selection.changeAddress request) (Value.lovelace amount) Datum.NoDatum Nothing)+ let utxo = Utxo.utxo (Utxo.input first) output+ exact <- evalEither (Selection.mkSelectionRequest ((options request) {Selection.selectionPreselected = [], Selection.selectionAvailable = [utxo], Selection.selectionTarget = Value.lovelace amount, Selection.selectionOutputHints = Nothing}))+ let answer = Selection.Selection [utxo] [] []+ selected <- evalIO (Native.invoke (fixed answer) exact) >>= evalEither+ selected === answer+ Selection.validateSelection exact selected === Right ()+ _ -> pure ()
@@ -0,0 +1,330 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Native raw collection operations checked against ordinary maps and lists.+-- These are original bounded generators, not normalized Value tests. The C+-- getter snapshots retain stored zero entries, duplicate names and empty policies.+-- Provenance: containers v0.6.7 Data.Map.Strict.Internal (BSD-3-Clause),+-- cardano-api c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a Value/Internal.hs+-- (Apache-2.0), and cardano-c a19dbc9185112ab2d7126c9c28058388a37bdccc+-- assets/{asset_id_map,asset_name_map,multi_asset}.c and common/withdrawal_map.c+-- (Apache-2.0). Upstream implementations are reviewed, not copied into this file.+module CollectionOperations (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Write as W+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as Name+import qualified Cometa.Encoding.Collections as Collections+import Cometa.Error (Error)+import qualified Cometa.PolicyId as Policy+import Control.Monad (forM_, replicateM, replicateM_)+import Data.Bifunctor (first, second)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.List (sortOn)+import qualified Data.List as List+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Gen, Property, classify, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++type Pairs = [(ByteString, Integer)]++data Snapshot = Flat Pairs [Integer] | Nested [(ByteString, Snapshot)] deriving (Eq, Show)++data Reply = Reply Snapshot Snapshot Snapshot (Maybe Bool) deriving (Eq, Show)++data Fixture = Fixture+ { names :: [Name.AssetName],+ identifiers :: [Asset.AssetId],+ policies :: [Policy.PolicyId],+ accounts :: [Reward.RewardAddress]+ }++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Raw collection operations"+ [ testCase "explicit zeros, duplicate first-match updates and clone independence" checkBoundaries,+ testCase "malformed requests release native owners and later calls recover" checkFailures,+ testProperty "asset-id maps correspond to zero-preserving host maps" propIds,+ testProperty "decoded asset-name maps retain duplicates and replace only the first match" propNames,+ testProperty "withdrawal insertion appends duplicate accounts rather than replacing" propWithdrawals,+ testProperty "nested raw multiasset maps retain empty policies and scoped arithmetic" propMulti+ ]++fixture :: Either Error Fixture+fixture = do+ short <- Name.fromBytes (B.singleton 255)+ long <- Name.fromBytes (B.pack [0, 0])+ zero <- Name.fromBytes (B.singleton 0)+ firstPolicy <- Policy.fromBytes (B.replicate 28 0)+ secondPolicy <- Policy.fromBytes (B.replicate 28 1)+ thirdPolicy <- Policy.fromBytes (B.replicate 28 2)+ addresses <- traverse Reward.fromBytes [B.cons 224 (B.replicate 28 0), B.cons 225 (B.replicate 28 1), B.cons 240 (B.replicate 28 2)]+ pure (Fixture [Name.empty, short, long, zero] [Asset.Ada, Asset.Native firstPolicy Name.empty, Asset.Native firstPolicy short, Asset.Native firstPolicy long, Asset.Native secondPolicy zero] [firstPolicy, secondPolicy, thirdPolicy] addresses)++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "Invalid fixture") pure++ordered :: Pairs -> Pairs+ordered = sortOn (\(key, _) -> (B.length key, key))++-- Native get returns the FIRST stored matching entry, including explicit zero.+flat :: Pairs -> Snapshot+flat pairs = Flat pairs [amount | (key, _) <- pairs, Just amount <- [lookup key pairs]]++mapBytes :: Pairs -> ByteString+mapBytes pairs = W.toStrictByteString (E.encodeMapLen (fromIntegral (length pairs)) <> foldMap (\(key, amount) -> E.encodeBytes key <> E.encodeInteger amount) pairs)++idBytes :: Asset.AssetId -> Either Error ByteString+idBytes Asset.Ada = Right B.empty+idBytes value = Asset.toBytes value++idPairs :: [(Asset.AssetId, Integer)] -> Either Error Pairs+idPairs = traverse (\(asset, amount) -> (,) <$> idBytes asset <*> pure amount)++-- Ordering for native indexed access is byte length then bytes, not Ord AssetId.+idState :: [(Asset.AssetId, Integer)] -> Either Error Pairs+idState values = ordered <$> idPairs (Map.toList (Map.fromList values))++namePairs :: [(Name.AssetName, Integer)] -> Pairs+namePairs = map (first Name.toBytes)++-- A first-occurrence association-list replacement keeps all later duplicates.+replaceFirst :: ByteString -> Integer -> Pairs -> Pairs+replaceFirst key amount values = case break ((== key) . fst) values of+ (before, []) -> ordered (before <> [(key, amount)])+ (before, _ : after) -> before <> [(key, amount)] <> after++updates :: Pairs -> Pairs -> Pairs+updates = List.foldl' (\values (key, amount) -> replaceFirst key amount values)++-- Copying lhs through insert makes its final occurrence win. Each rhs entry+-- then contributes once; arithmetic removes zero results but ordinary inserts do+-- not. Integer expectations cannot overflow the bounded native input ranges.+arithmetic :: Integer -> Pairs -> Pairs -> Pairs+arithmetic sign left right = ordered (Map.toList (Map.filter (/= 0) (Map.unionWith (+) (Map.fromList left) (Map.fromListWith (+) [(key, sign * amount) | (key, amount) <- right]))))++flatExpected :: Int -> Int -> Pairs -> Pairs -> Reply+flatExpected kind operation left right = Reply (flat result) (flat left) (flat right) equal+ where+ result = case operation of+ 1 | kind == 2 -> ordered (left <> right)+ 1 -> updates left right+ 2 -> arithmetic 1 left right+ 3 -> arithmetic (-1) left right+ _ -> left+ equal = if kind == 2 then Nothing else Just (result == right)++signedEntries :: (Show key) => [key] -> Gen [(key, Integer)]+signedEntries keys = Gen.list (Range.linear 0 12) ((,) <$> Gen.element keys <*> amount)+ where+ amount = Gen.frequency [(2, pure 0), (8, Gen.integral (Range.linear (-1000) 1000))]++propIds :: Property+propIds = property $ do+ f <- evalEither fixture+ left <- forAll (signedEntries (identifiers f))+ right <- forAll (signedEntries (identifiers f))+ rawLeft <- evalEither (idPairs left)+ rawRight <- evalEither (idPairs right)+ storedLeft <- evalEither (idState left)+ storedRight <- evalEither (idState right)+ classify "stored zero" (any ((== 0) . snd) storedLeft)+ classify "replacement" (length left > Map.size (Map.fromList left))+ forM_ [0 .. 3] $ \operation -> do+ actual <- evalIO (native 0 operation (mapBytes rawLeft) (mapBytes rawRight)) >>= evalEither+ actual === flatExpected 0 operation storedLeft storedRight++propNames :: Property+propNames = property $ do+ f <- evalEither fixture+ left <- forAll (signedEntries (names f))+ right <- forAll (signedEntries (names f))+ leftBytes <- evalEither (Collections.encodeAssetNamesCbor left)+ rightBytes <- evalEither (Collections.encodeAssetNamesCbor right)+ let storedLeft = ordered (namePairs left)+ storedRight = ordered (namePairs right)+ classify "duplicate names" (length left > Map.size (Map.fromList left))+ forM_ [0 .. 3] $ \operation -> do+ actual <- evalIO (native 1 operation leftBytes rightBytes) >>= evalEither+ actual === flatExpected 1 operation storedLeft storedRight++propWithdrawals :: Property+propWithdrawals = property $ do+ f <- evalEither fixture+ left <- forAll (Gen.list (Range.linear 0 12) ((,) <$> Gen.element (accounts f) <*> Gen.word64 (Range.linear 0 1000000)))+ right <- forAll (Gen.list (Range.linear 0 12) ((,) <$> Gen.element (accounts f) <*> Gen.word64 (Range.linear 0 1000000)))+ let stored values = ordered [(Reward.toBytes account, toInteger amount) | (account, amount) <- values]+ classify "duplicate reward accounts" (length left > Map.size (Map.fromList left))+ forM_ [0, 1] $ \operation -> do+ actual <- evalIO (native 2 operation (Collections.encodeWithdrawalsCbor left) (Collections.encodeWithdrawalsCbor right)) >>= evalEither+ actual === flatExpected 2 operation (stored left) (stored right)++type Policies = Map ByteString Pairs++multiBytes :: [(Policy.PolicyId, [(Name.AssetName, Integer)])] -> Either Error ByteString+multiBytes values = do+ encoded <- traverse (\(policy, entries) -> (\bytes -> E.encodeBytes (Policy.toBytes policy) <> E.encodePreEncoded bytes) <$> Collections.encodeAssetNamesCbor entries) values+ pure (W.toStrictByteString (E.encodeMapLen (fromIntegral (length values)) <> mconcat encoded))++multiState :: [(Policy.PolicyId, [(Name.AssetName, Integer)])] -> Policies+multiState values = Map.fromList [(Policy.toBytes policy, ordered (namePairs entries)) | (policy, entries) <- values]++multiSnapshot :: Policies -> Snapshot+multiSnapshot = Nested . map (second flat) . Map.toList++multiExpected :: Int -> Policies -> Policies -> Reply+multiExpected operation left right = Reply (multiSnapshot result) (multiSnapshot left) (multiSnapshot right) (Just (result == right))+ where+ result = case operation of+ 1 -> Map.union right left+ 2 -> Map.filter (not . null) (List.foldl' (combine 1) left (Map.toList right))+ 3 -> Map.filter (not . null) (List.foldl' (combine (-1)) left (Map.toList right))+ 4 -> List.foldl' set left (Map.toList right)+ _ -> left+ combine sign current (policy, values) = Map.alter (Just . maybe (if sign == 1 then values else arithmetic sign [] values) (\previous -> arithmetic sign previous values)) policy current+ set current (_, []) = current+ set current (policy, values) = Map.alter (Just . (`updates` values) . fromMaybe []) policy current++propMulti :: Property+propMulti = property $ do+ f <- evalEither fixture+ let generate = Gen.list (Range.linear 0 5) ((,) <$> Gen.element (policies f) <*> signedEntries (names f))+ left <- forAll generate+ right <- forAll generate+ leftBytes <- evalEither (multiBytes left)+ rightBytes <- evalEither (multiBytes right)+ let storedLeft = multiState left+ storedRight = multiState right+ classify "stored empty policy" (any null (Map.elems storedLeft))+ classify "outer duplicate replacement" (length left > Map.size storedLeft)+ forM_ [0 .. 4] $ \operation -> do+ actual <- evalIO (native 3 operation leftBytes rightBytes) >>= evalEither+ actual === multiExpected operation storedLeft storedRight++checkBoundaries :: IO ()+checkBoundaries = do+ f <- must fixture+ name <- must (Name.fromBytes (B.singleton 97))+ let duplicate = [(name, 1), (name, 0), (name, 3)]+ replacement = [(name, 7)]+ left <- must (Collections.encodeAssetNamesCbor duplicate)+ right <- must (Collections.encodeAssetNamesCbor replacement)+ actual <- native 1 1 left right >>= must+ actual @?= flatExpected 1 1 (namePairs duplicate) (namePairs replacement)+ added <- native 1 2 left (mapBytes []) >>= must+ added @?= flatExpected 1 2 (namePairs duplicate) []+ -- Both signed endpoints are legal stored quantities; no arithmetic is run on+ -- endpoint pairs because unchecked native add/subtract can overflow int64.+ forM_ [toInteger (minBound :: Int64), toInteger (maxBound :: Int64)] $ \amount -> do+ bytes <- must (Collections.encodeAssetNamesCbor [(name, amount)])+ result <- native 1 0 bytes bytes >>= must+ result @?= flatExpected 1 0 [(Name.toBytes name, amount)] [(Name.toBytes name, amount)]+ account <- case accounts f of+ value : _ -> pure value+ [] -> assertFailure "missing account fixture" >> fail "fixture"+ let withdrawals = [(account, 0), (account, maxBound :: Word64)]+ entries = [(Reward.toBytes account, 0), (Reward.toBytes account, toInteger (maxBound :: Word64))]+ reply <- native 2 1 (Collections.encodeWithdrawalsCbor withdrawals) (Collections.encodeWithdrawalsCbor [(account, 1)]) >>= must+ reply @?= flatExpected 2 1 entries [(Reward.toBytes account, 1)]+ policy <- case policies f of+ value : _ -> pure value+ [] -> assertFailure "missing policy fixture" >> fail "fixture"+ emptyPolicy <- must (multiBytes [(policy, [])])+ absentPolicy <- must (multiBytes [])+ zeros <- must (multiBytes [(policy, [(name, 0)])])+ forM_ [(emptyPolicy, absentPolicy, False), (zeros, emptyPolicy, False), (emptyPolicy, emptyPolicy, True)] $ \(a, b, equal) -> do+ Reply _ _ _ observedEqual <- native 3 0 a b >>= must+ observedEqual @?= Just equal++checkFailures :: IO ()+checkFailures = do+ forM_ [0 .. 3] $ \kind -> do+ forM_ [B.empty, B.singleton 128, B.pack [161, 64, 128], B.pack [160, 0]] $ \invalid ->+ replicateM_ 3 (native kind 0 invalid (B.singleton 160) >>= assertBool "invalid collection accepted" . isLeft)+ native kind 0 (B.singleton 160) (B.singleton 160) >>= must >>= \reply ->+ reply @?= if kind == 3 then Reply (Nested []) (Nested []) (Nested []) (Just True) else flatExpected kind 0 [] []++-- The test wire uses cborg only to expose native getter snapshots; expected+-- states are calculated by ordinary Haskell maps/lists before native execution.+native :: Int -> Int -> ByteString -> ByteString -> IO (Either String Reply)+native kind operation left right = B.useAsCStringLen left $ \(a, aSize) -> B.useAsCStringLen right $ \(b, bSize) ->+ allocaBytes 65536 $ \output -> alloca $ \size -> do+ code <- cOperation (fromIntegral kind) (fromIntegral operation) (castPtr a) (fromIntegral aSize) (castPtr b) (fromIntegral bSize) output 65536 size+ if code /= 0+ then pure (Left ("native collection status " <> show code))+ else do+ count <- peek size+ bytes <- B.packCStringLen (castPtr output, fromIntegral count)+ pure $ case R.deserialiseFromBytes (replyDecoder kind) (L.fromStrict bytes) of+ Left failure -> Left (show failure)+ Right (rest, value) | L.null rest -> Right value+ Right _ -> Left "Trailing native snapshot bytes"++replyDecoder :: Int -> D.Decoder s Reply+replyDecoder kind = do+ size <- D.decodeListLen+ if size /= 4 then fail "Expected collection reply" else Reply <$> snapshotDecoder kind <*> snapshotDecoder kind <*> snapshotDecoder kind <*> optionalBool++optionalBool :: D.Decoder s (Maybe Bool)+optionalBool = do+ token <- D.peekTokenType+ if token == D.TypeNull then D.decodeNull >> pure Nothing else Just <$> D.decodeBool++snapshotDecoder :: Int -> D.Decoder s Snapshot+snapshotDecoder 3 = do+ count <- D.decodeMapLen+ Nested <$> replicateM count ((,) <$> D.decodeBytes <*> snapshotDecoder 1)+snapshotDecoder _ = do+ arity <- D.decodeListLen+ if arity /= 2+ then fail "Expected raw map snapshot"+ else do+ count <- D.decodeMapLen+ pairs <- replicateM count ((,) <$> D.decodeBytes <*> D.decodeInteger)+ lookups <- D.decodeListLen >>= (`replicateM` D.decodeInteger)+ pure (Flat pairs lookups)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_collection_operation"+ cOperation :: CUInt -> CUInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt
@@ -0,0 +1,156 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module Collections (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Write as W+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetName as Name+import qualified Cometa.Crypto.Blake2b as Hash+import qualified Cometa.Encoding.Collections as Collections+import Cometa.Encoding.Set (SetEncoding (..))+import Cometa.Error (Error (..))+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.Word (Word8)+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Property, evalEither, evalIO, forAll, property, tripping, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Standalone collections"+ [ testCase "asset names preserve duplicates, zero, stable byte order and signed bounds" checkNames,+ testCase "withdrawals preserve empty, zero, duplicates and full unsigned bounds" checkWithdrawals,+ testCase "variable hash lengths, duplicate retention and tag choices" checkHashes,+ testCase "indefinite containers and bytes agree with native" checkIndefinite,+ testCase "malformed, wrong type, oversized and trailing CBOR fail" checkFailures,+ testProperty "asset-name quantities round trip including signed extremes" propNames+ ]++checkNames :: IO ()+checkNames = do+ short <- expectRight (Name.fromBytes (B.singleton 255))+ long <- expectRight (Name.fromBytes (B.pack [0, 0]))+ let pairs = [(long, 3), (short, 0), (Name.empty, toInteger (minBound :: Int64)), (short, -1), (Name.empty, toInteger (maxBound :: Int64))]+ ordered = [(Name.empty, toInteger (minBound :: Int64)), (Name.empty, toInteger (maxBound :: Int64)), (short, 0), (short, -1), (long, 3)]+ encoded <- expectRight (Collections.encodeAssetNamesCbor pairs)+ Collections.decodeAssetNamesCbor encoded @?= Right ordered+ native 0 encoded >>= (@?= Just encoded)+ Collections.encodeAssetNamesCbor [] @?= Right (B.singleton 160)+ forM_ [toInteger (minBound :: Int64) - 1, toInteger (maxBound :: Int64) + 1] $ \amount ->+ Collections.encodeAssetNamesCbor [(Name.empty, amount)] @?= Left (InvalidValueQuantity amount)++checkWithdrawals :: IO ()+checkWithdrawals = do+ first <- expectRight (Reward.fromBytes (B.cons 224 (B.replicate 28 0)))+ lastAccount <- expectRight (Reward.fromBytes (B.cons 241 (B.replicate 28 0)))+ let entries = [(lastAccount, maxBound), (first, 0), (first, 1)]+ encoded = Collections.encodeWithdrawalsCbor entries+ Collections.decodeWithdrawalsCbor encoded @?= Right [(first, 0), (first, 1), (lastAccount, maxBound)]+ native 1 encoded >>= (@?= Just encoded)+ Collections.decodeWithdrawalsCbor (B.singleton 160) @?= Right []+ native 1 (Collections.encodeWithdrawalsCbor []) >>= (@?= Just (B.singleton 160))++checkHashes :: IO ()+checkHashes = do+ short <- expectRight (Hash.fromBytes (B.singleton 255))+ long <- expectRight (Hash.fromBytes (B.pack [0, 0]))+ huge <- expectRight (Hash.fromBytes (B.replicate 65 1))+ let hashes = [huge, long, short, short]+ expected = [short, short, long, huge]+ encoded = Collections.encodeHashesCbor hashes+ Collections.decodeHashesCbor encoded @?= Right expected+ native 2 encoded >>= (@?= Just encoded)+ let untagged = Collections.encodeHashesCborWith UntaggedSet hashes+ Collections.decodeHashesCbor untagged @?= Right expected+ native 2 untagged >>= (@?= Just encoded)+ Collections.encodeHashesCborWith TaggedSet hashes @?= encoded+ Collections.decodeHashesCbor (Collections.encodeHashesCbor []) @?= Right []+ native 2 (Collections.encodeHashesCbor []) >>= (@?= Just (Collections.encodeHashesCbor []))++checkIndefinite :: IO ()+checkIndefinite = do+ let names = B.pack [191, 95, 65, 255, 255, 0, 255]+ hashes = B.pack [159, 65, 255, 255]+ withdrawals = B.pack [191, 255]+ decodedNames <- expectRight (Collections.decodeAssetNamesCbor names)+ encodedNames <- expectRight (Collections.encodeAssetNamesCbor decodedNames)+ native 0 names >>= (@?= Just encodedNames)+ decodedHashes <- expectRight (Collections.decodeHashesCbor hashes)+ native 2 hashes >>= (@?= Just (Collections.encodeHashesCbor decodedHashes))+ decodedWithdrawals <- expectRight (Collections.decodeWithdrawalsCbor withdrawals)+ native 1 withdrawals >>= (@?= Just (Collections.encodeWithdrawalsCbor decodedWithdrawals))++checkFailures :: IO ()+checkFailures = do+ forM_ [B.empty, B.pack [128], B.pack [161, 0, 0], W.toStrictByteString (E.encodeMapLen 1 <> E.encodeBytes (B.replicate 33 0) <> E.encodeInt 0), W.toStrictByteString (E.encodeMapLen 1 <> E.encodeBytes B.empty <> E.encodeInteger (2 ^ (63 :: Int)))] $ \bytes -> do+ assertBool "Haskell rejects malformed names" (isLeft (Collections.decodeAssetNamesCbor bytes))+ native 0 bytes >>= (@?= Nothing)+ forM_ [B.pack [161, 64, 0], W.toStrictByteString (E.encodeMapLen 1 <> E.encodeBytes (B.cons 224 (B.replicate 28 0)) <> E.encodeInt (-1)), W.toStrictByteString (E.encodeMapLen 1 <> E.encodeBytes (B.cons 224 (B.replicate 28 0)) <> E.encodeInteger (2 ^ (64 :: Int)))] $ \bytes -> do+ assertBool "Haskell rejects malformed withdrawals" (isLeft (Collections.decodeWithdrawalsCbor bytes))+ native 1 bytes >>= (@?= Nothing)+ forM_ [B.pack [159, 95, 65, 255, 255, 255], B.pack [129, 64], B.pack [216, 1, 128], B.pack [129, 0], B.pack [161, 0, 0]] $ \bytes -> do+ assertBool "Haskell rejects malformed hashes" (isLeft (Collections.decodeHashesCbor bytes))+ native 2 bytes >>= (@?= Nothing)+ assertBool "names reject trailing bytes" (isLeft (Collections.decodeAssetNamesCbor (B.pack [160, 0])))+ assertBool "withdrawals reject trailing bytes" (isLeft (Collections.decodeWithdrawalsCbor (B.pack [160, 0])))+ assertBool "hashes reject trailing bytes" (isLeft (Collections.decodeHashesCbor (B.pack [128, 0])))++propNames :: Property+propNames = property $ do+ amounts <- forAll (Gen.list (Range.linear 0 20) (Gen.int64 Range.constantBounded))+ let pairs = [(Name.empty, toInteger amount) | amount <- amounts]+ tripping pairs Collections.encodeAssetNamesCbor (>>= Collections.decodeAssetNamesCbor)+ encoded <- evalEither (Collections.encodeAssetNamesCbor pairs)+ actual <- evalIO (native 0 encoded)+ actual === Just encoded++expectRight :: (Show e) => Either e a -> IO a+expectRight = either (\problem -> assertFailure (show problem) >> fail "unreachable") pure++native :: CInt -> ByteString -> IO (Maybe ByteString)+native kind bytes = B.useAsCStringLen bytes $ \(input, size) ->+ allocaArray 8192 $ \output -> alloca $ \written -> do+ result <- cRoundtrip kind (castPtr input) (fromIntegral size) output 8192 written+ if result /= 0+ then pure Nothing+ else do+ count <- peek written+ Just <$> B.packCStringLen (castPtr output, fromIntegral count)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_collection_roundtrip"+ cRoundtrip :: CInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt
@@ -0,0 +1,221 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Complete address-family fixtures, boundaries and native reconstruction.+module CompleteAddress (tests) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Byron as Byron+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Control.Monad (forM_, replicateM_)+import Data.Bits (xor)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.Text (Text)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word32, Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+ testGroup+ "Complete addresses"+ [ testCase "Byron types, payload64 and magicInt64 boundaries reconstruct natively" checkByron,+ testCase "pointer key/script networks and uint32 boundaries reconstruct natively" checkPointer,+ testCase "CIP19 Byron and pointer fixtures match typed public assembly" checkPinned,+ testCase "generic address family dispatch preserves exact bytes and text" checkGeneric,+ testCase "Byron nonminimal and indefinite framing retains exact bytes" checkExact,+ testCase "Byron CRC/CBOR/attributes/Base58 and pointer invalid forms reject" checkInvalid,+ testCase "repeated native getter reconstruction releases every owner" (replicateM_ 50 (checkByron >> checkPointer)),+ testCase "standalone credential CBOR checks kinds, lengths and framing" credentialCbor,+ testProperty "generated Byron attributes and kinds reconstruct natively" propByron,+ testProperty "generated pointer components reconstruct natively" propPointer+ ]++byron :: Word8 -> Byron.AddressType -> Maybe ByteString -> Maybe Word64 -> Either Error Byron.Address+byron seed kind payload magic = do+ root <- Byron.rootFromBytes (B.replicate 28 seed)+ attrs <- Byron.attributes payload magic+ pure (Byron.address root attrs kind)++pointer :: Word8 -> Integer -> Bool -> Word32 -> Word32 -> Word32 -> Either Error Shelley.Address+pointer seed network script slot tx cert = do+ net <- Shelley.mkNetworkId network+ credential <-+ if script+ then Credential.ScriptCredential <$> Credential.scriptHashFromBytes (B.replicate 28 seed)+ else Credential.KeyCredential <$> Credential.keyHashFromBytes (B.replicate 28 seed)+ pure (Shelley.pointer net credential (Shelley.StakePointer slot tx cert))++checkByron :: IO ()+checkByron = forM_ [minBound .. maxBound] $ \kind ->+ forM_ [Nothing, Just B.empty, Just (B.replicate 64 7)] $ \payload ->+ forM_ [Nothing, Just 0, Just 42, Just (fromIntegral (maxBound :: Int64))] $ \magic -> do+ value <- require (byron 3 kind payload magic)+ Byron.fromBytes (Byron.toBytes value) @?= Right value+ Byron.fromText (Byron.toText value) @?= Right value+ native 0 (Byron.toBytes value) (Byron.toText value) >>= assertBool "native Byron agrees"++checkPointer :: IO ()+checkPointer = forM_ [0 .. 15] $ \network ->+ forM_ [False, True] $ \script ->+ forM_ [0, 127, 128, 16383, 16384, maxBound] $ \component -> do+ value <- require (pointer 9 network script component component component)+ Shelley.fromBytes (Shelley.toBytes value) @?= Right value+ Shelley.fromText (Shelley.toText value) @?= Right value+ native 1 (Shelley.toBytes value) (Shelley.toText value) >>= assertBool "native pointer agrees"++checkPinned :: IO ()+checkPinned = do+ digest <- require (hexBytes "ba970ad36654d8dd8f74274b733452ddeab9a62a397746be3c42ccdd" >>= Byron.rootFromBytes)+ attrs <- require (Byron.attributes Nothing Nothing)+ let value = Byron.address digest attrs Byron.PublicKey+ Byron.toText value @?= "Ae2tdPwUPEZFRbyhz3cpfC2CumGzNkFBN2L42rcUc2yjQpEkxDbkPodpMAi"+ forM_ ["addr1gx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer5pnz75xxcrzqf96k", "addr128phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtupnz75xxcrtw79hu"] $ \text -> do+ decoded <- require (Shelley.fromText text)+ location <- case Shelley.pointerRef decoded of+ Nothing -> assertFailure "expected pointer" >> fail "unreachable"+ Just result -> pure result+ let rebuilt = Shelley.pointer (Shelley.networkId decoded) (Shelley.paymentCredential decoded) location+ Shelley.toText rebuilt @?= text+ native 1 (Shelley.toBytes rebuilt) text >>= assertBool "CIP19 pointer native reconstruction"++checkGeneric :: IO ()+checkGeneric = do+ bootstrap <- require (byron 1 Byron.Redeem Nothing (Just 42))+ payment <- require (pointer 2 15 True 128 0 maxBound)+ stake <- require (Credential.keyHashFromBytes (B.replicate 28 3))+ let reward = Reward.fromCredential Shelley.testnet (Credential.KeyCredential stake)+ values = [Address.ByronAddress bootstrap, Address.ShelleyAddress payment, Address.RewardAddress reward]+ forM_ values $ \value -> do+ Address.fromBytes (Address.toBytes value) @?= Right value+ Address.fromText (Address.toText value) @?= Right value++checkExact :: IO ()+checkExact = do+ value <- require (byron 1 Byron.PublicKey Nothing Nothing)+ let bytes = Byron.toBytes value+ nonminimal = B.pack [0x98, 2] <> B.drop 1 bytes+ indefinite = B.singleton 0x9f <> B.drop 1 bytes <> B.singleton 0xff+ forM_ [nonminimal, indefinite] $ \encoded -> do+ decoded <- require (Byron.fromBytes encoded)+ Byron.toBytes decoded @?= encoded+ Byron.root decoded @?= Byron.root value+ Byron.addressAttributes decoded @?= Byron.addressAttributes value+ Byron.fromText (Byron.toText decoded) @?= Right decoded++checkInvalid :: IO ()+checkInvalid = do+ forM_ malformedByron $ \hex -> do+ bytes <- require (hexBytes hex)+ assertBool "invalid Byron payload rejected" (isLeft (Byron.fromBytes bytes))+ value <- require (byron 0 Byron.PublicKey Nothing Nothing)+ let bytes = Byron.toBytes value+ assertBool "CRC mismatch" (isLeft (Byron.fromBytes (B.init bytes <> B.singleton (B.last bytes `xor` 1))))+ assertBool "trailing Byron bytes" (isLeft (Byron.fromBytes (bytes <> B.singleton 0)))+ forM_ ["", "0", "O", "I", "l", " Ae2td", Text.replicate 513 "1"] $ \text -> assertBool "invalid Base58" (isLeft (Byron.fromText text))+ assertBool "root length" (isLeft (Byron.rootFromBytes (B.replicate 27 0)))+ assertBool "path payload65" (isLeft (Byron.attributes (Just (B.replicate 65 0)) Nothing))+ assertBool "magic aboveInt64" (isLeft (Byron.attributes Nothing (Just maxBound)))+ let header = B.singleton 0x40 <> B.replicate 28 0+ forM_ [B.empty, B.pack [0, 0], B.pack [0, 0, 0, 0], B.pack [0x80, 0, 0, 0], B.pack [0x90, 0x80, 0x80, 0x80, 0, 0, 0], B.replicate 6 0xff] $ \payload ->+ assertBool "invalid/truncated/nonminimal/overflow pointer" (isLeft (Shelley.fromBytes (header <> payload)))+ forM_ [0, 1] $ \kind -> native kind (B.singleton 0) "" >>= (@?= False)++propByron :: Property+propByron = property $ do+ seed <- forAll (Gen.word8 Range.constantBounded)+ kind <- forAll Gen.enumBounded+ payload <- forAll (Gen.maybe (Gen.bytes (Range.linear 0 64)))+ magic <- forAll (Gen.maybe (Gen.word64 (Range.linear 0 (fromIntegral (maxBound :: Int64)))))+ value <- evalEither (byron seed kind payload magic)+ parsed <- evalEither (Byron.fromBytes (Byron.toBytes value))+ parsed === value+ agreement <- evalIO (native 0 (Byron.toBytes value) (Byron.toText value))+ agreement === True++propPointer :: Property+propPointer = property $ do+ seed <- forAll (Gen.word8 Range.constantBounded)+ network <- forAll (Gen.integral (Range.linear 0 15))+ script <- forAll Gen.bool+ slot <- forAll (Gen.word32 Range.constantBounded)+ tx <- forAll (Gen.word32 Range.constantBounded)+ cert <- forAll (Gen.word32 Range.constantBounded)+ value <- evalEither (pointer seed network script slot tx cert)+ parsed <- evalEither (Shelley.fromBytes (Shelley.toBytes value))+ parsed === value+ agreement <- evalIO (native 1 (Shelley.toBytes value) (Shelley.toText value))+ agreement === True++hexBytes :: Text -> Either Error ByteString+hexBytes = maybe (Left InvalidHex) Right . Hex.decodeHex++require :: Either Error a -> IO a+require value = case value of+ Left failure -> assertFailure (show failure) >> fail "unreachable"+ Right result -> pure result++native :: CUInt -> ByteString -> Text -> IO Bool+native kind bytes text = B.useAsCStringLen bytes $ \(input, size) ->+ B.useAsCStringLen (Text.encodeUtf8 text) $ \(rendered, textSize) ->+ (/= 0) <$> cAgree kind (castPtr input) (fromIntegral size) (castPtr rendered) (fromIntegral textSize)++foreign import ccall unsafe "cometa_test_complete_address_agree"+ cAgree :: CUInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CInt++-- CIP19 constants above are imported from cardano-c pin+-- eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/address/cip19_test_vectors.h (Apache-2.0).+-- Invalid payload fixtures below were independently generated with Python zlib+-- CRC32, so failures reach inner semantic validation after a valid outer CRC.+malformedByron :: [Text]+malformedByron =+ [ "82d818582083581b000000000000000000000000000000000000000000000000000000a0001a0ebb62f2",+ "82d818582183581c00000000000000000000000000000000000000000000000000000000a0031a477eeddb",+ "82d818582483581c00000000000000000000000000000000000000000000000000000000a1034100001a6ec81c59",+ "82d818582783581c00000000000000000000000000000000000000000000000000000000a2024100024100001a1c4df8b7",+ "82d818586783581c00000000000000000000000000000000000000000000000000000000a101584358410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001a789e6cea",+ "82d818582c83581c00000000000000000000000000000000000000000000000000000000a102491b8000000000000000001accf143b1",+ "82d818582583581c00000000000000000000000000000000000000000000000000000000a102420000001aef0e489f",+ "82d818582283581c00000000000000000000000000000000000000000000000000000000a000001ae869c9ff"+ ]++credentialCbor :: IO ()+credentialCbor = do+ key <- require (Credential.keyHashFromBytes (B.replicate 28 7))+ script <- require (Credential.scriptHashFromBytes (B.replicate 28 8))+ forM_ [Credential.KeyCredential key, Credential.ScriptCredential script] $ \credential -> do+ let encoded = Credential.encodeCbor credential+ (Credential.decodeCbor encoded :: Either Error (Credential.Credential Credential.Payment)) @?= Right credential+ (Credential.decodeCbor (B.singleton 0x9f <> B.drop 1 encoded <> B.singleton 0xff) :: Either Error (Credential.Credential Credential.Payment)) @?= Right credential+ forM_ [B.empty, B.pack [0x82, 2, 0x58, 28] <> B.replicate 28 0, B.pack [0x82, 0, 0x41, 0], B.pack [0x82, 0, 0x58, 28] <> B.replicate 28 0 <> B.singleton 0] $ \bytes ->+ assertBool "invalid credential rejected" (isLeft (Credential.decodeCbor bytes :: Either Error (Credential.Credential Credential.Payment)))
@@ -0,0 +1,137 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Offline execution of the same recipes used by the connected C++ ports.+-- Fixture conservation/signature checks do not establish ledger registration state.+module ConnectedGovernance (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.NetworkId as Network+import qualified Cometa.Script as Script+import qualified Cometa.Transaction as Transaction+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as TransactionId+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified DRepPubkey as Governance (drepKey)+import qualified DRepScript as Governance (drepScript)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified DeferredWithdrawZero as Governance (withdrawZero)+import qualified DonateToTreasury as Governance (donate)+import qualified Fixtures.TransactionWorkflows as Native+import qualified Fixtures.Workflow as Fixture+import qualified ProposeTreasuryWithdrawal as Governance (treasury)+import qualified RewardAccountPubkey as Governance (rewardKey)+import qualified RewardAccountScript as Governance (rewardScript)+import qualified Support.Governance as Governance+import qualified Support.Scripts as Scripts+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase)+import qualified VoteForProposalPubkey as Governance (voteKey)+import qualified VoteForProposalScript as Governance (voteScript)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Connected governance recipes"+ [ testCase "key reward registration and cleanup" (execute 2 $ \context fixture -> pool >>= Governance.rewardKey context (Fixture.stakeCredential fixture)),+ testCase "V2 reward registration and cleanup" (execute 2 $ \context _ -> pool >>= Governance.rewardScript context),+ testCase "canonical deferred zero withdrawal" (execute 2 $ \context _ -> pool >>= Governance.withdrawZero context),+ testCase "key DRep delegation and both cleanups" (execute 4 $ \context fixture -> Governance.drepKey context (Fixture.drepCredential fixture) (Fixture.stakeCredential fixture)),+ testCase "reference-sourced V3 DRep delegation and both cleanups" (execute 4 $ \context fixture -> reference context >>= \source -> Governance.drepScript context source (Fixture.stakeCredential fixture)),+ testCase "key DRep vote and cleanup" (execute 3 $ \context fixture -> action >>= Governance.voteKey context (Fixture.drepCredential fixture)),+ testCase "V3 DRep vote and cleanup" (execute 3 $ \context _ -> do source <- reference context; proposal <- action; Governance.voteScript context source proposal),+ testCase "two ADA donation" (execute 1 $ \context _ -> Governance.donate context),+ testCase "treasury proposal preserves reference input" treasury,+ testCase "wrong constitution hash fails before submission" wrongHash,+ testCase "public script discovery has both reward identities" discovery+ ]++pool :: IO (Credential.KeyHash Credential.StakePool)+pool = must (Credential.keyHashFromBytes (B.replicate 28 10))++action :: IO ActionId.ActionId+action = do+ identifier <- must (TransactionId.fromBytes (B.replicate 32 11))+ pure (ActionId.ActionId identifier 0)++-- This reference is used only as a resolved source of the exact compiled V3+-- program, matching the C++ DRep/vote examples' addScript workflow.+reference :: Native.Context -> IO Utxo.Utxo+reference context = do+ script <- Scripts.alwaysSucceedsV3 >>= must+ output <- must (Output.mkOutput (Native.wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just (Script.Plutus script)))+ identifier <- must (TransactionId.fromBytes (B.replicate 32 12))+ pure (Utxo.utxo (Input.input identifier 0) output)++execute :: Int -> (Native.Context -> Fixture.Fixture -> IO (Either Error a)) -> IO ()+execute expected operation = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ _ <- ExceptT (operation context fixture)+ history <- ExceptT (Right <$> Fixture.submitted fixture)+ except (unless (length history == expected) (Left (InvalidBuildingRequest "Unexpected connected workflow stage count")))+ _ <- must result+ pure ()++treasury :: IO ()+treasury = execute 2 $ \context fixture -> runExceptT $ do+ source <- ExceptT (Right <$> reference context)+ funded <- ExceptT (Native.runStage context (Plan.payTo (Utxo.output source)))+ identifier <- ExceptT (Transaction.transactionId funded)+ let actual = Utxo.utxo (Input.input identifier 0) (Utxo.output source)+ account = Reward.fromCredential Network.testnet (Fixture.stakeCredential fixture)+ script <- except (maybe (Left (InvalidBuildingRequest "Missing reference script")) Right (Output.referenceScript (Utxo.output actual)))+ hash <- ExceptT (Script.hash script)+ transaction <- ExceptT (Governance.treasury context account actual hash 1000)++ let references = Fields.fieldReferenceInputs (Body.bodyFields (Body.toBody (Transaction.body transaction)))+ except $+ unless (references == Just [Utxo.input actual]) $+ Left (InvalidBuildingRequest "Constitution reference input was not preserved")++wrongHash :: IO ()+wrongHash = do+ result <- Fixture.withFixture $ \context fixture -> do+ source <- reference context+ hash <- must (Credential.scriptHashFromBytes (B.replicate 28 0))+ attempt <- Governance.treasury context (Reward.fromCredential Network.testnet (Fixture.stakeCredential fixture)) source hash 1000+ history <- Fixture.submitted fixture+ pure (Right (isLeft attempt && null history))+ must result >>= assertBool "mismatched constitution must fail before submission"++discovery :: IO ()+discovery = do+ identities <- Governance.describeScripts Network.testnet >>= must+ accounts <- must (traverse (Reward.fromText . snd) identities)+ assertBool "both script accounts" (map fst identities == ["reward-script", "withdraw-zero-script"] && not (any (B.null . Reward.toBytes) accounts))++must :: (Show failure) => Either failure value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure
@@ -0,0 +1,261 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module ContextualTransaction (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.AssetId as AssetId+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Governance.ActionId as Action+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.ContextualTransaction as Internal+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as PlutusData+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.SubTransaction.Indices as SubIndices+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Authority as Authority+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Value+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified Data.Set as Set+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Contextual transaction utilities"+ [ testCase "withdrawal, voter and redeemer ranks match native ledger order" lookupRanks,+ testCase "subtransaction primitive positions and empty collections" subPrimitives,+ testCase "certificate comparison uses native canonical data and exact rational components" certificates,+ testCase "top-level direct required keys exclude scripts and nested levels" authorities,+ testCase "invalid resolution and malformed transports are total on repeated calls" failures+ ]++key :: Word8 -> IO (Credential.KeyHash purpose)+key = require . Credential.keyHashFromBytes . B.replicate 28++script :: Word8 -> IO Credential.ScriptHash+script = require . Credential.scriptHashFromBytes . B.replicate 28++identifier :: Word8 -> IO TxId.TransactionId+identifier = require . TxId.fromBytes . B.replicate 32++rankFixture :: IO (Tx.Transaction, Sub.SubTransaction, [Reward.RewardAddress], [Voting.Voter])+rankFixture = do+ hash <- key 1+ scriptHash <- script 9+ alias <- require (Network.mkNetworkId 2)+ let rewards =+ [ Reward.fromCredential Network.testnet (Credential.KeyCredential hash),+ Reward.fromCredential Network.testnet (Credential.ScriptCredential scriptHash),+ Reward.fromCredential Network.mainnet (Credential.ScriptCredential scriptHash),+ Reward.fromCredential alias (Credential.KeyCredential hash)+ ]+ committee <- key 0+ drep <- key 1+ pool <- key 0+ let voters = [Voting.CommitteeVoter (Credential.KeyCredential committee), Voting.CommitteeVoter (Credential.ScriptCredential scriptHash), Voting.DRepVoter (Credential.KeyCredential drep), Voting.DRepVoter (Credential.ScriptCredential scriptHash), Voting.StakePoolVoter pool]+ txId <- identifier 0+ withdrawals <- require (Fields.mkEntries (zip rewards [1 ..]))+ votes <- require (Voting.fromList ([(voter, Action.ActionId txId 0, Voting.VotingProcedure Voting.Yes Nothing) | voter <- voters] ++ [(headVoter committee, Action.ActionId txId 1, Voting.VotingProcedure Voting.No Nothing)]))+ let fields = (Fields.fields [] []) {Fields.fieldWithdrawals = Just withdrawals, Fields.fieldVotingProcedures = Just votes}+ argument = PlutusData.fromData (PlutusData.Integer 0)+ redeemers = [Redeemer.Redeemer Redeemer.Voting 0 argument (ExUnits 0 0), Redeemer.Redeemer Redeemer.Spending 3 argument (ExUnits 0 0), Redeemer.Redeemer Redeemer.Spending 1 argument (ExUnits 0 0)]+ witnesses <- require (Witnesses.mkWitnesses [] [] [] [] redeemers)+ body <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = fields})+ subBody <- require (SubBody.fromBody (SubBody.fromFields fields))+ pure (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing, Sub.assemble subBody (Witnesses.fromWitnesses witnesses) Nothing, rewards, voters)+ where+ headVoter = Voting.CommitteeVoter . Credential.KeyCredential++lookupRanks :: IO ()+lookupRanks = do+ (transaction, sub, rewards, voters) <- rankFixture+ forM_ (zip rewards [1, 0, 3, 1]) $ \(reward, expected) -> do+ Indices.findWithdrawal reward transaction @?= Just expected+ SubIndices.findWithdrawal reward sub @?= Just expected+ native transaction 0 (Reward.toBytes reward) 0 >>= (@?= Just expected)+ forM_ (zip voters [1, 0, 3, 2, 4]) $ \(voter, expected) -> do+ Indices.findVote voter transaction @?= Just expected+ SubIndices.findVote voter sub @?= Just expected+ native transaction 1 (Voting.encodeVoter voter) 0 >>= (@?= Just expected)+ forM_ [(Redeemer.Spending, 1, Just 0), (Redeemer.Spending, 3, Just 1), (Redeemer.Voting, 0, Just 2), (Redeemer.Guarding, 0, Nothing)] $ \(purpose, index, expected) -> do+ let target = Evaluation.RedeemerId purpose index+ Indices.findRedeemer target transaction @?= expected+ SubIndices.findRedeemer target sub @?= expected+ native transaction 2 (B.singleton (fromIntegral (fromEnum purpose))) (fromIntegral index) >>= (@?= expected)+ missing <- key 55+ Indices.findWithdrawal (Reward.fromCredential Network.mainnet (Credential.KeyCredential missing)) transaction @?= Nothing+ missingVoter <- key 55+ Indices.findVote (Voting.CommitteeVoter (Credential.KeyCredential missingVoter)) transaction @?= Nothing++subPrimitives :: IO ()+subPrimitives = do+ txId <- identifier 0+ policy <- require (Policy.fromBytes (B.replicate 28 4))+ destination <- require (Address.fromBytes (B.cons 0x60 (B.replicate 28 1)))+ output <- require (Output.mkOutput destination (Value.lovelace 5) Datum.NoDatum Nothing)+ mint <- require (Fields.mkMint (Value.singleton (AssetId.Native policy AssetName.empty) 1))+ let reference = Input.input txId 1+ fields = (Fields.fields [Input.input txId 9, reference] [output]) {Fields.fieldReferenceInputs = Just [reference], Fields.fieldMint = Just mint}+ body <- require (SubBody.fromBody (SubBody.fromFields fields))+ let sub = Sub.assemble body (Witnesses.fromWitnesses Witnesses.empty) Nothing+ SubIndices.findInput reference sub @?= Just 0+ SubIndices.findReferenceInput reference sub @?= Just 0+ SubIndices.findOutput destination 5 sub @?= Just 0+ SubIndices.findOutput destination 6 sub @?= Nothing+ SubIndices.findMintPolicy policy sub @?= Just 0+ cert <- key 1+ let certificate = Certificate.fromCertificate (Certificate.StakeDeregistration (Credential.KeyCredential cert))+ SubIndices.findCertificate certificate sub >>= (@?= Right Nothing)+ SubIndices.findWithdrawal (Reward.fromCredential Network.testnet (Credential.KeyCredential cert)) sub @?= Nothing+ SubIndices.findRedeemer (Evaluation.RedeemerId Redeemer.Spending 0) sub @?= Nothing++-- Native pool certificates retain numerator/denominator components, whereas+-- public semantic equality compares their rational value. Preserve this distinction.+poolCertificate :: Word64 -> Word64 -> ByteString+poolCertificate numerator denominator =+ Cbor.encode $+ E.encodeListLen 10+ <> E.encodeWord 3+ <> E.encodeBytes (B.replicate 28 1)+ <> E.encodeBytes (B.replicate 32 2)+ <> E.encodeWord 0+ <> E.encodeWord 0+ <> E.encodeTag 30+ <> E.encodeListLen 2+ <> E.encodeWord64 numerator+ <> E.encodeWord64 denominator+ <> E.encodeBytes (B.cons 0xe0 (B.replicate 28 3))+ <> E.encodeTag 258+ <> E.encodeListLen 0+ <> E.encodeListLen 0+ <> E.encodeNull++certificates :: IO ()+certificates = do+ certificate <- require (Certificate.decodeCbor (poolCertificate 2 4))+ reduced <- require (Certificate.decodeCbor (poolCertificate 1 2))+ Certificate.toCertificate certificate @?= Certificate.toCertificate reduced+ deregistration <- key 4+ let semantic = Certificate.StakeDeregistration (Credential.KeyCredential deregistration)+ canonical = Certificate.fromCertificate semantic+ nonminimal = B.pack [0x9f, 0x18, 1] <> B.drop 2 (Certificate.toCbor canonical) <> B.singleton 0xff+ candidates = Cbor.encode (E.encodeTag 258 <> E.encodeListLen 3 <> Cbor.raw (poolCertificate 2 4) <> Cbor.raw nonminimal <> Cbor.raw (Certificate.toCbor canonical))+ txBytes = Cbor.encode (E.encodeListLen 4 <> E.encodeMapLen 4 <> E.encodeWord 0 <> E.encodeListLen 0 <> E.encodeWord 1 <> E.encodeListLen 0 <> E.encodeWord 2 <> E.encodeWord 0 <> E.encodeWord 4 <> Cbor.raw candidates <> E.encodeMapLen 0 <> E.encodeBool True <> E.encodeNull)+ transaction <- require (Tx.decodeCbor txBytes)+ subBody <- require (SubBody.decodeCbor (Cbor.encode (E.encodeMapLen 3 <> E.encodeWord 0 <> E.encodeListLen 0 <> E.encodeWord 1 <> E.encodeListLen 0 <> E.encodeWord 4 <> Cbor.raw candidates)))+ let sub = Sub.assemble subBody (Tx.witnesses transaction) Nothing+ forM_ [(certificate, Just 0), (reduced, Nothing), (canonical, Just 1)] $ \(target, expected) -> do+ Indices.findCertificate target transaction >>= (@?= Right expected)+ SubIndices.findCertificate target sub >>= (@?= Right expected)+ native transaction 3 (Certificate.toCbor target) 0 >>= (@?= expected)+ Tx.encodeCbor transaction @?= txBytes++authorityFixture :: IO (Tx.Transaction, [Utxo.Utxo])+authorityFixture = do+ txId <- identifier 0+ payment <- require (Address.fromBytes (B.cons 0x60 (B.replicate 28 1)))+ collateral <- require (Address.fromBytes (B.cons 0x60 (B.replicate 28 2)))+ out <- require (Output.mkOutput payment (Value.lovelace 1) Datum.NoDatum Nothing)+ collateralOut <- require (Output.mkOutput collateral (Value.lovelace 1) Datum.NoDatum Nothing)+ guard <- key 3+ withdrawal <- key 4+ cert <- key 5+ voter <- key 6+ nativeKey <- key 7+ nested <- key 8+ scriptHash <- script 9+ withdrawals <- require (Fields.mkEntries [(Reward.fromCredential Network.testnet (Credential.KeyCredential withdrawal), 1)])+ votes <- require (Voting.fromList [(Voting.DRepVoter (Credential.KeyCredential voter), Action.ActionId txId 0, Voting.VotingProcedure Voting.Yes Nothing)])+ let input = Input.input txId 0+ collateralInput = Input.input txId 1+ referenceInput = Input.input txId 2+ fields = (Fields.fields [input] []) {Fields.fieldGuards = Just [Credential.KeyCredential guard, Credential.ScriptCredential scriptHash], Fields.fieldWithdrawals = Just withdrawals, Fields.fieldCertificates = Just (Certificates.fromList [Certificate.StakeDeregistration (Credential.KeyCredential cert)]), Fields.fieldVotingProcedures = Just votes, Fields.fieldReferenceInputs = Just [referenceInput]}+ subFields = (Fields.fields [] []) {Fields.fieldGuards = Just [Credential.KeyCredential nested]}+ subBody <- require (SubBody.fromBody (SubBody.fromFields subFields))+ let sub = Sub.assemble subBody (Witnesses.fromWitnesses Witnesses.empty) Nothing+ body <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = fields, Body.bodyCollateral = Just [collateralInput], Body.bodySubTransactions = Just [sub]})+ witnesses <- require (Witnesses.mkWitnesses [] [] [Script.Native (NativeScript.signature nativeKey)] [] [])+ pure (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing, [Utxo.utxo input out, Utxo.utxo collateralInput collateralOut])++authorities :: IO ()+authorities = do+ (transaction, resolved) <- authorityFixture+ expected <- Set.fromList <$> traverse (require . Blake2b.fromBytes . B.replicate 28) [1 .. 6]+ actual <- Authority.requiredKeyHashes transaction resolved >>= require+ actual @?= expected+ assertBool "result hashes have 28 bytes" (all ((== 28) . B.length . Blake2b.toBytes) actual)+ replicateM_ 20 (Authority.requiredKeyHashes transaction resolved >>= (@?= Right expected))++failures :: IO ()+failures = do+ (transaction, resolved) <- authorityFixture+ Authority.requiredKeyHashes transaction [] >>= assertBool "missing spending/collateral resolution" . isLeft+ Authority.requiredKeyHashes transaction (resolved ++ resolved) >>= assertBool "duplicate resolution" . isLeft+ replicateM_ 20 $ do+ Internal.runRequiredKeys (B.singleton 0) (B.singleton 0x80) >>= assertBool "partial transaction parse" . isLeft+ Internal.runRequiredKeys (Tx.encodeCbor transaction) (B.pack [0x81, 0]) >>= assertBool "partial UTxO parse" . isLeft++require :: (Show error) => Either error value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "invalid fixture") pure++native :: Tx.Transaction -> CUInt -> ByteString -> Word64 -> IO (Maybe Word64)+native transaction operation keyBytes argument =+ B.useAsCStringLen (Tx.encodeCbor transaction) $ \(bytes, size) ->+ B.useAsCStringLen keyBytes $ \(keyData, keySize) -> alloca $ \result -> do+ status <- cIndex (castPtr bytes) (fromIntegral size) operation (castPtr keyData) (fromIntegral keySize) argument result+ if status == 0 then Just <$> peek result else (status @?= 9) >> pure Nothing++foreign import ccall unsafe "cometa_test_contextual_index"+ cIndex :: Ptr Word8 -> CSize -> CUInt -> Ptr Word8 -> CSize -> Word64 -> Ptr Word64 -> IO CUInt
@@ -0,0 +1,368 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Offline native deferred-argument registration, resolution and lifetime tests.+module DeferredRedeemer (tests, fixture, scriptFixture) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionPlan as InternalPlan+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Deferred as Deferred+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Exception (SomeException, displayException, throw, try)+import Control.Monad (replicateM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (elemIndex, isInfixOf, sort)+import Data.Word (Word64)+import qualified Fixtures.ProtocolParameters as Fixture+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Deferred redeemers"+ [ testCase "query adapters match raw callbacks through native balancing and cleanup" querySpending,+ testCase "canonical spending index and selected snapshots survive repeated balances" spending,+ testCase "native VM accepts the resolved late mint argument" nativeMinting,+ testCase "one policy group mints several assets with one redeemer" minting,+ testCase "withdrawal and certificate callbacks share one balanced draft" otherPurposes,+ testCase "empty and net-zero mint groups never evaluate their callbacks" emptyMint,+ testCase "duplicate and mixed registrations fail before callbacks" conflicts,+ testCase "typed failures and lazy exceptions preserve identity and cleanup" failures,+ testCase "cancellation of a pure callback restores registration baseline" cancellation,+ testCase "deferred plans obey observational monoid laws" laws+ ]++must :: (Show e) => Either e a -> IO a+must = either (\e -> assertFailure (show e) >> fail "fixture") pure++fixture :: IO (Builder.Config, Output.Output, Utxo.Utxo)+fixture = do+ raw <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ previous <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ params =+ raw+ { P.parameterMinFeeA = 0,+ P.parameterMinFeeB = 0,+ P.parameterMaxTxSize = 16384,+ P.parameterMaxValueSize = Just 5000,+ P.parameterAdaPerUtxoByte = Just 4310,+ P.parameterProtocolVersion = Version.ProtocolVersion 10 0,+ P.parameterCollateralPercentage = Just 150,+ P.parameterMaxCollateralInputs = Just 3,+ P.parameterKeyDeposit = 2000000,+ P.parameterMaxTxExUnits = Just (ExUnits 10000000 10000000000)+ }+ funding <- must (Output.mkOutput destination (Value.lovelace 10000000) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput destination (Value.lovelace 2000000) Datum.NoDatum Nothing)+ let utxo = Utxo.utxo (Input.input previous 0) funding+ config =+ (Builder.defaultConfig params Slot.preview destination)+ { Builder.availableUtxos = [utxo],+ Builder.minimumFee = 200000+ }+ pure (config, output, utxo)++scriptFixture :: IO (Builder.Config, Output.Output, Utxo.Utxo, Script.Script)+scriptFixture = do+ (config, output, wallet) <- fixture+ script <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V2 (B.pack [1, 2, 3]))+ model <- must (Models.mkCostModel 1 (replicate 175 0))+ hash <- Script.hash script >>= must+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.ScriptCredential hash))+ datum = Data.fromData (Data.Integer 42)+ locked <- must (Output.mkOutput destination (Value.lovelace 10000000) (Datum.InlineDatum datum) Nothing)+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateralOutput <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ let evaluator = Evaluation.Evaluator $ \_ tx _ ->+ pure+ ( Evaluation.mkBudgets+ [(Evaluation.RedeemerId (Redeemer.purpose r) (Redeemer.index r), ExUnits 100 200) | r <- redeemers tx]+ )+ configured =+ config+ { Builder.availableUtxos = [],+ Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateralOutput],+ Builder.evaluator = Just evaluator,+ Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model])}+ }+ pure (configured, output, Utxo.utxo (Utxo.input wallet) locked, script)++redeemers :: Tx.Transaction -> [Redeemer.Redeemer]+redeemers = Witnesses.redeemers . Witnesses.toWitnesses . Tx.witnesses++spending :: IO ()+spending = do+ baseline <- Runtime.liveContexts+ (config, output, input, script) <- scriptFixture+ precedingId <- must (Id.fromBytes (B.replicate 32 1))+ precedingOutput <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 3000000) Datum.NoDatum Nothing)+ let preceding = Utxo.utxo (Input.input precedingId 0) precedingOutput+ callback tx inputs = do+ let canonical = Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body tx)))+ if map Utxo.input inputs /= sort canonical+ then Left (InvalidTransactionPlan "Deferred inputs are not selected canonical snapshots")+ else case elemIndex (Utxo.input input) canonical of+ Nothing -> Left (InvalidTransactionPlan "Required spending input disappeared")+ Just index -> Right (Data.fromData (Data.Constr 0 [Data.Integer (toInteger index)]))+ plan = Plan.spendWithDeferredRedeemer input callback Nothing <> Plan.spend preceding <> Plan.attachScript script <> Plan.payTo output+ replicateM_ 3 $ do+ tx <- Builder.build config plan >>= must+ let expected = case elemIndex (Utxo.input input) (Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body tx)))) of+ Nothing -> Nothing+ Just index -> Just (Data.fromData (Data.Constr 0 [Data.Integer (toInteger index)]))+ map Redeemer.index (redeemers tx) @?= [1]+ map (Just . Redeemer.argument) (redeemers tx) @?= [expected]+ Runtime.liveContexts >>= (@?= baseline)++minting :: IO ()+minting = do+ (config, output, locked, script) <- scriptFixture+ funding <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 10000000) Datum.NoDatum Nothing)+ let input = Utxo.utxo (Utxo.input locked) funding+ hash <- Script.hash script >>= must+ policy <- must (Policy.fromBytes (Credential.scriptHashBytes hash))+ second <- must (AssetName.fromBytes (B.singleton 1))+ calls <- newIORef (0 :: Int)+ let argument = Data.fromData (Data.Integer 123)+ checked = Evaluation.Evaluator $ \_ tx _ -> do+ modifyIORef' calls (+ 1)+ map Redeemer.argument (redeemers tx) @?= [argument]+ pure (Evaluation.mkBudgets [(Evaluation.RedeemerId Redeemer.Minting 0, ExUnits 100 200)])+ plan =+ Plan.spend input+ <> Plan.payTo output+ <> Plan.attachScript script+ <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 2), (second, 3)] (\_ _ -> Right argument)+ tx <- Builder.build config {Builder.evaluator = Just checked} plan >>= must+ map Redeemer.argument (redeemers tx) @?= [argument]+ let outputs = foldMap Output.value (Fields.fieldOutputs (Body.bodyFields (Body.toBody (Tx.body tx))))+ Value.quantity (Asset.Native policy AssetName.empty) outputs @?= 2+ Value.quantity (Asset.Native policy second) outputs @?= 3+ count <- readIORef calls+ assertBool "no balancing evaluation" (count > 0)++otherPurposes :: IO ()+otherPurposes = do+ (config, output, locked, script) <- scriptFixture+ funding <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 10000000) Datum.NoDatum Nothing)+ let input = Utxo.utxo (Utxo.input locked) funding+ hash <- Script.hash script >>= must+ let credential = Credential.ScriptCredential hash+ reward = Reward.fromCredential Network.testnet credential+ cert = Certificate.StakeDeregistration credential+ callback tag tx _ = Right (Data.fromData (Data.Constr tag [Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body tx))))]))+ plan =+ Plan.spend input+ <> Plan.payTo output+ <> Plan.attachScript script+ <> Plan.withdrawWithDeferredRedeemer reward 0 (callback 1)+ <> Plan.certificateWithDeferredRedeemer cert (callback 2)+ tx <- Builder.build config plan >>= must+ map Redeemer.purpose (redeemers tx) @?= [Redeemer.Certifying, Redeemer.Rewarding]+ let fee = Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body tx))))+ map Redeemer.argument (redeemers tx) @?= [Data.fromData (Data.Constr 2 [fee]), Data.fromData (Data.Constr 1 [fee])]++emptyMint :: IO ()+emptyMint = do+ (config, output, _) <- fixture+ policy <- must (Policy.fromBytes (B.replicate 28 1))+ let never _ _ = throw (userError "unused deferred callback")+ payment = Plan.payTo output+ empty = Plan.mintWithDeferredRedeemer policy [] never+ zero = Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 5), (AssetName.empty, -5)] never+ ordinary <- Builder.build config payment >>= must+ Builder.build config (payment <> empty <> zero) >>= (@?= Right ordinary)++conflicts :: IO ()+conflicts = do+ (config, output, input, script) <- scriptFixture+ hash <- Script.hash script >>= must+ policy <- must (Policy.fromBytes (Credential.scriptHashBytes hash))+ let argument = Data.fromData (Data.Integer 1)+ callback _ _ = Right argument+ deferred = Plan.spendWithDeferredRedeemer input callback Nothing+ minted = Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] callback+ reward = Reward.fromCredential Network.testnet (Credential.ScriptCredential hash)+ withdrawal = Plan.withdrawWithDeferredRedeemer reward 0 callback+ plans =+ [ deferred <> deferred,+ deferred <> Plan.spend input,+ minted <> minted,+ minted <> Plan.mint (Asset.Native policy AssetName.empty) 1,+ withdrawal <> withdrawal+ ]+ mapM_ (\plan -> Builder.build config (plan <> Plan.payTo output) >>= assertBool "conflict accepted" . isLeft) plans++failures :: IO ()+failures = do+ baseline <- Runtime.liveContexts+ (config, output, input, script) <- scriptFixture+ let plan callback = Plan.spendWithDeferredRedeemer input callback Nothing <> Plan.payTo output <> Plan.attachScript script+ expected = InvalidTransactionPlan "deferred callback refused draft"+ Builder.build config (plan (\_ _ -> Left expected)) >>= (@?= Left expected)+ let lazyFailure _ _ = Right (Data.fromData (Data.List [Data.Integer (throw (userError "lazy deferred payload"))]))+ outcome <- try (Builder.build config (plan lazyFailure))+ case outcome of+ Left (failure :: SomeException) -> assertBool "lazy exception lost" ("lazy deferred payload" `isInfixOf` displayException failure)+ Right result -> assertFailure ("lazy exception returned normally: " <> show result)+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ baseline <- Runtime.liveContexts+ (config, output, input, script) <- scriptFixture+ let never _ _ = Right (Data.fromData (Data.Integer (sum [1 ..])))+ plan = Plan.spendWithDeferredRedeemer input never Nothing <> Plan.payTo output <> Plan.attachScript script+ outcome <- timeout 200000 (Builder.build config plan)+ outcome @?= Nothing+ Runtime.liveContexts >>= (@?= baseline)++{-# ANN laws ("HLint: ignore Monoid law, left identity" :: String) #-}+{-# ANN laws ("HLint: ignore Monoid law, right identity" :: String) #-}+laws :: IO ()+laws = do+ (_, _, input, _) <- scriptFixture+ let callback _ _ = Right (Data.fromData (Data.Integer 1))+ x = Plan.spendWithDeferredRedeemer input callback Nothing+ y = Plan.validFrom 10 <> Plan.spendWithDeferredRedeemer input (\_ _ -> Right (Data.fromData (Data.Integer 2))) Nothing+ z = Plan.spendWithDeferredRedeemer input (\_ _ -> Right (Data.fromData (Data.Integer 3))) Nothing <> Plan.validUntil 100+ observe = InternalPlan.encodePlan 0+ observe ((x <> y) <> z) @?= observe (x <> (y <> z))+ observe (mempty <> x) @?= observe x+ observe (x <> mempty) @?= observe x++nativeMinting :: IO ()+nativeMinting = do+ (config, output, _) <- fixture+ script <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ hash <- Plutus.hash script >>= must+ model <- must (Models.mkCostModel 3 (replicate 369 100))+ collateralId <- must (Id.fromBytes (B.replicate 32 9))+ collateral <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ let policy = Policy.fromScriptHash hash+ params =+ (Builder.parameters config)+ { P.parameterProtocolVersion = Version.ProtocolVersion 12 0,+ P.parameterCostModels = Just (Models.fromList [model]),+ P.parameterMaxTxExUnits = Just (ExUnits 100000000 100000000000)+ }+ configured =+ config+ { Builder.parameters = params,+ Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateral]+ }+ callback tx _ = Right (Data.fromData (Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body tx))))))+ plan =+ Plan.payTo output+ <> Plan.attachScript (Script.Plutus script)+ <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] callback+ tx <- Builder.build configured plan >>= must+ let expected = Data.fromData (Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body tx)))))+ map Redeemer.argument (redeemers tx) @?= [expected]+ assertBool "native evaluator left zero budgets" (all ((/= ExUnits 0 0) . Redeemer.executionUnits) (redeemers tx))++-- Compiles the query/explicit-encoder workflow shown in transaction-building.md+-- and compares it at the native builder boundary with the raw callback contract.+querySpending :: IO ()+querySpending = do+ baseline <- Runtime.liveContexts+ (config, output, input, script) <- scriptFixture+ precedingId <- must (Id.fromBytes (B.replicate 32 1))+ precedingOutput <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 3000000) Datum.NoDatum Nothing)+ let preceding = Utxo.utxo (Input.input precedingId 0) precedingOutput+ encodePositions :: (Word64, Word64) -> Data.PlutusData+ encodePositions (inputIndex, outputIndex) = Data.Constr 0 [Data.Integer (toInteger inputIndex), Data.Integer (toInteger outputIndex)]+ positions = (,) <$> Deferred.inputIndex (Utxo.input input) <*> Deferred.outputIndex output+ checkedPositions = do+ transaction <- Deferred.draft+ selected <- Deferred.selectedInputs+ let canonical = Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body transaction)))+ Deferred.fromEither $+ if map Utxo.input selected == sort canonical+ then Right ()+ else Left (InvalidBuildingRequest "Query selected-input snapshot differs from draft")+ positions+ adapted = Deferred.redeemer encodePositions checkedPositions+ raw transaction selected = do+ let fields = Body.bodyFields (Body.toBody (Tx.body transaction))+ canonical = Fields.fieldInputs fields+ if map Utxo.input selected == sort canonical+ then Right ()+ else Left (InvalidBuildingRequest "Query selected-input snapshot differs from draft")+ inputIndex <- maybe (Left (InvalidBuildingRequest "Raw input missing")) Right (elemIndex (Utxo.input input) canonical)+ outputIndex <- case [index | (index, candidate) <- zip [0 :: Int ..] (Fields.fieldOutputs fields), candidate == output] of+ [index] -> Right index+ _ -> Left (InvalidBuildingRequest "Raw output missing or ambiguous")+ pure (Data.fromData (encodePositions (fromIntegral inputIndex, fromIntegral outputIndex)))+ plan callback = Plan.spendWithDeferredRedeemer input callback Nothing <> Plan.spend preceding <> Plan.attachScript script <> Plan.payTo output+ rawTransaction <- Builder.build config (plan raw) >>= must+ replicateM_ 3 $ do+ adaptedTransaction <- Builder.build config (plan adapted) >>= must+ Tx.encodeCbor adaptedTransaction @?= Tx.encodeCbor rawTransaction+ redeemers adaptedTransaction @?= redeemers rawTransaction+ map Redeemer.index (redeemers adaptedTransaction) @?= [1]+ map Redeemer.argument (redeemers adaptedTransaction) @?= [Data.fromData (encodePositions (1, 0))]+ Runtime.liveContexts >>= (@?= baseline)+ let expected = InvalidBuildingRequest "Deferred query refused draft"+ rejected = Deferred.redeemer Data.Integer (Deferred.fromEither (Left expected))+ Builder.build config (plan rejected) >>= (@?= Left expected)+ Runtime.liveContexts >>= (@?= baseline)+ missingId <- must (Id.fromBytes (B.replicate 32 99))+ let missing = Deferred.redeemer (Data.Integer . toInteger) (Deferred.inputIndex (Input.input missingId 0))+ Builder.build config (plan missing) >>= (@?= Left (InvalidBuildingRequest "Deferred spending input is missing"))+ Runtime.liveContexts >>= (@?= baseline)
@@ -0,0 +1,244 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module DerivationPath (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32 as Bip32+import qualified Cometa.Crypto.Bip32.PrivateKey as Private+import qualified Cometa.Crypto.Bip32.PublicKey as Public+import qualified Cometa.Crypto.DerivationPath as Path+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import Control.Monad (when)+import Data.Bits ((.|.))+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import Data.Word (Word32, Word64, Word8)+import qualified Fixtures.Bip32 as Fixture+import Foreign.C.Types (CInt (..), CUInt (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (allocaArray, peekArray, withArray)+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, assert, evalEither, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Derivation paths"+ [ testCase "all CIP-1852 constants match native headers" checkConstants,+ testCase "account paths agree with real software-handler struct consumption" checkHandlerAccount,+ testCase "component bounds preserve exact invalid input" checkBounds,+ testCase "maximum raw fields encode without wraparound" checkMaximumEncoding,+ testCase "standard, multisig, governance and custom paths match native keys" checkNativePaths,+ testCase "public derivation helpers preserve vectors, passwords and snapshots" checkPublicHelpers,+ testCase "public derivation helpers preserve invalid entropy errors" checkHelperErrors,+ testProperty "bounded components agree with validated construction" propBounded,+ testProperty "encoding and inspection preserve arbitrary valid components" propEncoding+ ]++checkConstants :: IO ()+checkConstants = allocaArray 9 $ \output -> do+ cConstants output+ values <- peekArray 9 output+ values+ @?= map+ Path.indexValue+ [ Path.cardanoCoinType,+ Path.standardPurpose,+ Path.multisigPurpose,+ Path.externalRole,+ Path.internalRole,+ Path.stakingRole,+ Path.drepRole,+ Path.committeeColdRole,+ Path.committeeHotRole+ ]++checkBounds :: IO ()+checkBounds = do+ mapM_+ (\value -> Path.mkIndex value @?= Left (InvalidDerivationIndex value))+ [-(2 ^ (100 :: Int)), -1, 2147483648, 4294967295, 4294967296, 18446744073709551615, 2 ^ (100 :: Int)]+ mapM_+ (\value -> fmap Path.indexValue (Path.mkIndex value) @?= Right (fromInteger value))+ [0, 1, 2147483647]++checkMaximumEncoding :: IO ()+checkMaximumEncoding = do+ let maximumIndex = maxBound+ prefix = Path.accountPath maximumIndex maximumIndex maximumIndex+ path = Path.derivationPath prefix maximumIndex maximumIndex++ Path.toIndices path @?= [0xffffffff, 0xffffffff, 0xffffffff, 0x7fffffff, 0x7fffffff]++checkNativePaths :: IO ()+checkNativePaths =+ mapM_+ checkNativePath+ ([[1852, 1815, 0, role, 0] | role <- [0 .. 5]] ++ [[1854, 1815, 7, 0, 42], [123, 456, 789, 17, 29], replicate 5 2147483647])++checkNativePath :: [Integer] -> IO ()+checkNativePath components = case traverse Path.mkIndex components of+ Right [purpose, coin, account, role, index] -> do+ let prefix = Path.accountPath purpose coin account+ path = Path.derivationPath prefix role index+ expected <- nativePublic components False+ expectedAccount <- nativePublic components True+ actual <- require $ Private.withKeyHex Fixture.privateHex $ \root ->+ Private.withDerived root (Path.toIndices path) Private.publicKey+ Public.toBytes actual @?= expected+ accountPublic <- require $ Private.withKeyHex Fixture.privateHex $ \root ->+ Private.withDerived root (Path.accountIndices prefix) Private.publicKey+ Public.toBytes accountPublic @?= expectedAccount+ relative <- require (Public.derive accountPublic (Path.relativeIndices path))+ relative @?= actual+ when (purpose == Path.standardPurpose && coin == Path.cardanoCoinType) $+ Path.standardAccountPath account @?= prefix+ _ -> assertFailure "invalid test components"++nativePublic :: [Integer] -> Bool -> IO ByteString.ByteString+nativePublic components accountOnly = case Hex.decodeHex Fixture.privateHex of+ Nothing -> assertFailure "invalid fixture" >> pure ByteString.empty+ Just bytes -> ByteString.useAsCString bytes $ \input ->+ withArray (map fromInteger components) $ \values -> allocaBytes 64 $ \output -> do+ status <- cPublic (castPtr input) values (if accountOnly then 1 else 0) output+ status @?= 0+ ByteString.packCStringLen (castPtr output, 64)++checkHandlerAccount :: IO ()+checkHandlerAccount = do+ entropy <-+ maybe (fail "invalid fixture entropy") pure $+ Hex.decodeHex "387183ffe785d467ab662c01acbcf79400e2430dde6c9aee74cf0602de0d82e8"+ mapM_ (checkHandlerPrefix entropy) [[1852, 1815, 0], [1854, 1815, 7], [123, 456, 789], replicate 3 2147483647]++checkHandlerPrefix :: ByteString.ByteString -> [Integer] -> IO ()+checkHandlerPrefix entropy values = do+ components <- either (fail . show) pure (traverse Path.mkIndex values)+ case components of+ [purpose, coin, account] -> do+ let prefix = Path.accountPath purpose coin account+ actual <- require $ Private.withEntropy ByteString.empty entropy $ \root ->+ Private.withDerived root (Path.accountIndices prefix) Private.publicKey+ expected <- ByteString.useAsCString entropy $ \input ->+ withArray (map fromInteger values) $ \raw -> allocaBytes 64 $ \output -> do+ status <- cHandlerAccount (castPtr input) raw output+ status @?= 0+ ByteString.packCStringLen (castPtr output, 64)+ Public.toBytes actual @?= expected+ helper <- require (Bip32.deriveAccountPublicKey ByteString.empty entropy prefix)+ Public.toBytes helper @?= expected+ when (values == [1852, 1815, 0]) $+ Public.toHex actual @?= "1b39889a420374e41917cf420d88a84d9b40d7eeef533ac37f323076c5f7106a15ef170481a5c4333be2b4cf498525512ac4a3427e1a0e9c9f42cfcb42ba6deb"+ _ -> assertFailure "invalid account fixture length"++checkPublicHelpers :: IO ()+checkPublicHelpers = do+ entropy <- maybe (fail "invalid fixture entropy") pure (Hex.decodeHex Fixture.entropyHex)+ let prefix = Path.standardAccountPath minBound+ path = Path.derivationPath prefix Path.externalRole minBound+ vectors =+ [ ("some_password_@#$%^&", entropy, Fixture.entropyRootHex),+ (ByteString.empty, ByteString.replicate 16 0, Fixture.emptyPasswordRootHex),+ ("a\0b", ByteString.pack [0 .. 31], Fixture.nulPasswordRootHex)+ ]+ mapM_ (checkHelperVector prefix path) vectors++checkHelperVector :: Path.AccountPath -> Path.DerivationPath -> (ByteString.ByteString, ByteString.ByteString, Text.Text) -> IO ()+checkHelperVector prefix path (password, entropy, rootHex) = do+ expectedAccount <- require $ Private.withKeyHex rootHex $ \root ->+ Private.withDerived root (Path.accountIndices prefix) Private.publicKey+ expected <- require $ Private.withKeyHex rootHex $ \root ->+ Private.withDerived root (Path.toIndices path) Private.publicKey+ accountPublic <- require (Bip32.deriveAccountPublicKey password entropy prefix)+ public <- require (Bip32.derivePublicKey password entropy path)+ performGC+ accountPublic @?= expectedAccount+ public @?= expected+ relative <- require (Public.derive accountPublic (Path.relativeIndices path))+ relative @?= public+ Public.fromBytes (Public.toBytes public) @?= Right expected++checkHelperErrors :: IO ()+checkHelperErrors = mapM_ check [0, 1, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 64]+ where+ prefix = Path.standardAccountPath minBound+ path = Path.derivationPath prefix Path.externalRole minBound+ check size = do+ let entropy = ByteString.replicate size 0+ expected = Left (InvalidBip39EntropyLength size)+ Bip32.deriveAccountPublicKey "password" entropy prefix >>= (@?= expected)+ Bip32.derivePublicKey "password" entropy path >>= (@?= expected)++propBounded :: Property+propBounded = property $ do+ value <- forAll (Gen.integral (Range.linear (-2147483648) 4294967295))+ let lower = minBound :: Path.Index+ upper = maxBound :: Path.Index+ valid = value >= toInteger (Path.indexValue lower) && value <= toInteger (Path.indexValue upper)+ Path.indexValue lower === 0+ Path.indexValue upper === 2147483647+ Path.mkIndex 0 === Right lower+ Path.mkIndex 2147483647 === Right upper+ case Path.mkIndex value of+ Left err -> do+ assert (not valid)+ err === InvalidDerivationIndex value+ Right component -> do+ assert valid+ assert (lower <= component && component <= upper)+ toInteger (Path.indexValue component) === value++propEncoding :: Property+propEncoding = property $ do+ values <- forAll (Gen.list (Range.singleton 5) (Gen.integral (Range.linear 0 2147483647)))+ components <- evalEither (traverse Path.mkIndex values)+ case components of+ [purpose, coin, account, role, index] -> do+ let prefix = Path.accountPath purpose coin account+ path = Path.derivationPath prefix role index+ map Path.indexValue [Path.purpose prefix, Path.coinType prefix, Path.account prefix, Path.role path, Path.index path]+ === map fromInteger values+ Path.accountPrefix path === prefix+ Path.accountIndices prefix === map ((.|. 0x80000000) . fromInteger) (take 3 values)+ Path.relativeIndices path === map fromInteger (drop 3 values)+ Path.toIndices path === Path.accountIndices prefix ++ Path.relativeIndices path+ _ -> fail "generator length invariant"++require :: IO (Either Error a) -> IO a+require action = action >>= either (\err -> assertFailure (show err) >> fail "operation failed") pure++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_path_constants"+ cConstants :: Ptr Word32 -> IO ()++foreign import ccall safe "cometa_test_path_public"+ cPublic :: Ptr Word8 -> Ptr Word64 -> CInt -> Ptr Word8 -> IO CUInt++foreign import ccall safe "cometa_test_handler_account"+ cHandlerAccount :: Ptr Word8 -> Ptr Word64 -> Ptr Word8 -> IO CUInt
@@ -0,0 +1,104 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Typed diagnostic labels checked against native enum labels, independently+-- extracting the discriminant from the existing public CBOR encodings.+module Diagnostics (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Certificates+import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Read as Read+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Credential as Credential+import qualified Cometa.Diagnostics as Display+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.NetworkMagic as Network+import qualified Cometa.Script.Native as Native+import Control.Monad (forM_)+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word32)+import Foreign.C.String (CString, peekCString)+import Foreign.C.Types (CUInt (..))+import qualified Scripts+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++-- FOREIGN IMPORTS ------------------------------------------------------------++-- | Borrow a static ASCII label; no owner is created or released.+foreign import ccall unsafe "cometa_test_diagnostic_label"+ nativeLabel :: CUInt -> Word32 -> IO CString++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Diagnostic labels"+ [ testCase "network magics and unknown names match native values" checkNetworks,+ testCase "all certificate kinds match native labels" checkCertificates,+ testCase "all native script kinds match native labels" checkScripts,+ testCase "all votes and voter authorities match native labels" checkVoting+ ]++label :: CUInt -> Word32 -> IO Text+label category number = Text.pack <$> (nativeLabel category number >>= peekCString)++-- | All encoders emit an array whose first word is its domain discriminant.+kind :: ByteString.ByteString -> IO Word32+kind bytes = case Read.deserialiseFromBytes (Decode.decodeListLenOrIndef >> Decode.decodeWord32) (Lazy.fromStrict bytes) of+ Left failure -> fail (show failure)+ Right (_, number) -> pure number++checkNetworks :: IO ()+checkNetworks = do+ [Network.mainnet, Network.preprod, Network.preview, Network.sanchonet] @?= [764824073, 1, 2, 4]+ forM_ [Network.mainnet, Network.preprod, Network.preview, Network.sanchonet, 0, 3, maxBound] $ \magic ->+ label 0 magic >>= (@?= Network.name magic)++checkCertificates :: IO ()+checkCertificates = forM_ [0, 17, 255] $ \seed -> do+ certificates <- either (fail . show) pure (Certificates.sampleCertificates seed maxBound)+ forM_ certificates $ \certificate -> do+ tag <- kind (Certificate.encodeCbor certificate)+ label 1 tag >>= (@?= Display.certificateKind certificate)++checkScripts :: IO ()+checkScripts = do+ scripts <- Scripts.nativeValues+ forM_ scripts $ \script -> do+ tag <- kind (Native.encodeCbor script)+ label 2 tag >>= (@?= Display.nativeScriptKind script)++checkVoting :: IO ()+checkVoting = do+ forM_ [minBound .. maxBound] $ \choice ->+ label 3 (fromIntegral (fromEnum choice)) >>= (@?= Display.vote choice)+ key <- either (fail . show) pure (Credential.keyHashFromBytes (ByteString.replicate 28 1))+ drep <- either (fail . show) pure (Credential.keyHashFromBytes (ByteString.replicate 28 2))+ pool <- either (fail . show) pure (Credential.keyHashFromBytes (ByteString.replicate 28 3))+ committeeScript <- either (fail . show) pure (Credential.scriptHashFromBytes (ByteString.replicate 28 4))+ drepScript <- either (fail . show) pure (Credential.scriptHashFromBytes (ByteString.replicate 28 5))+ let voters = [Voting.CommitteeVoter (Credential.KeyCredential key), Voting.CommitteeVoter (Credential.ScriptCredential committeeScript), Voting.DRepVoter (Credential.KeyCredential drep), Voting.DRepVoter (Credential.ScriptCredential drepScript), Voting.StakePoolVoter pool]+ forM_ voters $ \voter -> do+ tag <- kind (Voting.encodeVoter voter)+ label 4 tag >>= (@?= Display.voterKind voter)
@@ -0,0 +1,389 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Offline native Dijkstra and governance builder workflows.+module DijkstraBuilder (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Interval+import qualified Cometa.Value as Value+import Control.Monad (forM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified Fixtures.ProtocolParameters as Fixture+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Dijkstra transaction building"+ [ testCase "guards, accumulated account deposits, intervals and donation balance" accounts,+ testCase "all seven proposal actions use the protocol deposit and preserve order" proposals,+ testCase "treasury assertions preserve explicit zero and full-width values" treasury,+ testCase "policy-less proposals need no evaluator or collateral" policylessProposals,+ testCase "proposal redeemers use insertion indices and preserve callback errors" proposalArguments,+ testCase "key votes retain multiple action choices" keyVotes,+ testCase "native V4 guards and deferred grouped votes have distinct purposes" scripts,+ testCase "batch deficits and surpluses preserve subtransaction bytes" batches,+ testCase "attached scripts must fit their signed execution budgets" signedBudgets,+ testCase "conflicts, arithmetic bounds and unresolved batches fail" invalid+ ]++must :: (Show e) => Either e a -> IO a+must = either (\e -> assertFailure (show e) >> fail "fixture") pure++fixture :: IO (Builder.Config, Output.Output, Utxo.Utxo)+fixture = do+ raw <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ previous <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ params =+ raw+ { P.parameterMinFeeA = 0,+ P.parameterMinFeeB = 0,+ P.parameterMaxTxSize = 16384,+ P.parameterMaxValueSize = Just 5000,+ P.parameterAdaPerUtxoByte = Just 4310,+ P.parameterProtocolVersion = Version.ProtocolVersion 10 0,+ P.parameterCollateralPercentage = Just 150,+ P.parameterMaxCollateralInputs = Just 3,+ P.parameterKeyDeposit = 2000000,+ P.parameterMaxTxExUnits = Just (ExUnits 10000000 10000000000)+ }+ funding <- must (Output.mkOutput destination (Value.lovelace 10000000) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput destination (Value.lovelace 2000000) Datum.NoDatum Nothing)+ let utxo = Utxo.utxo (Input.input previous 0) funding+ config =+ (Builder.defaultConfig params Slot.preview destination)+ { Builder.availableUtxos = [utxo],+ Builder.minimumFee = 200000+ }+ pure (config, output, utxo)++dijkstra :: IO (Builder.Config, Output.Output, Utxo.Utxo)+dijkstra = do+ (config, output, funding) <- fixture+ pure (config {Builder.parameters = (Builder.parameters config) {P.parameterProtocolVersion = Version.ProtocolVersion 12 0, P.parameterGovernanceActionDeposit = Just 100000}}, output, funding)++fields :: Tx.Transaction -> Fields.Fields+fields = Body.bodyFields . Body.toBody . Tx.body++reward :: IO Reward.RewardAddress+reward = Reward.fromCredential Network.testnet . Credential.KeyCredential <$> must (Credential.keyHashFromBytes (B.replicate 28 9))++anchor :: IO Anchor.Anchor+anchor = Anchor.Anchor <$> must (Anchor.mkUrl "https://example.com/proposal") <*> must (Anchor.dataHashFromBytes (B.replicate 32 0))++accounts :: IO ()+accounts = do+ (config, output, _) <- dijkstra+ account <- reward+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ let credential = Credential.KeyCredential key+ interval = Fields.BalanceRange (Just 1000000) (Just 5000000)+ plan =+ Plan.payTo output+ <> Plan.requireGuard credential+ <> Plan.requireGuard credential+ <> Plan.directDeposit account 1000000+ <> Plan.directDeposit account 1000000+ <> Plan.accountBalance account interval+ <> Plan.accountBalance account interval+ <> Plan.startingAccountBalance account (Fields.ExactBalance 3000000)+ <> Plan.donate 100000+ <> Plan.donate 100000+ transaction <- Builder.build config plan >>= must+ Fields.fieldGuards (fields transaction) @?= Just [credential]+ fmap Fields.entries (Fields.fieldDirectDeposits (fields transaction)) @?= Just [(account, 2000000)]+ fmap Fields.entries (Fields.fieldAccountBalanceIntervals (fields transaction)) @?= Just [(account, interval)]+ fmap Fields.entries (Body.bodyStartingAccountBalanceIntervals (Body.toBody (Tx.body transaction))) @?= Just [(account, Fields.ExactBalance 3000000)]+ Fields.fieldDonation (fields transaction) @?= Just 200000+ Value.quantity Asset.Ada (foldMap Output.value (Fields.fieldOutputs (fields transaction))) @?= 7600000++proposals :: IO ()+proposals = do+ (config, output, _) <- dijkstra+ account <- reward+ metadata <- anchor+ policyBody <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ policy <- Plutus.hash policyBody >>= must+ model <- must (Models.mkCostModel 3 (replicate 369 100))+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateral <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ quorum <- must (Interval.mkUnitInterval 2 3)+ withdrawals <- must (Action.withdrawalsFromList [(account, 1)])+ let actions =+ [ Action.ParameterChange Nothing Update.empty (Just policy),+ Action.HardForkInitiation Nothing (Version.ProtocolVersion 12 0),+ Action.TreasuryWithdrawals withdrawals (Just policy),+ Action.NoConfidence Nothing,+ Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers quorum,+ Action.NewConstitution Nothing (Constitution.Constitution metadata Nothing),+ Action.InfoAction+ ]+ configured = config {Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model])}, Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateral]}+ plan = Plan.payTo output <> Plan.attachScript (Script.Plutus policyBody) <> foldMap (\action -> Plan.propose account action metadata) actions+ transaction <- Builder.build configured plan >>= must+ fmap Proposal.toList (Fields.fieldProposalProcedures (fields transaction)) @?= Just [Proposal.Proposal 100000 account action metadata | action <- actions]+ Value.quantity Asset.Ada (foldMap Output.value (Fields.fieldOutputs (fields transaction))) @?= 9100000++keyVotes :: IO ()+keyVotes = do+ (config, output, _) <- dijkstra+ key <- must (Credential.keyHashFromBytes (B.replicate 28 5))+ identifier <- must (Id.fromBytes (B.replicate 32 3))+ let voter = Voting.DRepVoter (Credential.KeyCredential key)+ first = ActionId.ActionId identifier 0+ second = ActionId.ActionId identifier 1+ yes = Voting.VotingProcedure Voting.Yes Nothing+ no = Voting.VotingProcedure Voting.No Nothing+ plan = Plan.payTo output <> Plan.vote voter first yes <> Plan.vote voter second no <> Plan.vote voter first yes+ transaction <- Builder.build config plan >>= must+ expected <- must (Voting.fromList [(voter, first, yes), (voter, second, no)])+ Fields.fieldVotingProcedures (fields transaction) @?= Just expected+ Builder.build config (plan <> Plan.voteWithDeferredRedeemer voter [] (\_ _ -> Left (InvalidTransactionPlan "empty vote callback invoked"))) >>= (@?= Right transaction)++scripts :: IO ()+scripts = do+ baseline <- Runtime.liveContexts+ (config, output, _) <- dijkstra+ script <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ hash <- Plutus.hash script >>= must+ model <- must (Models.mkCostModel 3 (replicate 369 100))+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateral <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ identifier <- must (Id.fromBytes (B.replicate 32 3))+ let first = ActionId.ActionId identifier 0+ second = ActionId.ActionId identifier 1+ voter = Voting.DRepVoter (Credential.ScriptCredential hash)+ yes = Voting.VotingProcedure Voting.Yes Nothing+ guardArgument = Data.fromData (Data.Integer 7)+ callback transaction _ = Right (Data.fromData (Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body transaction))))))+ configured =+ config+ { Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model]), P.parameterMaxTxExUnits = Just (ExUnits 100000000 100000000000)},+ Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateral]+ }+ plan =+ Plan.payTo output+ <> Plan.attachScript (Script.Plutus script)+ <> Plan.guardWithRedeemer hash guardArgument+ <> Plan.voteWithDeferredRedeemer voter [(first, yes), (second, yes)] callback+ transaction <- Builder.build configured plan >>= must+ let values = Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction))+ map Redeemer.purpose values @?= [Redeemer.Voting, Redeemer.Guarding]+ let voteArgument = Data.fromData (Data.Integer (toInteger (Body.fee (Body.toBody (Tx.body transaction)))))+ map Redeemer.argument values @?= [voteArgument, guardArgument]+ immediate <-+ Builder.build+ configured+ (Plan.payTo output <> Plan.attachScript (Script.Plutus script) <> Plan.voteWithRedeemer voter [(first, yes), (second, yes)] guardArgument)+ >>= must+ map Redeemer.argument (Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses immediate))) @?= [guardArgument]+ let failure = InvalidTransactionPlan "voter callback refused draft"+ failed = Plan.payTo output <> Plan.attachScript (Script.Plutus script) <> Plan.voteWithDeferredRedeemer voter [(first, yes)] (\_ _ -> Left failure)+ Builder.build configured failed >>= (@?= Left failure)+ Runtime.liveContexts >>= (@?= baseline)++subFixture :: Builder.Config -> Integer -> IO (Sub.SubTransaction, Utxo.Utxo)+subFixture config amount = do+ identifier <- must (Id.fromBytes (B.replicate 32 1))+ funding <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 10000000) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace amount) Datum.NoDatum Nothing)+ let resolved = Utxo.utxo (Input.input identifier 0) funding+ body <- must (SubBody.fromBody (SubBody.body [Utxo.input resolved] [output]))+ pure (Sub.fromBody body, resolved)++batches :: IO ()+batches = do+ (config, output, wallet) <- dijkstra+ (deficit, input) <- subFixture config 12000000+ transaction <- Builder.build config {Builder.availableUtxos = [input, wallet]} (Plan.payTo output <> Plan.attachSubTransaction deficit [input]) >>= mustNamed "batch deficit"+ fmap (map Sub.encodeCbor) (Body.bodySubTransactions (Body.toBody (Tx.body transaction))) @?= Just [Sub.encodeCbor deficit]+ assertBool "sub input selected by parent" (Utxo.input input `notElem` Fields.fieldInputs (fields transaction))+ Value.quantity Asset.Ada (foldMap Output.value (Fields.fieldOutputs (fields transaction))) @?= 7800000+ (surplus, surplusInput) <- subFixture config 5000000+ Builder.build config {Builder.availableUtxos = []} (Plan.payTo output <> Plan.attachSubTransaction surplus [surplusInput]) >>= assertBool "default selector accepted no outer input" . isLeft+ carried <- Builder.build config (Plan.payTo output <> Plan.attachSubTransaction surplus [surplusInput]) >>= mustNamed "batch surplus"+ Fields.fieldInputs (fields carried) @?= [Utxo.input wallet]+ Value.quantity Asset.Ada (foldMap Output.value (Fields.fieldOutputs (fields carried))) @?= 14800000++invalid :: IO ()+invalid = do+ (config, output, _) <- dijkstra+ account <- reward+ identifier <- must (Id.fromBytes (B.replicate 32 3))+ key <- must (Credential.keyHashFromBytes (B.replicate 28 5))+ (sub, input) <- subFixture config 5000000+ overflowBody <- must (SubBody.fromBody (SubBody.fromFields (SubBody.fields (SubBody.toBody (Sub.body sub))) {Fields.fieldInvalidAfter = Just maxBound}))+ let overflowSub = Sub.fromBody overflowBody+ let tooSmall = config {Builder.parameters = (Builder.parameters config) {P.parameterMaxValueSize = Just 4}}+ Builder.build tooSmall (Plan.attachSubTransaction sub [input]) >>= (@?= Left (InvalidBuildingRequest "Attached subtransaction output exceeds maximum value size"))+ let voter = Voting.DRepVoter (Credential.KeyCredential key)+ action = ActionId.ActionId identifier 0+ yes = Voting.VotingProcedure Voting.Yes Nothing+ no = Voting.VotingProcedure Voting.No Nothing+ plans =+ [ Plan.directDeposit account 0,+ Plan.directDeposit account maxBound,+ Plan.directDeposit account (2 ^ (62 :: Int)) <> Plan.directDeposit account (2 ^ (62 :: Int)),+ Plan.donate maxBound,+ Plan.accountBalance account (Fields.ExactBalance 1) <> Plan.accountBalance account (Fields.ExactBalance 2),+ Plan.startingAccountBalance account (Fields.ExactBalance 1) <> Plan.startingAccountBalance account (Fields.ExactBalance 2),+ Plan.vote voter action yes <> Plan.vote voter action no,+ Plan.attachSubTransaction sub [],+ Plan.attachSubTransaction overflowSub [input],+ Plan.attachSubTransaction sub [input] <> Plan.spend input,+ Plan.attachSubTransaction sub [input] <> Plan.attachSubTransaction sub [input]+ ]+ mapM_ (\plan -> Builder.build config (Plan.payTo output <> plan) >>= assertBool "invalid plan accepted" . isLeft) plans++mustNamed :: (Show error) => String -> Either error value -> IO value+mustNamed context = either (\failure -> assertFailure (context <> ": " <> show failure) >> fail "fixture") pure++signedBudgets :: IO ()+signedBudgets = do+ (config, output, _) <- dijkstra+ (plain, input) <- subFixture config 10000000+ script <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ hash <- Plutus.hash script >>= must+ model <- must (Models.mkCostModel 3 (replicate 369 100))+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateral <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 20000000) Datum.NoDatum Nothing)+ body <- must (SubBody.fromBody (SubBody.fromFields (SubBody.fields (SubBody.toBody (Sub.body plain))) {Fields.fieldGuards = Just [Credential.ScriptCredential hash]}))+ let argument = Data.fromData (Data.Constr 0 [])+ configured =+ config+ { Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model])},+ Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateral]+ }+ intent units = do+ witnesses <- must (Witnesses.mkWitnesses [] [] [Script.Plutus script] [] [Redeemer.Redeemer Redeemer.Guarding 0 argument units])+ pure (Sub.assemble body (Witnesses.fromWitnesses witnesses) Nothing)+ underbudget <- intent (ExUnits 0 0)+ Builder.build configured (Plan.payTo output <> Plan.attachSubTransaction underbudget [input])+ >>= (@?= Left (InvalidBuildingRequest "Attached subtransaction execution exceeds its declared budget"))+ sufficient <- intent (ExUnits 1000000 1000000)+ transaction <- Builder.build configured (Plan.payTo output <> Plan.attachSubTransaction sufficient [input]) >>= must+ fmap (map Sub.encodeCbor) (Body.bodySubTransactions (Body.toBody (Tx.body transaction))) @?= Just [Sub.encodeCbor sufficient]++treasury :: IO ()+treasury = do+ (config, output, _) <- dijkstra+ forM_ [0, 12345, maxBound] $ \amount -> do+ transaction <- Builder.build config (Plan.payTo output <> Plan.currentTreasuryValue amount <> Plan.currentTreasuryValue amount) >>= must+ Fields.fieldTreasuryValue (fields transaction) @?= Just amount+ Value.quantity Asset.Ada (foldMap Output.value (Fields.fieldOutputs (fields transaction))) @?= 9800000+ Builder.build config (Plan.payTo output <> Plan.currentTreasuryValue 1 <> Plan.currentTreasuryValue 2)+ >>= (@?= Left (InvalidTransactionPlan "Conflicting current treasury values"))++policylessProposals :: IO ()+policylessProposals = do+ (config, output, _) <- dijkstra+ account <- reward+ metadata <- anchor+ withdrawals <- must (Action.withdrawalsFromList [(account, 1)])+ let actions = [Action.ParameterChange Nothing Update.empty Nothing, Action.TreasuryWithdrawals withdrawals Nothing]+ plan = Plan.payTo output <> foldMap (\action -> Plan.propose account action metadata) actions+ transaction <- Builder.build config plan >>= must+ fmap Proposal.toList (Fields.fieldProposalProcedures (fields transaction)) @?= Just [Proposal.Proposal 100000 account action metadata | action <- actions]+ Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction)) @?= []+ Builder.build config (plan <> Plan.propose account (Action.ParameterChange Nothing Update.empty Nothing) metadata)+ >>= (@?= Left (InvalidTransactionPlan "Duplicate governance proposal"))+ Builder.build config (Plan.payTo output <> Plan.proposeWithRedeemer account Action.InfoAction metadata (Data.fromData (Data.Integer 1)))+ >>= (@?= Left (InvalidTransactionPlan "A proposing redeemer requires a guardrails policy"))+ halves <- must (mapM (uncurry Interval.mkUnitInterval) [(1, 2), (2, 4)])+ let committees = [Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers threshold | threshold <- halves]+ distinct <- Builder.build config (Plan.payTo output <> foldMap (\action -> Plan.propose account action metadata) committees) >>= must+ fmap (map Proposal.encodeCbor . Proposal.toList) (Fields.fieldProposalProcedures (fields distinct))+ @?= Just [Proposal.encodeCbor (Proposal.Proposal 100000 account action metadata) | action <- committees]++proposalArguments :: IO ()+proposalArguments = do+ baseline <- Runtime.liveContexts+ (config, output, _) <- dijkstra+ account <- reward+ metadata <- anchor+ script <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ policy <- Plutus.hash script >>= must+ model <- must (Models.mkCostModel 3 (replicate 369 100))+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateral <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ withdrawals <- must (Action.withdrawalsFromList [(account, 1)])+ let action = Action.TreasuryWithdrawals withdrawals (Just policy)+ expected = Proposal.Proposal 100000 account action metadata+ immediate = Data.fromData (Data.Integer 42)+ callback transaction _ = case Indices.findProposal expected transaction of+ Nothing -> Left (InvalidTransactionPlan "Proposal absent from callback draft")+ Just index -> Right (Data.fromData (Data.Integer (toInteger index)))+ configured = config {Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model])}, Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateral]}+ prefix = Plan.payTo output <> Plan.attachScript (Script.Plutus script) <> Plan.propose account Action.InfoAction metadata+ plan = prefix <> Plan.proposeWithRedeemer account (Action.ParameterChange Nothing Update.empty (Just policy)) metadata immediate <> Plan.proposeWithDeferredRedeemer account action metadata callback+ transaction <- Builder.build configured plan >>= must+ let redeemers = Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction))+ map Redeemer.purpose redeemers @?= [Redeemer.Proposing, Redeemer.Proposing]+ map Redeemer.index redeemers @?= [1, 2]+ map Redeemer.argument redeemers @?= [immediate, Data.fromData (Data.Integer 2)]+ Indices.findProposal expected transaction @?= Just 2+ Indices.findProposal (expected {Proposal.proposalDeposit = 1}) transaction @?= Nothing+ let failure = InvalidTransactionPlan "Proposal callback refused draft"+ Builder.build configured (prefix <> Plan.proposeWithDeferredRedeemer account action metadata (\_ _ -> Left failure)) >>= (@?= Left failure)+ Runtime.liveContexts >>= (@?= baseline)
@@ -0,0 +1,550 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Public Ed25519 values, published known answers and scoped secret lifetimes.+-- All signing material is deterministic test data, never application keys.+module Ed25519 (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.FFI.SigningKey as Native+import qualified Cometa.Internal.Failure as Failure+import Cometa.Internal.Hex (decodeHex, encodeHex)+import qualified Cometa.Internal.SigningKey as Core+import Control.Concurrent (MVar, ThreadId, forkFinally, killThread, newEmptyMVar, putMVar, takeMVar, tryPutMVar, yield)+import Control.Exception (AsyncException (ThreadKilled), Exception, SomeException, bracket, finally, fromException, mask_, throw, throwIO, try)+import Control.Monad (replicateM_, void)+import Data.Bits (xor)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.Text (Text)+import qualified Data.Text as Text+import Fixtures.Ed25519 (Vector (..))+import qualified Fixtures.Ed25519 as Fixture+import Foreign.C.Types (CSize (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (poke)+import GHC.Conc (BlockReason (BlockedOnMVar), ThreadStatus (..), threadStatus)+import Hedgehog (Property, PropertyT, evalEither, evalIO, forAll, forAllWith, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++data ScopeException = ScopeException deriving (Eq, Show)++instance Exception ScopeException++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Ed25519"+ [ testCase "published normal and extended known answers" $ mapM_ checkKnownAnswer Fixture.allVectors,+ testCase "altered message, public key and signature fail verification" $ mapM_ checkTampering Fixture.allVectors,+ testCase "public key and signature byte/hex bounds" checkPublicBounds,+ testCase "public hex imports normalize case and reject malformed input" checkPublicHex,+ testCase "normal and extended signing imports reject invalid lengths" checkSigningBounds,+ testCase "unusable expanded scalar fails safely and closes its scope" checkUnusableScalar,+ testCase "signing hex imports reject malformed input without echoing it" checkSigningHex,+ testCase "explicit key exports preserve normal and extended input" $ mapM_ checkExport Fixture.allVectors,+ testCase "closed and escaped signing keys reject every operation" checkClosedKeys,+ testCase "callback Left closes an escaped signing key" checkScopeFailure,+ testCase "scope exception closes an escaped signing key" checkScopeException,+ testCase "scope cancellation closes an escaped signing key" checkScopeCancellation,+ testCase "a deep clone survives closing its source" checkClone,+ testCase "public results survive closed key, native churn and GC" checkSnapshots,+ testCase "throwing message input does not leave a signing key locked" checkMessageException,+ testCase "concurrent signing and close leave no live escaped key" checkSignCloseRaces,+ testCase "native key scope releases one reference after success or exception" checkNativeScopeRelease,+ testCase "cancelled native key scope releases its reference" checkNativeScopeCancellation,+ testCase "close waits for an in-flight native signing operation" checkInFlightClose,+ testCase "clone owns a distinct native allocation" checkNativeClone,+ testProperty "public key byte and hex round trips" propPublicKey,+ testProperty "signature byte and hex round trips" propSignature,+ testProperty "normal sign and verify agree for arbitrary test seeds and messages" propNormalSign,+ testProperty "extended sign and verify agree for arbitrary messages" propExtendedSign+ ]++checkKnownAnswer :: Vector -> IO ()+checkKnownAnswer vector = do+ bytes <- hexBytes (privateHex vector)+ message <- hexBytes (messageHex vector)+ (key, signature) <- requireRight $ withVector vector bytes $ \secret -> do+ public <- SigningKey.publicKey secret+ signed <- SigningKey.sign secret message+ pure ((,) <$> public <*> signed)+ PublicKey.toHex key @?= publicHex vector+ Signature.toHex signature @?= signatureHex vector+ PublicKey.verify key message signature >>= (@?= Right True)+ digest <- requireRight (PublicKey.hash key)+ Blake2b.toHex digest @?= publicHashHex vector+ PublicKey.byteLength key @?= 32+ PublicKey.hexLength key @?= 64+ Signature.byteLength signature @?= 64+ Signature.hexLength signature @?= 128++checkTampering :: Vector -> IO ()+checkTampering vector = do+ key <- requirePure (PublicKey.fromHex (publicHex vector))+ signature <- requirePure (Signature.fromHex (signatureHex vector))+ message <- hexBytes (messageHex vector)+ otherKey <- requirePure (PublicKey.fromBytes (alterFirst (PublicKey.toBytes key)))+ otherSignature <- requirePure (Signature.fromBytes (alterFirst (Signature.toBytes signature)))+ PublicKey.verify key (message <> ByteString.singleton 0) signature >>= (@?= Right False)+ PublicKey.verify otherKey message signature >>= (@?= Right False)+ PublicKey.verify key message otherSignature >>= (@?= Right False)++checkPublicBounds :: IO ()+checkPublicBounds = do+ mapM_ (\size -> PublicKey.fromBytes (ByteString.replicate size 0) @?= Left (InvalidEd25519PublicKeyLength size)) [0, 1, 31, 33, 64]+ mapM_ (\size -> Signature.fromBytes (ByteString.replicate size 0) @?= Left (InvalidEd25519SignatureLength size)) [0, 1, 32, 63, 65, 128]+ -- Public constructors validate encoding length, not curve or signature validity.+ key <- requirePure (PublicKey.fromBytes (ByteString.replicate 32 0))+ signature <- requirePure (Signature.fromBytes (ByteString.replicate 64 0))+ PublicKey.byteLength key @?= 32+ Signature.byteLength signature @?= 64++checkPublicHex :: IO ()+checkPublicHex = do+ let vector = Fixture.normalVector+ key <- requirePure (PublicKey.fromHex (Text.toUpper (publicHex vector)))+ PublicKey.toHex key @?= publicHex vector+ signature <- requirePure (Signature.fromHex (Text.toUpper (signatureHex vector)))+ Signature.toHex signature @?= signatureHex vector+ mapM_ (\input -> PublicKey.fromHex input @?= Left InvalidHex) malformedHex+ mapM_ (\input -> Signature.fromHex input @?= Left InvalidHex) malformedHex+ PublicKey.fromHex (Text.replicate 31 "00") @?= Left (InvalidEd25519PublicKeyLength 31)+ Signature.fromHex (Text.replicate 63 "00") @?= Left (InvalidEd25519SignatureLength 63)++checkSigningBounds :: IO ()+checkSigningBounds = do+ mapM_ (check SigningKey.withNormalKey 32) [0, 1, 31, 33, 64]+ mapM_ (check SigningKey.withExtendedKey 64) [0, 1, 32, 63, 65, 128]+ where+ check constructor expected actual = do+ result <- constructor (ByteString.replicate actual 0) (const (pure (Right ())))+ result @?= Left (InvalidEd25519SigningKeyLength expected actual)++checkUnusableScalar :: IO ()+checkUnusableScalar = do+ escaped <- newIORef Nothing+ result <- SigningKey.withExtendedKey (ByteString.replicate 64 0) $ \key -> do+ writeIORef escaped (Just key)+ public <- SigningKey.publicKey key+ signature <- SigningKey.sign key ByteString.empty+ public @?= Left (failure "ed25519.publicKey")+ signature @?= Left (failure "ed25519.sign")+ pure (Left (failure "ed25519.publicKey") :: Either Error ())+ result @?= Left (failure "ed25519.publicKey")+ readIORef escaped >>= maybe (assertFailure "missing unusable test handle") checkClosed+ checkUnusableScalarRelease+ where+ failure operation = NativeError operation Code.GenericFailure "Generic error"++checkUnusableScalarRelease :: IO ()+checkUnusableScalarRelease = withRetainedNative $ \owner -> do+ result <- Core.withExtendedKey (ByteString.replicate 64 0) $ \key -> do+ _ <- requireRight (Core.withKey key (retainNative owner))+ Core.signBytes key ByteString.empty+ result @?= Right (Left (Core.NativeFailure (Failure.NativeFailure "ed25519.sign" 1 "Generic error")))+ assertSingleReference owner++checkSigningHex :: IO ()+checkSigningHex = do+ mapM_ checkMalformed malformedHex+ mapM_ checkValid [Fixture.normalVector, Fixture.extendedVector]+ where+ checkMalformed input = do+ SigningKey.withNormalKeyHex input (const (pure (Right ()))) >>= (@?= Left InvalidHex)+ SigningKey.withExtendedKeyHex input (const (pure (Right ()))) >>= (@?= Left InvalidHex)+ checkValid vector = do+ let constructor = if isExtended vector then SigningKey.withExtendedKeyHex else SigningKey.withNormalKeyHex+ key <- requireRight $ constructor (Text.toUpper (privateHex vector)) SigningKey.publicKey+ PublicKey.toHex key @?= publicHex vector++checkExport :: Vector -> IO ()+checkExport vector = do+ bytes <- hexBytes (privateHex vector)+ result <- withVector vector bytes $ \key -> do+ SigningKey.byteLength key >>= (@?= Right (ByteString.length bytes))+ SigningKey.hexLength key >>= (@?= Right (Text.length (privateHex vector)))+ exported <- SigningKey.exportBytes key+ encoded <- SigningKey.exportHex key+ pure $ do+ copied <- exported+ hex <- encoded+ pure (copied == bytes && hex == privateHex vector)+ result @?= Right True++checkClosedKeys :: IO ()+checkClosedKeys = mapM_ check [Fixture.normalVector, Fixture.extendedVector]+ where+ check vector = do+ bytes <- hexBytes (privateHex vector)+ escaped <- requireRight $ withVector vector bytes $ \key -> do+ SigningKey.close key+ SigningKey.close key+ checkClosed key+ pure (Right key)+ checkClosed escaped++checkClosed :: SigningKey.SigningKey -> IO ()+checkClosed key = do+ SigningKey.sign key ByteString.empty >>= (@?= Left SigningKeyClosed)+ SigningKey.publicKey key >>= (@?= Left SigningKeyClosed)+ exported <- SigningKey.exportBytes key+ assertClosed exported+ encoded <- SigningKey.exportHex key+ assertClosed encoded+ SigningKey.byteLength key >>= (@?= Left SigningKeyClosed)+ SigningKey.hexLength key >>= (@?= Left SigningKeyClosed)+ SigningKey.withClone key (const (pure (Right ()))) >>= (@?= Left SigningKeyClosed)+ where+ assertClosed result = case result of+ Left failure -> failure @?= SigningKeyClosed+ Right _ -> assertFailure "closed key exported secret material"++checkScopeFailure :: IO ()+checkScopeFailure = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ escaped <- newIORef Nothing+ result <- SigningKey.withNormalKey bytes $ \key -> do+ writeIORef escaped (Just key)+ pure (Left InvalidHex :: Either Error ())+ result @?= Left InvalidHex+ readIORef escaped >>= maybe (assertFailure "missing escaped test handle") checkClosed++checkScopeException :: IO ()+checkScopeException = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ escaped <- newIORef Nothing+ result <- try $ SigningKey.withNormalKey bytes $ \key -> do+ writeIORef escaped (Just key)+ throwIO ScopeException+ (result :: Either ScopeException (Either Error ())) @?= Left ScopeException+ readIORef escaped >>= maybe (assertFailure "missing escaped test handle") checkClosed++checkScopeCancellation :: IO ()+checkScopeCancellation = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ escaped <- newEmptyMVar+ blocked <- newEmptyMVar :: IO (MVar ())+ finished <- newEmptyMVar+ worker <-+ forkFinally+ (SigningKey.withNormalKey bytes $ \key -> putMVar escaped key >> takeMVar blocked >> pure (Right ()))+ (putMVar finished)+ key <- waitFor "signing scope entry" (takeMVar escaped)+ result <- waitFor "signing scope cancellation" (killThread worker >> takeMVar finished)+ case result of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right _ -> assertFailure "cancelled signing scope completed"+ checkClosed key++checkClone :: IO ()+checkClone = do+ let vector = Fixture.extendedVector+ bytes <- hexBytes (privateHex vector)+ message <- hexBytes (messageHex vector)+ result <- SigningKey.withExtendedKey bytes $ \source ->+ SigningKey.withClone source $ \copy -> do+ SigningKey.close source+ checkClosed source+ performGC+ signature <- SigningKey.sign copy message+ pure (Signature.toHex <$> signature)+ result @?= Right (signatureHex vector)++checkSnapshots :: IO ()+checkSnapshots = do+ let vector = Fixture.normalVector+ bytes <- hexBytes (privateHex vector)+ (public, signature) <- requireRight $ SigningKey.withNormalKey bytes $ \key -> do+ performGC+ pub <- SigningKey.publicKey key+ sig <- SigningKey.sign key ByteString.empty+ pure ((,) <$> pub <*> sig)+ replicateM_ 100 $ do+ _ <- requireRight $ SigningKey.withNormalKey bytes (`SigningKey.sign` "temporary native signing allocation")+ pure ()+ performGC+ PublicKey.toHex public @?= publicHex vector+ Signature.toHex signature @?= signatureHex vector+ PublicKey.verify public ByteString.empty signature >>= (@?= Right True)++checkMessageException :: IO ()+checkMessageException = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ result <- SigningKey.withNormalKey bytes $ \key -> do+ outcome <- try (SigningKey.sign key (throw ScopeException))+ (outcome :: Either ScopeException (Either Error Signature.Signature)) @?= Left ScopeException+ SigningKey.close key+ checkClosed key+ pure (Right ())+ result @?= Right ()++checkSignCloseRaces :: IO ()+checkSignCloseRaces = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ public <- requirePure (PublicKey.fromHex (publicHex Fixture.normalVector))+ let message = ByteString.replicate 65536 42+ replicateM_ 25 $ do+ result <- SigningKey.withNormalKey bytes $ \key -> do+ started <- newEmptyMVar+ finished <- newEmptyMVar+ _ <- forkFinally (putMVar started () >> SigningKey.sign key message) (putMVar finished)+ waitFor "signing race entry" (takeMVar started)+ SigningKey.close key+ outcome <- waitFor "signing race completion" (takeMVar finished)+ case outcome of+ Left cause -> assertFailure (show (cause :: SomeException))+ Right (Left failure) -> failure @?= SigningKeyClosed+ Right (Right signature) -> PublicKey.verify public message signature >>= (@?= Right True)+ checkClosed key+ pure (Right ())+ result @?= Right ()++checkNativeScopeRelease :: IO ()+checkNativeScopeRelease = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ withRetainedNative $ \owner -> do+ _ <- requireRight $ Core.withNormalKey bytes $ \key ->+ requireRight (Core.withKey key (retainNative owner))+ assertSingleReference owner+ withRetainedNative $ \owner -> do+ failure <- Core.withNormalKey bytes $ \key -> do+ _ <- requireRight (Core.withKey key (retainNative owner))+ pure (Left Core.InvalidHex :: Either Core.Failure ())+ failure @?= Right (Left Core.InvalidHex)+ assertSingleReference owner+ withRetainedNative $ \owner -> do+ outcome <- try $ Core.withNormalKey bytes $ \key -> do+ _ <- requireRight (Core.withKey key (retainNative owner))+ throwIO ScopeException+ (outcome :: Either ScopeException (Either Core.Failure ())) @?= Left ScopeException+ assertSingleReference owner++checkNativeScopeCancellation :: IO ()+checkNativeScopeCancellation = do+ bytes <- hexBytes (privateHex Fixture.extendedVector)+ withRetainedNative $ \owner -> do+ entered <- newEmptyMVar+ blocked <- newEmptyMVar :: IO (MVar ())+ finished <- newEmptyMVar+ worker <-+ forkFinally+ ( Core.withExtendedKey bytes $ \key -> do+ _ <- requireRight (Core.withKey key (retainNative owner))+ putMVar entered key+ takeMVar blocked+ )+ (putMVar finished)+ key <- waitFor "native key scope entry" (takeMVar entered)+ outcome <- waitFor "native key scope cancellation" (killThread worker >> takeMVar finished)+ case outcome of+ Left cause -> fromException cause @?= Just ThreadKilled+ Right _ -> assertFailure "cancelled native key scope completed"+ Core.withKey key (const (pure (Right ()))) >>= (@?= Left Core.Closed)+ assertSingleReference owner++checkInFlightClose :: IO ()+checkInFlightClose = do+ bytes <- hexBytes (privateHex Fixture.normalVector)+ result <- Core.withNormalKey bytes $ \key -> do+ entered <- newEmptyMVar+ resume <- newEmptyMVar+ signed <- newEmptyMVar+ closed <- newEmptyMVar+ _ <-+ forkFinally+ (Core.withKey key (pausedSign entered resume))+ (putMVar signed)+ ( do+ waitFor "native sign lock entry" (takeMVar entered)+ closer <- forkFinally (Core.close key) (putMVar closed)+ waitFor "close waiting on active signing lock" (waitUntilBlocked closer)+ putMVar resume ()+ outcome <- waitFor "native signing completion" (takeMVar signed)+ signature <- case outcome of+ Left cause -> assertFailure (show (cause :: SomeException)) >> fail "native signer failed"+ Right value -> requirePure value+ encodeHex signature @?= signatureHex Fixture.normalVector+ waitFor "close after native signing" (takeMVar closed) >>= requireThreadSuccess+ Core.withKey key (const (pure (Right ()))) >>= (@?= Left Core.Closed)+ )+ `finally` void (tryPutMVar resume ())+ result @?= Right ()++pausedSign :: MVar () -> MVar () -> Ptr Native.NativeKey -> IO (Either Core.Failure ByteString)+pausedSign entered resume pointer = do+ putMVar entered ()+ takeMVar resume+ performGC+ ByteString.useAsCStringLen ByteString.empty $ \(message, size) ->+ allocaBytes 64 $ \signature -> do+ status <- Native.cSign pointer (castPtr message) (fromIntegral size) signature+ status @?= 0+ bytes <- ByteString.packCStringLen (castPtr signature, 64)+ pure (Right bytes)++checkNativeClone :: IO ()+checkNativeClone = do+ bytes <- hexBytes (privateHex Fixture.extendedVector)+ result <- Core.withExtendedKey bytes $ \source ->+ requireRight $ Core.withClone source $ \copy -> do+ first <- requireRight (Core.withKey source (pure . Right))+ second <- requireRight (Core.withKey copy (pure . Right))+ assertBool "clone shares its native allocation" (first /= second)+ cNativeRefCount first >>= (@?= 1)+ cNativeRefCount second >>= (@?= 1)+ result @?= Right ()++withRetainedNative :: (IORef (Ptr Native.NativeKey) -> IO value) -> IO value+withRetainedNative = bracket (newIORef nullPtr) release+ where+ release owner = do+ pointer <- readIORef owner+ if pointer == nullPtr then pure () else alloca $ \slot -> poke slot pointer >> cNativeUnref slot++retainNative :: IORef (Ptr Native.NativeKey) -> Ptr Native.NativeKey -> IO (Either Core.Failure ())+retainNative owner pointer = mask_ $ do+ cNativeRef pointer+ writeIORef owner pointer+ cNativeRefCount pointer >>= (@?= 2)+ pure (Right ())++assertSingleReference :: IORef (Ptr Native.NativeKey) -> IO ()+assertSingleReference owner = do+ pointer <- readIORef owner+ assertBool "native lifecycle fixture did not retain its reference" (pointer /= nullPtr)+ cNativeRefCount pointer >>= (@?= 1)++waitUntilBlocked :: ThreadId -> IO ()+waitUntilBlocked thread = do+ status <- threadStatus thread+ case status of+ ThreadBlocked BlockedOnMVar -> pure ()+ ThreadRunning -> yield >> waitUntilBlocked thread+ _ -> assertFailure "close did not wait on the active key operation"++requireThreadSuccess :: Either SomeException () -> IO ()+requireThreadSuccess result = case result of+ Right () -> pure ()+ Left cause -> assertFailure (show cause)++propPublicKey :: Property+propPublicKey = withTests 300 $ property $ do+ bytes <- forAll (Gen.bytes (Range.singleton 32))+ key <- evalEither (PublicKey.fromBytes bytes)+ PublicKey.toBytes key === bytes+ PublicKey.fromHex (PublicKey.toHex key) === Right key+ PublicKey.byteLength key === 32+ PublicKey.hexLength key === 64++propSignature :: Property+propSignature = withTests 300 $ property $ do+ bytes <- forAll (Gen.bytes (Range.singleton 64))+ signature <- evalEither (Signature.fromBytes bytes)+ Signature.toBytes signature === bytes+ Signature.fromHex (Signature.toHex signature) === Right signature+ Signature.byteLength signature === 64+ Signature.hexLength signature === 128++propNormalSign :: Property+propNormalSign = withTests 300 $ property $ do+ seed <- forAllWith (const "<generated test key>") (Gen.bytes (Range.singleton 32))+ message <- forAll (Gen.bytes (Range.linear 0 512))+ pair <- evalIO (SigningKey.withNormalKey seed (signPair message)) >>= evalEither+ checkVerification message pair++propExtendedSign :: Property+propExtendedSign = withTests 300 $ property $ do+ message <- forAll (Gen.bytes (Range.linear 0 512))+ pair <- evalIO (hexBytes (privateHex Fixture.extendedVector) >>= \bytes -> SigningKey.withExtendedKey bytes (signPair message)) >>= evalEither+ checkVerification message pair++checkVerification :: ByteString -> (PublicKey.PublicKey, Signature.Signature) -> PropertyT IO ()+checkVerification message (public, signature) = do+ valid <- evalIO (PublicKey.verify public message signature) >>= evalEither+ valid === True+ altered <- evalIO (PublicKey.verify public (message <> ByteString.singleton 0) signature) >>= evalEither+ altered === False++signPair :: ByteString -> SigningKey.SigningKey -> IO (Either Error (PublicKey.PublicKey, Signature.Signature))+signPair message key = do+ public <- SigningKey.publicKey key+ signature <- SigningKey.sign key message+ pure ((,) <$> public <*> signature)++withVector :: Vector -> ByteString -> (SigningKey.SigningKey -> IO (Either Error value)) -> IO (Either Error value)+withVector vector = if isExtended vector then SigningKey.withExtendedKey else SigningKey.withNormalKey++hexBytes :: Text -> IO ByteString+hexBytes text = case decodeHex text of+ Just bytes -> pure bytes+ Nothing -> assertFailure "invalid hexadecimal test fixture" >> fail "invalid fixture"++requirePure :: (Show failure) => Either failure value -> IO value+requirePure result = case result of+ Right value -> pure value+ Left failure -> assertFailure (show failure) >> fail "Ed25519 fixture operation failed"++requireRight :: (Show failure) => IO (Either failure value) -> IO value+requireRight action = action >>= requirePure++waitFor :: String -> IO value -> IO value+waitFor label action = do+ result <- timeout 10000000 action+ case result of+ Just value -> pure value+ Nothing -> assertFailure (label <> " timed out") >> fail label++alterFirst :: ByteString -> ByteString+alterFirst bytes = case ByteString.uncons bytes of+ Nothing -> ByteString.singleton 1+ Just (first, rest) -> ByteString.cons (first `xor` 1) rest++malformedHex :: [Text]+malformedHex = ["", "a", "gg", " 00", "0x00", "12"]++-- FOREIGN IMPORTS ------------------------------------------------------------++-- Test-only retained references observe deterministic disposal without adding+-- allocation counters or pointer access to the public signing API.+foreign import ccall unsafe "cardano_ed25519_private_key_ref"+ cNativeRef :: Ptr Native.NativeKey -> IO ()++foreign import ccall unsafe "cardano_ed25519_private_key_refcount"+ cNativeRefCount :: Ptr Native.NativeKey -> IO CSize++foreign import ccall unsafe "cardano_ed25519_private_key_unref"+ cNativeUnref :: Ptr (Ptr Native.NativeKey) -> IO ()
@@ -0,0 +1,363 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Explicit representation changes and immutable identity-bearing snapshots.+-- All fixtures are synthetic public data. The fixed signing seed is test-only;+-- no live wallet or ledger acceptance is involved.+module EncodingNormalization (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as Name+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Hash+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey+import qualified Cometa.Encoding.Cbor as Encoded+import qualified Cometa.Encoding.Collections as Collections+import qualified Cometa.Encoding.Reencode as Reencode+import Cometa.Encoding.Set (SetEncoding (TaggedSet, UntaggedSet))+import Cometa.Error (Error (InvalidValueQuantity))+import Cometa.Internal.FFI.Native (NativeCode)+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Script.Native as Native+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Value+import qualified Cometa.Value.Raw as Raw+import Control.Monad (forM_, replicateM, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Maybe (fromMaybe)+import Data.Word (Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr)+import Foreign.Storable (peek)+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Encoding normalization and signed identity"+ [ testCase "raw value clones preserve signed coin, zeros, duplicates and empty groups" rawSnapshots,+ testCase "encoded input tag observer differs from native dirty-cache heuristic" bodySetMode,+ testCase "fresh scripts match cache clearing with definite child-list policy" scripts,+ testCase "script-list clearing normalizes descendants and preserves its envelope" scriptLists,+ testCase "composite cache clearing preserves indefinite child-list policy" scriptPolicies,+ testCase "native transaction cache clearing changes signed identity" transactions,+ testCase "native subtransaction cache clearing changes only that intent's identity" subTransactions,+ testCase "deep-cloned digest bytes survive source release and encoding changes" hashSnapshots,+ testCase "malformed oracle inputs release all partial owners" failures+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++normalize :: CUInt -> ByteString -> IO (Either Error ByteString)+normalize kind bytes = Runtime.withBytes bytes $ \input size -> Runtime.withOwnedBuffer "test.encoding.normalize" (cNormalize kind input size)++freshScript :: Native.NativeScript -> Either Error Native.NativeScript+freshScript = Native.fromJson . Native.toJson++scriptFixtures :: IO [Native.NativeScript]+scriptFixtures = do+ payment <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ guard <- must (Credential.keyHashFromBytes (B.replicate 28 2))+ script <- must (Credential.scriptHashFromBytes (B.replicate 28 3))+ let leaves = [Native.signature payment, Native.invalidBefore 7, Native.invalidAfter maxBound, Native.requireGuard (Credential.KeyCredential guard), Native.requireGuard (Credential.ScriptCredential script)]+ composites = [Native.allOf leaves, Native.anyOf (reverse leaves), Native.atLeast 2 [Native.anyOf leaves, Native.allOf leaves, Native.invalidBefore 0]]+ traverse (must . Native.decodeCbor . nonminimalScript) (leaves <> composites)++-- Deliberately indefinite node arrays and nonminimal discriminants.+-- Child collections use definite policy here; the separate policy regression+-- exercises the native flag which construction JSON does not retain.+-- Child order and duplicate conditions retain their semantic significance.+nonminimalScript :: Native.NativeScript -> ByteString+nonminimalScript script = indefinite $ case Native.view script of+ Native.RequireSignature key -> tag 0 <> Cbor.encode (E.encodeBytes (Credential.keyHashBytes key))+ Native.RequireAll children -> tag 1 <> childrenBytes children+ Native.RequireAny children -> tag 2 <> childrenBytes children+ Native.RequireAtLeast required children -> tag 3 <> Cbor.encode (E.encodeWord64 required) <> childrenBytes children+ Native.InvalidBefore slot -> tag 4 <> Cbor.encode (E.encodeWord64 slot)+ Native.InvalidAfter slot -> tag 5 <> Cbor.encode (E.encodeWord64 slot)+ Native.RequireGuard credential -> tag 6 <> Credential.encodeCbor credential+ where+ tag number = B.pack [0x18, number]+ childrenBytes children = Cbor.encode (E.encodeListLen (fromIntegral (length children))) <> foldMap nonminimalScript children++indefinite :: ByteString -> ByteString+indefinite payload = B.singleton 0x9f <> payload <> B.singleton 0xff++scripts :: IO ()+scripts = do+ values <- scriptFixtures+ forM_ values $ \original -> do+ fresh <- must (freshScript original)+ let bytes = Native.encodeCbor original+ changed = Native.encodeCbor fresh+ assertBool "Nonminimal fixture already fresh" (bytes /= changed)+ Native.toJson fresh @?= Native.toJson original+ normalize 0 bytes >>= (@?= Right changed)+ Reencode.nativeScript original >>= (@?= Right fresh)+ sourceHash <- Native.hash original >>= must+ freshHash <- Native.hash fresh >>= must+ assertBool "Script hash ignored original representation" (sourceHash /= freshHash)+ -- Native oracle invalidates a deep clone; original native and Haskell+ -- snapshots retain their bytes even after the changed owner is released.+ copies <- replicateM 5 (normalize 0 bytes >>= must)+ performGC+ copies @?= replicate 5 changed+ Native.encodeCbor original @?= bytes+ Native.hash original >>= (@?= Right sourceHash)++scriptLists :: IO ()+scriptLists = do+ values <- scriptFixtures+ let supplied = values <> reverse values+ original = indefinite (foldMap Native.encodeCbor supplied)+ fresh <- traverse (must . freshScript) supplied+ let expected = indefinite (foldMap Native.encodeCbor fresh)+ definite = Cbor.encode (E.encodeListLen (fromIntegral (length fresh))) <> foldMap Native.encodeCbor fresh+ normalize 1 original >>= (@?= Right expected)+ encoded <- Encoded.fromBytes original >>= must+ result <- Reencode.nativeScripts encoded >>= must+ Encoded.toBytes result @?= expected+ assertBool "List envelope policy was erased" (expected /= definite)+ map Native.encodeCbor supplied @?= map nonminimalScript supplied++-- Native clearing resets node caches but keeps the child-list indefinite flag.+-- Semantic JSON reconstruction deliberately has a different representation+-- contract; these cases prevent claiming a general cache-clear equivalence.+scriptPolicies :: IO ()+scriptPolicies = do+ values <- scriptFixtures+ case values of+ leaf : _ -> do+ freshLeaf <- must (freshScript leaf)+ let children = indefinite (Native.encodeCbor leaf)+ freshChildren = indefinite (Native.encodeCbor freshLeaf)+ cases = [(B.pack [0x18, 1], B.pack [0x82, 1]), (B.pack [0x18, 2], B.pack [0x82, 2]), (B.pack [0x18, 3, 0x18, 1], B.pack [0x83, 3, 1])]+ forM_ cases $ \(sourcePrefix, freshPrefix) -> do+ let original = indefinite (sourcePrefix <> children)+ expected = freshPrefix <> freshChildren+ imported <- must (Native.decodeCbor original)+ fresh <- must (freshScript imported)+ changed <- normalize 0 original >>= must+ changed @?= expected+ public <- Reencode.nativeScript imported >>= must+ Native.encodeCbor public @?= expected+ assertBool "Construction JSON silently retained native indefinite policy" (changed /= Native.encodeCbor fresh)+ parsed <- must (Native.decodeCbor changed)+ Native.toJson parsed @?= Native.toJson fresh+ normalize 0 changed >>= (@?= Right expected)+ Native.encodeCbor imported @?= original+ [] -> assertFailure "Missing leaf fixture"++-- A nonminimal body with the same semantic zero fee as fresh assembly. Its+-- original bytes, not its decoded Fields record, define the signature message.+originalBodyBytes :: ByteString+originalBodyBytes = B.pack [0xa3, 0, 0x80, 1, 0x80, 2, 0x18, 0]++signedWitnesses :: ByteString -> IO Witnesses.EncodedWitnesses+signedWitnesses message = do+ (public, signature) <-+ SigningKey.withNormalKey+ (B.replicate 32 7)+ ( \key -> do+ public <- SigningKey.publicKey key+ signature <- SigningKey.sign key message+ pure ((,) <$> public <*> signature)+ )+ >>= must+ witnesses <- must (Witnesses.mkWitnesses [Witness.verificationWitness public signature] [] [] [] [])+ pure (Witnesses.fromWitnesses witnesses)++verifyWitnesses :: ByteString -> Witnesses.EncodedWitnesses -> IO ()+verifyWitnesses message witnesses = forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses witnesses)) $ \witness ->+ PublicKey.verify (Witness.publicKey witness) message (Witness.signature witness) >>= (@?= Right True)++transactions :: IO ()+transactions = do+ body <- must (Body.decodeCbor originalBodyBytes)+ let unsigned = Tx.fromBody body+ identifier <- Tx.transactionId unsigned >>= must+ witnesses <- signedWitnesses (TxId.toBytes identifier)+ let signed = Tx.assemble body witnesses Nothing+ original = Tx.encodeCbor signed+ verifyWitnesses (TxId.toBytes identifier) witnesses+ changedBytes <- normalize 2 original >>= must+ public <- Reencode.transaction signed >>= must+ Tx.encodeCbor public @?= changedBytes+ changed <- must (Tx.decodeCbor changedBytes)+ changedId <- Tx.transactionId changed >>= must+ assertBool "Native body cache clearing retained nonminimal hash" (changedId /= identifier)+ Body.toBody (Tx.body changed) @?= Body.toBody body+ forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses changed))) $ \witness ->+ PublicKey.verify (Witness.publicKey witness) (TxId.toBytes changedId) (Witness.signature witness) >>= (@?= Right False)+ freshBody <- must (Body.fromBody (Body.toBody body))+ -- The public setter treats representation-only replacement as a semantic+ -- no-op, keeping signed bytes; a real body edit drops outer signatures.+ Tx.encodeCbor (Tx.setBody freshBody signed) @?= original+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses (Tx.setFee 1 signed))) @?= []+ Tx.encodeCbor signed @?= original+ Tx.transactionId signed >>= (@?= Right identifier)++subTransactions :: IO ()+subTransactions = do+ let bodyBytes = B.pack [0xb8, 2, 0, 0x80, 1, 0x80]+ body <- must (SubBody.decodeCbor bodyBytes)+ identifier <- Sub.transactionId (Sub.fromBody body) >>= must+ witnesses <- signedWitnesses (TxId.toBytes identifier)+ let signed = Sub.assemble body witnesses Nothing+ original = Sub.encodeCbor signed+ changedBytes <- normalize 3 original >>= must+ public <- Reencode.subTransaction signed >>= must+ Sub.encodeCbor public @?= changedBytes+ changed <- must (Sub.decodeCbor changedBytes)+ changedId <- Sub.transactionId changed >>= must+ assertBool "Sub-body cache clearing retained nonminimal hash" (changedId /= identifier)+ SubBody.toBody (Sub.body changed) @?= SubBody.toBody body+ forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses (Sub.witnesses changed))) $ \witness ->+ PublicKey.verify (Witness.publicKey witness) (TxId.toBytes changedId) (Witness.signature witness) >>= (@?= Right False)+ freshBody <- must (SubBody.fromBody (SubBody.toBody body))+ Sub.encodeCbor (Sub.setBody freshBody signed) @?= original+ modifiedBody <- must (SubBody.fromBody (SubBody.fromFields ((SubBody.fields (SubBody.toBody body)) {Fields.fieldDonation = Just 0})))+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Sub.witnesses (Sub.setBody modifiedBody signed))) @?= []+ -- Clearing an enclosing transaction does NOT recurse into signed intents.+ outerBody <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodySubTransactions = Just [signed]}))+ let outer = Tx.fromBody outerBody+ outerChanged <- normalize 2 (Tx.encodeCbor outer) >>= must >>= must . Tx.decodeCbor+ case fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body outerChanged))) of+ [intent] -> do+ SubBody.toCbor (Sub.body intent) @?= bodyBytes+ Sub.transactionId intent >>= (@?= Right identifier)+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Sub.witnesses intent)) @?= Witnesses.verificationWitnesses (Witnesses.toWitnesses witnesses)+ verifyWitnesses (TxId.toBytes identifier) (Sub.witnesses intent)+ _ -> assertFailure "Enclosing cache clearing lost its intent"+ Sub.encodeCbor signed @?= original++hashSnapshots :: IO ()+hashSnapshots = forM_ [1, 28, 32, 64, 256] $ \size -> do+ let bytes = B.pack (take size (cycle ([0 .. 255] :: [Word8])))+ hash <- must (Hash.fromBytes bytes)+ -- The source owner is released by C before serializing its deep clone.+ result <- normalize 4 (Hash.encodeCbor hash) >>= must+ parsed <- must (Hash.decodeCbor result)+ Hash.toBytes parsed @?= bytes+ performGC+ Hash.toBytes hash @?= bytes++failures :: IO ()+failures = do+ values <- scriptFixtures+ let script = case values of+ first : _ -> Native.encodeCbor first+ [] -> B.empty+ list = Cbor.encode (E.encodeListLen 1) <> script+ transaction = B.singleton 0x84 <> originalBodyBytes <> B.pack [0xa0, 0xf5, 0xf6]+ sub = B.singleton 0x83 <> B.pack [0xa2, 0, 0x80, 1, 0x80, 0xa0, 0xf6]+ hash = B.pack [0x41, 0xff]+ forM_ (zip [0 ..] [script, list, transaction, sub, hash]) $ \(kind, valid) ->+ forM_ [B.empty, valid <> B.singleton 0, B.take (B.length valid - 1) valid] (normalize kind >=> (assertBool "Malformed normalization input accepted" . isLeft))++-- Raw snapshots have deliberately more information than normalized Value.+-- Serialize native stored associations via getters rather than value_to_cbor,+-- whose map serialization can omit the empty groups under examination.+rawSnapshots :: IO ()+rawSnapshots = do+ first <- must (Policy.fromBytes (B.replicate 28 1))+ second <- must (Policy.fromBytes (B.replicate 28 2))+ empty <- must (Name.fromBytes B.empty)+ binary <- must (Name.fromBytes (B.pack [0, 255]))+ let groups = [(second, []), (first, [(binary, 7)]), (first, [(binary, 2), (empty, 0), (binary, -1)])]+ forM_ [negate (2 ^ (63 :: Int)), -1, 0, 2 ^ (63 :: Int) - 1] $ \amount -> do+ snapshot <- must (Raw.mkSnapshot amount groups)+ Raw.coin snapshot @?= amount+ Raw.assets snapshot @?= [(first, [(empty, 0), (binary, 2), (binary, -1)]), (second, [])]+ request <- must (rawBytes amount groups)+ expected <- must (rawBytes (Raw.coin snapshot) (Raw.assets snapshot))+ copy <- Runtime.withBytes request $ \input size -> Runtime.withOwnedBuffer "test.rawValue.clone" (cRawValueClone input size)+ copy @?= Right expected+ performGC+ Raw.assets snapshot @?= [(first, [(empty, 0), (binary, 2), (binary, -1)]), (second, [])]+ snapshot <- must (Raw.mkSnapshot 0 groups)+ let normalized = Raw.toValue snapshot+ Value.quantity (Asset.Native first binary) normalized @?= 1+ Value.quantity (Asset.Native first empty) normalized @?= 0+ roundTrip <- must (Raw.fromValue normalized)+ assertBool "Lossy normalization unexpectedly retained raw representation" (roundTrip /= snapshot)+ Raw.toValue roundTrip @?= normalized+ forM_ [negate (2 ^ (63 :: Int)) - 1, 2 ^ (63 :: Int)] $ \quantity -> do+ Raw.mkSnapshot quantity [] @?= Left (InvalidValueQuantity quantity)+ Raw.mkSnapshot 0 [(first, [(empty, quantity)])] @?= Left (InvalidValueQuantity quantity)+ Raw.fromValue (Value.lovelace quantity) @?= Left (InvalidValueQuantity quantity)+ emptySnapshot <- must (Raw.mkSnapshot 0 [])+ emptyBytes <- must (rawBytes (Raw.coin emptySnapshot) (Raw.assets emptySnapshot))+ Runtime.withBytes emptyBytes (\input size -> Runtime.withOwnedBuffer "test.rawValue.emptyClone" (cRawValueClone input size)) >>= (@?= Right emptyBytes)+ where+ rawBytes amount groups = do+ encoded <- traverse (\(policy, names) -> (Cbor.encode (E.encodeBytes (Policy.toBytes policy)) <>) <$> Collections.encodeAssetNamesCbor names) groups+ pure (Cbor.encode (E.encodeListLen 2 <> E.encodeInteger amount <> E.encodeMapLen (fromIntegral (length groups))) <> mconcat encoded)++bodySetMode :: IO ()+bodySetMode = do+ key <- must (Credential.keyHashFromBytes (B.replicate 28 6))+ base <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldGuards = Just [Credential.KeyCredential key]}}))+ forM_ [base, Body.withSetEncoding Body.Inputs TaggedSet base, Body.withSetEncoding Body.Inputs UntaggedSet base] $ \body -> do+ let expected = Body.setEncoding Body.Inputs body == Just TaggedSet+ Body.inputsAreTagged body @?= expected+ Runtime.withBytes (Body.toCbor body) $ \input size -> alloca $ \before -> alloca $ \after -> do+ cBodySetMode input size before after >>= (@?= 0)+ observed <- peek before+ dirty <- peek after+ observed @?= if expected then 1 else 0+ dirty @?= 1+ let mixed = Body.withSetEncoding Body.Inputs UntaggedSet base+ Body.setEncoding Body.Guards mixed @?= Just TaggedSet+ Body.inputsAreTagged mixed @?= False+ -- Once the body cache is discarded, the native input-set writer emits+ -- tag258 unconditionally. Observe the new bytes, keeping the source exact.+ reencoded <- Reencode.transaction (Tx.fromBody mixed) >>= must+ Body.inputsAreTagged (Tx.body reencoded) @?= True+ Body.inputsAreTagged mixed @?= False++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_encoding_normalize"+ cNormalize :: CUInt -> Ptr Word8 -> CSize -> Ptr (Ptr Runtime.Buffer) -> IO NativeCode++foreign import ccall safe "cometa_test_raw_value_clone"+ cRawValueClone :: Ptr Word8 -> CSize -> Ptr (Ptr Runtime.Buffer) -> IO NativeCode++foreign import ccall safe "cometa_test_body_set_mode"+ cBodySetMode :: Ptr Word8 -> CSize -> Ptr CUInt -> Ptr CUInt -> IO NativeCode
@@ -0,0 +1,176 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}++module ErrorCode (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.FFI.Native as Native+import Data.List (nub)+import Foreign.C.String (CString, peekCString)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Storable (sizeOf)+import Hedgehog (Property, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertEqual, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Native error codes"+ [ testCase "copied codes agree with all installed native header constants" $ do+ count <- cErrorCodeCount+ count @?= fromIntegral (length Code.knownCodes)+ mapM_+ ( \(index, code) -> do+ symbol <- cErrorCodeName index >>= peekCString+ number <- cErrorCodeValue index+ assertEqual symbol (Code.toNumber code) (toInteger number)+ )+ (zip [0 .. count - 1] Code.knownCodes),+ testCase "explicit unsigned status ABI matches C width and range" $ do+ cStatusSize >>= (@?= fromIntegral (sizeOf (0 :: Native.NativeCode)))+ cStatusMax >>= (@?= (maxBound :: Native.NativeCode))+ mapM_+ ( \code -> do+ let number = fromInteger (Code.toNumber code)+ cStatusRoundTrip number >>= (@?= number)+ )+ Code.knownCodes,+ testCase "every pinned header code has its expected name and number" $+ mapM_+ ( \(code, number) -> do+ Code.toNumber code @?= number+ Code.fromNumber number @?= code+ Code.isKnown code @?= True+ )+ expectedCodes,+ testCase "known codes are complete, ordered, and distinct" $ do+ Code.knownCodes @?= map fst expectedCodes+ nub (map Code.toNumber Code.knownCodes) @?= map snd expectedCodes,+ testCase "unknown gaps and unbounded integers survive without truncation" $+ mapM_+ ( \number -> do+ let code = Code.fromNumber number+ Code.toNumber code @?= number+ Code.isKnown code @?= False+ Code.fromNumber (Code.toNumber code) @?= code+ )+ [-1, 24, 99, 103, 199, 207, 299, 306, 1201, negate (2 ^ (128 :: Int)), 2 ^ (128 :: Int)],+ testProperty "arbitrary numeric codes round trip" propNumberRoundTrip+ ]++propNumberRoundTrip :: Property+propNumberRoundTrip = property $ do+ number <- forAll (Gen.integral (Range.linear (negate (2 ^ (256 :: Int))) (2 ^ (256 :: Int))))+ let code = Code.fromNumber number+ Code.toNumber code === number+ Code.fromNumber (Code.toNumber code) === code++-- Independent expectations transcribed from cardano/error.h at the pinned+-- revision 8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d (Apache-2.0). These do not+-- reuse the implementation's copied values. The C oracle independently reads+-- every installed header constant, so changed native assignments trigger review.+expectedCodes :: [(Code.ErrorCode, Integer)]+expectedCodes =+ [ (Code.Success, 0),+ (Code.GenericFailure, 1),+ (Code.InsufficientBufferSize, 2),+ (Code.NullPointer, 3),+ (Code.MemoryAllocationFailed, 4),+ (Code.OutOfBoundsMemoryRead, 5),+ (Code.OutOfBoundsMemoryWrite, 6),+ (Code.InvalidArgument, 7),+ (Code.InvalidUrl, 8),+ (Code.ElementNotFound, 9),+ (Code.EncodingFailure, 10),+ (Code.DecodingFailure, 11),+ (Code.ChecksumMismatch, 12),+ (Code.InvalidJson, 13),+ (Code.IntegerOverflow, 14),+ (Code.IntegerUnderflow, 15),+ (Code.ConversionFailed, 16),+ (Code.IndexOutOfBounds, 17),+ (Code.InvalidCertificateType, 18),+ (Code.NotImplemented, 19),+ (Code.InvalidPassphrase, 20),+ (Code.IllegalState, 21),+ (Code.DuplicateKey, 22),+ (Code.JsonTypeMismatch, 23),+ (Code.LossOfPrecision, 100),+ (Code.InvalidMagic, 101),+ (Code.InvalidChecksum, 102),+ (Code.InvalidBlake2bHashSize, 200),+ (Code.InvalidEd25519SignatureSize, 201),+ (Code.InvalidEd25519PublicKeySize, 202),+ (Code.InvalidEd25519PrivateKeySize, 203),+ (Code.InvalidBip32PublicKeySize, 204),+ (Code.InvalidBip32PrivateKeySize, 205),+ (Code.InvalidBip32DerivationIndex, 206),+ (Code.UnexpectedCborType, 300),+ (Code.InvalidCborValue, 301),+ (Code.InvalidCborArraySize, 302),+ (Code.InvalidCborMapSize, 303),+ (Code.DuplicateCborMapKey, 304),+ (Code.InvalidCborMapKey, 305),+ (Code.InvalidAddressType, 400),+ (Code.InvalidAddressFormat, 401),+ (Code.InvalidCredentialType, 500),+ (Code.InvalidPlutusDataConversion, 600),+ (Code.InvalidDatumType, 601),+ (Code.InvalidScriptLanguage, 700),+ (Code.InvalidNativeScriptType, 701),+ (Code.InvalidPlutusCostModel, 702),+ (Code.InvalidProposalProcedureType, 800),+ (Code.InvalidMetadatumConversion, 900),+ (Code.InvalidMetadatumTextStringSize, 901),+ (Code.InvalidMetadatumBoundedBytesSize, 902),+ (Code.InvalidHttpRequest, 1000),+ (Code.InsufficientBalance, 1100),+ (Code.UtxoNotFragmentedEnough, 1101),+ (Code.UtxoFullyDepleted, 1102),+ (Code.MaximumInputCountExceeded, 1103),+ (Code.UnbalancedSubTransactions, 1104),+ (Code.DisallowedSupplementalDatums, 1105),+ (Code.MissingRedeemer, 1106),+ (Code.ScriptEvaluationFailure, 1200)+ ]++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_error_code_count"+ cErrorCodeCount :: IO CSize++foreign import ccall unsafe "cometa_test_error_code_name"+ cErrorCodeName :: CSize -> IO CString++foreign import ccall unsafe "cometa_test_error_code_value"+ cErrorCodeValue :: CSize -> IO CUInt++foreign import ccall unsafe "cometa_test_status_size"+ cStatusSize :: IO CSize++foreign import ccall unsafe "cometa_test_status_max"+ cStatusMax :: IO CUInt++foreign import ccall unsafe "cometa_test_status_roundtrip"+ cStatusRoundTrip :: CUInt -> IO CUInt
@@ -0,0 +1,325 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Injected evaluation and signing workflows, correspondence and callback lifetime.+module Evaluation (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Evaluation as Values+import qualified Cometa.Internal.EvaluationNative as Native+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.KeyHandler.Software as Software+import qualified Cometa.PlutusData as Data+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Signer as Signer+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, displayException, finally, fromException, try)+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Text as Text+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Evaluation and signer injection"+ [ testCase "direct and native budgets correspond exactly without installing edits" correspondence,+ testCase "explicit sub-target returns only that level's arguments and budgets" subTarget,+ testCase "duplicate, missing, unknown identifiers and changed arguments fail" invalidResults,+ testCase "invalid target and duplicate resolved refs fail before dispatch" invalidRequests,+ testCase "native repeated callbacks and retained aliases root registrations" retention,+ testCase "native callback domain errors and thrown/lazy exceptions preserve identity" exceptions,+ testCase "same-registration callback reentry fails promptly" reentry,+ testCase "cancellation joins callback cleanup and evaluator remains usable" cancellation,+ testCase "partial native parse failures and malformed replies release resources" partialFailures,+ testCase "signer closures compose existing scoped keys and handlers" signing,+ testProperty "generated full-range budgets retain exact redeemer arguments" propBudgets+ ]++fixture :: Either Error Tx.Transaction+fixture = do+ argument <- Data.decodeCbor (B.pack [0x18, 0])+ let redeemers = [Redeemer.Redeemer purpose (fromIntegral (fromEnum purpose)) argument (ExUnits 1 2) | purpose <- [minBound .. maxBound]]+ ws <- Witnesses.mkWitnesses [] [] [] [] redeemers+ subWs <- Witnesses.mkWitnesses [] [] [] [] [Redeemer.Redeemer Redeemer.Minting maxBound argument (ExUnits 3 4)]+ subBody <- SubBody.fromBody (SubBody.body [] [])+ body <- Body.fromBody (Body.body [] [] 0) {Body.bodySubTransactions = Just [Sub.assemble subBody (Witnesses.fromWitnesses subWs) Nothing]}+ pure (Tx.assemble body (Witnesses.fromWitnesses ws) Nothing)++computed :: Evaluation.Target -> Tx.Transaction -> Either Error Evaluation.Budgets+computed target transaction = do+ values <- Values.targetRedeemers target transaction+ Evaluation.mkBudgets [(Evaluation.RedeemerId (Redeemer.purpose r) (Redeemer.index r), ExUnits maxBound (fromIntegral (Redeemer.index r))) | r <- values]++backend :: Evaluation.Evaluator+backend = Evaluation.Evaluator (\target transaction _ -> pure (computed target transaction))++correspondence :: IO ()+correspondence = do+ transaction <- require fixture+ let original = Tx.encodeCbor transaction+ expected <- require (computed Evaluation.TopLevel transaction)+ Evaluation.evaluate backend Evaluation.TopLevel transaction [] >>= (@?= Right expected)+ actual <- Native.withEvaluator backend Evaluation.TopLevel $ \native -> Native.evaluate native transaction []+ actual @?= Right expected+ providerResult <- Native.withProviderEvaluator backend $ \native -> Native.evaluateRepeated 3 native transaction []+ providerResult @?= Right expected+ Tx.encodeCbor transaction @?= original+ resolved <- require (hexBytes utxoHex >>= Utxo.decodeCbor)+ observed <- newIORef Nothing+ let snapshotEvaluator = Evaluation.Evaluator (\target tx inputs -> writeIORef observed (Just (tx, inputs)) >> pure (computed target tx))+ indefiniteBytes = B.singleton 0x9f <> B.drop 1 original <> B.singleton 0xff+ indefinite <- require (Tx.decodeCbor indefiniteBytes)+ snapshotResult <- Native.withEvaluator snapshotEvaluator Evaluation.TopLevel $ \native -> Native.evaluate native indefinite [resolved]+ snapshotResult @?= Right expected+ snapshot <- readIORef observed+ case snapshot of+ Nothing -> assertFailure "native evaluator did not receive resolved context"+ Just (received, inputs) -> do+ -- Snapshots remain valid after C owners and the callback registration die.+ Body.toCbor (Tx.body received) @?= Body.toCbor (Tx.body indefinite)+ Witnesses.toCbor (Tx.witnesses received) @?= Witnesses.toCbor (Tx.witnesses indefinite)+ inputs @?= [resolved]+ Tx.encodeCbor indefinite @?= indefiniteBytes+ -- No implicit budget installation: the original budgets still equal [1,2].+ let originalRedeemers = Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses transaction))+ map Redeemer.executionUnits originalRedeemers @?= replicate 7 (ExUnits 1 2)+ emptyBody <- require (Body.fromBody (Body.body [] [] 0))+ empty <- require (Evaluation.mkBudgets [])+ Evaluation.evaluate backend Evaluation.TopLevel (Tx.fromBody emptyBody) [] >>= (@?= Right empty)++subTarget :: IO ()+subTarget = do+ transaction <- require fixture+ let target = Evaluation.SubTransaction 0+ expected <- require (computed target transaction)+ result <- Native.withEvaluator backend target $ \native -> Native.evaluate native transaction []+ result @?= Right expected+ map fst (Evaluation.budgets expected) @?= [Evaluation.RedeemerId Redeemer.Minting maxBound]+ Evaluation.evaluate backend (Evaluation.SubTransaction maxBound) transaction [] >>= assertBool "out of range target" . isLeft++invalidResults :: IO ()+invalidResults = do+ transaction <- require fixture+ let identifier = Evaluation.RedeemerId Redeemer.Spending 0+ budget = (identifier, ExUnits 1 2)+ assertBool "duplicate rejected" (isLeft (Evaluation.mkBudgets [budget, budget]))+ missing <- require (Evaluation.mkBudgets [])+ extra <- require (Evaluation.mkBudgets [(Evaluation.RedeemerId Redeemer.Guarding maxBound, ExUnits 1 2)])+ forM_ [missing, extra] $ \result -> do+ let evaluator = Evaluation.Evaluator (\_ _ _ -> pure (Right result))+ Evaluation.evaluate evaluator Evaluation.TopLevel transaction [] >>= assertBool "incomplete result rejected" . isLeft+ Native.withEvaluator evaluator Evaluation.TopLevel (\native -> Native.evaluate native transaction []) >>= assertBool "native incomplete result rejected" . isLeft+ computedBudgets <- require (computed Evaluation.TopLevel transaction)+ values <- require (Values.checkedRedeemers Evaluation.TopLevel transaction computedBudgets)+ let changed = map (\r -> r {Redeemer.argument = Data.fromData (Data.Integer 0)}) values+ assertBool "semantic-equal argument with different exact bytes rejected" (isLeft (Values.budgetsFromRedeemers Evaluation.TopLevel transaction changed))++invalidRequests :: IO ()+invalidRequests = do+ transaction <- require fixture+ calls <- newIORef (0 :: Int)+ let evaluator = Evaluation.Evaluator (\target tx _ -> modifyIORef' calls (+ 1) >> pure (computed target tx))+ Evaluation.evaluate evaluator (Evaluation.SubTransaction 1) transaction [] >>= assertBool "invalid target rejected" . isLeft+ readIORef calls >>= (@?= 0)+ -- Duplicate resolution is checked even when output bytes agree. Use a typed+ -- fixture from an independently encoded UTxO, rather than faking a handle.+ resolved <- require (hexBytes utxoHex >>= Utxo.decodeCbor)+ Evaluation.evaluate evaluator Evaluation.TopLevel transaction [resolved, resolved] >>= assertBool "duplicate refs rejected" . isLeft+ readIORef calls >>= (@?= 0)++retention :: IO ()+retention = do+ baseline <- Runtime.liveContexts+ transaction <- require fixture+ calls <- newIORef (0 :: Int)+ let evaluator =+ Evaluation.Evaluator+ ( \target tx _ -> do+ performGC+ modifyIORef' calls (+ 1)+ pure (computed target tx)+ )+ result <- Native.withEvaluator evaluator Evaluation.TopLevel $ \native -> Native.withRetained native $ \alias -> do+ Native.close native >>= (@?= Right ())+ Native.evaluate native transaction [] >>= (@?= Left RuntimeClosed)+ Native.evaluateRepeated 8 alias transaction []+ expected <- require (computed Evaluation.TopLevel transaction)+ result @?= Right expected+ readIORef calls >>= (@?= 8)+ Runtime.liveContexts >>= (@?= baseline)++exceptions :: IO ()+exceptions = do+ baseline <- Runtime.liveContexts+ transaction <- require fixture+ let expectedError = UnsupportedOperation (Text.replicate 2048 "e")+ failed = Evaluation.Evaluator (\_ _ _ -> pure (Left expectedError))+ result <- Native.withEvaluator failed Evaluation.TopLevel (\native -> Native.evaluate native transaction [])+ result @?= Left expectedError+ forM_ [Evaluation.Evaluator (\_ _ _ -> ioError (userError "evaluator throw")), Evaluation.Evaluator (\_ _ _ -> pure (Right (error "evaluator lazy poison")))] $ \evaluator -> do+ outcome <- try (Native.withEvaluator evaluator Evaluation.TopLevel (\native -> Native.evaluate native transaction []))+ case outcome of+ Left (cause :: SomeException) -> assertBool "exception preserved" ("evaluator" `Text.isInfixOf` Text.pack (displayException cause))+ Right _ -> assertFailure "callback exception was swallowed"+ Runtime.liveContexts >>= (@?= baseline)++reentry :: IO ()+reentry = within $ do+ transaction <- require fixture+ installed <- newIORef Nothing+ observed <- newEmptyMVar+ let evaluator =+ Evaluation.Evaluator+ ( \target tx _ -> do+ active <- readIORef installed+ case active of+ Nothing -> assertFailure "missing native evaluator" >> pure (Left RuntimeClosed)+ Just native -> do+ nested <- Native.evaluate native tx []+ putMVar observed nested+ pure (computed target tx)+ )+ _ <- Native.withEvaluator evaluator Evaluation.TopLevel $ \native -> do+ writeIORef installed (Just native)+ Native.evaluate native transaction []+ takeMVar observed >>= (@?= Left RuntimeBusy)++cancellation :: IO ()+cancellation = within $ do+ transaction <- require fixture+ entered <- newEmptyMVar+ cleaned <- newEmptyMVar+ blocked <- newEmptyMVar+ finished <- newEmptyMVar+ calls <- newIORef (0 :: Int)+ let evaluator =+ Evaluation.Evaluator+ ( \target tx _ -> do+ index <- readIORef calls+ modifyIORef' calls (+ 1)+ if index == 0+ then (putMVar entered () >> takeMVar blocked) `finally` putMVar cleaned ()+ else pure (computed target tx)+ )+ result <- Native.withEvaluator evaluator Evaluation.TopLevel $ \native -> do+ worker <- forkFinally (Native.evaluate native transaction []) (putMVar finished)+ takeMVar entered+ killThread worker+ outcome <- takeMVar finished+ takeMVar cleaned+ case outcome of+ Left cause -> (fromException cause :: Maybe AsyncException) @?= Just ThreadKilled+ Right _ -> assertFailure "cancelled evaluation returned normally"+ Native.evaluate native transaction []+ assertBool "evaluator usable after cancellation" (not (isLeft result))++partialFailures :: IO ()+partialFailures = do+ baseline <- Runtime.liveContexts+ transaction <- require fixture+ -- First valid map entry allocates data/units/redeemer, then the second entry+ -- fails; trailing reply also fails after a whole list has been acquired.+ forM_ [B.pack [0xa2, 0x82, 0, 0, 0x82, 0, 0x82, 0, 0, 0x82, 1, 0, 0x82, 0], B.pack [0xa0, 0]] $ \reply ->+ replicateM_ 20 $ do+ result <- Native.withDispatch Evaluation.TopLevel (\_ _ -> pure (Right reply)) $ \native -> Native.runUnchecked 1 native (Tx.encodeCbor transaction) (B.singleton 0x80)+ assertBool "malformed reply rejected" (isLeft result)+ Native.withEvaluator backend Evaluation.TopLevel (\native -> Native.runUnchecked 1 native (B.pack [0x84, 0xa0]) (B.singleton 0x80)) >>= assertBool "partial tx parse fails" . isLeft+ Native.withEvaluator backend Evaluation.TopLevel (\native -> Native.runUnchecked 1 native (Tx.encodeCbor transaction) (B.pack [0x81, 0x82, 0x80])) >>= assertBool "partial UTxO parse fails" . isLeft+ Runtime.liveContexts >>= (@?= baseline)++signing :: IO ()+signing = do+ transaction <- require fixture+ escaped <- newEmptyMVar+ partial <- Key.withNormalKey (B.replicate 32 4) $ \key -> do+ let signer = Signer.ed25519 key+ putMVar escaped signer+ Signer.signTransaction signer transaction+ witnesses <- require partial+ signed <- require (Tx.addWitnesses witnesses transaction)+ Body.toCbor (Tx.body signed) @?= Body.toCbor (Tx.body transaction)+ length (Witnesses.verificationWitnesses (Witnesses.toWitnesses witnesses)) @?= 1+ closedSigner <- takeMVar escaped+ Signer.signTransaction closedSigner transaction >>= (@?= Left SigningKeyClosed)+ normal <- Key.withNormalKey (B.replicate 32 4) $ \key -> Software.withSigningKey key "password" (pure "password") (\handler -> Signer.signTransaction (Signer.software handler) transaction)+ require normal >>= (@?= witnesses)+ let path = Path.derivationPath (Path.standardAccountPath minBound) Path.externalRole minBound+ hierarchical <- Software.withEntropy (B.replicate 16 0) "password" (pure "password") (\handler -> Signer.signTransaction (Signer.bip32 handler (path :| [])) transaction)+ result <- require hierarchical+ length (Witnesses.verificationWitnesses (Witnesses.toWitnesses result)) @?= 1++propBudgets :: Property+propBudgets = property $ do+ amount <- forAll (Gen.word64 Range.constantBounded)+ index <- forAll (Gen.word32 Range.constantBounded)+ purpose <- forAll Gen.enumBounded+ argument <- evalEither (Data.decodeCbor (B.pack [0x18, 0]))+ ws <- evalEither (Witnesses.mkWitnesses [] [] [] [] [Redeemer.Redeemer purpose index argument (ExUnits 0 0)])+ body <- evalEither (Body.fromBody (Body.body [] [] 0))+ let transaction = Tx.assemble body (Witnesses.fromWitnesses ws) Nothing+ result <- evalEither (Evaluation.mkBudgets [(Evaluation.RedeemerId purpose index, ExUnits amount amount)])+ let evaluator = Evaluation.Evaluator (\_ _ _ -> pure (Right result))+ actual <- evalIO (Native.withEvaluator evaluator Evaluation.TopLevel (\native -> Native.evaluate native transaction []))+ actual === Right result+ bytes <- evalEither (Redeemer.encodeCollectionCbor [Redeemer.Redeemer purpose index argument (ExUnits amount amount)])+ decoded <- evalEither (Redeemer.decodeCollectionCbor bytes)+ map (Data.toCbor . Redeemer.argument) decoded === [Data.toCbor argument]++within :: IO a -> IO a+within action = do+ result <- timeout 5000000 action+ case result of+ Nothing -> assertFailure "callback operation timed out" >> fail "unreachable"+ Just value -> pure value++hexBytes :: Text.Text -> Either Error ByteString+hexBytes = maybe (Left InvalidHex) Right . Hex.decodeHex++require :: Either Error a -> IO a+require = either (\failure -> assertFailure (show failure) >> fail "unreachable") pure++-- Original deterministic fixture: input32zero/index0 and a legacy enterprise+-- output (network0, key28zero, lovelace1). No live chain or funded wallet data.+utxoHex :: Text.Text+utxoHex = "8282582000000000000000000000000000000000000000000000000000000000000000000082581d600000000000000000000000000000000000000000000000000000000001"
@@ -0,0 +1,128 @@+# Independent fee and accounting properties++`AccountingReliability.hs` adds four generated properties and a fixed rounding+regression through public bindings, with no new dependencies. No upstream code,+generator or fixture was copied.++## Gap audit against existing tests++`TransactionAccountingProperties` already checks generated certificate/proposal+and withdrawal totals, signed mint conservation, one outer plus one local intent,+and pool identities with repeated identical pool parameter records. The new+properties do not add another copy of those equations. ContextualTransaction+checks lookup/order/authority rather than fees. TransactionBuilding already has+fixed fee, size, execution and pool examples, but some expected values call+native fee/size oracles; it does not generate witness23/24 boundaries, reference+payload partitions, several intent execution rounding, or changing pool+registration contents with retirement interleaving at signed accumulator limits.++## Pinned primary upstream sources actually reviewed++All cardano-ledger paths below are from commit+`7827506b7518284d7f9dbbe3502a20431e513fe9`, Apache-2.0. Primary URLs are+`https://github.com/IntersectMBO/cardano-ledger/blob/7827506b7518284d7f9dbbe3502a20431e513fe9/`+followed by the exact paths below. Source files were fetched directly from that+commit for this review. The Apache-2.0 license was reviewed alongside them.++- `eras/alonzo/impl/src/Cardano/Ledger/Alonzo/Tx.hs`:+ `toCBORForSizeComputation` encodes the three-member envelope+ `[body,witnesses,auxiliary-data-or-null]`, omitting the validity Boolean;+ `alonzoMinFeeTx` combines linear size charge with one fee on all execution units.+- `libs/cardano-ledger-core/src/Cardano/Ledger/Plutus/ExUnits.hs`: `txscriptfee` rounds the+ combined memory/step rational charge upward once. The Alonzo Scripts module+ re-exports this implementation.+- `eras/conway/impl/src/Cardano/Ledger/Conway/Tx.hs`: `tierRefScriptFee` prices+ bytes in fixed-stride exponentially increasing/decreasing rational tiers and+ floors the entire sum once. Test oracle instead assigns each byte its marginal+ tier rate; it does not copy that upstream tier-loop implementation or the+ native checked mixed-number/coarsening algorithm.+- `eras/conway/impl/src/Cardano/Ledger/Conway/UTxO.hs`: produced/consumed values+ delegate to Mary accounting, while treasury donation is an additional produced+ coin term. This scopes accounting independently of witness/script admission.+- `eras/mary/impl/src/Cardano/Ledger/Mary/UTxO.hs`: produced value takes a+ predicate keyed by pool identity; consumed value includes withdrawals/refunds+ and positive mint, while negative mint is produced burn.+- `eras/shelley/impl/src/Cardano/Ledger/Shelley/UTxO.hs`: `produced` supplies pool+ registration membership from a map keyed by pool identifier; produced value+ includes outputs, fee and deposits. The identity is not the complete mutable+ pool parameters record. Native Cometa cannot supply existing chain state, so+ its documented batch contract charges each observed operator once instead.++Pinned upstream tests were reviewed to distinguish arithmetic from admission:++- `eras/conway/impl/testlib/Test/Cardano/Ledger/Conway/Imp/CertsSpec.hs`: withdrawals from an+ unregistered or wrong-network account fail state/witness conditions. A correct+ arithmetic sum alone therefore does not imply ledger acceptance.+- `eras/dijkstra/impl/testlib/Test/Cardano/Ledger/Dijkstra/Imp/SubUtxowSpec.hs`: pool registrations+ require the owner witness; staking unregistration uses the stored deposit and+ credential witness. These are real ledger-context obligations deliberately+ outside standalone fee/accounting snapshots. No such stateful test is imported+ or claimed to execute through Cometa.++## Independent expectations and supported generated domain++### Linear fee++Builds real typed witnesses with unique 32-byte keys/64-byte signatures and+metadata optionality. These are structurally valid byte lengths, not claims of+curve-point/signature validity. Counts 0,1,2,22,23,24,25 cross the witness list+header boundary; metadata byte counts 0,1,23,24,63,64 and body fee amounts cross+CBOR width boundaries. The oracle is++`constant + coefficient * (1 + bodyBytes + witnessBytes + auxBytesOrNull)`.++Lengths come from separately observable public constituent bytes. No full+transaction size or native fee helper supplies the expected answer. Flipping+the script-validity flag must preserve the fee, and the original transaction's+exact encoding remains unchanged. This covers fresh definite frames, not a+claim about every historical/nonminimal transaction envelope.++### Reference tiers and partition invariance++Each byte index j contributes `price * multiplier^(j div stride)` as an exact+Haskell Rational; the total is floored once. Generated strides 1,2,5,23,24,64,+zero/exact-boundary/+/-1 sizes and up to six tiers exercise rounding and the+zero-price case. Multipliers 1/2,1,3/2,6/5 cover decreasing, constant and increasing+rates without unsafe zero denominators. Prices are small bounded rationals.+Reference scripts are arbitrary nonempty Plutus V2 byte programs, because this+native fee path prices stored bytes without executing UPLC. Distinct resolved+UTxO identities partition one total payload at generated cut points; each+partition and a single contiguous payload must match the independent byte-rate+sum. This catches per-script rounding or tier-reset bugs. Actual UPLC validity,+script admission and transaction size limits are not asserted.++### Native whole-batch execution fee++Generates one outer group and up to four local intent groups of declared+memory/step budgets. Nonmonetary validity-start fields keep local body identities+distinct even when budget lists shrink to equal/empty values. Every nonempty+witness group uses distinct redeemer indices, and no scripts are executed.+The oracle sums raw generated memory/step charges over every group and takes+one ceiling. Linear fee parameters and reference byte price are zero, isolating+the actual native execution contribution inside `Building.minimumFee`; neither+Building.executionFee nor native pricing helpers supply an expected result.+The fixed case has four separate half-unit memory charges: native total must+be 2 rather than four individually rounded charges. Classifications record cases+where separate intent rounding would overcharge. Empty nested sets are absent,+not invalid Just-empty fields. Native minimum-fee resolution is exactly empty+because there are no spending/reference inputs.++### Pool updates, retirements and many bodies++Generates two through five total bodies with registration/retirement events over+four raw pool IDs. Every registration occurrence varies pledge/cost by body and+position, so duplicate operator identities do NOT disappear as byte-identical+certificates before accounting. Expected batch produced coin is+`number of distinct generated registered IDs * deposit`; retirement has no+immediate refund. Exact top-level deposits are also checked separately.+The oracle consumes generated IDs, not decoded certificates or native results.+Nonmonetary validity-start values ensure distinct local body IDs. Large deposits+are bounded by `INT64_MAX / max(1,total registration occurrences)`, keeping even+an undeduplicated intermediate total signed-safe; a wrong dedup result therefore+fails numerically rather than entering native overflow. 0/1/23/24/65536 and+near-signed-limit deposits are included. Tags, counters, syntax and actual chain+registration/refund state are not interpreted as admission tests.++No mint field is constructed by these tests, avoiding the previously found+Just-empty mint shrink case. All generators retain valid independent snapshots+when shrinking. Original transaction bytes are compared after native calls.
@@ -0,0 +1,36 @@+# Shelley address fixtures++`Fixtures/Address.hs` imports the 16 base/enterprise/reward mainnet/testnet+Bech32 vectors from cardano-c commit+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`,+`lib/tests/address/cip19_test_vectors.h`, under Apache-2.0 (copyright Biglup+Labs, 2024; native header retains attribution to CIP-19). Hash bytes in `Address.hs`+come from the same fixture. Current verification uses a fresh native static+build of the merged revision with interprocedural optimization disabled, matching+the repository CI recipe. The earlier reviewed source revision+`7a65f2c7309bbba9e86f6aa73214b003fab88aee` has identical relevant source content.+No upstream test/generator implementation was copied. Equality with native+constructors and Bech32 operations is binding conformance, not an independent+cryptographic or ledger oracle.++The test-only C oracle reconstructs native credentials and each supported+address form from separate Haskell header/hash fields, checks native header,+network, exact bytes and pure Haskell Bech32 text, and releases all references.+Every form is tested on all 16 network tags. A separate native Bech32 encoder deliberately produces+valid-checksum mismatched HRPs and trailing payloads, proving strict Haskell+rejection independently of checksum validation. New shrinking generators are+local Hedgehog code; no imported generator license applies.++The production text codec uses bech32 >=1.1.10 && <1.2 (locally tested with+1.1.11). Its four private built-in prefixes use the public HRP validator; a+source-controlled fixed-literal invariant assertion is checked by direct prefix+validation and all 16 native text vectors. No external input reaches that+assertion, and there is no native call or unsafePerformIO in the codecs.++The suite checks exact input bounds, all supported discriminants, unsupported+pointer/Byron/reserved discriminants, lowercase and uppercase input, mixed-case+and malformed text, public-key hashing, copied-value GC survival, repeated+success/failure, strict nonzero/excessive bit padding, and shared pure codec+evaluation through GC. There is no persistent native address handle or callback+registry in production.+Deterministic native allocation-failure injection is not implemented.
@@ -0,0 +1,33 @@+# Asset and value fixtures++`test/Value.hs` selects identifier bytes from cardano-c revision+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`:++- `lib/tests/assets/asset_name.cpp`: `skywalker`, hexadecimal+ `736b7977616c6b6572`.+- `lib/tests/assets/multi_asset.cpp` and+ `lib/tests/transaction_body/value.cpp`: 28-byte all-zero/all-0x11 policies,+ names `30313232`, `33343536`, `40414242`, and the 1,000,000-lovelace coin.++These upstream fixtures are Apache-2.0, copyright Biglup Labs 2024. No upstream+implementation, test, property or generator code was copied. Binary/UTF-8,+zero/negative, exact int64 endpoints and arbitrary-precision cases are local+Cometa tests. The association-list quantity model and shrinking Hedgehog+properties are independently authored here.++The test-only C oracle constructs native names, asset IDs and values from+public Haskell components, compares exact identifier bytes and native Ada flags,+and checks coin/token quantities after native addition/subtraction. It also+checks inputs after arithmetic, detecting observable mutation. It owns and+releases all references in each call; no mutable object escapes. Native agreement+is conformance evidence, not an independent ledger oracle.++Haskell checks every input, sum and difference in Integer against signed int64+bounds before conversion. The native code has unchecked signed arithmetic;+int64 endpoint fixtures use a zero right operand. Native coin fields are signed+int64 even though native output CBOR uses unsigned integers. No decoder, encoder,+production marshaling boundary or native allocation-failure injection is added.+Integer values outside native bounds remain lawful pure bundles, and are tested+without entering C. Negative quantities remain signed; no output or mint validity+is inferred. Native collection duplicate/zero representation and CBOR ordering+are deliberately separate from normalized semantic bundle equality and ordering.
@@ -0,0 +1,45 @@+-- Copyright 2024 Biglup Labs+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | CIP-19 vectors imported from the pinned native fixture; provenance in ADDRESSES.md.+module Fixtures.Address (vectors) where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++vectors :: [(Integer, Int, Text)]+vectors =+ [ (1, 0, "addr1qx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgse35a3x"),+ (1, 1, "addr1z8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs9yc0hh"),+ (1, 2, "addr1yx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs2z78ve"),+ (1, 3, "addr1x8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shskhj42g"),+ (1, 6, "addr1vx2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzers66hrl8"),+ (1, 7, "addr1w8phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcyjy7wx"),+ (1, 14, "stake1uyehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gh6ffgw"),+ (1, 15, "stake178phkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcccycj5"),+ (0, 0, "addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3n0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgs68faae"),+ (0, 1, "addr_test1zrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gten0d3vllmyqwsx5wktcd8cc3sq835lu7drv2xwl2wywfgsxj90mg"),+ (0, 2, "addr_test1yz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerkr0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shsf5r8qx"),+ (0, 3, "addr_test1xrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gt7r0vd4msrxnuwnccdxlhdjar77j6lg0wypcc9uar5d2shs4p04xh"),+ (0, 6, "addr_test1vz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzerspjrlsz"),+ (0, 7, "addr_test1wrphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcl6szpr"),+ (0, 14, "stake_test1uqehkck0lajq8gr28t9uxnuvgcqrc6070x3k9r8048z8y5gssrtvn"),+ (0, 15, "stake_test17rphkx6acpnf78fuvxn0mkew3l0fd058hzquvz7w36x4gtcljw6kf")+ ]
@@ -0,0 +1,72 @@+# BIP32 test fixture provenance++All secrets are deterministic test material, never application keys or funded+wallet material. Tests use no credentials, network, Python packages or random+wallet secrets.++## Imported native vectors++Fixture source revision: `8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d`.+The current build revision is recorded separately in `native/cardano-c.ref`.+Values in `Fixtures.Bip32` were transcribed from:++- `lib/tests/crypto/bip32_private_key.cpp`: constant `BIP32_PRIVATE_KEY_HEX`;+ `deriveCorrectHardenedKey` for `[1852',1815',0']`;+ `deriveCorrectUnHardenedKey` for `[1852,1815,0]` (this scenario uses a different+ input key); `canComputeTheCorrectPublicKey`; and+ `computesTheRightKeyFromTheEntropyAndPassword`.+- `lib/tests/crypto/bip32_public_key.cpp`: constant `BIP32_PUBLIC_KEY_HEX` and+ `deriveCorrectUnhardenedKey` for `[1852,1815,0]`.++Both native files are Copyright 2024 Biglup Labs, licensed under Apache-2.0.+This repository retains Apache-2.0 in `LICENSE`; this provenance preserves source+attribution. Only numerical vectors were transcribed. These are native Cardano+Ed25519-BIP32 vectors, not Bitcoin/secp256k1 BIP32 or RFC 8032 derivation vectors.+The Haskell Hedgehog generators and properties are new, not copied test code.++## Independent checks++Python 3 standard-library `hashlib.pbkdf2_hmac` independently regenerated the+imported password/entropy root and two additional fixed roots. Recipe:++```python+import hashlib++def root(password, entropy):+ key = bytearray(hashlib.pbkdf2_hmac("sha512", password, entropy, 4096, 96))+ key[0] &= 248+ key[31] = (key[31] & 31) | 64+ return bytes(key).hex()+```++Inputs: imported entropy `caec96d09fc2020ab230199e0188cd6a554e2da2cba32de9ff6c0908c7f04d65`+with ASCII password `some_password_@#$%^&`; sixteen zero bytes with empty password;+and `bytes(range(32))` with password `b"a\x00b"`. The last case proves embedded+NUL preservation. Literal expected outputs are stored in `Fixtures.Bip32`.+`publicHashHex` was computed with+`hashlib.blake2b(bytes.fromhex(publicHex), digest_size=28).hexdigest()`.++These independent checks cover root KDF and full-xpub hashing. Derived child+known answers come from the pinned native corpus; Haskell/native agreement is+not an independent proof of the derivation algorithm.++## Binding contract adaptations and lifecycle++Native root import accepts arbitrary nonempty entropy. The Haskell BIP39 entropy+constructor deliberately accepts only standard BIP39 sizes (16,20,24,28,32 bytes).+Native derive rejects empty paths; Haskell uses the identity law instead: immutable+public reuse or an independent private clone. `harden` preserves native idempotent+high-bit OR semantics. Public derivation rejects high-bit indices before native+work. Length-only key import preserves native validation policy.++Tests cover fixed vectors, invalid lengths/hex/curve points/scalars, boundary+indices, chain codes and Ed25519 projection, public round trips, soft derivation+commutation, path composition, clone/derived/signing independence, early close,+escaped handles, callback errors/exceptions/cancellation, retained native ownership,+concurrent derive/close, input exceptions, public snapshots and GC.++At the pinned revision the final BIP32 private deallocator calls `sodium_memzero`+on its secret buffer before free. The allocation uses ordinary heap storage;+root PBKDF2 result and derivation intermediate stack buffers are not all wiped.+The binding does not claim comprehensive native or Haskell secret erasure.+Deterministic native allocator-failure injection remains unverified here.
@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2013-2016 Pavol Rusnak++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
@@ -0,0 +1,51 @@+# BIP39 test fixture provenance++All entropy and phrases are deterministic, public test-only secrets. Never use+these fixtures for a real wallet. Tests need no credentials or live network.++## Fixed vectors++`Fixtures.Bip39` contains all 24 entropy/English phrase pairs from cardano-c+`lib/tests/bip39.cpp`, revision+`8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d`. The current build revision is+recorded separately in `native/cardano-c.ref`. That file is+Copyright 2024 Biglup Labs, licensed Apache-2.0; only vector data was transcribed.+Every pair was crosschecked byte-for-byte against the 24 English cases in+[Trezor python-mnemonic vectors.json](https://github.com/trezor/python-mnemonic/blob/b57a5ad77a981e743f4167ab2f7927a55c1e82a8/vectors.json),+revision `b57a5ad77a981e743f4167ab2f7927a55c1e82a8`. The Trezor seed and extended-key+columns are not imported or tested: the Cardano root KDF is distinct.++Trezor's MIT notice is retained in `BIP39-TREZOR-LICENSE.md`.++Two additional fixed cases cover 20 and 28 zero entropy bytes, absent from both+corpora. Expected phrases were generated independently with Python 3's+`hashlib.sha256` and the pinned native English wordlist. This checks bit/checksum+marshaling with an independent algorithm, not independent dictionary content:++```python+import hashlib++def phrase(entropy, words):+ bits = ''.join(f'{byte:08b}' for byte in entropy)+ bits += f'{hashlib.sha256(entropy).digest()[0]:08b}'[:len(entropy) // 4]+ return ' '.join(words[int(bits[i:i + 11], 2)]+ for i in range(0, len(bits), 11))+```++## New tests++The Haskell generators, properties and lifecycle scenarios are original. Three+hundred Hedgehog cases cover all five entropy sizes, entropy/phrase roundtrips+and canonical text. Invalid tests cover length/count bounds, unknown dictionary+words, checksum, case, NUL, empty elements, whitespace inside words, non-ASCII+input and the Unicode replacement character (as seen after lossy UTF-8 decoding).+The public input is `Text`, so invalid UTF-8 bytes cannot enter this API directly.+Unicode whitespace between words is accepted and canonicalized to ASCII spaces.++Repeated success/failure, snapshots after GC, cancellation and scoped BIP32 root+integration exercise native buffer lifetime. Both native conversions allocate+no native owners: word pointers borrow static strings; entropy is caller-owned+scratch and is wiped on every exit, including checksum failure after native+output is written. Validation does not make a hidden Haskell entropy copy.+Native stack intermediates and host secret values are not comprehensively wiped.+No native allocation-failure or owner-retention test applies to these functions.
@@ -0,0 +1,60 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Deterministic test material; see BIP32.md for pinned provenance.+module Fixtures.Bip32 (privateHex, publicHex, hardChildHex, softRootHex, softChildHex, softPublicHex, softPublicChildHex, entropyHex, entropyRootHex, emptyPasswordRootHex, nulPasswordRootHex, publicHashHex) where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++privateHex :: Text+privateHex = "a0ab55b174ba8cd95e2362d035f377b4dc779a0fae65767e3b8dd790fa748250f3ef2cc372c207d7902607ffef01872a4c785cd27e7342de7f4332f2d5fdc3a8d0c110e1d6a061d3558eb6a3138a3982253c6616e1bf4d8bd31e92de8328affe"++publicHex :: Text+publicHex = "311f8914b8934efbe7cbb8cc4745853de12e8ea402df6f9f69b18d2792c6bed8d0c110e1d6a061d3558eb6a3138a3982253c6616e1bf4d8bd31e92de8328affe"++hardChildHex :: Text+hardChildHex = "3809937b61bd4f180a1e9bd15237e7bc20e36b9037dd95ef60d84f6004758250a22e1bfc0d81e9adb7760bcba7f5214416b3e9f27c8d58794a3a7fead2d5b6958d515cb54181fb2f5fc3af329e80949c082fb52f7b07e359bd7835a6762148bf"++softRootHex :: Text+softRootHex = "d8287e922756977dc0b79659e6eebcae3a1fb29a22ce1449c94f125462586951390af99a0350130451e9bf4f4691f37c352dc7025d52d9132f61a82f61d3803d00b5f1652f5cbe257e567c883dc2b16e0a9568b19c5b81ea8bd197fc95e8bdcf"++softChildHex :: Text+softChildHex = "08f9d7de597d31fade994b8a1e9d3e3afe53ac8393297e8f4d96225d725869517ae54c631588abb408fcab0676a4da6b60c82b3a3d7045a26a576c7901e5e9579db12d11a3559131a47f51f854a6234725ab8767d3fcc4c9908be55508f3c712"++softPublicHex :: Text+softPublicHex = "6fd8d9c696b01525cc45f15583fc9447c66e1c71fd1a11c8885368404cd0a4ab00b5f1652f5cbe257e567c883dc2b16e0a9568b19c5b81ea8bd197fc95e8bdcf"++softPublicChildHex :: Text+softPublicChildHex = "b857a8cd1dbbfed1824359d9d9e58bc8ffb9f66812b404f4c6ffc315629835bf9db12d11a3559131a47f51f854a6234725ab8767d3fcc4c9908be55508f3c712"++entropyHex :: Text+entropyHex = "caec96d09fc2020ab230199e0188cd6a554e2da2cba32de9ff6c0908c7f04d65"++entropyRootHex :: Text+entropyRootHex = "60292301b8dd20a74b58a0bd4ecdeb244a95e757c7a2d25962ada75e271d045ff827c85a5530bfe76975b4189c5fd6d32d4fe43c81373f386fde2fa0e6d0255a2ac1f1560a893ea7937c5bfbfdeab459b1a396f1174b9c5a673a640d01880c35"++emptyPasswordRootHex :: Text+emptyPasswordRootHex = "60ce7dbec3616e9fc17e0c32578b3f380337b1b61a1f3cb9651aee30670e6f53970419a23a2e4e4082d12bf78faa8645dfc882cee2ae7179e2b07fe88098abb2072310084784c7308182dbbdb1449b2706586f1ff5cbf13d15e9b6e78c15f067"++nulPasswordRootHex :: Text+nulPasswordRootHex = "f834649918cd8633584736a4778d99c22c0f5444ca493e26d78bf8fb785f3c51d227b626bad5ad23212265a292bf72499b96a4f40e47fa6aac84b22411f58d4592e48c3cb808d1b79e3529d4770b930b6b836c5ffbdce8a193fd3d8eab0e82b4"++publicHashHex :: Text+publicHashHex = "b9b5e117f1c14f503128385392f9b37f224d6d1a715d680f46a0ced1"
@@ -0,0 +1,54 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Deterministic test-only vectors; see BIP39.md for source and attribution.+module Fixtures.Bip39 (vectors) where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)++-- DEFINITIONS ----------------------------------------------------------------++vectors :: [(Text, Text)]+vectors =+ [ ("00000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"),+ ("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank yellow"),+ ("80808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage above"),+ ("ffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong"),+ ("000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent"),+ ("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will"),+ ("808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always"),+ ("ffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when"),+ ("0000000000000000000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art"),+ ("7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title"),+ ("8080808080808080808080808080808080808080808080808080808080808080", "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless"),+ ("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote"),+ ("9e885d952ad362caeb4efe34a8e91bd2", "ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic"),+ ("6610b25967cdcca9d59875f5cb50b0ea75433311869e930b", "gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog"),+ ("68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length"),+ ("c0ba5a8e914111210f2bd131f3d5e08d", "scheme spot photo card baby mountain device kick cradle pact join borrow"),+ ("6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3", "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave"),+ ("9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863", "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside"),+ ("23db8160a31d3e0dca3688ed941adbf3", "cat swing flag economy stadium alone churn speed unique patch report train"),+ ("8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0", "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access"),+ ("066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform"),+ ("f30f8c1da665478f49b001d94c5fc452", "vessel ladder alter error federal sibling chat ability sun glass valve picture"),+ ("c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05", "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump"),+ ("f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold"),+ ("0000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon address"),+ ("00000000000000000000000000000000000000000000000000000000", "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon admit")+ ]
@@ -0,0 +1,106 @@+# Native coin selection property provenance++The generated properties in `test/NativeCoinSelection.hs` adapt contracts reviewed+at cardano-foundation/cardano-coin-selection revision+`57efda2eda720b9e793a6f907319cc84aa02058c` (retrieved 2026-11-08):++- [`test/spec/Cardano/CoinSelection/BalanceSpec.hs`](https://github.com/cardano-foundation/cardano-coin-selection/blob/57efda2eda720b9e793a6f907319cc84aa02058c/test/spec/Cardano/CoinSelection/BalanceSpec.hs):+ `prop_runSelection_UTxO_exactlyEnough`,+ `prop_runSelection_UTxO_moreThanEnough`,+ `prop_runSelection_UTxO_notEnough`, `genMakeChangeData`,+ `prop_splitBundlesWithExcessiveAssetCounts_sum`, and+ `prop_splitBundlesWithExcessiveTokenQuantities_length`/`_sum`.+- [`test/gens/Cardano/CoinSelection/Types/TokenBundle/Gen.hs`](https://github.com/cardano-foundation/cardano-coin-selection/blob/57efda2eda720b9e793a6f907319cc84aa02058c/test/gens/Cardano/CoinSelection/Types/TokenBundle/Gen.hs):+ `genTokenBundleSmallRangePositive` and its interleaved positive-coin shrinker.++These are Apache-2.0 sources. BalanceSpec records copyright 2018–2026 IOHK and+2024–2026 Cardano Foundation. The upstream LICENSE was retrieved at the same+revision and is the Apache License, Version 2.0, reproduced in this repository's+`LICENSE`. Its NOTICE is retained verbatim below. Test implementations here are+new Haskell adaptations of the contracts, with Hedgehog generators and integrated+shrinking in place of upstream QuickCheck generators; no upstream implementation+or generator source is vendored.++## Execution and independent expectations++Every generated case calls public `Cometa.CoinSelection.select` with actual native+largest-first, seeded random-improve Optimal, and seeded random-improve Minimal+selectors. The seeds are generated and retained in Hedgehog failure reports.+Selections need not agree between strategies. Shrinking preserves positive input+bundles, uniquely indexed input references, ample change Ada in solvable cases,+and a strict supply deficit in failure cases.++The new properties check exact/surplus supply, mandatory input preservation with+both disjoint and overlapping available sets, full input snapshot membership,+unique selected and remaining references, remaining-set equality, per-asset+conservation, change destination/nonnegativity, Babbage minimum Ada, serialized+bundle limits, and positive token quantities including CBOR width transitions+and the signed int64 endpoint. The independent accounting model sums raw+association lists into `Map AssetId Integer`; it does not use `Value` addition,+`validateSelection`, or a direct call to the same C selector as an oracle.+Minimum Ada is `(160 + outputBytesAtMinimumCoinWidth) * 4310`; the generated+plain enterprise outputs keep this amount in the five-byte CBOR coin range.+The width is asserted. Public Haskell output/value encoders supply lengths,+with no native minimum-Ada oracle. Size checks reserve the total Ada supply's+coin width to match the documented native size assessment.++These properties complement existing fixed native regression tests and the+Ada-only accounting property. They add generated multiasset membership/accounting,+mandatory overlap, coin-versus-token deficits and bundle splitting. The generated+known-solvable cases have bounded small asset universes and generous Ada; they do+not claim every mathematically feasible heuristic input succeeds. Native+insufficient supply must report status 1100 (`CARDANO_ERROR_BALANCE_INSUFFICIENT`),+not merely any error.++## Adaptation limits++Upstream `runSelection` returns a depleted partial selection for insufficient+supply; Cometa's complete selection operation must fail. Nonempty positive inputs+avoid the different empty/zero-target contracts already covered by fixed cases.+The native public selector splits bundles by maximum serialized value size; it+does not expose upstream's independently configurable maximum token quantity.+The adaptation therefore checks conservation and int64 quantity bounds across+size splitting, including endpoint quantities, without claiming configurable+quantity splitting. Upstream's mock constraints and collateral selector are not+imported. The target is already the net externally assessed payment/fee/deposit/+refund/mint/burn requirement; this first slice does not claim generated builder+fee assessment, mint/burn, deposit/refund, collateral, or ledger acceptance coverage.++## Upstream NOTICE++```text+cardano-coin-selection++Copyright 2018-2022 IOHK+Copyright 2023-2026 Cardano Foundation++This product includes software developed at IOHK+(https://iohk.io/) as part of the cardano-wallet project+(https://github.com/cardano-foundation/cardano-wallet).++Original authors and contributors+----------------------------------++The coin selection algorithm, data structures, and primitive types were+designed and implemented primarily by:++ Jonathan Knowles — round-robin algorithm, change generation,+ collateral selection, UTxO index/selection,+ TokenMap, TokenBundle, Coin, numeric utilities+ Matthias Benkort (KtorZ) — original coin selection design+ Pawel Jakubas — original coin selection, UTxO index++With contributions from:++ Heinrich Apfelmus — coin selection+ Johannes Lund (Anviking) — early coin selection+ Yura (Unisay) — coin selection, numeric utilities+ Rodney Lorrimar — numeric utilities+ Erik de Castro Lopo — coin selection+ Jean-Baptiste Giraudeau — numeric utilities+ Piotr Stachyra — coin selection++Forked and maintained by:++ Paolo Veronelli — Cardano Foundation (High Assurance Lab)+```
@@ -0,0 +1,28 @@+# Derivation-path oracle provenance++Native revision: `7811fe94dad90f30478ed4b61d96677f188abaa8` (cardano-c,+Apache-2.0, Copyright Biglup Labs). Native headers audited:+`lib/include/cardano/key_handlers/{derivation_path,account_derivation_path,cip_1852_constants}.h`.++The nine constants are read directly from pinned headers by+`test/cbits/derivation_path_oracle.c`. Full-path oracle construction adapts the+encoding in `lib/src/key_handlers/software_secure_key_handler.c`,+`bip32_sign_hash`: first three fields cast to uint32 and hardened; final two cast+to uint32. It compares real derived public keys but repeats the native encoding+formula, so it is not an independent cryptographic oracle. Root fixture provenance+is recorded in `BIP32.md`.++The account oracle actually calls the software secure handler with a native+account-path struct and compares all 64 public bytes against public Haskell BIP32+derivation. Standard, multisignature, custom distinct components, and maximum+components are exercised. Its deterministic entropy and standard account xpub+come from `lib/tests/key_handlers/software_secure_key_handler.cpp`,+`ENTROPY_BYTES` and `canCreateABip32SecureKeyHandler`. Test-only encryption password+is `x`; root derivation uses the handler's empty derivation passphrase. This uses+no live wallet or secrets. The handler oracle creates randomized encrypted storage,+but its account public output is deterministic.++Bounds and shrinking Hedgehog properties are original Cometa tests. The Haskell+API rejects every component outside 0..2^31-1; it does not copy native silent+uint64 truncation, high-bit aliasing of hardened prefixes, or hardened role/index+inputs. Custom purpose, coin and role numbers within that range remain supported.
@@ -0,0 +1,114 @@+# Ed25519 test fixture provenance++All key material in `Fixtures.Ed25519` is published or deterministically derived+fixture data. It must never be used for application wallets. No user keys,+credentials, operational signing material, or network access are involved.+The ordinary Haskell tests need no Python packages.++## Pinned native sources and notices++Fixture source revision: `8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d`.+The current build revision is recorded separately in `native/cardano-c.ref`.++The four normal-key vectors were transcribed from+`lib/tests/crypto/ed25519_vectors.h`, array `cardano_ed25519_test_vectors`.+That source identifies them as the RFC 8032 section 7.1 Ed25519 cases TEST 1,+TEST 2, TEST 3, and TEST 1024. Their message lengths are respectively 0, 1, 2,+and 1023 bytes; TEST 1024 is the RFC's label, not its message length.++The fixed extended-key vector was transcribed from+`lib/tests/crypto/ed25519_private_key.cpp`, constants+`PRIVATE_EXTENDED_PRIVATE_HEX`, `PRIVATE_EXTENDED_PUBLIC_HEX`,+`MESSAGE_VECTOR_PRIVATE_EXTENDED_BYTES`, and+`SIGNATURE_VECTOR_PRIVATE_EXTENDED`. Its message contains 64 bytes.++Both native fixture sources are Copyright 2024 Biglup Labs, licensed under+Apache-2.0. This repository includes that license in `LICENSE`. The fixture+module retains the project notice, and this provenance preserves attribution+for the imported values. No native test generator or implementation was copied.++Original RFC source: [RFC 8032, section 7.1](https://www.rfc-editor.org/rfc/rfc8032.html#section-7.1),+Simon Josefsson and Ilari Liusvaara, January 2017. Its notice is Copyright (c)+2017 IETF Trust and the persons identified as the document authors, with terms+at [IETF Trust legal provisions](https://trustee.ietf.org/license-info/).+The RFC's published numerical test values are carried here through the pinned+native fixture source.++## Independent checks++Python `cryptography` 48.0.0 (OpenSSL Ed25519) independently regenerated the+public keys and exact signatures of all four normal-key vectors. It also+verified the fixed extended-key signature against its public key and message.+These checks were performed when importing the fixtures; Haskell CI uses the+literal expected values and does not install Python cryptography dependencies.++Every fixture public-key hash was computed independently using+`hashlib.blake2b(public_key_bytes, digest_size=28)`:++| Fixture | BLAKE2b-224 public-key hash |+| --- | --- |+| RFC TEST 1 | `35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3` |+| RFC TEST 2 | `977efb35ab621d39dbeb7274ec7795a34708ff4d25a01a1df04c1f27` |+| RFC TEST 3 | `7f8a76c0ebaa4ad20dfdcd51a5de070ab771f4bf377f2c41e6b71c0a` |+| RFC TEST 1024 | `3fa478a09cf841058b3e63abe2cfc50aac0ea46d84eaa50a6ae5accc` |+| Extended | `ebf46bc374bda5b937d4d964fc0b73e940a9ea7d8cfdf39162a6f207` |++## Additional empty and embedded-NUL cases++A normal-key embedded-NUL case uses RFC TEST 1's published seed and message+bytes `00 01 00 ff`. Its expected signature was generated using+`cryptography`'s `Ed25519PrivateKey.sign`.++The extended-key empty-message and embedded-NUL cases use the pinned extended+key and messages `[]` and `[0, 1, 0, 255]`. Expected signatures were independently+constructed with the standard expanded-secret Ed25519 equations, using PyNaCl's+scalar arithmetic and base-point operations plus Python `hashlib.sha512`:++```text+secret = scalar || prefix+A = scalar * B+r = SHA512(prefix || message) mod L+R = r * B+k = SHA512(R || A || message) mod L+S = (r + k * scalar) mod L+signature = R || S+```++PyNaCl 1.5.0 supplied `crypto_core_ed25519_scalar_reduce`, scalar multiplication+and addition, and `crypto_scalarmult_ed25519_base_noclamp`. OpenSSL Ed25519 via+`cryptography` then independently verified the resulting signatures. These are+expanded-key Ed25519 fixtures, not Ed25519ph, Ed25519ctx, or BIP32 derivation+vectors. The copied key type is 64-byte scalar-and-prefix material, rather than+a 32-byte normal seed.++## Lifecycle and property evidence++A separate 64-byte all-zero expanded-key input deliberately passes length+validation but fails native scalar multiplication. Native source+`ed25519_private_key.c` checks the base-point operation in+`compute_extended_public_key` and `compute_signature_with_extended_key`, returning+a generic error for this unusable scalar. Tests assert exact sanitized operation+errors, closure of the escaped public handle, and native reference disposal after+that operation failure. This is not treated as an import-length error.++The Haskell properties are new project code: 300 public-key byte/hex round trips,+300 signature byte/hex round trips, 300 normal seed/message sign-and-verify+cases, and 300 extended-key message cases. Generated normal seeds are redacted+in property diagnostics. The fixture record deliberately has no `Show` instance.++Lifecycle tests exercise scoped success, callback `Left`, thrown exceptions,+asynchronous cancellation, explicit repeated close, escaped handles, explicit+exports, independent clone allocation, public snapshots after close and GC,+and signing concurrent with close.++Test-only native ref/refcount/unref imports retain an independent reference while+checking that scope exit releases exactly one reference (2 to 1) after success,+callback failure, exception, or cancellation. The retained test reference is+released by a surrounding bracket on every exit. A trusted private operation+pauses under the same key lock used for signing, then signs with the real native+function while a concurrent close waits for that lock. No allocation counters or+pointer hooks are added to the public API.++These tests establish disposal and lifetime behavior, not comprehensive erasure+of every stack or runtime copy. Explicit key export produces ordinary Haskell+bytes/text with a lifetime outside the scoped key handle.
@@ -0,0 +1,191 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Published deterministic test keys, never application keys. Intentionally no+-- Show instance: test diagnostics identify a vector by name, not key material.+-- Attribution and independent checks are in test/Fixtures/ED25519.md.+module Fixtures.Ed25519+ ( Vector (..),+ rfcVectors,+ normalVector,+ extendedVector,+ allVectors,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)+import qualified Data.Text as Text++-- TYPES ----------------------------------------------------------------------++data Vector = Vector+ { vectorName :: String,+ isExtended :: Bool,+ privateHex :: Text,+ publicHex :: Text,+ messageHex :: Text,+ signatureHex :: Text,+ publicHashHex :: Text+ }++-- DEFINITIONS ----------------------------------------------------------------++allVectors :: [Vector]+allVectors = rfcVectors ++ [normalNulVector, extendedVector, extendedEmptyVector, extendedNulVector]++normalVector :: Vector+normalVector = rfc1++rfcVectors :: [Vector]+rfcVectors = [rfc1, rfc2, rfc3, rfc1023]++rfc1 :: Vector+rfc1 =+ Vector+ { vectorName = "RFC 8032 TEST 1",+ isExtended = False,+ privateHex = "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",+ publicHex = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",+ messageHex = "",+ signatureHex =+ Text.concat+ [ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46b",+ "d25bf5f0595bbe24655141438e7a100b"+ ],+ publicHashHex = "35dedd2982a03cf39e7dce03c839994ffdec2ec6b04f1cf2d40e61a3"+ }++rfc2 :: Vector+rfc2 =+ Vector+ { vectorName = "RFC 8032 TEST 2",+ isExtended = False,+ privateHex = "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",+ publicHex = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",+ messageHex = "72",+ signatureHex =+ Text.concat+ [ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c",+ "387b2eaeb4302aeeb00d291612bb0c00"+ ],+ publicHashHex = "977efb35ab621d39dbeb7274ec7795a34708ff4d25a01a1df04c1f27"+ }++rfc3 :: Vector+rfc3 =+ Vector+ { vectorName = "RFC 8032 TEST 3",+ isExtended = False,+ privateHex = "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",+ publicHex = "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",+ messageHex = "af82",+ signatureHex =+ Text.concat+ [ "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc659",+ "4a7c15e9716ed28dc027beceea1ec40a"+ ],+ publicHashHex = "7f8a76c0ebaa4ad20dfdcd51a5de070ab771f4bf377f2c41e6b71c0a"+ }++rfc1023 :: Vector+rfc1023 =+ Vector+ { vectorName = "RFC 8032 TEST 1024",+ isExtended = False,+ privateHex = "f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5",+ publicHex = "278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e",+ messageHex =+ Text.concat+ [ "08b8b2b733424243760fe426a4b54908632110a66c2f6591eabd3345e3e4eb98fa6e264bf09efe12ee50f8f54e9f77b1",+ "e355f6c50544e23fb1433ddf73be84d879de7c0046dc4996d9e773f4bc9efe5738829adb26c81b37c93a1b270b20329d",+ "658675fc6ea534e0810a4432826bf58c941efb65d57a338bbd2e26640f89ffbc1a858efcb8550ee3a5e1998bd177e93a",+ "7363c344fe6b199ee5d02e82d522c4feba15452f80288a821a579116ec6dad2b3b310da903401aa62100ab5d1a36553e",+ "06203b33890cc9b832f79ef80560ccb9a39ce767967ed628c6ad573cb116dbefefd75499da96bd68a8a97b928a8bbc10",+ "3b6621fcde2beca1231d206be6cd9ec7aff6f6c94fcd7204ed3455c68c83f4a41da4af2b74ef5c53f1d8ac70bdcb7ed1",+ "85ce81bd84359d44254d95629e9855a94a7c1958d1f8ada5d0532ed8a5aa3fb2d17ba70eb6248e594e1a2297acbbb39d",+ "502f1a8c6eb6f1ce22b3de1a1f40cc24554119a831a9aad6079cad88425de6bde1a9187ebb6092cf67bf2b13fd65f270",+ "88d78b7e883c8759d2c4f5c65adb7553878ad575f9fad878e80a0c9ba63bcbcc2732e69485bbc9c90bfbd62481d9089b",+ "eccf80cfe2df16a2cf65bd92dd597b0707e0917af48bbb75fed413d238f5555a7a569d80c3414a8d0859dc65a46128ba",+ "b27af87a71314f318c782b23ebfe808b82b0ce26401d2e22f04d83d1255dc51addd3b75a2b1ae0784504df543af8969b",+ "e3ea7082ff7fc9888c144da2af58429ec96031dbcad3dad9af0dcbaaaf268cb8fcffead94f3c7ca495e056a9b47acdb7",+ "51fb73e666c6c655ade8297297d07ad1ba5e43f1bca32301651339e22904cc8c42f58c30c04aafdb038dda0847dd988d",+ "cda6f3bfd15c4b4c4525004aa06eeff8ca61783aacec57fb3d1f92b0fe2fd1a85f6724517b65e614ad6808d6f6ee34df",+ "f7310fdc82aebfd904b01e1dc54b2927094b2db68d6f903b68401adebf5a7e08d78ff4ef5d63653a65040cf9bfd4aca7",+ "984a74d37145986780fc0b16ac451649de6188a7dbdf191f64b5fc5e2ab47b57f7f7276cd419c17a3ca8e1b939ae49e4",+ "88acba6b965610b5480109c8b17b80e1b7b750dfc7598d5d5011fd2dcc5600a32ef5b52a1ecc820e308aa342721aac09",+ "43bf6686b64b2579376504ccc493d97e6aed3fb0f9cd71a43dd497f01f17c0e2cb3797aa2a2f256656168e6c496afc5f",+ "b93246f6b1116398a346f1a641f3b041e989f7914f90cc2c7fff357876e506b50d334ba77c225bc307ba537152f3f161",+ "0e4eafe595f6d9d90d11faa933a15ef1369546868a7f3a45a96768d40fd9d03412c091c6315cf4fde7cb68606937380d",+ "b2eaaa707b4c4185c32eddcdd306705e4dc1ffc872eeee475a64dfac86aba41c0618983f8741c5ef68d3a101e8a3b8ca",+ "c60c905c15fc910840b94c00a0b9d0"+ ],+ signatureHex =+ Text.concat+ [ "0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350aa5371b1508f9f4528ecea23c436d94b",+ "5e8fcd4f681e30a6ac00a9704a188a03"+ ],+ publicHashHex = "3fa478a09cf841058b3e63abe2cfc50aac0ea46d84eaa50a6ae5accc"+ }++extendedVector :: Vector+extendedVector =+ Vector+ { vectorName = "cardano-c extended Ed25519",+ isExtended = True,+ privateHex =+ Text.concat+ [ "a0ab55b174ba8cd95e2362d035f377b4dc779a0fae65767e3b8dd790fa748250f3ef2cc372c207d7902607ffef01872a",+ "4c785cd27e7342de7f4332f2d5fdc3a8"+ ],+ publicHex = "311f8914b8934efbe7cbb8cc4745853de12e8ea402df6f9f69b18d2792c6bed8",+ messageHex =+ Text.concat+ [ "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd",+ "454d4423643ce80e2a9ac94fa54ca49f"+ ],+ signatureHex =+ Text.concat+ [ "843aa4353184193bdf01aab7f636ac53f86746dd97a2a2e01fe7923c37bfec40b68a73881a26ba57dc974abc1123d086",+ "6b542a5447e03677134a8f4e1db2bc0c"+ ],+ publicHashHex = "ebf46bc374bda5b937d4d964fc0b73e940a9ea7d8cfdf39162a6f207"+ }++extendedEmptyVector :: Vector+extendedEmptyVector =+ extendedVector+ { vectorName = "extended empty message",+ messageHex = "",+ signatureHex = "d54ebb1afebf7f0d7ef9cafeb318c0880a8b5eeb902cfe42a5e3610d3a3a9223b133125792a0f5be3e2e40f58fd71516eda072cd35f577d1c25e1575482db80c"+ }++extendedNulVector :: Vector+extendedNulVector =+ extendedVector+ { vectorName = "extended embedded NUL",+ messageHex = "000100ff",+ signatureHex = "091f234d061be3ff73151fb832d342b7a490ff6f1c79907658e3c610d06d6827a663cbbd6474171703012c4495a1a79d998a2faa22df598bfa21e5b96fd9130a"+ }++normalNulVector :: Vector+normalNulVector =+ rfc1+ { vectorName = "normal embedded NUL",+ messageHex = "000100ff",+ signatureHex = "d6bea3eb43f22edff0d0669474dada1fb561ced14a8e25356e1f875db02f23e37c48b2ae101aecd78e2a471e68ce03af64f25c070c39b446cdc10f6adf4c3107"+ }
@@ -0,0 +1,98 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Synthetic protocol parameters for the offline subtransaction example.+module Fixtures.ExampleParameters (parameters) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.UnitInterval as Unit++-- DEFINITIONS ----------------------------------------------------------------++-- | Use a provider snapshot for real transactions; this fixture performs no Plutus evaluation.+parameters :: Either Error P.Parameters+parameters = do+ r <- Rational.mkNonNegativeRational 3 10+ u <- Unit.mkUnitInterval 1 5+ let ex = Ex.ExUnits 14000000 10000000000+ version = Version.ProtocolVersion 12 0+ prices = Prices.ExUnitPrices r r+ pure+ P.Parameters+ { P.parameterMinFeeA = 44,+ P.parameterMinFeeB = 155381,+ P.parameterMaxBlockBodySize = 90112,+ P.parameterMaxTxSize = 16384,+ P.parameterMaxBlockHeaderSize = 1100,+ P.parameterKeyDeposit = 2000000,+ P.parameterPoolDeposit = 500000000,+ P.parameterMaxEpoch = 18,+ P.parameterDesiredPoolCount = 500,+ P.parameterPoolPledgeInfluence = r,+ P.parameterExpansionRate = u,+ P.parameterTreasuryGrowthRate = u,+ P.parameterDecentralization = Nothing,+ P.parameterExtraEntropy = Nothing,+ P.parameterProtocolVersion = version,+ P.parameterMinPoolCost = 170000000,+ P.parameterAdaPerUtxoByte = Just 4310,+ P.parameterCostModels = Just Models.empty,+ P.parameterExecutionCosts = Just prices,+ P.parameterMaxTxExUnits = Just ex,+ P.parameterMaxBlockExUnits = Just ex,+ P.parameterMaxValueSize = Just 5000,+ P.parameterCollateralPercentage = Just 150,+ P.parameterMaxCollateralInputs = Just 3,+ P.parameterPoolVotingThresholds = Nothing,+ P.parameterDrepVotingThresholds = Nothing,+ P.parameterMinCommitteeSize = Nothing,+ P.parameterCommitteeTermLimit = Nothing,+ P.parameterGovernanceActionValidityPeriod = Nothing,+ P.parameterGovernanceActionDeposit = Nothing,+ P.parameterDrepDeposit = Nothing,+ P.parameterDrepInactivityPeriod = Nothing,+ P.parameterRefScriptCostPerByte = Nothing,+ P.parameterMaxRefScriptSizePerBlock = Nothing,+ P.parameterMaxRefScriptSizePerTx = Nothing,+ P.parameterRefScriptCostStride = Nothing,+ P.parameterRefScriptCostMultiplier = Nothing,+ P.parameterMaxPledgeLeverage = Nothing,+ P.parameterMinPoolMargin = Nothing,+ P.parameterLeiosAnnouncementPeriodLength = Nothing,+ P.parameterLeiosVotePeriodLength = Nothing,+ P.parameterLeiosDiffusionPeriodLength = Nothing,+ P.parameterLeiosCommitteeSize = Nothing,+ P.parameterLeiosQuorumStakeThreshold = Nothing,+ P.parameterMaxEndorserBlockReferencesSize = Nothing,+ P.parameterMaxEndorserBlockTxsSize = Nothing,+ P.parameterMaxEndorserBlockExecutionUnits = Nothing,+ P.parameterMaxRefScriptSizePerEndorserBlock = Nothing,+ P.parameterPerasMinCandidateBlockAge = Nothing,+ P.parameterPerasHealingFactor = Nothing,+ P.parameterPerasCertBoost = Nothing,+ P.parameterPerasTargetCommitteeSize = Nothing,+ P.parameterPerasBootstrapRound = Nothing,+ P.parameterPerasQuorumThresholdSafetyMargin = Nothing,+ P.parameterRefInputsCostPerMultiAssetByte = Nothing,+ P.parameterRefInputsCostPerDatumByte = Nothing+ }
@@ -0,0 +1,46 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Pinned Apache-2.0 native corpus; see Governance.md for provenance.+module Fixtures.Governance (anchorVector, actionVector, drepVectors, procedureVectors, votingVector) where++-- DEFINITIONS ----------------------------------------------------------------++anchorVector :: String+anchorVector = "827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"++actionVector :: String+actionVector = "825820000000000000000000000000000000000000000000000000000000000000000003"++votingVector :: String+votingVector = "a28202581c10000000000000000000000000000000000000000000000000000000a38258201000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258202000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258203000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008203581c20000000000000000000000000000000000000000000000000000000a28258201000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258203000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"++drepVectors :: [String]+drepVectors =+ [ "8200581c00000000000000000000000000000000000000000000000000000000",+ "8201581c00000000000000000000000000000000000000000000000000000000",+ "8102",+ "8103"+ ]++procedureVectors :: [String]+procedureVectors =+ [ "8200f6",+ "8201f6",+ "8202f6",+ "8200827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000",+ "8201827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000",+ "8202827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000"+ ]
@@ -0,0 +1,21 @@+# Governance corpus provenance++The hexadecimal CBOR constants in Governance.hs are imported from cardano-c+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`:++* `lib/tests/common/anchor.cpp`: ANCHOR_CBOR.+* `lib/tests/common/governance_action_id.cpp`: GOVERNANCE_ACTION_ID_CBOR.+* `lib/tests/common/drep.cpp`: DREP_KEY_HASH_CBOR, DREP_SCRIPT_HASH_CBOR,+ DREP_ABSTAIN_CBOR and DREP_NO_CONFIDENCE_CBOR.+* `lib/tests/voting_procedures/voting_procedure.cpp`: the six CBOR choice/anchor constants.+* `lib/tests/voting_procedures/voting_procedures.cpp`: CBOR.++Copyright 2024 Biglup Labs, Apache License 2.0 (repository LICENSE).+Tests independently assemble public Haskell credentials, anchors, choices,+action identifiers and nested maps to these bytes. The native oracle decodes+those bytes, obtains typed fields, constructs fresh anchors/actions/DReps/voters/+procedures/collections, and compares native serialization to Haskell encoding.+No corpus inputs require a network or signing key.++Hedgehog generators and boundary encodings in Governance.hs are original Cometa+2026 tests under Apache-2.0, not imported upstream generator implementations.
@@ -0,0 +1,46 @@+# Transaction inspection fixture provenance++Native baseline: `Biglup/cardano-c`, commit+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`, Apache-2.0.+The native source is Copyright Biglup Labs; the repository `LICENSE` contains the+license. `Fixtures.Inspection` retains the project's Apache-2.0 notice.++`Fixtures.Inspection.fixtures` imports the complete transaction CBOR and expected+inspection JSON from every transaction inspection fixture in the pinned binding+corpus:++| Fixture | Native path |+| --- | --- |+| `conway-key-guard` | `lib/tests/vectors/bindings/v1/conway-key-guard.json` |+| `dijkstra-account-balances` | `lib/tests/vectors/bindings/v1/dijkstra-account-balances.json` |+| `dijkstra-signed-subtransaction` | `lib/tests/vectors/bindings/v1/dijkstra-signed-subtransaction.json` |++Only `transaction_cbor` and `inspection` are copied. Signing seeds, other key+material and unrelated fields are excluded. The expected JSON is compared as a+whole semantic `Data.Aeson.Value`; JSON object order is ignored, array order and+all field values remain significant.++Two complete native test pairs extend the domain coverage:++- `native-rich-babbage`: `lib/tests/transaction/transaction.cpp`, constant `CBOR`+ and the full expected JSON in+ `cardano_transaction_to_cip116_json.canConvertToCip116Json`. This covers native+ scripts, multiassets, bootstrap and key witnesses, Plutus scripts/data/redeemers,+ metadata and auxiliary data.+- `native-dijkstra-all-fields`: the complete CBOR and expected JSON in+ `cardano_transaction_to_cip116_json.preservesDijkstraFieldsAndNestedTransactions`+ in the same file. This covers nested subtransactions, guards, direct deposits,+ exact/range account intervals, V4 witnesses, auxiliary data and maximum unsigned+ 64-bit decimal values.++Tests independently inspect every embedded subtransaction and body against its+complete corresponding expected JSON subtree, including subtransaction witnesses+and auxiliary data. The native function implementations are not copied into a+Haskell oracle.++Additional original tests construct arbitrary positive/negative Plutus integers+and nontext bytes through public Haskell values, verify exact source CBOR/body ID+and witness preservation, exercise malformed/trailing native input cleanup,+retain returned JSON through garbage collection, and invoke concurrent independent+operations. Ordinary fixtures need no credentials, network access or funded wallet+material. They establish inspection encoding agreement, not ledger validity.
@@ -0,0 +1,43 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Exact CBOR/expected JSON pairs imported from the pinned Apache-2.0 native+-- corpus. See INSPECTION.md; signing seeds and unrelated fields are excluded.+module Fixtures.Inspection (Fixture (..), fixtures) where++-- IMPORTS --------------------------------------------------------------------++import Data.ByteString (ByteString)+import Data.Text (Text)++-- TYPES ----------------------------------------------------------------------++data Fixture = Fixture+ { fixtureName :: String,+ fixtureCbor :: Text,+ fixtureJson :: ByteString+ }++-- DEFINITIONS ----------------------------------------------------------------++fixtures :: [Fixture]+fixtures =+ [ Fixture "conway-key-guard" "84a400818258200000000000000000000000000000000000000000000000000000000000000000000181a200581d6011111111111111111111111111111111111111111111111111111111011a001e8480021a000298100ed9010281581c22222222222222222222222222222222222222222222222222222222a0f5f6" "{\"body\":{\"inputs\":[{\"transaction_id\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"index\":0}],\"outputs\":[{\"address\":\"addr_test1vqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxrcya6\",\"amount\":{\"coin\":\"2000000\"}}],\"fee\":\"170000\",\"guards\":[{\"tag\":\"pubkey_hash\",\"value\":\"22222222222222222222222222222222222222222222222222222222\"}]},\"is_valid\":true,\"witness_set\":{}}",+ Fixture "dijkstra-account-balances" "84a600d90102818258203b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b70a0181a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc011a02d9d0e3021a00029b1d1819a1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d01a001e8480181aa1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821a000f4240f6181ba1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d01bffffffffffffffffa0f5f6" "{\"body\":{\"inputs\":[{\"transaction_id\":\"3b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b7\",\"index\":10}],\"outputs\":[{\"address\":\"addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp\",\"amount\":{\"coin\":\"47829219\"}}],\"fee\":\"170781\",\"direct_deposits\":[{\"key\":\"stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27\",\"value\":\"2000000\"}],\"account_balance_intervals\":[{\"key\":\"stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27\",\"value\":{\"tag\":\"range\",\"inclusive_lower_bound\":\"1000000\",\"exclusive_upper_bound\":null}}],\"starting_account_balance_intervals\":[{\"key\":\"stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27\",\"value\":{\"tag\":\"exact\",\"value\":\"18446744073709551615\"}}]},\"is_valid\":true,\"witness_set\":{}}",+ Fixture "dijkstra-signed-subtransaction" "84a500d90102818258203b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b70a0181a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc011a02abdadf021a0002ca610ed9010281581c7ed010b0b444eb2d3eeb37e8485931bbdc3d9cda18b8924467fbd0fd17d901028183a300d90102818258203b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b7000181a200583900657c03ae96fbe2c30eab4a9971aec71f0738b6614c74c5e9c8e23d878a04df66478dea681da4b55c15ee7d4ef0230c87817631912b8aff29011a00e4e1c01818a18200581c7ed010b0b444eb2d3eeb37e8485931bbdc3d9cda18b8924467fbd0fd182aa100d9010281825820cdfe5c2a7b4b06e4cec00cc8c83353a948ce3b1b50dacf7bd64a3f6329389a7f5840557e9294ab486a2d797a23d72c5fbee703e73557fd171f4e0702c03b1e387380dfd6b887d8e14dcd71adb03bc34b99f524de325ceb0536b461fcc0c3b5a3a20ff6a0f5f6" "{\"body\":{\"inputs\":[{\"transaction_id\":\"3b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b7\",\"index\":10}],\"outputs\":[{\"address\":\"addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp\",\"amount\":{\"coin\":\"44817119\"}}],\"fee\":\"182881\",\"guards\":[{\"tag\":\"pubkey_hash\",\"value\":\"7ed010b0b444eb2d3eeb37e8485931bbdc3d9cda18b8924467fbd0fd\"}],\"sub_transactions\":[{\"body\":{\"inputs\":[{\"transaction_id\":\"3b40265111d8bb3c3c608d95b3a0bf83461ace32d79336579a1939b3aad1c0b7\",\"index\":0}],\"outputs\":[{\"address\":\"addr_test1qpjhcqawjma79scw4d9fjudwcu0sww9kv9x8f30fer3rmpu2qn0kv3udaf5pmf94ts27ul2w7q3sepupwccez2u2lu5s7aa8rv\",\"amount\":{\"coin\":\"15000000\"}}],\"required_top_level_guards\":[{\"key\":{\"tag\":\"pubkey_hash\",\"value\":\"7ed010b0b444eb2d3eeb37e8485931bbdc3d9cda18b8924467fbd0fd\"},\"value\":{\"tag\":\"integer\",\"value\":\"42\"}}]},\"witness_set\":{\"vkey_witnesses\":[{\"vkey\":\"cdfe5c2a7b4b06e4cec00cc8c83353a948ce3b1b50dacf7bd64a3f6329389a7f\",\"signature\":\"557e9294ab486a2d797a23d72c5fbee703e73557fd171f4e0702c03b1e387380dfd6b887d8e14dcd71adb03bc34b99f524de325ceb0536b461fcc0c3b5a3a20f\"}]}}]},\"is_valid\":true,\"witness_set\":{}}",+ Fixture "native-rich-babbage" "84af00d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000181a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc01820aa3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c411832581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e020a031903e804d90102828304581c26b17b78de4f035dc0bfce60d1d3c3a8085c38dcce5fb8767e518bed1901f48405581c0d94e174732ef9aae73f395ab44507bfa983d65023c11a951f0c32e4581ca646474b8f5431261506b6c273d307c7569a4eb6c96b42dd4a29520a582003170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131405a1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0050758202ceb364d93225b4a0f004a0975a13eb50c3cc6348474b4fe9121f8dc72ca0cfa08186409a3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c413831581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e0b58206199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d38abc123de0dd90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5010ed9010281581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d3910a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc01820aa3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c411832581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e11186412d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d500a700d90102818258206199186adb51974690d7247d2646097d2c62763b767b528816fb7ed3f9f55d395840bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c8918755bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c891875501d90102868205186482041901f48200581cb5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f548201818200581cb5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f548202818200581cb5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f54830301818200581cb5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f5402d9010281845820deeb8f82f2af5836ebbc1b450b6dbf0b03c93afe5696f10d49e8a8304ebfac01584064676273786767746f6768646a7074657476746b636f6376796669647171676775726a687268716169697370717275656c6876797071786565777072796676775820b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b45041a003d90102815820b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b45004d9010281187b05a282010082d87a9f187bff82190bb8191b5882020182d87a9f187bff821913881907d006d90102815820b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450f5d90103a100a6011904d20263737472039f1904d263737472ff0445627974657305a2667374726b6579187b9f676c6973746b6579ff6873747276616c75650626" "{\"body\":{\"inputs\":[{\"transaction_id\":\"0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5\",\"index\":0}],\"outputs\":[{\"address\":\"addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp\",\"amount\":{\"coin\":\"10\",\"assets\":{\"2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740\":{\"\":\"20\"},\"659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82\":{\"54534c41\":\"50\"},\"7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373\":{\"\":\"40\",\"504154415445\":\"30\"}}}}],\"fee\":\"10\",\"ttl\":\"1000\",\"certs\":[{\"tag\":\"pool_retirement\",\"pool_keyhash\":\"pool1y6chk7x7fup4ms9leesdr57r4qy9cwxuee0msan72x976a6u0nc\",\"epoch\":500},{\"tag\":\"genesis_key_delegation\",\"genesis_hash\":\"0d94e174732ef9aae73f395ab44507bfa983d65023c11a951f0c32e4\",\"genesis_delegate_hash\":\"a646474b8f5431261506b6c273d307c7569a4eb6c96b42dd4a29520a\",\"vrf_keyhash\":\"vrf_vkh1qvts5tn4j7mm0c7cfsznj8gnnf3tz4l8s7rd3syz72wu7nq3zv2qegvt5c\"}],\"withdrawals\":[{\"key\":\"stake_test1uqfu74w3wh4gfzu8m6e7j987h4lq9r3t7ef5gaw497uu85qsqfy27\",\"value\":\"5\"}],\"auxiliary_data_hash\":\"2ceb364d93225b4a0f004a0975a13eb50c3cc6348474b4fe9121f8dc72ca0cfa\",\"validity_start_interval\":\"100\",\"mint\":[{\"script_hash\":\"2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740\",\"assets\":{\"\":\"20\"}},{\"script_hash\":\"659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82\",\"assets\":{\"54534c41\":\"-50\"}},{\"script_hash\":\"7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373\",\"assets\":{\"\":\"40\",\"504154415445\":\"30\"}}],\"script_data_hash\":\"6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d38abc123de\",\"collateral\":[{\"transaction_id\":\"0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5\",\"index\":1}],\"guards\":[{\"tag\":\"pubkey_hash\",\"value\":\"6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d39\"}],\"collateral_return\":{\"address\":\"addr_test1qz2fxv2umyhttkxyxp8x0dlpdt3k6cwng5pxj3jhsydzer3jcu5d8ps7zex2k2xt3uqxgjqnnj83ws8lhrn648jjxtwq2ytjqp\",\"amount\":{\"coin\":\"10\",\"assets\":{\"2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740\":{\"\":\"20\"},\"659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82\":{\"54534c41\":\"50\"},\"7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373\":{\"\":\"40\",\"504154415445\":\"30\"}}}},\"total_collateral\":\"100\",\"reference_inputs\":[{\"transaction_id\":\"0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5\",\"index\":0}]},\"is_valid\":true,\"witness_set\":{\"vkey_witnesses\":[{\"vkey\":\"6199186adb51974690d7247d2646097d2c62763b767b528816fb7ed3f9f55d39\",\"signature\":\"bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c8918755bdea87fca1b4b4df8a9b8fb4183c0fab2f8261eb6c5e4bc42c800bb9c8918755\"}],\"native_scripts\":[{\"tag\":\"timelock_expiry\",\"slot\":\"100\"},{\"tag\":\"timelock_start\",\"slot\":\"500\"},{\"tag\":\"pubkey\",\"pubkey\":\"b5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f54\"},{\"tag\":\"all\",\"scripts\":[{\"tag\":\"pubkey\",\"pubkey\":\"b5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f54\"}]},{\"tag\":\"any\",\"scripts\":[{\"tag\":\"pubkey\",\"pubkey\":\"b5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f54\"}]},{\"tag\":\"n_of_k\",\"scripts\":[{\"tag\":\"pubkey\",\"pubkey\":\"b5ae663aaea8e500157bdf4baafd6f5ba0ce5759f7cd4101fc132f54\"}],\"n\":1}],\"bootstraps\":[{\"attributes\":\"a0\",\"chain_code\":\"b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450\",\"signature\":\"64676273786767746f6768646a7074657476746b636f6376796669647171676775726a687268716169697370717275656c687679707178656577707279667677\",\"vkey\":\"deeb8f82f2af5836ebbc1b450b6dbf0b03c93afe5696f10d49e8a8304ebfac01\"}],\"plutus_scripts\":[{\"language\":\"plutus_v1\",\"bytes\":\"b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450\"},{\"language\":\"plutus_v2\",\"bytes\":\"b6dbf0b03c93afe5696f10d49e8a8304ebfac01deeb8f82f2af5836ebbc1b450\"}],\"plutus_data\":[{\"tag\":\"integer\",\"value\":\"123\"}],\"redeemers\":[{\"tag\":\"mint\",\"index\":\"0\",\"data\":{\"tag\":\"constr\",\"alternative\":\"1\",\"data\":[{\"tag\":\"integer\",\"value\":\"123\"}]},\"ex_units\":{\"mem\":\"3000\",\"steps\":\"7000\"}},{\"tag\":\"cert\",\"index\":\"1\",\"data\":{\"tag\":\"constr\",\"alternative\":\"1\",\"data\":[{\"tag\":\"integer\",\"value\":\"123\"}]},\"ex_units\":{\"mem\":\"5000\",\"steps\":\"2000\"}}]},\"auxiliary_data\":{\"metadata\":[{\"key\":\"1\",\"value\":{\"tag\":\"int\",\"value\":\"1234\"}},{\"key\":\"2\",\"value\":{\"tag\":\"string\",\"value\":\"str\"}},{\"key\":\"3\",\"value\":{\"tag\":\"list\",\"contents\":[{\"tag\":\"int\",\"value\":\"1234\"},{\"tag\":\"string\",\"value\":\"str\"}]}},{\"key\":\"4\",\"value\":{\"tag\":\"bytes\",\"value\":\"6279746573\"}},{\"key\":\"5\",\"value\":{\"tag\":\"map\",\"contents\":[{\"key\":{\"tag\":\"string\",\"value\":\"strkey\"},\"value\":{\"tag\":\"int\",\"value\":\"123\"}},{\"key\":{\"tag\":\"list\",\"contents\":[{\"tag\":\"string\",\"value\":\"listkey\"}]},\"value\":{\"tag\":\"string\",\"value\":\"strvalue\"}}]}},{\"key\":\"6\",\"value\":{\"tag\":\"int\",\"value\":\"-7\"}}]}}",+ Fixture "native-dijkstra-all-fields" "84a90080018002010e828200581c111111111111111111111111111111111111111111111111111111118201581c22222222222222222222222222222222222222222222222222222222178283a6008001800e828200581c111111111111111111111111111111111111111111111111111111118201581c222222222222222222222222222222222222222222222222222222221818a28200581c11111111111111111111111111111111111111111111111111111111f68201581c22222222222222222222222222222222222222222222222222222222182a1819a1581de0111111111111111111111111111111111111111111111111111111111bffffffffffffffff181aa1581de01111111111111111111111111111111111111111111111111111111182001bffffffffffffffffa30081825820333333333333333333333333333333333333333333333333333333333333333358404444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444405a182060082182a821901f41a000167c4088146450100002499a101647465737483a200800180a0f61818a28200581c11111111111111111111111111111111111111111111111111111111f68201581c22222222222222222222222222222222222222222222222222222222182a1819a1581de0111111111111111111111111111111111111111111111111111111111bffffffffffffffff181aa1581de01111111111111111111111111111111111111111111111111111111182001bffffffffffffffff181ba1581de0111111111111111111111111111111111111111111111111111111111bffffffffffffffffa0f5f6" "{\"body\":{\"inputs\":[],\"outputs\":[],\"fee\":\"1\",\"guards\":[{\"tag\":\"pubkey_hash\",\"value\":\"11111111111111111111111111111111111111111111111111111111\"},{\"tag\":\"script_hash\",\"value\":\"22222222222222222222222222222222222222222222222222222222\"}],\"sub_transactions\":[{\"body\":{\"inputs\":[],\"outputs\":[],\"guards\":[{\"tag\":\"pubkey_hash\",\"value\":\"11111111111111111111111111111111111111111111111111111111\"},{\"tag\":\"script_hash\",\"value\":\"22222222222222222222222222222222222222222222222222222222\"}],\"required_top_level_guards\":[{\"key\":{\"tag\":\"pubkey_hash\",\"value\":\"11111111111111111111111111111111111111111111111111111111\"},\"value\":null},{\"key\":{\"tag\":\"script_hash\",\"value\":\"22222222222222222222222222222222222222222222222222222222\"},\"value\":{\"tag\":\"integer\",\"value\":\"42\"}}],\"direct_deposits\":[{\"key\":\"stake_test1uqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxtxu2s\",\"value\":\"18446744073709551615\"}],\"account_balance_intervals\":[{\"key\":\"stake_test1uqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxtxu2s\",\"value\":{\"tag\":\"range\",\"inclusive_lower_bound\":\"0\",\"exclusive_upper_bound\":\"18446744073709551615\"}}]},\"witness_set\":{\"vkey_witnesses\":[{\"vkey\":\"3333333333333333333333333333333333333333333333333333333333333333\",\"signature\":\"44444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444\"}],\"plutus_scripts\":[{\"language\":\"plutus_v4\",\"bytes\":\"450100002499\"}],\"redeemers\":[{\"tag\":\"guarding\",\"index\":\"0\",\"data\":{\"tag\":\"integer\",\"value\":\"42\"},\"ex_units\":{\"mem\":\"500\",\"steps\":\"92100\"}}]},\"auxiliary_data\":{\"metadata\":[{\"key\":\"1\",\"value\":{\"tag\":\"string\",\"value\":\"test\"}}]}},{\"body\":{\"inputs\":[],\"outputs\":[]},\"witness_set\":{}}],\"required_top_level_guards\":[{\"key\":{\"tag\":\"pubkey_hash\",\"value\":\"11111111111111111111111111111111111111111111111111111111\"},\"value\":null},{\"key\":{\"tag\":\"script_hash\",\"value\":\"22222222222222222222222222222222222222222222222222222222\"},\"value\":{\"tag\":\"integer\",\"value\":\"42\"}}],\"direct_deposits\":[{\"key\":\"stake_test1uqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxtxu2s\",\"value\":\"18446744073709551615\"}],\"account_balance_intervals\":[{\"key\":\"stake_test1uqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxtxu2s\",\"value\":{\"tag\":\"range\",\"inclusive_lower_bound\":\"0\",\"exclusive_upper_bound\":\"18446744073709551615\"}}],\"starting_account_balance_intervals\":[{\"key\":\"stake_test1uqg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3zygxtxu2s\",\"value\":{\"tag\":\"exact\",\"value\":\"18446744073709551615\"}}]},\"is_valid\":true,\"witness_set\":{}}"+ ]
@@ -0,0 +1,16 @@+# Changed-parameter Plutus data++The scalar/rational/execution-unit case in `test/Parameters.hs` adapts+`lib/tests/protocol_params/protocol_param_update.cpp`, test+`encodesTagsValuesAndReducesRationals`, from cardano-c commit+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1` (Apache-2.0).+The expected semantic data is assembled independently with Haskell constructors.+It verifies rational reduction and memory-before-steps ordering, rather than+comparing a native conversion with itself.++The nullable, unsigned-64-bit and complete-field tests are Cometa-authored.+They check explicit unbounded values, exact large integers, unchanged input+encoding, repeated conversions and all supported field identifiers. Legacy+parameter keys 12–14 are intentionally excluded from ChangedParameters; key15+is not a supported parameter. These tests make no claim about governance+acceptance of the constructed updates on a network.
@@ -0,0 +1,36 @@+# Password crypto vector provenance++All inputs are deterministic public test data, never wallet material.++Native source: Biglup/cardano-c revision+`7811fe94dad90f30478ed4b61d96677f188abaa8`,+`lib/tests/crypto/pbkdf2.cpp` (password/salt, one iteration, 64 bytes) and+`lib/tests/crypto/emip3.cpp` (first two decrypt vectors, including empty password; plaintext bytes 00 through 09).+Copyright 2024 / 2023 Biglup Labs, Apache-2.0, same license as this repository.+Native PBKDF and EMIP format/ownership are audited from the matching headers,+implementations and vendored libsodium, not inferred only from fixtures.++Independent locally generated answers use Python hashlib.pbkdf2_hmac and+cryptography.hazmat.primitives.ciphers.aead.ChaCha20Poly1305. They do not call+cardano-c. Reproduce with the following recipe (hex strings are asserted by+`test/PasswordCrypto.hs`):++```python+import hashlib+from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305++print(hashlib.pbkdf2_hmac('sha512', b'pass\x00word', b'sa\x00lt', 2, 65).hex())+salt, nonce = bytes(range(32)), bytes(range(32, 44))+key = hashlib.pbkdf2_hmac('sha512', b'p\x00w', salt, 19162, 32)+aead = ChaCha20Poly1305(key).encrypt(nonce, b'hello\x00world', b'')+print((salt + nonce + aead[-16:] + aead[:-16]).hex())+empty = ChaCha20Poly1305(key).encrypt(nonce, b'', b'')+print((salt + nonce + empty[-16:] + empty[:-16]).hex())+```++The binary case explicitly checks length-aware NUL handling and multi-block+PBKDF output. The independent EMIP answers cover nonempty and empty plaintext and check tag placement, salt/nonce+lengths, iteration count, key length and empty AAD. Encryption tests roundtrip+randomly generated envelopes; they never assume deterministic encryption.+The prefix property is newly authored and checks a PBKDF law, not independent+algorithm correctness. No external text or independent implementation is copied.
@@ -0,0 +1,32 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Pinned native integer encodings and independent expected datum digests.+module Fixtures.PlutusData (integerVectors) where++-- DEFINITIONS ----------------------------------------------------------------++integerVectors :: [(Integer, String, String)]+integerVectors =+ [ (-9223372036854775809, "3b8000000000000000", "e2a47752ef4828f7483c5026a4bc7ed4e452f8101dcf82864f1b1e907c60c572"),+ (-18446744073709551616, "3bffffffffffffffff", "69393b55a0ae218f47bfa0376159277a159c76662f738592c1553e3d904c5ac7"),+ (-18446744073709551617, "c349010000000000000000", "42e2692b0e46ba0dc699ee2f1aa07e1bffb800c35c7b138ddb756d8bf998bc89"),+ (-18446744073709551618, "c349010000000000000001", "4030e370c7a0cb0efdeb05c42cca353d0740f9fc7f05f9a585c69b0850208e30"),+ (-340282366920938463463374607431768211456, "c350ffffffffffffffffffffffffffffffff", "ffab25cae61e7a695eff9e2b32281b5e0eea2096242c598d6236b0c551751c44"),+ (340282366920938463463374607431768211456, "c2510100000000000000000000000000000000", "4ea513acfa0740583f1c5abc413d985ad01c48d3d62e0d65b8721e3de8390a3d"),+ (18446744073709551616, "c249010000000000000000", "0b854352f6a4c02db6f13ac878a41f0b11f54950ad9b88170fb509c916ff0a71"),+ (-13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096, "c35840ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "8e07c147a103e69aadc9be059aeed25e358741ff27f5496e0322f17f0d6d8cf2"),+ (-13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084097, "c35f5840010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004100ff", "8e7a1e2d24d1199e843eaeecff59890724e47f712c32ac9f2c3547b794e8285d")+ ]
@@ -0,0 +1,5 @@+Plutus Data integer boundary vectors originate from cardano-c revision+`eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`,+`lib/tests/plutus_data/plutus_data.cpp`, `INTEGER_BOUNDARY_VECTORS`.+Copyright Biglup Labs; Apache-2.0, as retained in the Haskell fixture notice.+The nine decimal, CBOR and digest triples are transcribed unchanged.
@@ -0,0 +1,105 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Deterministic field-coverage data; these are not parameters for a live network.+module Fixtures.ProtocolParameters (parameters) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.DRepVotingThresholds as DRep+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.PoolVotingThresholds as Pool+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.UnitInterval as Unit+import qualified Data.ByteString as BS++-- DEFINITIONS ----------------------------------------------------------------++-- | Validated full-field snapshot shared by conversion and callback tests.+parameters :: Either Error P.Parameters+parameters = do+ r <- Rational.mkNonNegativeRational 7 3+ u <- Unit.mkUnitInterval 2 3+ stride <- P.mkReferenceScriptCostStride 4294967295+ nonce <- P.mkNonce (BS.pack [0 .. 31])+ let ex = Ex.ExUnits maxBound 123456789+ version = Version.ProtocolVersion 12 maxBound+ prices = Prices.ExUnitPrices r r+ pool = Pool.PoolVotingThresholds u u u u u+ drep = DRep.DRepVotingThresholds u u u u u u u u u u+ pure+ P.Parameters+ { P.parameterMinFeeA = 100,+ P.parameterMinFeeB = 101,+ P.parameterMaxBlockBodySize = 102,+ P.parameterMaxTxSize = 103,+ P.parameterMaxBlockHeaderSize = 104,+ P.parameterKeyDeposit = 105,+ P.parameterPoolDeposit = 106,+ P.parameterMaxEpoch = 107,+ P.parameterDesiredPoolCount = 108,+ P.parameterPoolPledgeInfluence = r,+ P.parameterExpansionRate = u,+ P.parameterTreasuryGrowthRate = u,+ P.parameterDecentralization = Just u,+ P.parameterExtraEntropy = Just nonce,+ P.parameterProtocolVersion = version,+ P.parameterMinPoolCost = 116,+ P.parameterAdaPerUtxoByte = Just 117,+ P.parameterCostModels = Just Models.empty,+ P.parameterExecutionCosts = Just prices,+ P.parameterMaxTxExUnits = Just ex,+ P.parameterMaxBlockExUnits = Just ex,+ P.parameterMaxValueSize = Just 122,+ P.parameterCollateralPercentage = Just 123,+ P.parameterMaxCollateralInputs = Just 124,+ P.parameterPoolVotingThresholds = Just pool,+ P.parameterDrepVotingThresholds = Just drep,+ P.parameterMinCommitteeSize = Just 127,+ P.parameterCommitteeTermLimit = Just 128,+ P.parameterGovernanceActionValidityPeriod = Just 129,+ P.parameterGovernanceActionDeposit = Just 130,+ P.parameterDrepDeposit = Just 131,+ P.parameterDrepInactivityPeriod = Just 132,+ P.parameterRefScriptCostPerByte = Just r,+ P.parameterMaxRefScriptSizePerBlock = Just 134,+ P.parameterMaxRefScriptSizePerTx = Just 135,+ P.parameterRefScriptCostStride = Just stride,+ P.parameterRefScriptCostMultiplier = Just r,+ P.parameterMaxPledgeLeverage = Just (Just r),+ P.parameterMinPoolMargin = Just u,+ P.parameterLeiosAnnouncementPeriodLength = Just 140,+ P.parameterLeiosVotePeriodLength = Just 141,+ P.parameterLeiosDiffusionPeriodLength = Just 142,+ P.parameterLeiosCommitteeSize = Just 143,+ P.parameterLeiosQuorumStakeThreshold = Just u,+ P.parameterMaxEndorserBlockReferencesSize = Just 145,+ P.parameterMaxEndorserBlockTxsSize = Just 146,+ P.parameterMaxEndorserBlockExecutionUnits = Just ex,+ P.parameterMaxRefScriptSizePerEndorserBlock = Just 148,+ P.parameterPerasMinCandidateBlockAge = Just 149,+ P.parameterPerasHealingFactor = Just r,+ P.parameterPerasCertBoost = Just 151,+ P.parameterPerasTargetCommitteeSize = Just 152,+ P.parameterPerasBootstrapRound = Just (Just maxBound),+ P.parameterPerasQuorumThresholdSafetyMargin = Just u,+ P.parameterRefInputsCostPerMultiAssetByte = Just 155,+ P.parameterRefInputsCostPerDatumByte = Just 156+ }
@@ -0,0 +1,70 @@+# Independent reliability properties++These tests call the public Haskell API backed by cardano-c. Expected arithmetic,+hashes and signatures are calculated independently. They test library contracts;+they do not run the ledger state machine or prove that a transaction is admissible+on a network. No upstream implementation, generator or test vector was copied.++## Selection++`SelectionReliability.hs` extends the laws reviewed in+[cardano-coin-selection BalanceSpec](https://github.com/cardano-foundation/cardano-coin-selection/blob/57efda2eda720b9e793a6f907319cc84aa02058c/test/spec/Cardano/CoinSelection/BalanceSpec.hs):+`prop_performSelection`, the user/non-user asset change sum properties, and+`genSelectionParams`. The source revision, Apache-2.0 license and notices are+recorded in [COIN_SELECTION.md](COIN_SELECTION.md).++The new generators cover sparse asset incidence, signed funding requirements,+mandatory inputs, output shape hints, both change address lengths, and retained+datum/reference-script snapshots. Every policy must preserve the eligible input+partition and satisfy per-asset conservation using independent Integer maps.+A minted asset absent from every input must appear in change.++Minimum Ada uses the least fixed point of+`coin = costPerByte * (160 + encodedOutputBytes)`. Only the public Haskell CBOR+encoder supplies byte lengths; no native fee helper supplies the expectation.+Exactly sufficient token change succeeds; one lovelace less fails with the+insufficient-funds status, after which the same selector must still succeed.+The generated domain bounds quantities and supplies enough Ada for the success+cases. It deliberately does not prescribe random selection order.++## Transaction identity and signatures++`IdentityReliability.hs` checks six differently encoded but semantically equal+bodies against literal BLAKE2b-256 hashes and Ed25519 signatures from two keys.+Envelope framing, script validity and outer witness order must not change the+signed message. Nested witness changes must affect the enclosing body commitment+while preserving the nested body identity. Cross-message signatures must fail.++The reviewed signing contract is+[cardano-api Sign.hs](https://github.com/IntersectMBO/cardano-api/blob/c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a/cardano-api/src/Cardano/Api/Tx/Internal/Sign.hs)+(`makeShelleySignature`, `makeShelleyKeyWitness'`, `hashTxBody`). The stale nested+body signature case comes from+[ledger SubUtxowSpec](https://github.com/IntersectMBO/cardano-ledger/blob/7827506b7518284d7f9dbbe3502a20431e513fe9/eras/dijkstra/impl/testlib/Test/Cardano/Ledger/Dijkstra/Imp/SubUtxowSpec.hs)+(`SubInvalidWitnessesUTXOW`). Both sources are Apache-2.0. The latter file was+retrieved at the stated revision and has SHA-256+`a6eca1fb7ba28d2dd82fe8f13b3870f816f3cb50a37294404dc6941de71b494f`.++The original fixtures were generated with Python `hashlib` and cryptography+48.0.0 (OpenSSL 4.0.0), without Cometa or cardano-c. For each `bodyHex` literal,+the independent calculation is:++```python+import hashlib+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++body = bytes.fromhex(body_hex)+digest = hashlib.blake2b(body, digest_size=32).digest()+key = Ed25519PrivateKey.from_private_bytes(bytes([7]) * 32)+signature = key.sign(digest)+```++Repeat with seed byte 8 for the second signature. These are public synthetic+fixtures, not wallet material. The nested body is the same input/output map with+the fee field omitted. A nested frame is `[body, witnesses, null]`; its enclosing+body has empty tagged inputs, empty outputs, fee 10, and field 23 containing its+single tagged subtransaction. The four nested witness sets contain zero, one,+two, or the same two signatures in reverse order. Hash each complete enclosing+body with the same independent formula. Ordinary tests use only the literal+results and have no Python/OpenSSL dependency.++These structural fixtures include empty outputs and do not claim ledger validity.
@@ -0,0 +1,27 @@+# Software-handler fixture provenance++All inputs are public deterministic test material, never application keys or+funded wallet material. No tests use live credentials or a network.++`SoftwareKeyHandler.hs` transcribes numerical vectors from cardano-c revision+`7811fe94dad90f30478ed4b61d96677f188abaa8`,+`lib/tests/key_handlers/software_secure_key_handler.cpp`:+`SERIALIZED_BIP32_KEY_HANDLER`, `EXTENDED_ACCOUNT_0_PUB_KEY`,+`ED25519_NOR_PRIVATE_KEY_HEX`, `ED25519_NOR_PUBLIC_KEY_HEX`,+`ED25519_PRIVATE_KEY_HEX`, and `ED25519_PUBLIC_KEY_HEX`.+Their password is ASCII `password`, and the account path is 1852'/1815'/0'.+The source is Copyright 2024 Biglup Labs, Apache-2.0. This repository retains the+license in `LICENSE`; no native test code was copied.++The fixed serialized input is tested for byte-preserving serialization and its+account public key through public Haskell values. Fresh encryption intentionally+uses random salt/nonce, so only repeated serialization of one handler is equal.+The normal and extended Ed25519 vectors exercise both key modes through scoped+signing keys, not opaque storage forwarding. Additional generated entropy sizes+compare account keys against the existing public BIP32 derivation API; that is+binding conformance, not an independent cryptographic oracle. Maximum raw account+components establish no truncation or ordering error in the C struct adapter.+The concurrency, exception, framing and cancellation scenarios are newly written+Haskell tests. External-consumer compile-fail checks in+`tools/check-key-handler-roles.py` verify capability separation and the nominal+role against `Data.Coerce.coerce`.
@@ -0,0 +1,49 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++-- | Pinned native golden vectors. See Scripts.md for provenance.+module Fixtures.Scripts (applyVectors, compiledScript, nativeVectors) where++import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString++-- | A canonical serialized identity program from the native binding corpus.+compiledScript :: ByteString+compiledScript = ByteString.pack [0x45, 0x01, 0x00, 0x00, 0x24, 0x99]++-- | Parameters encoded as CBOR with expected serialized program bytes.+applyVectors :: [(String, String)]+applyVectors =+ [ ("80", "450100002499"),+ ("8100", "4b0100003249930101000001"),+ ("81c249010000000000000000", "55010000324993010bc2490100000000000000000001"),+ ("820041ff", "5201000033249930010100004c010241ff0001")+ ]++-- | All native tags, including nested Dijkstra key/script guards.+nativeVectors :: [String]+nativeVectors =+ [ "8200581c00112233445566778899aabbccddeeff00112233445566778899aabb",+ "820180",+ "820280",+ "83030080",+ "820400",+ "82051bffffffffffffffff",+ "82068200581c00112233445566778899aabbccddeeff00112233445566778899aabb",+ "82068201581caabbccddeeff00112233445566778899aabbccddeeff001122334455",+ "8201828200581c00112233445566778899aabbccddeeff00112233445566778899aabb82068200581c00112233445566778899aabbccddeeff00112233445566778899aabb",+ "82028182068201581caabbccddeeff00112233445566778899aabbccddeeff001122334455",+ "8303018182068200581c00112233445566778899aabbccddeeff00112233445566778899aabb"+ ]
@@ -0,0 +1,16 @@+# Script vectors++Native source revision: `eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1`.++The four `apply_params` expected encodings and identity script come from+`lib/tests/vectors/bindings/v1/primitives.json` (`apply-params-empty`,+`apply-params-integer-zero`, `apply-params-integer-above-uint64`,+`apply-params-two-parameters`). Guard encodings and nested combinations come from+`lib/tests/scripts/native_scripts/script_require_guard.cpp`, constants+`KEY_HASH_CREDENTIAL_CBOR`, `SCRIPT_HASH_CREDENTIAL_CBOR`, `NESTED_ALL_CBOR`,+`NESTED_ANY_CBOR`, `NESTED_N_OF_K_CBOR`. Empty all/any/threshold and slot extrema+are independently handwritten from the native CBOR schema.++Upstream license: Apache-2.0. Copyright 2024-2026 Biglup Labs; retain this notice+with derived vectors. Tests construct corresponding Haskell values rather than+merely forwarding opaque encoded script bytes. No wallet or network is involved.
@@ -0,0 +1,123 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Port of cardano-c examples/src/sub_transaction_batch_example.c at+-- eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1 (Apache-2.0): buyer and seller sign+-- independent token/coin intents; a third party funds and signs their batch.+module Fixtures.Swap (Swap (..), runSwap) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Address (Address)+import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import Cometa.AssetId (AssetId (Native))+import qualified Cometa.AssetName as AssetName+import Cometa.Credential (Credential, Guard)+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error (..))+import qualified Cometa.NetworkId as Network+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.Parameters (Parameters)+import qualified Cometa.SlotConfig as Slots+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Builder as SubBuilder+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Signing as Signing+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import qualified Data.ByteString as B+import Data.Word (Word8)+import qualified Fixtures.ExampleParameters as Sample++-- TYPES ----------------------------------------------------------------------++data Swap = Swap+ { transaction :: Tx.Transaction,+ buyerIntent :: SubTransaction,+ sellerIntent :: SubTransaction,+ resolvedInputs :: [Utxo]+ }++data Party = Party Address (Credential Guard) Utxo Key.SigningKey++-- DEFINITIONS ----------------------------------------------------------------++runSwap :: IO (Either Error Swap)+runSwap = runExceptT $ do+ params <- except Sample.parameters+ policy <- except (Policy.fromHex "1ec85dcee27f2d90ec1f9a1e4ce74a667dc9be8b184463223f9c9601")+ name <- except (AssetName.fromHex "54534c41")+ let token = Native policy name+ ExceptT $ withParty token 1 100000000 0 $ \buyer ->+ withParty token 2 10000000 5000 $ \seller ->+ withParty token 3 20000000 0 $ \batcher ->+ settle params token buyer seller batcher++-- Public demonstration seeds and synthetic UTxOs only; never fund these keys.+withParty :: AssetId -> Word8 -> Integer -> Integer -> (Party -> IO (Either Error a)) -> IO (Either Error a)+withParty token seed coin tokens action = Key.withNormalKey (B.replicate 32 seed) $ \key -> do+ prepared <- runExceptT $ do+ public <- ExceptT (Key.publicKey key)+ payment <- ExceptT (Credential.fromPublicKey public)+ guard <- ExceptT (Credential.fromPublicKey public)+ previous <- except (Id.fromBytes (B.replicate 32 seed))+ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet payment)+ value = Value.lovelace coin <> Value.singleton token tokens+ output <- except (Output.mkOutput address value Datum.NoDatum Nothing)+ pure (Party address guard (Utxo.utxo (Input.input previous 0) output) key)+ either (pure . Left) action prepared++signedIntent :: Parameters -> AssetId -> Credential Guard -> Party -> Integer -> Integer -> IO (Either Error SubTransaction)+signedIntent params token batcherGuard (Party address _ input key) coin tokens = runExceptT $ do+ output <- except (Output.mkOutput address (Value.lovelace coin <> Value.singleton token tokens) Datum.NoDatum Nothing)+ let plan = SubPlan.spend input <> SubPlan.payTo output <> SubPlan.requireTopLevelGuard batcherGuard Nothing+ local <- ExceptT (SubBuilder.build (SubBuilder.Config params Slots.preprod Fields.Testnet) plan)+ identifier <- ExceptT (Sub.transactionId local)+ signed <- ExceptT (Signing.signSubTransaction key local)+ signedId <- ExceptT (Sub.transactionId signed)+ unless (identifier == signedId) (throwE (InvalidBuildingRequest "Signing changed an intent body"))+ pure signed++settle :: Parameters -> AssetId -> Party -> Party -> Party -> IO (Either Error Swap)+settle params token buyer@(Party _ _ buyerInput _) seller@(Party _ _ sellerInput _) (Party address guard batcherInput key) = runExceptT $ do+ buyerSub <- ExceptT (signedIntent params token guard buyer 50000000 1000)+ sellerSub <- ExceptT (signedIntent params token guard seller 60000000 4000)+ let settings = (Builder.defaultConfig params Slots.preprod address) {Builder.availableUtxos = [batcherInput]}+ plan = Plan.attachSubTransaction buyerSub [buyerInput] <> Plan.attachSubTransaction sellerSub [sellerInput] <> Plan.requireGuard guard+ batch <- ExceptT (Builder.build settings plan)+ signed <- ExceptT (Signing.sign key batch)+ let resolved = [buyerInput, sellerInput, batcherInput]+ preserved = fmap (map Sub.encodeCbor) (Body.bodySubTransactions (Body.toBody (Tx.body signed)))+ unless (preserved == Just [Sub.encodeCbor buyerSub, Sub.encodeCbor sellerSub]) (throwE (InvalidBuildingRequest "Batch changed independently signed intent bytes"))+ balanced <- ExceptT (Building.isBalanced params resolved signed)+ unless balanced (throwE (InvalidBuildingRequest "Two-party swap does not conserve value"))+ pure (Swap signed buyerSub sellerSub resolved)
@@ -0,0 +1,130 @@+# Transaction fixture provenance++These fixtures test the private P03 transaction representation. They do not+establish ledger validity, balancing, signing support, or a public transaction API.+The ordinary test suite needs no Python packages and no network access.++## Native baseline and notices++Native source: `Biglup/cardano-c`, revision+`8dc0c55f4132fcaa2e7961b6cfbfea96a6d93b5d`, the original fixture baseline.+The current build revision is recorded in `native/cardano-c.ref`. Imported transaction bytes are from+`lib/tests/transaction/transaction.cpp`, symbol `CBOR_NULLIFY_ENTROPY`, and its+exported counterpart in+`lib/tests/vectors/bindings/v1/serialization.json`, case+`transaction-transaction-cbor-nullify-entropy`.++The original test source is Copyright 2024 Biglup Labs, licensed under Apache-2.0.+The repository's `LICENSE` contains that license. The Haskell fixture file keeps+the project's Apache-2.0 notice; this provenance preserves attribution for the+copied bytes. No native generator or property implementation was copied.++## Historical signed transaction++`Fixtures.Transaction.historical` copies the original 1175-byte transaction,+its exact body, and its exact witness set. It has the older three-element frame+`[body, witnesses, auxiliaryData]`, a fee of 217553, and eight verification-key+witnesses. The body contains historical transaction update data, rather than+being a minimal synthetic envelope.++Independent BLAKE2b-256 of the exact body:++```text+fc863a441b55acceebb7d25c81ff7259e4fc9b92fbdf6d594118fb8f1110a78c+```++All eight original verification-key signatures were independently checked over+that exact digest using Python `cryptography` 48.0.0's+`Ed25519PublicKey.verify`. The body was extracted by a `cbor2` 6.1.2 decoder+tracking byte-stream positions, without re-encoding it, and the digest was+computed with Python's `hashlib.blake2b(body, digest_size=32)`. The digest also+matches the native corpus's `expected.hash`.++The other native `CBOR` and `CBOR2` constants contain verification-key witness+bytes that do not verify over their original body digests. They were deliberately+not used as evidence of valid signed identity.++## Synthetic noncanonical transaction++`noncanonical` uses an explicitly constructed body with reordered keys and a+non-shortest integer encoding for fee 10:++```text+a30219000a018000d9010280+```++Its fields are fee (key 2), empty outputs (key 1), and a tagged empty input set+(key 0), in that order. The empty collections make this an encoding fixture,+not a spendable transaction. Its independently computed body digest is:++```text+6715bbd7c4477c3cc6dd32e3f8e3c513c136dd4cef9d58a275fe1e3b04a6e50b+```++The fixture's Ed25519 signature was generated and verified independently using+`cryptography` 48.0.0 over this digest. Construction uses the public deterministic+native-corpus test seed consisting of bytes 0 through 31; no operational wallet+key is present. Its public key is:++```text+03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8+```++The enclosing frame is `[body, witnesses, true, null]`. The signature and public+key are literal fixture bytes, not values generated by the Haskell code under+test. Equality of the retained witness bytes and exact signed digest establishes+signature preservation; the test-only native oracle also verifies the signature.++`rich` uses the same signed body and vkey witness, adding a bootstrap witness,+a native signature script, noncanonical auxiliary metadata, datum 42, and one+redeemer with execution units+`[10, 20]`. The bootstrap witness reuses the public test key and signature, has a+32-byte chain code consisting of `0x22`, and attributes containing encoded `{}`.+The native script's key hash is 28 bytes of `0x11`. These auxiliary witnesses are+serialization fixtures; no script execution or bootstrap address validation is+claimed. The auxiliary metadata is label 1 with text `aux`, encoded as+`a1017803617578` using a non-shortest text-length encoding. Fee edits preserve+those exact auxiliary bytes. Counts are pinned independently as one vkey, one+bootstrap, one native script, one datum, and one redeemer.++Changing the synthetic fee to 42 produces this expected body:++```text+a300d9010280018002182a+```++Its independent BLAKE2b-256 digest is:++```text+a5412fe55fd15ed71f2e55fdb9c4f8a3105f8e41cb770e2ed848f73f0382a38b+```++The fee-edit policy strips vkey and bootstrap signatures, while preserving native+scripts, datums and redeemers. Setting the original fee is an exact no-op,+including the noncanonical encoding and original signatures.++## Independent native oracle++`test/cbits/transaction_oracle.c` calls native transaction, body, witness and+Ed25519 APIs directly, independently of the production transaction adapter. It+reports fee, body hash, witness-kind counts and the count of valid vkey+signatures. All retained getter references are released on every exit.+The oracle is compiled against the same installed headers and native revision+as the library. Agreement establishes binding consistency; the independent+hash/signature checks above supply evidence beyond native self-agreement.++## CBOR scalar and collection cases++`test/Cbor.hs` contains handwritten primitive major-type examples following+RFC 8949: integer encoding boundaries, byte strings, UTF-8 text, Booleans,+arrays, ordered maps, duplicate keys, tags, and indefinite/non-shortest forms.+The tests distinguish exact raw-item preservation from scalar and collection+marshaling. They do not claim semantic validation of arbitrary tags or ledger+schemas. Tagged bignums are preserved as raw items; primitive integer codecs+cover only `[-2^64, 2^64 - 1]`.++The new Hedgehog generators are written for this project. They exercise 300+cases per law, including deliberately repeated map keys and 64-bit fee edits.+Lifecycle cases repeatedly decode and edit historical transactions, then check+that retained snapshots survive native cleanup and garbage collection. The same+tests can run under Valgrind without any additional fixture dependencies.
@@ -0,0 +1,147 @@+# Generated transaction accounting property provenance++`test/TransactionAccountingProperties.hs` contains original Cometa Hedgehog+properties. They adapt reviewed conservation contracts, not upstream Haskell+implementations, test frameworks, generators, ledger fixtures or state transitions.+The following primary sources were read before choosing the equations and cases.++- cardano-foundation/cardano-coin-selection+ [`57efda2eda720b9e793a6f907319cc84aa02058c`,+ `test/spec/Cardano/CoinSelection/BalanceSpec.hs`](https://github.com/cardano-foundation/cardano-coin-selection/blob/57efda2eda720b9e793a6f907319cc84aa02058c/test/spec/Cardano/CoinSelection/BalanceSpec.hs),+ cached at `/tmp/cometa-pinned-balance-spec.hs`: in particular+ `prop_addMintValueToChangeMaps_value` and+ `prop_removeBurnValueFromChangeMaps_value` establish the positive mint and+ negative burn contribution to aggregate change. Copyright 2018–2026 IOHK,+ 2024–2026 Cardano Foundation; Apache-2.0. Its complete upstream NOTICE is already+ retained in [COIN_SELECTION.md](COIN_SELECTION.md#upstream-notice).+- IntersectMBO/cardano-api+ [`c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a`,+ `cardano-api/test/cardano-api-test/Test/Cardano/Api/Experimental/Fee.hs`](https://github.com/IntersectMBO/cardano-api/blob/c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a/cardano-api/test/cardano-api-test/Test/Cardano/Api/Experimental/Fee.hs),+ reviewed from the complete checkout cached below+ `/tmp/p15-source-cardano-api/cardano-api-c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a`:+ `genWithdrawalFundedTx` explains the independent coin equation+ `change = input + withdrawal - output - fee`; the+ `evaluateSignedTx` balanced/mempty test motivates checking zero balance as well+ as signed surpluses and deficits. The same checkout's LICENSE is Apache-2.0;+ its NOTICE is retained verbatim below.+- IntersectMBO/cardano-ledger+ [`7827506b7518284d7f9dbbe3502a20431e513fe9`,+ `libs/cardano-ledger-binary/src/Cardano/Ledger/Binary/Encoding/Encoder.hs`](https://github.com/IntersectMBO/cardano-ledger/blob/7827506b7518284d7f9dbbe3502a20431e513fe9/libs/cardano-ledger-binary/src/Cardano/Ledger/Binary/Encoding/Encoder.hs),+ cached at `/tmp/cometa-ledger-encoder-review.hs`, with this revision recorded in+ the implementation plan's serialization audit: `encodeSet` varies tag presence+ with protocol version. This informs the tag-invariance cases; no ledger+ round-trip or Dijkstra state-transition property is imported. Apache-2.0; the+ cached upstream LICENSE `/tmp/review-ledger-license.txt` was also reviewed.++Other cached Conway RoundTrip and Dijkstra SubUtxow source files were inspected,+but their cache files do not establish a verifiable source revision. They are not+claimed as pinned test provenance or used as imported fixtures/properties here.++## What executes in native code++Every generated case assembles typed public values and calls+`Cometa.Transaction.Building`. `implicitCoin`, `subTransactionImplicitCoin`,+`imbalance`, `subTransactionImbalance`, `batchImbalance`, and `isBalanced` execute+native CBOR parsing and accounting through the binding. Production Haskell+preflight also validates snapshots and signed intermediate bounds. No direct+call to the same C implementation supplies an expected result.++The audited native checkout is cardano-c+`a19dbc9185112ab2d7126c9c28058388a37bdccc`,+`lib/src/transaction_builder/balancing/implicit_coin.c` and+`lib/src/transaction_builder/balancing/transaction_balancing.c`+(`cardano_compute_transaction_imbalance`,+`cardano_compute_sub_transaction_imbalance`,+`cardano_compute_transaction_batch_imbalance`). Native source was reviewed+to bound the contract: legacy stake deposits/refunds use the supplied current+parameter, explicit Conway certificates and proposals carry their own amounts,+pool deposits are deduplicated by pool operator, and pool retirement has no+immediate refund. These native mechanics determine supported inputs, not the+independent numerical oracle. This native tree was previously documented as+matching merged dependency pin `b98afee9de25c09f29d1c5fe4af3e538d1830d44` for the+relevant construction implementation. Native source is Copyright Biglup Labs,+Apache-2.0; no native source is copied into these properties.++## Independent equations and shrinking++Implicit totals come from generated event descriptions, before construction of+certificates. An independent integer model sums paid amounts, refunded amounts,+and distinct reward-account withdrawals. It includes all explicit deposit+certificate forms, legacy stake registration/deregistration, governance proposal+deposits and pool retirements. It does not recover expected amounts by inspecting+decoded certificates, native output or serialized fields.++For conservation, the generator constructs ample nonnegative funding and output+amounts using:++```text+outputCoin = inputCoin + withdrawal + refund+ - deposit - fee - donation - directDeposit + perturbation+outputAsset = inputAsset + signedMint + perturbation+expectedImbalance[coin] = expectedImbalance[asset] = -perturbation+```++The fee is zero for a subtransaction. Both levels use the same token identity and+different spending references: opposing imbalances can cancel in a complete+Dijkstra batch. Each local result is checked separately, and the batch expectation+is independent `Map.unionWith (+)` on raw `Integer` quantities, with zero entries+removed. `Value` construction feeds the public binding, but `Value` addition,+subtraction and normalization are not used as the oracle. Extra resolved UTxOs,+reference inputs and collateral do not add spending supply. `isBalanced` must+agree exactly with the independent empty-map condition.++Pool-registration lists shrink as lists of a small set of integer identifiers.+Distinct-identifier cardinalities independently determine deposits per body and+across the complete batch, covering duplicates within and between bodies. Retirement+refunds are excluded from these counts.++Amounts include CBOR unsigned-width boundaries 23/24, 255/256 and 65535/65536,+zero and bounded random quantities. Funding keeps all outputs positive under+shrinking; signed mint stays within native bounds; maps use distinct validated+keys; generated lists and values remain far below unsigned/signed accumulator+limits. Perturbations are chosen from negative, zero and positive alternatives.+Hedgehog reports the replay seed and shrinks these constraints together.+Classifications identify minting, burning, complete balance, surplus, deficit,+legacy events, governance deposits, retirement and duplicate pools.++Top-level empty certificate/proposal collections remain explicitly present in+the generated cases; their subtransaction counterparts are absent when empty,+as required by the subtransaction grammar.++Both tagged and untagged body encodings are fed back through public decoding+before native accounting. The equation must hold for both, and accounting must+leave the exact transaction bytes unchanged. This exercises representation+handling through the native parser; it does not claim an independent reference+CBOR serializer or hash implementation.++## Limits++These properties test bounded accounting, not ledger admission. Repeated+certificate operations on the same credential are intentional accounting inputs+and are not claimed valid against any staking/governance state. Legacy refunds+use current supplied parameters rather than historical registration deposits;+already-registered pools cannot be identified without chain state. Fees are+explicit inputs, not minimum-fee estimates. Script execution, witnesses, actual+balances in reward accounts, withdrawal authorization, mint authorization,+collateral eligibility, era validity and live-network behavior are outside this+suite. Dijkstra coverage checks local/top-level/batch arithmetic and pool deposit+scope, not ledger conformance or successful submission. Native overflow and+invalid-resolution regressions remain in the existing fixed Building tests.++## cardano-api NOTICE++```text+Copyright 2021-2025 Input Output Global Inc (IOG).++Licensed under the Apache License, Version 2.0 (the "License");+you may not use this file except in compliance with the License.+You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++Unless required by applicable law or agreed to in writing, software+distributed under the License is distributed on an "AS IS" BASIS,+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+See the License for the specific language governing permissions and+limitations under the License.+```
@@ -0,0 +1,176 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Public transaction bytes and independent expected results. Provenance and+-- reproduction details are recorded in test/Fixtures/TRANSACTIONS.md.+module Fixtures.Transaction+ ( Fixture (..),+ historical,+ noncanonical,+ rich,+ allFixtures,+ )+where++-- IMPORTS --------------------------------------------------------------------++import Data.Text (Text)+import qualified Data.Text as Text+import Data.Word (Word64)++-- TYPES ----------------------------------------------------------------------++data Fixture = Fixture+ { fixtureName :: String,+ transactionHex :: Text,+ bodyHex :: Text,+ witnessHex :: Text,+ hashHex :: Text,+ expectedFee :: Word64,+ -- Counts: vkeys, bootstrap, native scripts, datums, redeemers, verified vkeys.+ expectedCounts :: [Word64]+ }++-- DEFINITIONS ----------------------------------------------------------------++allFixtures :: [Fixture]+allFixtures = [historical, noncanonical, rich]++historical :: Fixture+historical =+ Fixture+ { fixtureName = "Historical Shelley 3-element envelope",+ transactionHex =+ Text.concat+ [ "83a50081825820bf30608a974d09c56dd62ca10199ec11746ea2d90dbd83649d4f37c629b1ba840001818258390117d2",+ "37fb8f952c995cd28f73c555adc2307322d819b7f565196ce754348144bff68f23c1386b85dea0f8425ca574b1a11e18",+ "8ffaba67537c1a0048f96f021a000351d1031a019732f30682a7581c162f94554ac8c225383a2248c245659eda870eaa",+ "82d0ef25fc7dcd82a10d8100581c2075a095b3c844a29c24317a94a643ab8e22d54a3a3a72a420260af6a10d8100581c",+ "268cfc0b89e910ead22e0ade91493d8212f53f3e2164b2e4bef0819ba10d8100581c60baee25cbc90047e83fd01e1e57",+ "dc0b06d3d0cb150d0ab40bbfead1a10d8100581cad5463153dc3d24b9ff133e46136028bdc1edbb897f5a7cf1b37950c",+ "a10d8100581cb9547b8a57656539a8d9bc42c008e38d9c8bd9c8adbb1e73ad529497a10d8100581cf7b341c14cd58fca",+ "4195a9b278cce1ef402dc0e06deb77e543cd1757a10d8100190103a1008882582061261a95b7613ee6bf2067dad77b70",+ "349729b0c50d57bc1cf30de0db4a1e73a858407d72721e7504e12d50204f7d9e9d9fe60d9c6a4fd18ad629604729df4f",+ "7f3867199b62885623fab68a02863e7877955ca4a56c867157a559722b7b350b668a0b8258209180d818e69cd997e346",+ "63c418a648c076f2e19cd4194e486e159d8580bc6cda5840af668e57c98f0c3d9b47c66eb9271213c39b4ea1b4d543b0",+ "892f03985edcef4216d1f98f7b731eedc260a2154124b5cab015bfeaf694d58966d124ad2ff60f0382582089c29f8c4a",+ "f27b7accbe589747820134ebbaa1caf3ce949270a3d0c7dcfd541b58401ad69342385ba6c3bef937a79456d7280c0d53",+ "9128072db15db120b1579c46ba95d18c1fa073d7dbffb4d975b1e02ebb7372936940cff0a96fce950616d2f504825820",+ "f14f712dc600d793052d4842d50cefa4e65884ea6cf83707079eb8ce302efc855840638f7410929e7eab565b1451effd",+ "fbeea2a8839f7cfcc4c4483c4931d489547a2e94b73e4b15f8494de7f42ea31e573c459a9a7e5269af17b0978e70567d",+ "e80e8258208b53207629f9a30e4b2015044f337c01735abe67243c19470c9dae8c7b73279858400c4ed03254c33a1925",+ "6b7a3859079a9b75215cad83871a9b74eb51d8bcab52911c37ea5c43bdd212d006d1e6670220ff1d03714addf94f490e",+ "482edacbb08f068258205fddeedade2714d6db2f9e1104743d2d8d818ecddc306e176108db14caadd4415840bf48f5dd",+ "577b5cb920bfe60e13c8b1b889366c23e2f2e28d51814ed23def3a0ff4a1964f806829d40180d83b5230728409c1f18d",+ "db5a61c44e614b823bd43f01825820cbc6b506e94fbefe442eecee376f3b3ebaf89415ef5cd2efb666e06ddae4839358",+ "4089bff8f81a20b22f2c3f8a2288b15f1798b51f3363e0437a46c0a2e4e283b7c1018eba0b2b192d6d522ac8df2f2e95",+ "b4c8941b387cda89857ab0ae77db14780c825820e8c03a03c0b2ddbea4195caf39f41e669f7d251ecf221fbb2f275c0a",+ "5d7e05d158402643ac53dd4da4f6e80fb192b2bf7d1dd9a333bbacea8f07531ba450dd8fb93e481589d370a6ef33a97e",+ "03b2f5816e4b2c6a8abf606a859108ba6f416e530d07f6"+ ],+ bodyHex =+ Text.concat+ [ "a50081825820bf30608a974d09c56dd62ca10199ec11746ea2d90dbd83649d4f37c629b1ba840001818258390117d237",+ "fb8f952c995cd28f73c555adc2307322d819b7f565196ce754348144bff68f23c1386b85dea0f8425ca574b1a11e188f",+ "faba67537c1a0048f96f021a000351d1031a019732f30682a7581c162f94554ac8c225383a2248c245659eda870eaa82",+ "d0ef25fc7dcd82a10d8100581c2075a095b3c844a29c24317a94a643ab8e22d54a3a3a72a420260af6a10d8100581c26",+ "8cfc0b89e910ead22e0ade91493d8212f53f3e2164b2e4bef0819ba10d8100581c60baee25cbc90047e83fd01e1e57dc",+ "0b06d3d0cb150d0ab40bbfead1a10d8100581cad5463153dc3d24b9ff133e46136028bdc1edbb897f5a7cf1b37950ca1",+ "0d8100581cb9547b8a57656539a8d9bc42c008e38d9c8bd9c8adbb1e73ad529497a10d8100581cf7b341c14cd58fca41",+ "95a9b278cce1ef402dc0e06deb77e543cd1757a10d8100190103"+ ],+ witnessHex =+ Text.concat+ [ "a1008882582061261a95b7613ee6bf2067dad77b70349729b0c50d57bc1cf30de0db4a1e73a858407d72721e7504e12d",+ "50204f7d9e9d9fe60d9c6a4fd18ad629604729df4f7f3867199b62885623fab68a02863e7877955ca4a56c867157a559",+ "722b7b350b668a0b8258209180d818e69cd997e34663c418a648c076f2e19cd4194e486e159d8580bc6cda5840af668e",+ "57c98f0c3d9b47c66eb9271213c39b4ea1b4d543b0892f03985edcef4216d1f98f7b731eedc260a2154124b5cab015bf",+ "eaf694d58966d124ad2ff60f0382582089c29f8c4af27b7accbe589747820134ebbaa1caf3ce949270a3d0c7dcfd541b",+ "58401ad69342385ba6c3bef937a79456d7280c0d539128072db15db120b1579c46ba95d18c1fa073d7dbffb4d975b1e0",+ "2ebb7372936940cff0a96fce950616d2f504825820f14f712dc600d793052d4842d50cefa4e65884ea6cf83707079eb8",+ "ce302efc855840638f7410929e7eab565b1451effdfbeea2a8839f7cfcc4c4483c4931d489547a2e94b73e4b15f8494d",+ "e7f42ea31e573c459a9a7e5269af17b0978e70567de80e8258208b53207629f9a30e4b2015044f337c01735abe67243c",+ "19470c9dae8c7b73279858400c4ed03254c33a19256b7a3859079a9b75215cad83871a9b74eb51d8bcab52911c37ea5c",+ "43bdd212d006d1e6670220ff1d03714addf94f490e482edacbb08f068258205fddeedade2714d6db2f9e1104743d2d8d",+ "818ecddc306e176108db14caadd4415840bf48f5dd577b5cb920bfe60e13c8b1b889366c23e2f2e28d51814ed23def3a",+ "0ff4a1964f806829d40180d83b5230728409c1f18ddb5a61c44e614b823bd43f01825820cbc6b506e94fbefe442eecee",+ "376f3b3ebaf89415ef5cd2efb666e06ddae48393584089bff8f81a20b22f2c3f8a2288b15f1798b51f3363e0437a46c0",+ "a2e4e283b7c1018eba0b2b192d6d522ac8df2f2e95b4c8941b387cda89857ab0ae77db14780c825820e8c03a03c0b2dd",+ "bea4195caf39f41e669f7d251ecf221fbb2f275c0a5d7e05d158402643ac53dd4da4f6e80fb192b2bf7d1dd9a333bbac",+ "ea8f07531ba450dd8fb93e481589d370a6ef33a97e03b2f5816e4b2c6a8abf606a859108ba6f416e530d07"+ ],+ hashHex = "fc863a441b55acceebb7d25c81ff7259e4fc9b92fbdf6d594118fb8f1110a78c",+ expectedFee = 217553,+ expectedCounts = [8, 0, 0, 0, 0, 8]+ }++noncanonical :: Fixture+noncanonical =+ Fixture+ { fixtureName = "Synthetic signed noncanonical body",+ transactionHex =+ Text.concat+ [ "84a30219000a018000d9010280a1008182582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc866412",+ "5531b85840dc836ca35ce76211f3e2c28b6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79b",+ "a1354d96e323e8c37c81958c103e49f47a801a820af5f6"+ ],+ bodyHex =+ Text.concat+ [ "a30219000a018000d9010280"+ ],+ witnessHex =+ Text.concat+ [ "a1008182582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b85840dc836ca35ce76211",+ "f3e2c28b6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79ba1354d96e323e8c37c81958c10",+ "3e49f47a801a820a"+ ],+ hashHex = "6715bbd7c4477c3cc6dd32e3f8e3c513c136dd4cef9d58a275fe1e3b04a6e50b",+ expectedFee = 10,+ expectedCounts = [1, 0, 0, 0, 0, 1]+ }++rich :: Fixture+rich =+ Fixture+ { fixtureName = "Synthetic signed noncanonical body with script, bootstrap, datum and redeemer",+ transactionHex =+ Text.concat+ [ "84a30219000a018000d9010280a5008182582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc866412",+ "5531b85840dc836ca35ce76211f3e2c28b6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79b",+ "a1354d96e323e8c37c81958c103e49f47a801a820a01d90102818200581c111111111111111111111111111111111111",+ "11111111111111111111028184582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b858",+ "40dc836ca35ce76211f3e2c28b6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79ba1354d96",+ "e323e8c37c81958c103e49f47a801a820a58202222222222222222222222222222222222222222222222222222222222",+ "22222241a004d9010281182a05a182000082182a820a14f5a1017803617578"+ ],+ bodyHex =+ Text.concat+ [ "a30219000a018000d9010280"+ ],+ witnessHex =+ Text.concat+ [ "a5008182582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b85840dc836ca35ce76211",+ "f3e2c28b6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79ba1354d96e323e8c37c81958c10",+ "3e49f47a801a820a01d90102818200581c11111111111111111111111111111111111111111111111111111111028184",+ "582003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b85840dc836ca35ce76211f3e2c28b",+ "6bbae69086ac3d40734865202771b7c30973c1e05ad9ce2c9bb2192851e79ba1354d96e323e8c37c81958c103e49f47a",+ "801a820a5820222222222222222222222222222222222222222222222222222222222222222241a004d9010281182a05",+ "a182000082182a820a14"+ ],+ hashHex = "6715bbd7c4477c3cc6dd32e3f8e3c513c136dd4cef9d58a275fe1e3b04a6e50b",+ expectedFee = 10,+ expectedCounts = [1, 1, 1, 1, 1, 1]+ }
@@ -0,0 +1,321 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Generic transaction recipes used by provider/FFI regression fixtures.+module Fixtures.TransactionWorkflows+ ( Context (..),+ builderConfig,+ awaitWallet,+ buildTransaction,+ signTransaction,+ submitAndConfirm,+ runStage,+ runStageWithIndexPolling,+ runPayment,+ runMintBurn,+ runLockSpend,+ runDeferredSelf,+ runDeferredBatch,+ runRewardCycle,+ runWithdrawZero,+ runDRepCycle,+ runVoteCycle,+ runDonation,+ runTreasuryWithdrawal,+ runGuardedSub,+ runSignedBatch,+ voidArgument,+ )+where++import Cometa.Address (Address)+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import Cometa.AssetId (AssetId (Native))+import Cometa.AssetName (AssetName)+import qualified Cometa.Certificate as Certificate+import Cometa.Credential (Credential, DRep, KeyHash, Stake, StakePool)+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import Cometa.Governance.ActionId (ActionId)+import Cometa.Governance.Anchor (Anchor)+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Provider as Provider+import Cometa.Script (Script)+import qualified Cometa.Script as Script+import qualified Cometa.Signer as Signer+import Cometa.SubTransaction (SubTransaction)+import qualified Cometa.SubTransaction.Builder as SubBuilder+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import Cometa.Transaction.Plan (Plan)+import qualified Cometa.Transaction.Plan as Plan+import Cometa.Transaction.Utxo (Utxo)+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Value as Value+import Control.Concurrent (threadDelay)+import Control.Monad (unless)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE)+import Data.Int (Int64)+import Data.List (sort)+import Data.Word (Word64)+import GHC.Clock (getMonotonicTimeNSec)+import Support.Transaction (Context (..), awaitWallet, builderConfig, outputAt)++voidArgument :: Data.EncodedPlutusData+voidArgument = Data.fromData (Data.Constr 0 [])++runStage :: Context -> Plan -> IO (Either Error Tx.Transaction)+runStage = runStageWithIndexPolling getMonotonicTimeNSec (threadDelay 1000000)++runStageWithIndexPolling :: IO Word64 -> IO () -> Context -> Plan -> IO (Either Error Tx.Transaction)+runStageWithIndexPolling clock pause context plan = runExceptT $ do+ liftIO (putStrLn "Building transaction...")+ unsigned <- ExceptT (buildTransaction context plan)+ liftIO (putStrLn "Signing with the encrypted wallet...")+ signed <- ExceptT (signTransaction context unsigned)+ liftIO (putStrLn "Submitting and waiting for confirmation...")+ ExceptT (submitWithIndexPolling clock pause context signed)++buildTransaction :: Context -> Plan -> IO (Either Error Tx.Transaction)+buildTransaction context plan = runExceptT $ do+ settings <- ExceptT (builderConfig context)+ ExceptT (Builder.build settings (plan <> Plan.validUntil (invalidAfter context)))++signTransaction :: Context -> Tx.Transaction -> IO (Either Error Tx.Transaction)+signTransaction context unsigned = runExceptT $ do+ witnesses <- ExceptT (Signer.signTransaction (signer context) unsigned)+ except (Tx.addWitnesses witnesses unsigned)++submitAndConfirm :: Context -> Tx.Transaction -> IO (Either Error Tx.Transaction)+submitAndConfirm = submitWithIndexPolling getMonotonicTimeNSec (threadDelay 1000000)++submitWithIndexPolling :: IO Word64 -> IO () -> Context -> Tx.Transaction -> IO (Either Error Tx.Transaction)+submitWithIndexPolling clock pause context signed = runExceptT $ do+ let backend = provider context+ identifier <- ExceptT (Tx.transactionId signed)+ accepted <- ExceptT (Provider.submitTransaction backend signed)+ unless (accepted == identifier) (throwE (InvalidProviderResponse "Submitted ID differs from signed transaction body"))+ confirmed <- ExceptT (Provider.awaitTransaction backend accepted (confirmationTimeoutMillis context))+ unless confirmed (throwE (InvalidBuildingRequest "Confirmation timed out; dependent workflow stages were not run"))+ ExceptT (awaitWalletSnapshot clock pause context signed)+ pure signed++awaitWalletSnapshot :: IO Word64 -> IO () -> Context -> Tx.Transaction -> IO (Either Error ())+awaitWalletSnapshot clock pause context transaction = runExceptT $ do+ identifier <- ExceptT (Tx.transactionId transaction)+ let fields = Body.bodyFields (Body.toBody (Tx.body transaction))+ expected = [Utxo.utxo (Input.input identifier index) output | (index, output) <- zip [0 ..] (Fields.fieldOutputs fields), Output.address output == wallet context]+ consumed = Fields.fieldInputs fields+ started <- liftIO clock+ let deadline = toInteger started + toInteger (confirmationTimeoutMillis context) * 1000000+ poll = runExceptT $ do+ current <- ExceptT (Provider.utxosAt (provider context) (wallet context))+ if all (`elem` current) expected && all ((`notElem` consumed) . Utxo.input) current+ then pure ()+ else do+ now <- liftIO clock+ if toInteger now >= deadline+ then throwE (InvalidBuildingRequest "Confirmed transaction is not yet reflected in the wallet index; dependent stages stopped")+ else liftIO pause >> ExceptT poll+ ExceptT poll++runPayment :: Context -> Address -> Word64 -> IO (Either Error Tx.Transaction)+runPayment context recipient amount = runExceptT $ do+ output <- except (Output.mkOutput recipient (Value.lovelace (toInteger amount)) Datum.NoDatum Nothing)+ ExceptT (runStage context (Plan.payTo output))++runMintBurn :: Context -> Script -> Maybe Utxo -> AssetName -> Int64 -> IO (Either Error [Tx.Transaction])+runMintBurn context script reference name amount+ | amount <= 0 = pure (Left (InvalidBuildingRequest "Mint quantity must be positive"))+ | otherwise = runExceptT $ do+ digest <- ExceptT (Script.hash script)+ let asset = Native (Policy.fromScriptHash digest) name+ operation quantity =+ maybe (Plan.attachScript script) Plan.referenceInput reference <> case script of+ Script.Native _ -> Plan.mint asset quantity+ Script.Plutus _ -> Plan.mintWithRedeemer asset quantity voidArgument+ minted <- ExceptT (runStage context (operation amount))+ burned <- ExceptT (runStage context (operation (negate amount)))+ pure [minted, burned]++runLockSpend :: Context -> Script -> Word64 -> IO (Either Error [Tx.Transaction])+runLockSpend context script amount = runExceptT $ do+ (locked, reference, funded) <- ExceptT (fundScript context script amount)+ let argument = case script of Script.Native _ -> Nothing; Script.Plutus _ -> Just voidArgument+ source = maybe (Plan.attachScript script) Plan.referenceInput reference+ payout <- except (Output.mkOutput (wallet context) (Value.lovelace 1000000) Datum.NoDatum Nothing)+ spent <- ExceptT (runStage context (Plan.payTo payout <> Plan.spendWith locked argument Nothing <> source))+ pure [funded, spent]++fundScript :: Context -> Script -> Word64 -> IO (Either Error (Utxo, Maybe Utxo, Tx.Transaction))+fundScript context = fundScriptPreserving context []++fundScriptPreserving :: Context -> [Utxo] -> Script -> Word64 -> IO (Either Error (Utxo, Maybe Utxo, Tx.Transaction))+fundScriptPreserving context protected script amount = runExceptT $ do+ digest <- ExceptT (Script.hash script)+ let destination = Address.ShelleyAddress (Shelley.enterprise (network context) (Credential.ScriptCredential digest))+ datum = case script of Script.Native _ -> Datum.NoDatum; Script.Plutus _ -> Datum.InlineDatum voidArgument+ output <- except (Output.mkOutput destination (Value.lovelace (toInteger amount)) datum Nothing)+ reference <- case script of+ Script.Native _ -> pure Nothing+ Script.Plutus _ -> Just <$> except (Output.mkOutput (wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just script))+ funded <- ExceptT (runStage context (Plan.payTo output <> maybe mempty Plan.payTo reference <> foldMap Plan.referenceInput protected))+ locked <- ExceptT (outputAt funded 0)+ referenceUtxo <- traverse (const (ExceptT (outputAt funded 1))) reference+ pure (locked, referenceUtxo, funded)++fundInlineScript :: Context -> Script -> IO (Either Error (Utxo, Tx.Transaction))+fundInlineScript context script = runExceptT $ do+ digest <- ExceptT (Script.hash script)+ let destination = Address.ShelleyAddress (Shelley.enterprise (network context) (Credential.ScriptCredential digest))+ output <- except (Output.mkOutput destination (Value.lovelace 2000000) (Datum.InlineDatum voidArgument) Nothing)+ funded <- ExceptT (runStage context (Plan.payTo output))+ locked <- ExceptT (outputAt funded 0)+ pure (locked, funded)++runDeferredSelf :: Context -> Script -> IO (Either Error [Tx.Transaction])+runDeferredSelf context script = runExceptT $ do+ (locked, funded) <- ExceptT (fundInlineScript context script)+ payout <- except (Output.mkOutput (wallet context) (Value.lovelace 1000000) Datum.NoDatum Nothing)+ let callback draft _ = do+ position <- maybe (Left (InvalidBuildingRequest "Deferred input disappeared")) Right (Indices.findInput (Utxo.input locked) draft)+ pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger position)]))+ plan = Plan.payTo payout <> Plan.spendWithDeferredRedeemer locked callback Nothing <> Plan.attachScript script+ spent <- ExceptT (runStage context plan)+ pure [funded, spent]++runDeferredBatch :: Context -> Script -> IO (Either Error [Tx.Transaction])+runDeferredBatch context script = runExceptT $ do+ (first, funded) <- ExceptT (fundInlineScript context script)+ -- Each order is funded independently; both confirmations precede settlement.+ (second, fundedAgain) <- ExceptT (fundInlineScript context script)+ firstPayout <- except (Output.mkOutput (wallet context) (Value.lovelace 1200000) Datum.NoDatum Nothing)+ secondPayout <- except (Output.mkOutput (wallet context) (Value.lovelace 1500000) Datum.NoDatum Nothing)+ let callback input minimumAmount draft _ = do+ own <- maybe (Left (InvalidBuildingRequest "Order input disappeared")) Right (Indices.findInput (Utxo.input input) draft)+ payout <- maybe (Left (InvalidBuildingRequest "Order payout disappeared")) Right (Indices.findOutput (wallet context) minimumAmount draft)+ pure (Data.fromData (Data.Constr 0 [Data.Integer (toInteger own), Data.Integer (toInteger payout)]))+ plan =+ Plan.payTo firstPayout+ <> Plan.payTo secondPayout+ <> Plan.spendWithDeferredRedeemer first (callback first 1200000) Nothing+ <> Plan.spendWithDeferredRedeemer second (callback second 1500000) Nothing+ <> Plan.attachScript script+ settled <- ExceptT (runStage context plan)+ pure [funded, fundedAgain, settled]++runRewardCycle :: Context -> Credential Stake -> Maybe Script -> KeyHash StakePool -> Word64 -> IO (Either Error [Tx.Transaction])+runRewardCycle context credential script pool deposit = runExceptT $ do+ let account = Reward.fromCredential (network context) credential+ cert = authorize script+ voting = case script of+ Nothing -> cert (Certificate.VoteDelegation credential DRep.AlwaysAbstain)+ Just _ -> mempty+ register =+ cert (Certificate.Registration credential deposit)+ <> cert (Certificate.StakeDelegation credential pool)+ <> voting+ registered <- ExceptT (runStage context register)+ rewards <- ExceptT (Provider.rewardBalance (provider context) account)+ let withdrawal = case script of+ Nothing -> Plan.withdraw account rewards+ Just value -> Plan.attachScript value <> Plan.withdrawWithRedeemer account rewards voidArgument+ cleaned <- ExceptT (runStage context (withdrawal <> cert (Certificate.Unregistration credential deposit)))+ pure [registered, cleaned]++runWithdrawZero :: Context -> Credential Stake -> Script -> KeyHash StakePool -> Word64 -> IO (Either Error [Tx.Transaction])+runWithdrawZero context credential script pool deposit = runExceptT $ do+ let account = Reward.fromCredential (network context) credential+ cert = authorize (Just script)+ registered <- ExceptT (runStage context (cert (Certificate.Registration credential deposit) <> cert (Certificate.StakeDelegation credential pool)))+ let callback draft inputs = do+ positions <- traverse (\input -> maybe (Left (InvalidBuildingRequest "Forwarded input disappeared")) Right (Indices.findInput (Utxo.input input) draft)) inputs+ pure (Data.fromData (Data.Constr 0 [Data.List (map (Data.Integer . toInteger) (sort positions))]))+ plan = Plan.attachScript script <> Plan.withdrawWithDeferredRedeemer account 0 callback <> cert (Certificate.Unregistration credential deposit)+ cleaned <- ExceptT (runStage context plan)+ pure [registered, cleaned]++authorize :: Maybe Script -> Certificate.Certificate -> Plan+authorize Nothing = Plan.certificate+authorize (Just script) = \certificate -> Plan.attachScript script <> Plan.certificateWithRedeemer certificate voidArgument++runDRepCycle :: Context -> Credential DRep -> Maybe Script -> Word64 -> Credential Stake -> Word64 -> Anchor -> IO (Either Error [Tx.Transaction])+runDRepCycle context credential script deposit stake stakeDeposit anchor = runExceptT $ do+ registered <- ExceptT (runStage context (authorize script (Certificate.RegisterDRep credential deposit (Just anchor))))+ delegated <- ExceptT (runStage context (Plan.certificate (Certificate.Registration stake stakeDeposit) <> Plan.certificate (Certificate.VoteDelegation stake (DRep.DRepCredential credential))))+ let account = Reward.fromCredential (network context) stake+ rewards <- ExceptT (Provider.rewardBalance (provider context) account)+ cleanedStake <- ExceptT (runStage context (Plan.withdraw account rewards <> Plan.certificate (Certificate.Unregistration stake stakeDeposit)))+ cleanedDRep <- ExceptT (runStage context (authorize script (Certificate.UnregisterDRep credential deposit)))+ pure [registered, delegated, cleanedStake, cleanedDRep]++runVoteCycle :: Context -> Credential DRep -> Maybe Script -> Word64 -> Anchor -> ActionId -> IO (Either Error [Tx.Transaction])+runVoteCycle context credential script deposit anchor action = runExceptT $ do+ registered <- ExceptT (runStage context (authorize script (Certificate.RegisterDRep credential deposit (Just anchor))))+ let voter = Voting.DRepVoter credential+ procedure = Voting.VotingProcedure Voting.Yes Nothing+ vote = case script of+ Nothing -> Plan.vote voter action procedure+ Just value -> Plan.attachScript value <> Plan.voteWithRedeemer voter [(action, procedure)] voidArgument+ voted <- ExceptT (runStage context vote)+ cleaned <- ExceptT (runStage context (authorize script (Certificate.UnregisterDRep credential deposit)))+ pure [registered, voted, cleaned]++runDonation :: Context -> Word64 -> IO (Either Error Tx.Transaction)+runDonation context amount = runStage context (Plan.donate amount)++runTreasuryWithdrawal :: Context -> Reward.RewardAddress -> Word64 -> Script -> Anchor -> IO (Either Error Tx.Transaction)+runTreasuryWithdrawal context account amount policy anchor = runExceptT $ do+ digest <- ExceptT (Script.hash policy)+ withdrawals <- except (Action.withdrawalsFromList [(account, amount)])+ ExceptT (runStage context (Plan.attachScript policy <> Plan.propose account (Action.TreasuryWithdrawals withdrawals (Just digest)) anchor))++runSignedBatch :: Context -> [(SubTransaction, [Utxo])] -> Plan -> IO (Either Error Tx.Transaction)+runSignedBatch context intents parent = runStage context (foldMap (uncurry Plan.attachSubTransaction) intents <> parent)++runGuardedSub :: Context -> Script -> Script -> (SubTransaction -> IO (Either Error SubTransaction)) -> IO (Either Error [Tx.Transaction])+runGuardedSub context validator guard signLocal = runExceptT $ do+ (locked, reference, funded) <- ExceptT (fundScript context validator 10000000)+ params <- ExceptT (Provider.protocolParameters (provider context))+ digest <- ExceptT (Script.hash guard)+ output <- except (Output.mkOutput (wallet context) (Value.lovelace 2000000) Datum.NoDatum Nothing)+ let source = maybe (SubPlan.attachScript validator) SubPlan.referenceInput reference+ plan =+ SubPlan.spendWith locked (Just voidArgument) Nothing+ <> SubPlan.payTo output+ <> source+ <> SubPlan.attachScript guard+ <> SubPlan.guardWithRedeemer digest voidArgument+ bodyNetwork = if network context == Network.mainnet then Fields.Mainnet else Fields.Testnet+ local <- ExceptT (SubBuilder.build (SubBuilder.Config params (slots context) bodyNetwork) plan)+ signed <- ExceptT (signLocal local)+ batch <- ExceptT (runSignedBatch context [(signed, SubPlan.resolvedInputs plan)] mempty)+ pure [funded, batch]
@@ -0,0 +1,176 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Deterministic provider state for executing example stages without HTTP.+-- This checks signed bytes and conservation; it does not emulate ledger rules.+module Fixtures.Workflow (Fixture (..), withFixture, verifyTransaction) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.PublicKey as Public+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error (..))+import qualified Cometa.NetworkId as Network+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Provider as Provider+import qualified Cometa.Signer as Signer+import qualified Cometa.SlotConfig as Slots+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (unless, when)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.ByteString as B+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe)+import qualified Fixtures.ProtocolParameters as Raw+import qualified Support.Transaction as Workflow++-- TYPES ----------------------------------------------------------------------++data Fixture = Fixture+ { submitted :: IO [Tx.Transaction],+ currentUtxos :: IO [Utxo.Utxo],+ stakeCredential :: Credential.Credential Credential.Stake,+ drepCredential :: Credential.Credential Credential.DRep,+ paymentHash :: Credential.KeyHash Credential.Payment,+ signIntent :: Sub.SubTransaction -> IO (Either Error Sub.SubTransaction)+ }++-- DEFINITIONS ----------------------------------------------------------------++withFixture :: (Workflow.Context -> Fixture -> IO (Either Error a)) -> IO (Either Error a)+withFixture action = Key.withNormalKey (B.replicate 32 7) $ \key -> do+ prepared <- runExceptT $ do+ raw <- except Raw.parameters+ zero <- except (Rational.mkNonNegativeRational 0 1)+ models <- except (traverse (\(language, count) -> Models.mkCostModel language (replicate count 100)) [(0, 166), (1, 175), (2, 251), (3, 369)])+ public <- ExceptT (Key.publicKey key)+ payment <- ExceptT (Credential.fromPublicKey public)+ stake <- ExceptT (Credential.fromPublicKey public)+ drep <- ExceptT (Credential.fromPublicKey public)+ hash <- case payment of+ Credential.KeyCredential value -> pure value+ Credential.ScriptCredential _ -> except (Left (InvalidBuildingRequest "Expected public-key credential"))+ previous <- except (Id.fromBytes (B.replicate 32 8))+ collateralId <- except (Id.fromBytes (B.replicate 32 9))+ let address = Address.ShelleyAddress (Shelley.base Network.testnet payment stake)+ params =+ raw+ { Parameters.parameterMinFeeA = 0,+ Parameters.parameterMinFeeB = 0,+ Parameters.parameterMaxTxSize = 65536,+ Parameters.parameterMaxValueSize = Just 5000,+ Parameters.parameterAdaPerUtxoByte = Just 4310,+ Parameters.parameterProtocolVersion = Version.ProtocolVersion 12 0,+ Parameters.parameterCostModels = Just (Models.fromList models),+ Parameters.parameterExecutionCosts = Just (Prices.ExUnitPrices zero zero),+ Parameters.parameterRefScriptCostPerByte = Just zero,+ Parameters.parameterMaxTxExUnits = Just (ExUnits 100000000 100000000000),+ Parameters.parameterCollateralPercentage = Just 150,+ Parameters.parameterMaxCollateralInputs = Just 3,+ Parameters.parameterKeyDeposit = 2000000,+ Parameters.parameterDrepDeposit = Just 2000000,+ Parameters.parameterGovernanceActionDeposit = Just 1000000+ }+ funding <- except (Output.mkOutput address (Value.lovelace 2000000000) Datum.NoDatum Nothing)+ collateral <- except (Output.mkOutput address (Value.lovelace 50000000) Datum.NoDatum Nothing)+ pure (params, address, stake, drep, hash, Utxo.utxo (Input.input previous 0) funding, Utxo.utxo (Input.input collateralId 0) collateral)+ case prepared of+ Left failure -> pure (Left failure)+ Right (params, address, stake, drep, hash, funding, reserved) -> do+ utxos <- newIORef [funding, reserved]+ history <- newIORef []+ let backend =+ (Provider.unavailable "Native example fixture" 42)+ { Provider.protocolParameters = pure (Right params),+ Provider.utxosAt = \target -> Right . filter ((== target) . Output.address . Utxo.output) <$> readIORef utxos,+ Provider.rewardBalance = \_ -> pure (Right 0),+ Provider.resolveInputs = \references -> Right . filter (\value -> Utxo.input value `elem` references) <$> readIORef utxos,+ Provider.submitTransaction = apply params utxos history,+ Provider.awaitTransaction = \identifier _ -> do+ values <- readIORef history+ identifiers <- traverse Tx.transactionId values+ pure (elem identifier <$> sequence identifiers)+ }+ context = Workflow.Context backend address (Signer.ed25519 key) Network.testnet Slots.preview 1000000 [Utxo.input reserved] 1 1000+ fixture = Fixture (readIORef history) (readIORef utxos) stake drep hash (Signing.signSubTransaction key)+ action context fixture++apply :: Parameters.Parameters -> IORef [Utxo.Utxo] -> IORef [Tx.Transaction] -> Tx.Transaction -> IO (Either Error Id.TransactionId)+apply params utxos history transaction = runExceptT $ do+ before <- ExceptT (Right <$> readIORef utxos)+ ExceptT (verifyTransaction transaction)+ balanced <- ExceptT (Building.isBalanced params before transaction)+ except (unless balanced (Left (InvalidBuildingRequest "Example transaction does not conserve value")))+ identifier <- ExceptT (Tx.transactionId transaction)+ nested <- traverse (ExceptT . subOutputs) (fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction))))+ let body = Body.toBody (Tx.body transaction)+ spent = Fields.fieldInputs (Body.bodyFields body) <> maybe [] (concatMap (Fields.fieldInputs . SubBody.fields . SubBody.toBody . Sub.body)) (Body.bodySubTransactions body)+ created = [Utxo.utxo (Input.input identifier index) output | (index, output) <- zip [0 ..] (Fields.fieldOutputs (Body.bodyFields body))] <> concat nested+ after = filter (\value -> Utxo.input value `notElem` spent) before <> created+ ExceptT (writeIORef utxos after >> modifyIORef' history (<> [transaction]) >> pure (Right ()))+ pure identifier++subOutputs :: Sub.SubTransaction -> IO (Either Error [Utxo.Utxo])+subOutputs transaction = do+ identifier <- Sub.transactionId transaction+ pure $ do+ digest <- identifier+ pure [Utxo.utxo (Input.input digest index) output | (index, output) <- zip [0 ..] (Fields.fieldOutputs (SubBody.fields (SubBody.toBody (Sub.body transaction))))]++-- | Verify every outer and nested verification witness against its own exact+-- body hash before fixture submission can mutate UTxOs or accepted-ID history.+verifyTransaction :: Tx.Transaction -> IO (Either Error ())+verifyTransaction transaction = runExceptT $ do+ outer <- ExceptT (Tx.transactionId transaction)+ ExceptT (verifyWitnesses (Id.toBytes outer) (Tx.witnesses transaction))+ let nested = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ mapM_ verifySub nested+ where+ verifySub intent = do+ identifier <- ExceptT (Sub.transactionId intent)+ ExceptT (verifyWitnesses (Id.toBytes identifier) (Sub.witnesses intent))++verifyWitnesses :: B.ByteString -> Witnesses.EncodedWitnesses -> IO (Either Error ())+verifyWitnesses message encoded = runExceptT $ do+ let values = Witnesses.verificationWitnesses (Witnesses.toWitnesses encoded)+ except (when (null values) (Left (InvalidBuildingRequest "Fixture expected signed transaction")))+ mapM_ verify values+ where+ verify witness = do+ valid <- ExceptT (Public.verify (Witness.publicKey witness) message (Witness.signature witness))+ except (unless valid (Left (InvalidBuildingRequest "Fixture verification witness does not verify against its transaction body")))
@@ -0,0 +1,376 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Governance bounds, collection laws, pinned vectors and native reconstruction.+module Governance (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.Binary.Bech32 as Bech32+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.TransactionId as TransactionId+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Either (isLeft)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word64, Word8)+import qualified Fixtures.Governance as Fixtures+import Foreign.C.Types (CChar, CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Governance"+ [ testCase "DRep text imports CIP-105 and exports checked CIP-129 credentials" checkDRepText,+ testCase "CIP-129 action text checks one-byte indices and native correspondence" checkActionText,+ testCase "public values reconstruct pinned anchors, actions, DReps and choices" checkPinnedScalars,+ testCase "all voter authorities and native ordering agree" checkVoters,+ testCase "public nested collection reconstructs pinned native voting corpus" checkPinnedVoting,+ testCase "URL and identity validation enforce byte bounds" checkValidation,+ testCase "schema decoders reject malformed and trailing input" checkInvalid,+ testCase "external map order and nonminimal encoding remain exact" checkExact,+ testCase "duplicates and empty voter maps never silently normalize" checkCollections,+ testCase "native repeated reconstruction releases retained getter outputs" checkRepeated,+ testProperty "typed values round trip and agree with native reconstruction" propRoundTrip,+ testProperty "disjoint vote merge is associative, commutative and has empty identity" propMerge+ ]++sampleAnchor :: IO Anchor.Anchor+sampleAnchor = do+ location <- expectRight (Anchor.mkUrl "https://www.someurl.io")+ digest <- expectRight (Anchor.dataHashFromBytes (ByteString.replicate 32 0))+ pure (Anchor.Anchor location digest)++actionWith :: Word8 -> Word64 -> IO ActionId.ActionId+actionWith prefix actionIndex = do+ transaction <- expectRight (TransactionId.fromBytes (ByteString.cons prefix (ByteString.replicate 31 0)))+ pure (ActionId.ActionId transaction actionIndex)++votersWith :: Word8 -> IO [Voting.Voter]+votersWith prefix = do+ let hashBytes = ByteString.cons prefix (ByteString.replicate 27 0)+ hotKey <- expectRight (Credential.keyHashFromBytes hashBytes)+ drepKey <- expectRight (Credential.keyHashFromBytes hashBytes)+ poolKey <- expectRight (Credential.keyHashFromBytes hashBytes)+ script <- expectRight (Credential.scriptHashFromBytes hashBytes)+ pure+ [ Voting.CommitteeVoter (Credential.KeyCredential hotKey),+ Voting.CommitteeVoter (Credential.ScriptCredential script),+ Voting.DRepVoter (Credential.KeyCredential drepKey),+ Voting.DRepVoter (Credential.ScriptCredential script),+ Voting.StakePoolVoter poolKey+ ]++checkPinnedScalars :: IO ()+checkPinnedScalars = do+ explanation <- sampleAnchor+ anchorBytes <- bytes Fixtures.anchorVector+ Anchor.encodeCbor explanation @?= anchorBytes+ Anchor.decodeCbor anchorBytes @?= Right explanation+ nativeAgreement 0 anchorBytes+ action <- actionWith 0 3+ actionBytes <- bytes Fixtures.actionVector+ ActionId.encodeCbor action @?= actionBytes+ ActionId.decodeCbor actionBytes @?= Right action+ nativeAgreement 1 actionBytes+ key <- expectRight (Credential.keyHashFromBytes (ByteString.replicate 28 0))+ script <- expectRight (Credential.scriptHashFromBytes (ByteString.replicate 28 0))+ let targets = [DRep.DRepCredential (Credential.KeyCredential key), DRep.DRepCredential (Credential.ScriptCredential script), DRep.AlwaysAbstain, DRep.AlwaysNoConfidence]+ forM_ (zip targets Fixtures.drepVectors) $ \(target, golden) -> do+ expected <- bytes golden+ DRep.encodeCbor target @?= expected+ DRep.decodeCbor expected @?= Right target+ nativeAgreement 2 expected+ let procedures = [Voting.VotingProcedure choice maybeAnchor | maybeAnchor <- [Nothing, Just explanation], choice <- [Voting.No, Voting.Yes, Voting.Abstain]]+ forM_ (zip procedures Fixtures.procedureVectors) $ \(procedure, golden) -> do+ expected <- bytes golden+ Voting.encodeProcedure procedure @?= expected+ Voting.decodeProcedure expected @?= Right procedure+ nativeAgreement 4 expected++checkVoters :: IO ()+checkVoters = do+ voters <- votersWith 0+ forM_ (zip [0 ..] voters) $ \(code, voter) -> do+ let expected = ByteString.pack [0x82, code, 0x58, 0x1c] <> ByteString.replicate 28 0+ Voting.encodeVoter voter @?= expected+ Voting.decodeVoter expected @?= Right voter+ nativeAgreement 3 expected+ action <- actionWith 255 maxBound+ votes <- expectRight (Voting.fromList [(voter, action, Voting.VotingProcedure Voting.Abstain Nothing) | voter <- reverse voters])+ map (\(voter, _, _) -> voter) (Voting.toList votes) @?= voters+ nativeAgreement 5 (Voting.encodeCbor votes)++pinnedVoting :: IO Voting.VotingProcedures+pinnedVoting = do+ key <- expectRight (Credential.keyHashFromBytes (ByteString.cons 0x10 (ByteString.replicate 27 0)))+ script <- expectRight (Credential.scriptHashFromBytes (ByteString.cons 0x20 (ByteString.replicate 27 0)))+ actions <- mapM (`actionWith` 3) [0x10, 0x20, 0x30]+ explanation <- sampleAnchor+ let procedure = Voting.VotingProcedure Voting.No (Just explanation)+ keyed = [(Voting.DRepVoter (Credential.KeyCredential key), action, procedure) | action <- actions]+ scripted = [(Voting.DRepVoter (Credential.ScriptCredential script), action, procedure) | (position, action) <- zip [0 :: Int ..] actions, position /= 1]+ expectRight (Voting.fromList (reverse (keyed <> scripted)))++checkPinnedVoting :: IO ()+checkPinnedVoting = do+ value <- pinnedVoting+ expected <- bytes Fixtures.votingVector+ Voting.encodeCbor value @?= expected+ encoded <- expectRight (Voting.decodeCbor expected)+ Voting.toVotingProcedures encoded @?= value+ Voting.toCbor encoded @?= expected+ nativeAgreement 5 expected++checkValidation :: IO ()+checkValidation = do+ Anchor.mkUrl "" @?= Left (InvalidAnchorUrlLength 0)+ Anchor.mkUrl (Text.replicate 129 "a") @?= Left (InvalidAnchorUrlLength 129)+ Anchor.mkUrl "a\0b" @?= Left InvalidAnchorUrl+ valid <- expectRight (Anchor.mkUrl (Text.replicate 64 "é"))+ ByteString.length (Text.encodeUtf8 (Anchor.urlText valid)) @?= 128+ assertBool "UTF8 byte bound" (isLeft (Anchor.mkUrl (Text.replicate 65 "é")))+ forM_ [0, 31, 33] $ \size -> do+ Anchor.dataHashFromBytes (ByteString.replicate size 0) @?= Left (InvalidAnchorDataHashLength size)+ TransactionId.fromBytes (ByteString.replicate size 0) @?= Left (InvalidTransactionIdLength size)+ transaction <- expectRight (TransactionId.fromHex (Text.replicate 64 "A"))+ TransactionId.toHex transaction @?= Text.replicate 64 "a"+ TransactionId.fromHex "zz" @?= Left InvalidHex+ emptyHash <- Anchor.hashData ByteString.empty+ assertBool "empty payload retains native hash failure" (case emptyHash of Left NativeError {} -> True; _ -> False)+ digest <- Anchor.hashData "Hello, World!" >>= expectRight+ expectedDigest <- bytes "511bc81dde11180838c562c82bb35f3223f46061ebde4a955c27b3f489cf1e03"+ Anchor.dataHashBytes digest @?= expectedDigest+ forM_ [0, 255, 256, 65535, 65536, maxBound] $ \actionIndex -> do+ action <- actionWith 7 actionIndex+ ActionId.decodeCbor (ActionId.encodeCbor action) @?= Right action+ nativeAgreement 1 (ActionId.encodeCbor action)++checkInvalid :: IO ()+checkInvalid = do+ forM_ ["", "80", "8100", "820440", "820140", "83004000", "810200", "9f0200ff", "8200581b" <> replicate 54 '0'] $ \hex -> do+ input <- bytes hex+ assertBool "invalid DRep rejected" (isLeft (DRep.decodeCbor input))+ forM_ ["820540", "820440", "8100", "83004000", "8200581d" <> replicate 58 '0'] $ \hex -> do+ input <- bytes hex+ assertBool "invalid voter rejected" (isLeft (Voting.decodeVoter input))+ forM_ ["8203f6", "8100", "8300f600", "8200f4", "8200f600"] $ \hex -> do+ input <- bytes hex+ assertBool "invalid choice/anchor rejected" (isLeft (Voting.decodeProcedure input))+ forM_ ["a0f6", "80", "a100a0", "bf00a0ff"] $ \hex -> do+ input <- bytes hex+ assertBool "invalid collection rejected" (isLeft (Voting.decodeCbor input))+ action <- actionWith 0 0+ let actionBytes = ActionId.encodeCbor action+ assertBool "negative index" (isLeft (ActionId.decodeCbor (ByteString.init actionBytes <> ByteString.singleton 0x20)))+ assertBool "trailing action bytes" (isLeft (ActionId.decodeCbor (actionBytes <> ByteString.singleton 0)))+ forM_ ["82605820" <> replicate 64 '0', "82636100625820" <> replicate 64 '0', "8261ff5820" <> replicate 64 '0'] $ \hex -> do+ input <- bytes hex+ assertBool "invalid URL anchor rejected" (isLeft (Anchor.decodeCbor input))++checkExact :: IO ()+checkExact = do+ voters <- votersWith 0+ action <- actionWith 0 0+ let procedure = Voting.VotingProcedure Voting.Yes Nothing+ entries = [(voter, action, procedure) | voter <- reverse voters]+ pair (voter, proposal, _) = Voting.encodeVoter voter <> ByteString.singleton 0xbf <> ActionId.encodeCbor proposal <> ByteString.pack [0x9f, 0x18, 1, 0xf6, 0xff, 0xff]+ original = ByteString.pack [0xb8, 5] <> foldMap pair entries+ decoded <- expectRight (Voting.decodeCbor original)+ semantic <- expectRight (Voting.fromList entries)+ Voting.toVotingProcedures decoded @?= semantic+ Voting.toCbor decoded @?= original+ assertBool "fresh serialization is different" (Voting.encodeCbor semantic /= original)+ assertBool "encoding identity is representation-sensitive" (decoded /= Voting.fromVotingProcedures semantic)+ let indefinite = ByteString.singleton 0xbf <> foldMap pair entries <> ByteString.singleton 0xff+ decodedIndefinite <- expectRight (Voting.decodeCbor indefinite)+ Voting.toVotingProcedures decodedIndefinite @?= semantic+ Voting.toCbor decodedIndefinite @?= indefinite++checkCollections :: IO ()+checkCollections = do+ voters <- votersWith 0+ action <- actionWith 0 0+ forM_ voters $ \voter -> do+ let procedure = Voting.VotingProcedure Voting.Yes Nothing+ triple = (voter, action, procedure)+ one = Voting.singleton voter action procedure+ voterBytes = Voting.encodeVoter voter+ entry = ActionId.encodeCbor action <> Voting.encodeProcedure procedure+ inner = ByteString.singleton 0xa1 <> entry+ Voting.fromList [triple, triple] @?= Left DuplicateGovernanceVote+ Voting.insert voter action (Voting.VotingProcedure Voting.No Nothing) one @?= Left DuplicateGovernanceVote+ Voting.merge one one @?= Left DuplicateGovernanceVote+ Voting.lookup voter action one @?= Just procedure+ Voting.lookup voter action Voting.empty @?= Nothing+ forM_ [ByteString.singleton 0xa1 <> voterBytes <> ByteString.singleton 0xa0, ByteString.singleton 0xa1 <> voterBytes <> ByteString.singleton 0xa2 <> entry <> entry, ByteString.singleton 0xa2 <> voterBytes <> inner <> voterBytes <> inner] $ \encoded ->+ assertBool "nonrepresentable maps rejected" (isLeft (Voting.decodeCbor encoded))+ Voting.encodeCbor Voting.empty @?= ByteString.singleton 0xa0+ Voting.toVotingProcedures <$> Voting.decodeCbor (ByteString.singleton 0xa0) @?= Right Voting.empty++checkRepeated :: IO ()+checkRepeated = do+ value <- pinnedVoting+ let encoded = Voting.encodeCbor value+ replicateM_ 64 (nativeAgreement 5 encoded)+ Voting.encodeCbor value @?= encoded++propRoundTrip :: Property+propRoundTrip = property $ do+ hashBytes <- forAll (Gen.bytes (Range.singleton 28))+ transactionBytes <- forAll (Gen.bytes (Range.singleton 32))+ actionIndex <- forAll (Gen.word64 Range.constantBounded)+ choice <- forAll (Gen.element [Voting.No, Voting.Yes, Voting.Abstain])+ withAnchor <- forAll Gen.bool+ locationText <- forAll (Gen.text (Range.linear 1 128) (Gen.element ['a', 'b', ':', '/']))+ location <- evalEither (Anchor.mkUrl locationText)+ digest <- evalEither (Anchor.dataHashFromBytes transactionBytes)+ transaction <- evalEither (TransactionId.fromBytes transactionBytes)+ hot <- evalEither (Credential.keyHashFromBytes hashBytes)+ drep <- evalEither (Credential.keyHashFromBytes hashBytes)+ pool <- evalEither (Credential.keyHashFromBytes hashBytes)+ script <- evalEither (Credential.scriptHashFromBytes hashBytes)+ let action = ActionId.ActionId transaction actionIndex+ explanation = Anchor.Anchor location digest+ procedure = Voting.VotingProcedure choice (if withAnchor then Just explanation else Nothing)+ voters = [Voting.CommitteeVoter (Credential.KeyCredential hot), Voting.CommitteeVoter (Credential.ScriptCredential script), Voting.DRepVoter (Credential.KeyCredential drep), Voting.DRepVoter (Credential.ScriptCredential script), Voting.StakePoolVoter pool]+ value <- evalEither (Voting.fromList [(voter, action, procedure) | voter <- reverse voters])+ decoded <- evalEither (Voting.decodeCbor (Voting.encodeCbor value))+ Voting.toVotingProcedures decoded === value+ Anchor.decodeCbor (Anchor.encodeCbor explanation) === Right explanation+ ActionId.decodeCbor (ActionId.encodeCbor action) === Right action+ Voting.decodeProcedure (Voting.encodeProcedure procedure) === Right procedure+ forM_ voters $ \voter -> do+ Voting.decodeVoter (Voting.encodeVoter voter) === Right voter+ evalIO (nativeAgreement 3 (Voting.encodeVoter voter))+ forM_ [DRep.DRepCredential (Credential.KeyCredential drep), DRep.DRepCredential (Credential.ScriptCredential script), DRep.AlwaysAbstain, DRep.AlwaysNoConfidence] $ \target -> do+ DRep.decodeCbor (DRep.encodeCbor target) === Right target+ evalIO (nativeAgreement 2 (DRep.encodeCbor target))+ evalIO (nativeAgreement 0 (Anchor.encodeCbor explanation))+ evalIO (nativeAgreement 1 (ActionId.encodeCbor action))+ evalIO (nativeAgreement 4 (Voting.encodeProcedure procedure))+ evalIO (nativeAgreement 5 (Voting.encodeCbor value))++propMerge :: Property+propMerge = property $ do+ hashBytes <- forAll (Gen.bytes (Range.singleton 28))+ transactionBytes <- forAll (Gen.bytes (Range.singleton 32))+ actionIndex <- forAll (Gen.word64 Range.constantBounded)+ key <- evalEither (Credential.keyHashFromBytes hashBytes)+ transaction <- evalEither (TransactionId.fromBytes transactionBytes)+ let voter = Voting.DRepVoter (Credential.KeyCredential key)+ action = ActionId.ActionId transaction actionIndex+ left = Voting.singleton voter action (Voting.VotingProcedure Voting.Yes Nothing)+ middle = Voting.singleton voter (ActionId.ActionId transaction (actionIndex + 1)) (Voting.VotingProcedure Voting.No Nothing)+ right = Voting.singleton voter (ActionId.ActionId transaction (actionIndex + 2)) (Voting.VotingProcedure Voting.Abstain Nothing)+ Voting.merge left Voting.empty === Right left+ Voting.merge Voting.empty left === Right left+ Voting.merge left middle === Voting.merge middle left+ (Voting.merge left middle >>= (`Voting.merge` right)) === (Voting.merge middle right >>= Voting.merge left)++nativeAgreement :: CUInt -> ByteString -> IO ()+nativeAgreement mode encoded = ByteString.useAsCStringLen encoded $ \(input, size) -> do+ agrees <- cAgreement mode (castPtr input) (fromIntegral size)+ agrees @?= 1++bytes :: String -> IO ByteString+bytes encoded = case Hex.decodeHex (Text.pack encoded) of+ Nothing -> assertFailure "invalid fixture hexadecimal" >> fail "unreachable assertion"+ Just value -> pure value++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Left failure -> assertFailure (show failure) >> fail "unreachable assertion"+ Right value -> pure value++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_governance_agreement"+ cAgreement :: CUInt -> Ptr Word8 -> CSize -> IO CInt++checkActionText :: IO ()+checkActionText = do+ forM_ [0, 1, 255] $ \actionIndex -> do+ action <- actionWith 7 actionIndex+ encoded <- expectRight (ActionId.toText action)+ ActionId.fromText encoded @?= Right action+ ActionId.fromText (Text.toUpper encoded) @?= Right action+ ByteString.useAsCString (TransactionId.toBytes (ActionId.transactionId action)) $ \hash ->+ ByteString.useAsCStringLen (Text.encodeUtf8 encoded) $ \(textPtr, size) -> do+ agrees <- cActionText (castPtr hash) (fromIntegral actionIndex) textPtr (fromIntegral size)+ agrees @?= 1+ forM_ [256, 65535, maxBound] $ \actionIndex -> do+ action <- actionWith 0 actionIndex+ ActionId.toText action @?= Left (InvalidGovernanceActionTextIndex actionIndex)+ ActionId.decodeCbor (ActionId.encodeCbor action) @?= Right action+ prefix <- expectRight (Bech32.humanReadablePartFromText "gov_action")+ wrongPrefix <- expectRight (Bech32.humanReadablePartFromText "stake")+ let invalidPayload size = Bech32.encodeLenient prefix (Bech32.dataPartFromBytes (ByteString.replicate size 0))+ forM_ ["", "gov_action1invalid", invalidPayload 32, invalidPayload 34, Bech32.encodeLenient wrongPrefix (Bech32.dataPartFromBytes (ByteString.replicate 33 0))] $ \encoded ->+ assertBool "reject malformed action identity" (isLeft (ActionId.fromText encoded))+ action <- actionWith 0 0+ encoded <- expectRight (ActionId.toText action)+ assertBool "checksum alteration" (isLeft (ActionId.fromText (Text.init encoded <> if Text.last encoded == 'q' then "p" else "q")))+ assertBool "mixed case" (isLeft (ActionId.fromText ("G" <> Text.drop 1 encoded)))++foreign import ccall safe "cometa_test_action_text"+ cActionText :: Ptr Word8 -> Word8 -> Ptr CChar -> CSize -> IO CInt++checkDRepText :: IO ()+checkDRepText = do+ let hash = ByteString.replicate 28 0xab+ key <- Credential.KeyCredential <$> expectRight (Credential.keyHashFromBytes hash)+ script <- Credential.ScriptCredential <$> expectRight (Credential.scriptHashFromBytes hash)+ forM_ [(False, key, "drep"), (True, script, "drep_script")] $ \(isScript, credential, legacyPrefix) -> do+ let drep = DRep.DRepCredential credential+ canonical <- expectRight (DRep.toText drep)+ DRep.fromText canonical @?= Right drep+ DRep.fromText (Text.toUpper canonical) @?= Right drep+ prefix <- expectRight (Bech32.humanReadablePartFromText legacyPrefix)+ let legacy = Bech32.encodeLenient prefix (Bech32.dataPartFromBytes hash)+ DRep.fromText legacy @?= Right drep+ forM_ [(True, canonical), (False, legacy)] $ \(isCanonical, encoded) ->+ ByteString.useAsCString hash $ \hashPtr ->+ ByteString.useAsCStringLen (Text.encodeUtf8 encoded) $ \(textPtr, size) -> do+ agrees <- cDRepText (castPtr hashPtr) (if isScript then 1 else 0) textPtr (fromIntegral size) (if isCanonical then 1 else 0)+ agrees @?= 1+ forM_ [DRep.AlwaysAbstain, DRep.AlwaysNoConfidence] $ \drep -> assertBool "special targets have no credential identifier" (isLeft (DRep.toText drep))+ prefix <- expectRight (Bech32.humanReadablePartFromText "drep")+ lookalike <- expectRight (Bech32.humanReadablePartFromText "drep_extra")+ let encoded payload = Bech32.encodeLenient prefix (Bech32.dataPartFromBytes payload)+ forM_ ["", "drep1bad", encoded (ByteString.replicate 27 0), encoded (ByteString.replicate 30 0), encoded (ByteString.cons 0x12 hash), encoded (ByteString.cons 0x24 hash), Bech32.encodeLenient lookalike (Bech32.dataPartFromBytes hash)] $ \text ->+ assertBool "invalid DRep prefix/header/checksum/length" (isLeft (DRep.fromText text))++foreign import ccall safe "cometa_test_drep_text"+ cDRepText :: Ptr Word8 -> CInt -> Ptr CChar -> CSize -> CInt -> IO CInt
@@ -0,0 +1,134 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module HexEncoding (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Credential as Credential+import qualified Cometa.Encoding.Hex as Hex+import Cometa.Error (Error (InvalidHex))+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified Data.Text as Text+import Hedgehog (Property, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Raw hexadecimal encoding"+ [ testCase "all byte values have independent lowercase encodings" vectors,+ testCase "empty and mixed-case raw inputs are accepted" accepted,+ testCase "malformed syntax fails without partial bytes" rejected,+ testCase "raw bytes compose with existing domain validators" typedWorkflows,+ testProperty "arbitrary byte snapshots round trip in either case" roundTrip+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++vectors :: IO ()+vectors = do+ let bytes = B.pack [0 .. 255]+ hexadecimal =+ "000102030405060708090a0b0c0d0e0f"+ <> "101112131415161718191a1b1c1d1e1f"+ <> "202122232425262728292a2b2c2d2e2f"+ <> "303132333435363738393a3b3c3d3e3f"+ <> "404142434445464748494a4b4c4d4e4f"+ <> "505152535455565758595a5b5c5d5e5f"+ <> "606162636465666768696a6b6c6d6e6f"+ <> "707172737475767778797a7b7c7d7e7f"+ <> "808182838485868788898a8b8c8d8e8f"+ <> "909192939495969798999a9b9c9d9e9f"+ <> "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"+ <> "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"+ <> "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"+ <> "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"+ <> "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"+ <> "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"+ Hex.encode bytes @?= hexadecimal+ Hex.decode hexadecimal @?= Right bytes+ Hex.decode (Text.toUpper hexadecimal) @?= Right bytes++accepted :: IO ()+accepted = do+ Hex.encode B.empty @?= ""+ Hex.decode "" @?= Right B.empty+ Hex.decode "aBcDeF" @?= Right (B.pack [0xab, 0xcd, 0xef])+ Hex.encode (B.pack [0, 0, 128, 255]) @?= "000080ff"+ Hex.decode "000080ff" @?= Right (B.pack [0, 0, 128, 255])++rejected :: IO ()+rejected =+ mapM_+ (\text -> Hex.decode text @?= Left InvalidHex)+ [ "0",+ "000",+ "0x00",+ "0X00",+ "00 ",+ " 00",+ "00\n",+ "00\t",+ "0g",+ "gg",+ "+0",+ "-0",+ "00",+ "٠0",+ "é0",+ "00\NUL00",+ "0000gg",+ "\r\n"+ ]++typedWorkflows :: IO ()+typedWorkflows = do+ -- The public module's example uses the script's existing byte validator.+ script <- must (Hex.decode "0102" >>= Plutus.fromBytes Plutus.V3)+ Plutus.toBytes script @?= B.pack [1, 2]+ assertBool "Empty raw bytes bypassed Plutus validation" (isLeft (Hex.decode "" >>= Plutus.fromBytes Plutus.V3))+ condition <- must (Hex.decode "820401" >>= Native.decodeCbor)+ Native.encodeCbor condition @?= B.pack [0x82, 4, 1]+ credential <- must (Hex.decode (Text.replicate 28 "aB") >>= Credential.scriptHashFromBytes)+ Credential.scriptHashBytes credential @?= B.replicate 28 0xab+ assertBool "Short raw hash bypassed credential validation" (isLeft (Hex.decode "00" >>= Credential.scriptHashFromBytes))+ metadatum <- must (Hex.decode "00ff" >>= Metadata.mkBytes)+ Metadata.encodeMetadatumCbor metadatum @?= B.pack [0x42, 0, 255]+ encodedData <- must (Hex.decode "1801" >>= Data.decodeCbor)+ Data.toCbor encodedData @?= B.pack [0x18, 1]+ Data.toData encodedData @?= Data.Integer 1+ assertBool "Malformed CBOR bypassed script-data validation" (isLeft (Hex.decode "ff" >>= Data.decodeCbor))++roundTrip :: Property+roundTrip = property $ do+ bytes <- forAll (Gen.bytes (Range.linear 0 1024))+ let text = Hex.encode bytes+ Hex.decode text === Right bytes+ Hex.decode (Text.toUpper text) === Right bytes+ Text.length text === 2 * B.length bytes
@@ -0,0 +1,224 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Independent byte/hash/signature fixtures and generated witness perturbations.+module IdentityReliability (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Ed25519.PublicKey as Public+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import qualified Cometa.Encoding.Hex as Hex+import Cometa.Error (Error)+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import Control.Monad (forM_, zipWithM_, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Text (Text)+import Hedgehog (Property, evalIO, forAll, property)+import qualified Hedgehog.Gen as Gen+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Independent transaction identity"+ [ testCase "same semantic body has six independent byte-sensitive IDs and signatures" representationDomains,+ testProperty "framing, validity and witness order preserve the signed message" envelopeProperty,+ testCase "nested witnesses enter the outer commitment but never their own signed message" nestedCommitments+ ]++representationDomains :: IO ()+representationDomains = do+ canonical <- require (hex canonicalBodyHex) >>= require . Body.decodeCbor+ forM_ bodyFixtures $ \fixture -> do+ encoded <- require (hex (bodyHex fixture)) >>= require . Body.decodeCbor+ Body.toBody encoded @?= Body.toBody canonical+ let transaction = Tx.fromBody encoded+ checkIdentity fixture transaction+ expected <- require (hex (digestHex fixture))+ public <- require (Public.fromHex firstPublic)+ signature <- require (Signature.fromHex (firstSignature fixture))+ -- Neither raw body bytes nor complete envelopes are the Ed25519 message.+ Public.verify public (Body.toCbor encoded) signature >>= (@?= Right False)+ Public.verify public (Tx.encodeCbor transaction) signature >>= (@?= Right False)+ Public.verify public expected signature >>= (@?= Right True)+ forM_ bodyFixtures $ \other -> do+ otherDigest <- require (hex (digestHex other))+ Public.verify public otherDigest signature >>= (@?= Right (digestHex fixture == digestHex other))++-- Generated perturbations are deliberately outside the body. Expected IDs and+-- signatures below are independent literals, not a second call to Cometa hash.+envelopeProperty :: Property+envelopeProperty = property $ do+ fixture <- forAll (Gen.element bodyFixtures)+ reverseWitnesses <- forAll Gen.bool+ indefiniteWitnesses <- forAll Gen.bool+ frameStyle <- forAll (Gen.element [0 :: Int, 1, 2])+ valid <- forAll Gen.bool+ evalIO $ do+ encoded <- require (hex (bodyHex fixture))+ signatures <- mapM (require . Signature.fromHex) [firstSignature fixture, secondSignature fixture]+ publicKeys <- mapM (require . Public.fromHex) [firstPublic, secondPublic]+ let witnesses = zipWith Witness.verificationWitness publicKeys signatures+ ordered = if reverseWitnesses then reverse witnesses else witnesses+ witnessBytes =+ if indefiniteWitnesses+ then B.pack [0xbf, 0, 0xd9, 1, 2, 0x9f] <> foldMap Witness.encodeCbor ordered <> B.pack [0xff, 0xff]+ else B.pack [0xa1, 0, 0x82] <> foldMap Witness.encodeCbor ordered+ header = case frameStyle of+ 0 -> B.singleton 0x84+ 1 -> B.pack [0x98, 4]+ _ -> B.singleton 0x9f+ suffix = B.pack [if valid then 0xf5 else 0xf4, 0xf6] <> if frameStyle == 2 then B.singleton 0xff else B.empty+ bytes = header <> encoded <> witnessBytes <> suffix+ transaction <- require (Tx.decodeCbor bytes)+ Tx.encodeCbor transaction @?= bytes+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses transaction)) @?= ordered+ checkIdentity fixture transaction+ -- Existing independently valid partial signatures make signing an exact no-op,+ -- including nonminimal and indefinite containing frames and witness sets.+ forM_ [7, 8] $ \seed -> do+ signed <- Key.withNormalKey (B.replicate 32 seed) (`Signing.sign` transaction) >>= require+ Tx.encodeCbor signed @?= bytes+ Tx.encodeCbor transaction @?= bytes++checkIdentity :: BodyFixture -> Tx.Transaction -> IO ()+checkIdentity fixture transaction = do+ digest <- Tx.transactionId transaction >>= require+ Hex.encode (TxId.toBytes digest) @?= digestHex fixture+ zipWithM_ (checkWitness transaction) [7, 8] [firstSignature fixture, secondSignature fixture]+ where+ checkWitness original seed expected = do+ witness <- Key.withNormalKey (B.replicate 32 seed) (`Signing.verificationWitness` original) >>= require+ Hex.encode (Signature.toBytes (Witness.signature witness)) @?= expected+ Public.toHex (Witness.publicKey witness) @?= if seed == 7 then firstPublic else secondPublic++nestedCommitments :: IO ()+nestedCommitments = do+ subBody <- require (hex subBodyHex) >>= require . SubBody.decodeCbor+ expectedSubId <- require (hex subDigestHex)+ subWitnesses <- mapM (require . hex >=> require . Witness.decodeCbor) subWitnessHex+ expectedSubWitness <- require (hex firstSubWitnessHex) >>= require . Witness.decodeCbor+ -- These four native-backed outer IDs are checked against independent constants:+ -- no nested witnesses, one, two, and the same two in reverse order.+ forM_ nestedFixtures $ \(witnessHex, outerDigest) -> do+ encodedWitnesses <- require (hex witnessHex) >>= require . Witnesses.decodeCbor+ let nested = Sub.assemble subBody encodedWitnesses Nothing+ semanticOuter = (Body.body [] [] 10) {Body.bodySubTransactions = Just [nested]}+ enclosingBody <- require (Body.fromBody semanticOuter)+ let outer = Tx.fromBody enclosingBody+ Sub.transactionId nested >>= fmap TxId.toBytes . require >>= (@?= expectedSubId)+ Tx.transactionId outer >>= fmap (Hex.encode . TxId.toBytes) . require >>= (@?= outerDigest)+ forM_ subWitnesses $ \witness ->+ Public.verify (Witness.publicKey witness) expectedSubId (Witness.signature witness) >>= (@?= Right True)+ actualSubWitness <- Key.withNormalKey (B.replicate 32 7) (`Signing.subTransactionWitness` nested) >>= require+ Witness.encodeCbor actualSubWitness @?= Witness.encodeCbor expectedSubWitness+ signedOuter <- Key.withNormalKey (B.replicate 32 7) (`Signing.sign` outer) >>= require+ goldenOuterId <- require (hex outerDigest)+ forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses signedOuter))) $ \witness -> do+ Public.verify (Witness.publicKey witness) goldenOuterId (Witness.signature witness) >>= (@?= Right True)+ Public.verify (Witness.publicKey witness) expectedSubId (Witness.signature witness) >>= (@?= Right False)+ Public.verify (Witness.publicKey expectedSubWitness) goldenOuterId (Witness.signature expectedSubWitness) >>= (@?= Right False)+ -- A nested witness-only replacement is a real OUTER body edit. It drops only+ -- the outer signature; the replacement's independently signed body survives.+ let replacement = Sub.setWitnesses (Witnesses.fromWitnesses Witnesses.empty) nested+ changedBody <- require (Body.fromBody semanticOuter {Body.bodySubTransactions = Just [replacement]})+ let changedOuter = Tx.setBody changedBody signedOuter+ if witnessHex == "a0"+ then Tx.encodeCbor changedOuter @?= Tx.encodeCbor signedOuter+ else Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses changedOuter)) @?= []+ Body.toCbor (Tx.body signedOuter) @?= Body.toCbor enclosingBody+ removedId <- Tx.transactionId changedOuter >>= require+ Hex.encode (TxId.toBytes removedId) @?= emptyNestedDigest+ if witnessHex == "a0"+ then pure ()+ else assertBool "removing nested witnesses did not change the outer commitment" (Hex.encode (TxId.toBytes removedId) /= outerDigest)+ Sub.body replacement @?= Sub.body nested+ Sub.transactionId replacement >>= fmap TxId.toBytes . require >>= (@?= expectedSubId)++hex :: Text -> Either Error ByteString+hex = Hex.decode++require :: (Show failure) => Either failure value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "identity fixture") pure++-- Independently generated with Python hashlib.blake2b(digest_size=32) and+-- cryptography48/OpenSSL4 Ed25519, synthetic PUBLIC test seeds32*07 and32*08.+-- These are original structural fixtures, not claimed ledger-valid transactions.+-- Law provenance: cardano-api c2212851b06b9c2acc5bb0bfe1b8a8e8cf2be03a,+-- Cardano/Api/Tx/Internal/Sign.hs makeShelleyKeyWitness', hashTxBody (Apache2).+data BodyFixture = BodyFixture+ { bodyHex :: Text,+ digestHex :: Text,+ firstSignature :: Text,+ secondSignature :: Text+ }+ deriving (Show)++bodyFixtures :: [BodyFixture]+bodyFixtures =+ [ BodyFixture "a300818258200000000000000000000000000000000000000000000000000000000000000000000180020a" "892b5222180f305c1014d89c71f08222934fbfbb5811b0b7e70e23fe35a8c508" "3a8641a2ab663fef52344744c9816f65d016490ac666a46f205c140224b646c945f6caf9de51d2b5f45d463a841b56b0fa4593cefcdaad92722612519028ef0e" "a09077a52f3968494fa45cdf6e338f2710ded73ae17c492013bfc4749b3d235ddf34f56be4bafe281a0fdc3ac4fe2d85df1c1888599ec82c51b4d9e463857a0f",+ BodyFixture "a30081825820000000000000000000000000000000000000000000000000000000000000000000018002180a" "cd1eec9efaf5fe760d11e84ae6aff2ebd4febd389e22e683d24cf21b504b8ffa" "27d1a0574c4d8995e70b765fd316888c9693bef0c425aa54e53862d95852fd132f1bddcbdd63099d5f7cab81a00127898804f49f703c874e56dc01e42b56cc0f" "5d54058bd627a51162cc34df2aba9f33fb243295c7db93c335df90aa65ee50fa1952fd84563b7e2d01ad92b9097320f0c9c763e5af056d73ecd930c064d5eb0a",+ BodyFixture "a3008182582000000000000000000000000000000000000000000000000000000000000000000001800219000a" "5b096df8268eef6b34b513c44b3eee248c78bbcd08fde42d477acdda281f6f88" "1b697cbe33ba28fe9b225aa8dc839ddac5641b5979b4ae3d3db50c45f154b5169e00d64c6d57c92f64d3545f1566251d48af09085a59b5fea9e17aa963b55007" "11bddb083ad9f82adca19d2f4fd2c0582f01a66ca841e7c1afe6915d7ce6d0f16adba9d1387f68594cb71a73dd9b493a003a1fa5ee1ee19750ca463ebb154f01",+ BodyFixture "a300818258200000000000000000000000000000000000000000000000000000000000000000000180021b000000000000000a" "393de005eb8ff7e9f61c7a529bc84102aeaf2649eee2de828f7e0216139ef21c" "9e5010e0768cc319bf5c89487760bd729cc58939113879110a276008954129ffdc0295d7ddbfc53aac0143fbaf5a15df2c7dcc794ddc88988a2a09e061288402" "4342b685a337fba8a1ed5f7e1a47429558be9f99189ecbc09acf30c13a4b76a786ca683c3c89a8a23af9bb99296d1c56b2381e30a3d9de2e8bfec90d37bfe50d",+ BodyFixture "a3020a01800081825820000000000000000000000000000000000000000000000000000000000000000000" "3fa334549d9a1faf89ecdc39f7f79ca96d8d297d5ea432b586fb153cd4821f2e" "2e130759c748a1fcd9447fa690013f506c09e00aec852ae3e4436ff8a0d3f6fc84b483dea77303e43d42a144eb3d76a2ad5922a3bff75517e422441b1d210700" "0ead872221cb0335b19bdd57310321b6a7aa67e210f1c8a31510aefdc6d1239ddf9296392acbc0b01dd125d5336b6a9512acbea3b74b43d3df45a7b9c3cc6008",+ BodyFixture "a300d90102818258200000000000000000000000000000000000000000000000000000000000000000000180020a" "5dcf62a26468a0c62aedb191b1436592caeadd1296f0e002d85914fa3a4022a5" "cbc9d1658d6583f7b9a0d028b88b802c06c837990f1759f4a6f09770d472919a5ace88a2928f769b8e461c8a6bfff02265f4ae2f55cb2cdd702fdb56df99e30b" "f2f91bbc618b14b74ce2d7970944c722e3f6ad27e86f54711f42bcb471c7d2151cbd971295e0864713c84443a8b35d147e29dfee772d0ae39895e60895a08802"+ ]++canonicalBodyHex :: Text+canonicalBodyHex = "a300818258200000000000000000000000000000000000000000000000000000000000000000000180020a"++firstPublic :: Text+firstPublic = "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c"++secondPublic :: Text+secondPublic = "1398f62c6d1a457c51ba6a4b5f3dbd2f69fca93216218dc8997e416bd17d93ca"++subBodyHex :: Text+subBodyHex = "a200818258200000000000000000000000000000000000000000000000000000000000000000000180"++subDigestHex :: Text+subDigestHex = "fcd7d304d7fadb2f6813e5401cf4e610fde1c18836f05d14c05b931f2c55672b"++firstSubWitnessHex :: Text+firstSubWitnessHex = "825820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c5840a7b05e6901f110f045f1ffa076b0849e91373b1325dee814a35e7485d83c960b0cd24c699ed1525c6b26b21d9ef1149462686c6747b847cf3de3b40696529e0b"++subWitnessHex :: [Text]+subWitnessHex = ["825820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c5840a7b05e6901f110f045f1ffa076b0849e91373b1325dee814a35e7485d83c960b0cd24c699ed1525c6b26b21d9ef1149462686c6747b847cf3de3b40696529e0b", "8258201398f62c6d1a457c51ba6a4b5f3dbd2f69fca93216218dc8997e416bd17d93ca584091997dc4eb6b30716c2172aee040a0a25aa885b7068801bd8c0b4a240d699577f08e741fbc81af8d1172392a709a99882a1c4c68f63a35144a44ff4175007a0d"]++nestedFixtures :: [(Text, Text)]+nestedFixtures =+ [ ("a0", "6380afc9a4d13fb5bacab03c76ab0543478c90d622d8278b269d71f8aaef9004"),+ ("a10081825820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c5840a7b05e6901f110f045f1ffa076b0849e91373b1325dee814a35e7485d83c960b0cd24c699ed1525c6b26b21d9ef1149462686c6747b847cf3de3b40696529e0b", "1f393c5fe471664d9e3a6dc384b08266fa88fc6f598f419ec8ac2520d3f58f7a"),+ ("a10082825820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c5840a7b05e6901f110f045f1ffa076b0849e91373b1325dee814a35e7485d83c960b0cd24c699ed1525c6b26b21d9ef1149462686c6747b847cf3de3b40696529e0b8258201398f62c6d1a457c51ba6a4b5f3dbd2f69fca93216218dc8997e416bd17d93ca584091997dc4eb6b30716c2172aee040a0a25aa885b7068801bd8c0b4a240d699577f08e741fbc81af8d1172392a709a99882a1c4c68f63a35144a44ff4175007a0d", "f08f018f4f36ae1c7cebf80be1b86186b91dc7de736640d592e1ba816c6c5006"),+ ("a100828258201398f62c6d1a457c51ba6a4b5f3dbd2f69fca93216218dc8997e416bd17d93ca584091997dc4eb6b30716c2172aee040a0a25aa885b7068801bd8c0b4a240d699577f08e741fbc81af8d1172392a709a99882a1c4c68f63a35144a44ff4175007a0d825820ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c5840a7b05e6901f110f045f1ffa076b0849e91373b1325dee814a35e7485d83c960b0cd24c699ed1525c6b26b21d9ef1149462686c6747b847cf3de3b40696529e0b", "a4ff1bb5062b3f34f399dcd3ab9c3af57439d9f0f8bfa7270edac6388e1dad49")+ ]++emptyNestedDigest :: Text+emptyNestedDigest = "6380afc9a4d13fb5bacab03c76ab0543478c90d622d8278b269d71f8aaef9004"
@@ -0,0 +1,107 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Generated collection inspection laws with independent JSON expectations.+module InspectionCollections (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.AssetName as Name+import qualified Cometa.Crypto.Blake2b as Hash+import qualified Cometa.Inspection as Inspection+import qualified Cometa.PolicyId as Policy+import Data.Aeson (Value (String), object, toJSON, (.=))+import qualified Data.Aeson.Key as Key+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.List (sortOn)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import qualified Data.Text as Text+import Hedgehog (Gen, Property, classify, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Collection inspection properties"+ [ testProperty "asset-entry arrays retain zero, signed bounds and stable duplicates" assetEntries,+ testProperty "policy-entry arrays retain empty groups and replace repeated policies" policyEntries,+ testProperty "object projections reject duplicate keys instead of collapsing them" duplicateObjects,+ testProperty "hash collection order is length-first and retains duplicates" hashes+ ]++assetEntries :: Property+assetEntries = property $ do+ raw <- forAll (Gen.list (Range.linear 0 20) ((,) <$> nameBytes <*> quantity))+ pairs <- traverse (\(bytes, amount) -> do name <- evalEither (Name.fromBytes bytes); pure (name, amount)) raw+ classify "empty collection" (null raw)+ classify "zero amount" (any ((== 0) . snd) raw)+ classify "negative amount" (any ((< 0) . snd) raw)+ classify "duplicate names" (Set.size (Set.fromList (map fst raw)) < length raw)+ actual <- evalIO (Inspection.policyAssetEntries pairs) >>= evalEither+ let expected = toJSON [object ["asset_name" .= Name.toHex name, "amount" .= Text.pack (show amount)] | (name, amount) <- sortOn (byteOrder . Name.toBytes . fst) pairs]+ actual === expected++policyEntries :: Property+policyEntries = property $ do+ raw <- forAll (Gen.list (Range.linear 0 12) ((,) <$> Gen.word8 (Range.linear 0 3) <*> Gen.list (Range.linear 0 6) ((,) <$> nameBytes <*> quantity)))+ groups <- traverse makeGroup raw+ classify "empty policy group" (any (null . snd) groups)+ classify "duplicate policies" (Set.size (Set.fromList (map fst groups)) < length groups)+ actual <- evalIO (Inspection.assetEntries groups) >>= evalEither+ let expected = toJSON [object ["script_hash" .= Policy.toHex policy, "assets" .= object [Key.fromText (Name.toHex name) .= Text.pack (show amount) | (name, amount) <- pairs]] | (policy, pairs) <- Map.toAscList (Map.fromList groups)]+ actual === expected+ where+ makeGroup (seed, names) = do+ policy <- evalEither (Policy.fromBytes (B.replicate 28 seed))+ entries <- traverse (\(bytes, amount) -> do name <- evalEither (Name.fromBytes bytes); pure (name, amount)) (Map.toList (Map.fromList names))+ pure (policy, entries)++duplicateObjects :: Property+duplicateObjects = property $ do+ bytes <- forAll nameBytes+ first <- forAll quantity+ second <- forAll quantity+ name <- evalEither (Name.fromBytes bytes)+ policy <- evalEither (Policy.fromBytes (B.replicate 28 0))+ let duplicates = [(name, first), (name, second)]+ evalIO (Inspection.policyAssets duplicates) >>= (=== True) . isLeft+ evalIO (Inspection.assets [(policy, duplicates)]) >>= (=== True) . isLeft+ evalIO (Inspection.assetEntries [(policy, duplicates)]) >>= (=== True) . isLeft++hashes :: Property+hashes = property $ do+ raw <- forAll (Gen.list (Range.linear 0 20) (Gen.bytes (Range.linear 1 64)))+ let supplied = raw <> take 2 raw+ values <- traverse (evalEither . Hash.fromBytes) supplied+ actual <- evalIO (Inspection.hashes values) >>= evalEither+ actual === toJSON (map (String . Hash.toHex) (sortOn (byteOrder . Hash.toBytes) values))++nameBytes :: Gen B.ByteString+nameBytes = Gen.choice [pure B.empty, pure (B.singleton 255), pure (B.pack [0, 0]), Gen.bytes (Range.linear 0 32)]++quantity :: Gen Integer+quantity = Gen.choice [pure 0, pure (toInteger (minBound :: Int64)), pure (toInteger (maxBound :: Int64)), toInteger <$> Gen.int64 Range.linearBounded]++byteOrder :: B.ByteString -> (Int, B.ByteString)+byteOrder bytes = (B.length bytes, bytes)
@@ -0,0 +1,302 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}++-- | Differential checks for standard Integer workflows, not a native BigInt API.+-- Provenance: native merge c5edc7c8f16b3980b6e97ef7fda80fef94adf980,+-- lib/src/common/bigint.c and lib/external/gmp/mini-gmp.c.+-- Expectations are independently composed from base Integer/Data.Bits/Numeric;+-- no native arithmetic implementation or test vectors were copied.+-- Primary Haskell source reviewed at ghc-9.6.7-release:+-- https://github.com/ghc/ghc/blob/ghc-9.6.7-release/libraries/ghc-bignum/src/GHC/Num/Integer.hs+-- https://github.com/ghc/ghc/blob/ghc-9.6.7-release/libraries/base/Data/Bits.hs+-- The former documents magnitude popCount for negatives and implements signed+-- bitwise operations and arithmetic shift-right. Use abs explicitly for counts.+module IntegerSemantics (tests) where++-- IMPORTS --------------------------------------------------------------------++import Control.Exception (ArithException (DivideByZero), evaluate, try)+import Control.Monad (forM_, replicateM_)+import Data.Bits (clearBit, complement, complementBit, popCount, setBit, shiftL, shiftR, testBit, xor, (.&.), (.|.))+import qualified Data.ByteString as BS+import Data.Char (intToDigit)+import Data.Int (Int64)+import Data.List (unfoldr)+import qualified Data.List as List+import Data.Word (Word64, Word8)+import Foreign.C.String (CString, peekCString, withCString)+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Numeric (showIntAtBase)+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertEqual, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)+import Text.Read (readMaybe)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Integer semantics"+ [ testCase "native division and mod use truncating quot and rem" checkDivision,+ testCase "signed bitwise operations and boundary indices match Data.Bits" checkBits,+ testCase "magnitude population count and zero-inclusive binary length" checkCounts,+ testCase "ordinary arithmetic and bounded powers agree with Integer" checkArithmetic,+ testCase "unsigned conversion truncates magnitude, byte sizes include zero" checkConversions,+ testCase "unsigned byte import and signed export preserve zero and endian magnitude" checkBytes,+ testCase "full uint64 powers agree with Integer including aliased results" checkFullWidthPowers,+ testCase "signed64 conversion preserves INT64_MIN and wraps low bits" checkSignedConversions,+ testCase "bounded decimal spans accept exact bytes and stop within their limit" checkSpans,+ testCase "zero division is rejected before native abort and partial owners are released" checkFailures,+ testCase "copied results survive repeated success, failure and collection" checkLifetime,+ testProperty "signed multiword arithmetic agrees with independent Integer operations" propArithmetic,+ testProperty "signed64 export agrees with standard Integer to Int64 conversion" propSignedConversion,+ testProperty "magnitude bytes agree with an independent Integer codec" propMagnitudeBytes+ ]++boundaries :: [Integer]+boundaries = [0, 1, -1, 7, -7, 2 ^ (63 :: Int), negate (2 ^ (63 :: Int)), 2 ^ (64 :: Int) - 1, 2 ^ (127 :: Int) + 5, negate (2 ^ (257 :: Int) + 1)]++checkDivision :: IO ()+checkDivision = do+ forM_ boundaries $ \left -> forM_ [-17, -3, -1, 1, 3, 17, 2 ^ (65 :: Int) + 1] $ \right -> do+ expectOperation 3 left right 0 [left `quot` right]+ expectOperation 4 left right 0 [left `rem` right]+ expectOperation 5 left right 0 [left `rem` right]+ let (quotient, remainder) = left `quotRem` right+ expectOperation 6 left right 0 [quotient, remainder]+ left @?= quotient * right + remainder+ -- This distinction prevents accidentally documenting native mod as Prelude.mod.+ expectOperation 5 (-7) 3 0 [-1]+ ((-7) `mod` (3 :: Integer)) @?= 2++checkBits :: IO ()+checkBits = do+ forM_ boundaries $ \left -> do+ expectOperation 10 left 0 0 [complement left]+ forM_ boundaries $ \right -> do+ expectOperation 7 left right 0 [left .&. right]+ expectOperation 8 left right 0 [left .|. right]+ expectOperation 9 left right 0 [left `xor` right]+ forM_ [0, 1, 31, 32, 63, 64, 65, 127, 128, 257, 513, 4096] $ \index -> do+ let argument = fromIntegral index+ expectOperation 11 left 0 argument [left `shiftL` index]+ expectOperation 12 left 0 argument [left `shiftR` index]+ expectOperation 13 left 0 argument [if testBit left index then 1 else 0]+ expectOperation 14 left 0 argument [setBit left index]+ expectOperation 15 left 0 argument [clearBit left index]+ expectOperation 16 left 0 argument [complementBit left index]+ expectOperation 12 (-7) 0 1 [-4]++magnitudeLength :: Integer -> Integer+magnitudeLength value = toInteger (length (showIntAtBase 2 intToDigit (abs value) ""))++checkCounts :: IO ()+checkCounts = do+ forM_ (boundaries ++ [2 ^ (n :: Int) + delta | n <- [7, 8, 31, 32, 63, 64, 255, 256], delta <- [-1, 0, 1]]) $ \value -> do+ expectOperation 17 value 0 0 [toInteger (popCount (abs value))]+ expectOperation 18 value 0 0 [magnitudeLength value]+ expectOperation 17 (-7) 0 0 [3]+ expectOperation 18 0 0 0 [1]++checkArithmetic :: IO ()+checkArithmetic = do+ forM_ boundaries $ \left -> do+ expectOperation 21 left 0 0 [abs left]+ expectOperation 22 left 0 0 [negate left]+ expectOperation 23 left 0 0 [signum left]+ expectOperation 26 left 0 0 [left + 1]+ expectOperation 27 left 0 0 [left - 1]+ forM_ boundaries $ \right -> checkBinary left right+ forM_ [-7, -1, 0, 1, 7, 2 ^ (65 :: Int)] $ \value ->+ forM_ [0, 1, 2, 3, 16] $ \power -> expectOperation 19 value 0 power [value ^ power]++checkBinary :: Integer -> Integer -> IO ()+checkBinary left right =+ forM_ [(0, left + right), (1, left - right), (2, left * right), (20, gcd left right), (24, min left right), (25, max left right)] $ \(operation, expected) ->+ expectOperation operation left right 0 [expected]++checkConversions :: IO ()+checkConversions =+ forM_ (boundaries ++ [2 ^ (128 :: Int) + 17, negate (2 ^ (128 :: Int) + 17)]) $ \value -> do+ expectOperation 28 value 0 0 [toInteger (fromInteger (abs value) :: Word64)]+ expectOperation 29 value 0 0 [(magnitudeLength value + 7) `quot` 8]++checkBytes :: IO ()+checkBytes =+ forM_ [[0], [0, 0], [1], [0, 1], [128, 255], [0, 1, 0, 255], replicate 32 255] $ \bytes ->+ forM_ [False, True] $ \little -> forM_ [False, True] $ \negative -> do+ let ordered = if little then reverse bytes else bytes+ magnitude = List.foldl' (\acc byte -> acc * 256 + toInteger byte) 0 ordered+ value = if negative then negate magnitude else magnitude+ count = fromInteger ((magnitudeLength magnitude + 7) `quot` 8)+ expected = magnitudeBytes little value+ (status, decimal, encoded) <- byteOracle bytes little negative count+ status @?= 0+ readMaybe decimal @?= Just value+ encoded @?= expected++magnitudeBytes :: Bool -> Integer -> BS.ByteString+magnitudeBytes little value = BS.pack (if little then digits else reverse digits)+ where+ digits = if value == 0 then [0] else unfoldr next (abs value)+ next 0 = Nothing+ next remaining = let (quotient, byte) = remaining `quotRem` 256 in Just (fromInteger byte, quotient)++propMagnitudeBytes :: Property+propMagnitudeBytes = property $ do+ bytes <- forAll (Gen.list (Range.linear 1 64) (Gen.word8 Range.constantBounded))+ little <- forAll Gen.bool+ negative <- forAll Gen.bool+ let ordered = if little then reverse bytes else bytes+ magnitude = List.foldl' (\acc byte -> acc * 256 + toInteger byte) 0 ordered+ value = if negative then negate magnitude else magnitude+ expected = magnitudeBytes little value+ (status, decimal, encoded) <- evalIO (byteOracle bytes little negative (BS.length expected))+ status === 0+ readMaybe decimal === Just value+ encoded === expected++checkFullWidthPowers :: IO ()+checkFullWidthPowers =+ forM_ [30, 32] $ \operation ->+ forM_ [-1, 0, 1] $ \value ->+ forM_ [0, 1, 2, 2 ^ (32 :: Int) - 1, 2 ^ (32 :: Int), 2 ^ (32 :: Int) + 1, maxBound - 1, maxBound] $ \power ->+ expectOperation operation value 0 power [value ^ power]++checkSignedConversions :: IO ()+checkSignedConversions =+ forM_ (boundaries ++ [sign * (2 ^ width + delta) | sign <- [-1, 1], width <- [63, 64, 65, 127, 128, 257 :: Int], delta <- [-1, 0, 1]]) $ \value ->+ expectOperation 31 value 0 0 [toInteger (fromInteger value :: Int64)]++checkSpans :: IO ()+checkSpans = do+ -- Each adapter input is copied to an exact allocation without an appended+ -- terminator. These span sizes are independent of its allocation length.+ forM_+ [ (BS.pack [45, 49, 50, 51], 4, -123),+ (BS.pack [49, 50, 51, 120], 3, 123),+ (BS.pack [49, 50, 51, 0], 4, 123),+ (BS.pack [49, 50, 51, 0, 120, 120], 6, 123),+ (BS.pack [49, 50, 0, 120], 4, 12),+ (BS.singleton 55, 1, 7)+ ]+ $ \(bytes, size, expected) -> do+ (status, decimal) <- spanOracle bytes size 128+ status @?= 0+ readMaybe decimal @?= Just (expected :: Integer)+ forM_ [(BS.pack [49, 50, 120], 3), (BS.singleton 55, 0), (BS.singleton 0, 1)] $ \(bytes, size) -> do+ (status, _) <- spanOracle bytes size 128+ assertBool "invalid or empty bounded decimal span" (status /= 0)+ (short, _) <- spanOracle (BS.pack [49, 50, 51]) 3 1+ assertBool "parsed span still reports short output capacity" (short /= 0)++checkFailures :: IO ()+checkFailures = do+ forM_ [3 .. 6] $ \operation -> do+ (status, _) <- rawOracle operation "7" "0" 0 128+ assertBool "test adapter rejects zero before native process abort" (status /= 0)+ division <- try (evaluate ((7 :: Integer) `quot` 0)) :: IO (Either ArithException Integer)+ division @?= Left DivideByZero+ (invalid, _) <- rawOracle 0 "invalid" "1" 0 128+ assertBool "native parse failure" (invalid /= 0)+ (short, _) <- rawOracle 0 "12345" "1" 0 1+ assertBool "short caller buffer" (short /= 0)+ (tooLarge, _) <- rawOracle 11 "1" "0" 4097 128+ assertBool "oracle prevents unbounded test allocations" (tooLarge /= 0)++checkLifetime :: IO ()+checkLifetime = do+ signed <- oracle 31 (negate (2 ^ (63 :: Int))) 0 0+ spanResult <- spanOracle (BS.pack [45, 49, 50, 51]) 4 128+ retained <- oracle 6 (negate (2 ^ (257 :: Int) + 1)) 17 0+ replicateM_ 50 $ do+ checkFailures+ expectOperation 31 (negate (2 ^ (63 :: Int))) 0 0 [toInteger (minBound :: Int64)]+ expectOperation 14 (-1) 0 257 [-1]+ expectOperation 17 (2 ^ (256 :: Int) - 1) 0 0 [256]+ performGC+ signed @?= [toInteger (minBound :: Int64)]+ spanResult @?= (0, "-123")+ retained @?= let (q, r) = negate (2 ^ (257 :: Int) + 1) `quotRem` 17 in [q, r]++propArithmetic :: Property+propArithmetic = property $ do+ left <- forAll (Gen.integral (Range.linear (negate (2 ^ (260 :: Int))) (2 ^ (260 :: Int))))+ right <- forAll (Gen.integral (Range.linear (negate (2 ^ (260 :: Int))) (2 ^ (260 :: Int))))+ forM_ [(0, left + right), (1, left - right), (2, left * right), (7, left .&. right), (8, left .|. right), (9, left `xor` right), (20, gcd left right)] $ \(operation, expected) -> do+ actual <- evalIO (oracle operation left right 0)+ actual === [expected]++propSignedConversion :: Property+propSignedConversion = property $ do+ value <- forAll (Gen.integral (Range.linear (negate (2 ^ (260 :: Int))) (2 ^ (260 :: Int))))+ actual <- evalIO (oracle 31 value 0 0)+ actual === [toInteger (fromInteger value :: Int64)]++-- FUNCTIONS ------------------------------------------------------------------++expectOperation :: Word8 -> Integer -> Integer -> Word64 -> [Integer] -> IO ()+expectOperation operation left right argument expected = do+ actual <- oracle operation left right argument+ assertEqual (show (operation, left, right, argument)) expected actual++oracle :: Word8 -> Integer -> Integer -> Word64 -> IO [Integer]+oracle operation left right argument = do+ (status, encoded) <- rawOracle operation (show left) (show right) argument 4096+ status @?= 0+ case traverse readMaybe (words encoded) of+ Just values -> pure values+ Nothing -> assertFailure ("Invalid native decimal result: " ++ encoded) >> pure []++rawOracle :: Word8 -> String -> String -> Word64 -> Int -> IO (CInt, String)+rawOracle operation left right argument capacity =+ withCString left $ \first -> withCString right $ \second -> allocaBytes capacity $ \output -> do+ status <- cOracle operation first second argument output (fromIntegral capacity)+ encoded <- if status == 0 then peekCString output else pure ""+ pure (status, encoded)++byteOracle :: [Word8] -> Bool -> Bool -> Int -> IO (CInt, String, BS.ByteString)+byteOracle bytes little negative count =+ BS.useAsCStringLen (BS.pack bytes) $ \(input, size) -> allocaBytes 256 $ \output -> allocaBytes 1024 $ \decimal -> do+ status <- cBytes (castPtr input) (fromIntegral size) (if little then 1 else 0) (if negative then 1 else 0) output 256 decimal 1024+ text <- peekCString decimal+ encoded <- if status == 0 then BS.packCStringLen (castPtr output, count) else pure BS.empty+ pure (status, text, encoded)++spanOracle :: BS.ByteString -> Int -> Int -> IO (CInt, String)+spanOracle bytes size capacity =+ BS.useAsCStringLen bytes $ \(input, actualSize) -> allocaBytes capacity $ \output -> do+ status <- cSpan input (fromIntegral actualSize) (fromIntegral size) output (fromIntegral capacity)+ decimal <- if status == 0 then peekCString output else pure ""+ pure (status, decimal)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_integer_semantics"+ cOracle :: Word8 -> CString -> CString -> Word64 -> CString -> CSize -> IO CInt++foreign import ccall unsafe "cometa_test_integer_bytes"+ cBytes :: Ptr Word8 -> CSize -> Word8 -> Word8 -> Ptr Word8 -> CSize -> CString -> CSize -> IO CInt++foreign import ccall unsafe "cometa_test_integer_span"+ cSpan :: CString -> CSize -> CSize -> CString -> CSize -> IO CInt
@@ -0,0 +1,227 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++-- IMPORTS --------------------------------------------------------------------++import qualified AccountingReliability+import qualified Address+import qualified AssetId+import qualified Bip32+import qualified Bip39+import qualified Callback+import qualified Cbor+import qualified Certificates+import qualified Cip8+import qualified CollectionOperations+import qualified Collections+import qualified Cometa+import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified CompleteAddress+import qualified ConnectedGovernance+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar, threadDelay, yield)+import Control.Exception (AsyncException (ThreadKilled), fromException)+import Control.Monad (forever, replicateM_)+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import qualified DerivationPath+import qualified Diagnostics+import qualified Ed25519+import qualified ErrorCode+import qualified Governance+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import qualified HexEncoding+import qualified IdentityReliability+import qualified InspectionCollections+import qualified IntegerSemantics+import qualified Metadata+import qualified NativeWorkflows+import qualified NumericConversions+import qualified Ownership+import qualified Parameters+import qualified PasswordCrypto+import qualified PlutusData+import qualified Pool+import qualified Proposals+import qualified ProtocolValues+import qualified PublicTransaction+import qualified Scripts+import qualified SelectionReliability+import qualified SetEncoding+import qualified SlotConfig+import qualified SoftwareKeyHandler+import qualified StandaloneSetEncoding+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)+import qualified Transaction+import qualified TransactionAccountingProperties+import qualified TransactionBody+import qualified TransactionCollectionOperations+import qualified TransactionDeferred+import qualified TransactionMapOperations+import qualified TransactionWitnesses+import qualified Value++-- DEFINITIONS ----------------------------------------------------------------++main :: IO ()+main =+ defaultMain $+ testGroup "Cometa foundation" $+ [ AssetId.tests,+ Cip8.tests,+ CompleteAddress.tests,+ TransactionBody.tests,+ TransactionDeferred.tests,+ TransactionAccountingProperties.tests,+ AccountingReliability.tests,+ SelectionReliability.tests,+ IdentityReliability.tests,+ IntegerSemantics.tests,+ NumericConversions.tests,+ CollectionOperations.tests,+ TransactionCollectionOperations.tests,+ TransactionMapOperations.tests,+ InspectionCollections.tests,+ HexEncoding.tests,+ PublicTransaction.tests,+ TransactionWitnesses.tests,+ Proposals.tests,+ Certificates.tests,+ Pool.tests,+ Governance.tests,+ ProtocolValues.tests,+ Collections.tests,+ SetEncoding.tests,+ StandaloneSetEncoding.tests,+ SlotConfig.tests,+ Parameters.tests,+ Scripts.tests,+ Metadata.tests,+ NativeWorkflows.tests,+ ConnectedGovernance.tests,+ PlutusData.tests,+ Value.tests,+ Address.tests,+ ErrorCode.tests,+ Callback.tests,+ Ownership.tests,+ Cbor.tests,+ Diagnostics.tests,+ Transaction.tests,+ Ed25519.tests,+ Bip32.tests,+ Bip39.tests,+ PasswordCrypto.tests,+ DerivationPath.tests,+ SoftwareKeyHandler.tests+ ]+ ++ foundationTests++foundationTests :: [TestTree]+foundationTests =+ [ testCase "linked native version is available" $ do+ version <- Cometa.nativeVersion+ Text.null version @?= False,+ -- Independently checked with Python hashlib.blake2b(b"abc", digest_size=32).+ -- This is not claimed as a copied RFC test vector.+ testCase "BLAKE2b-256 abc known answer" $ do+ result <- Blake2b.compute 32 "abc"+ fmap Blake2b.toHex result @?= Right "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319",+ testCase "uppercase hex normalizes to lowercase" $+ fmap Blake2b.toHex (Blake2b.fromHex "00AbFF") @?= Right "00abff",+ testCase "malformed hex is rejected" $+ mapM_+ (\input -> Blake2b.fromHex input @?= Left InvalidHex)+ ["", "a", "xx", " 00", "0x00", "12"],+ testCase "invalid digest sizes never enter C" $+ mapM_ (\size -> Blake2b.compute size "abc" >>= (@?= Left (InvalidHashLength size))) [minBound, -1, 0, 15, 65, maxBound],+ testCase "empty digest bytes return a validation error" $+ Blake2b.fromBytes ByteString.empty @?= Left EmptyHash,+ testCase "native errors preserve exact code and operation" $ do+ computed <- Blake2b.compute 32 ByteString.empty+ checkNativeFailure "blake2b.compute" Code.OutOfBoundsMemoryRead computed,+ testCase "copied bytes survive native cleanup and GC" checkCopiedBytes,+ testCase "asynchronous cancellation completes and later calls remain usable" checkCancellation,+ testCase "digest CBOR checks shape and complete input" $ do+ digest <- either (fail . show) pure (Blake2b.fromBytes "ab")+ Blake2b.encodeCbor digest @?= ByteString.pack [0x42, 97, 98]+ Blake2b.decodeCbor (ByteString.pack [0x5f, 0x41, 97, 0x41, 98, 0xff]) @?= Right digest+ Blake2b.decodeCbor (ByteString.singleton 0x40) @?= Left EmptyHash+ mapM_ (\bytes -> case Blake2b.decodeCbor bytes of Left _ -> pure (); Right _ -> assertFailure "Invalid digest CBOR accepted") [ByteString.empty, ByteString.singleton 0, ByteString.pack [0x41, 0, 0]],+ testProperty "bytes and hexadecimal round trips" propRoundTrip,+ testProperty "computed digest has requested length" propDigestLength+ ]++checkCopiedBytes :: IO ()+checkCopiedBytes = do+ original <- Blake2b.compute 32 "abc"+ replicateM_ 1000 $ do+ _ <- Blake2b.compute 64 "temporary native allocation"+ pure ()+ performGC+ fmap Blake2b.toHex original @?= Right "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319"++checkCancellation :: IO ()+checkCancellation = replicateM_ 10 $ do+ started <- newEmptyMVar+ finished <- newEmptyMVar+ worker <-+ forkFinally+ (putMVar started () >> forever (Blake2b.compute 64 (ByteString.replicate (1024 * 1024) 42) >> yield))+ (putMVar finished)+ takeMVar started+ threadDelay 1000+ outcome <- timeout 10000000 (killThread worker >> takeMVar finished)+ case outcome of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ Just (Right ()) -> assertFailure "Worker completed before cancellation"+ Nothing -> assertFailure "Cancellation failed to finish"+ result <- Blake2b.compute 32 "abc"+ fmap Blake2b.toHex result @?= Right "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319"++checkNativeFailure :: Text.Text -> Code.ErrorCode -> Either Error value -> IO ()+checkNativeFailure operation code result = case result of+ Left (NativeError actualOperation actualCode message) -> do+ actualOperation @?= operation+ actualCode @?= code+ message @?= "Out of bounds memory read"+ Left other -> assertFailure ("Expected native error, got " <> show other)+ Right _ -> assertFailure "Expected native error, got success"++propRoundTrip :: Property+propRoundTrip = property $ do+ bytes <- forAll (Gen.bytes (Range.linear 1 512))+ digest <- evalEither (Blake2b.fromBytes bytes)+ Blake2b.toBytes digest === bytes+ Blake2b.decodeCbor (Blake2b.encodeCbor digest) === Right digest+ Blake2b.fromHex (Blake2b.toHex digest) === Right digest+ Blake2b.fromHex (Text.toUpper (Blake2b.toHex digest)) === Right digest++propDigestLength :: Property+propDigestLength = property $ do+ size <- forAll (Gen.int (Range.linear 16 64))+ bytes <- forAll (Gen.bytes (Range.linear 1 1024))+ result <- evalIO (Blake2b.compute size bytes)+ fmap (ByteString.length . Blake2b.toBytes) result === Right size
@@ -0,0 +1,244 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module Metadata (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.Metadata as Metadata+import Control.Monad (forM_)+import qualified Data.Aeson as Json+import qualified Data.ByteString as BS+import Data.Either (isLeft)+import Data.Scientific (scientific)+import qualified Data.Text as Text+import Data.Word (Word8)+import Foreign.C.Types (CChar, CInt (..), CSize (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Gen, Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Metadata"+ [ testCase "plain native JSON conversion checks bounds and prevents lost map data" checkPlainJson,+ testCase "integer and UTF-8 byte boundaries" checkBounds,+ testCase "ordered duplicate nested maps and unique labels" checkCollections,+ testCase "exact encodings retain identity until explicit normalization" checkExact,+ testCase "schema, UTF-8 and trailing input rejection" checkInvalid,+ testCase "pinned native corpus traversed through public values" checkCorpus,+ testCase "detailed JSON exact integers and invalid forms" checkJson,+ testProperty "nested metadata CBOR, JSON and native agreement" propRoundTrip,+ testProperty "left-biased metadata composition is associative" propComposition+ ]++checkBounds :: IO ()+checkBounds = do+ let bound = 2 ^ (64 :: Int)+ traverse_ (\n -> Metadata.view <$> Metadata.mkInteger n @?= Right (Metadata.IntegerValue n)) [-bound, -1, 0, bound - 1]+ traverse_ (\n -> Metadata.mkInteger n @?= Left (InvalidMetadataInteger n)) [-bound - 1, bound]+ Metadata.mkBytes (BS.replicate 65 0) @?= Left (InvalidMetadataBytesLength 65)+ Metadata.mkText (Text.replicate 17 "🙂") @?= Left (InvalidMetadataTextLength 68)+ value <- expectRight (Metadata.mkText (Text.replicate 16 "🙂"))+ Metadata.view value @?= Metadata.TextValue (Text.replicate 16 "🙂")+ nul <- expectRight (Metadata.mkText "\0")+ Metadata.view nul @?= Metadata.TextValue "\0"++checkCollections :: IO ()+checkCollections = do+ one <- expectRight (Metadata.mkInteger 1)+ two <- expectRight (Metadata.mkInteger 2)+ let pairs = [(one, two), (one, one)]+ value = Metadata.map pairs+ Metadata.view value @?= Metadata.MapValue pairs+ decoded <- expectRight (Metadata.decodeMetadatumCbor (Metadata.encodeMetadatumCbor value))+ Metadata.toMetadatum decoded @?= value+ Metadata.mkMetadata [(1, one), (1, two)] @?= Left (DuplicateMetadataLabel 1)+ metadata <- expectRight (Metadata.mkMetadata [(2, two), (1, one)])+ Metadata.toList metadata @?= [(1, one), (2, two)]+ Metadata.lookup 0 metadata @?= Nothing+ Metadata.lookup 1 (Metadata.singleton 1 two <> metadata) @?= Just two++checkExact :: IO ()+checkExact = do+ -- Indefinite map and nonminimal label/integer encodings have one semantic view.+ original <- expectRight (Metadata.decodeCbor (BS.pack [0xbf, 0x18, 0x01, 0x18, 0x02, 0xff]))+ normalized <- expectRight (Metadata.decodeCbor (BS.pack [0xa1, 0x01, 0x02]))+ Metadata.toMetadata original @?= Metadata.toMetadata normalized+ (original == normalized) @?= False+ Metadata.toCbor original @?= BS.pack [0xbf, 0x18, 0x01, 0x18, 0x02, 0xff]+ Metadata.encodeCbor (Metadata.toMetadata original) @?= Metadata.toCbor normalized+ left <- Blake2b.compute 32 (Metadata.toCbor original) >>= expectRight+ right <- Blake2b.compute 32 (Metadata.toCbor normalized) >>= expectRight+ (left == right) @?= False+ value <- expectRight (Metadata.decodeMetadatumCbor (BS.pack [0x7f, 0x61, 0x61, 0x61, 0x62, 0xff]))+ Metadata.view (Metadata.toMetadatum value) @?= Metadata.TextValue "ab"++checkInvalid :: IO ()+checkInvalid = do+ traverse_+ (assertLeft . Metadata.decodeMetadatumCbor . BS.pack)+ [ [],+ [0x01, 0x02],+ [0xf5],+ [0xf6],+ [0xc2, 0x41, 0x01],+ [0x61, 0xff],+ [0x7f, 0x61, 0xc3, 0x61, 0xa9, 0xff],+ [0x58, 0x41] ++ replicate 65 0+ ]+ deep <- expectRight (Metadata.decodeMetadatumCbor (BS.pack (replicate 130 0x81 ++ [0])))+ Metadata.encodeMetadatumCbor (Metadata.toMetadatum deep) @?= BS.pack (replicate 130 0x81 ++ [0])+ Metadata.decodeCbor (BS.pack [0xa2, 0x01, 0x00, 0x01, 0x01]) @?= Left (DuplicateMetadataLabel 1)+ traverse_ (assertLeft . Metadata.decodeCbor . BS.pack) [[0xa1, 0x20, 0x01], [0xa1, 0x61, 0x61, 0x01], [0x80]]++checkCorpus :: IO ()+checkCorpus = do+ -- Apache-2.0 cardano-c eadb95cd, lib/tests/auxiliary_data/metadatum.cpp+ -- METADATUM_CBOR, normalized from its indefinite outer and inner lists.+ n <- traverse (expectRight . Metadata.mkInteger) [1 .. 5]+ case n of+ [one, two, three, four, five] -> do+ let inner = Metadata.list [one, two, three, four, five]+ value = Metadata.list [one, two, inner, inner, five]+ encoded <- expectRight (Metadata.decodeMetadatumCbor (BS.pack [0x9f, 1, 2, 0x9f, 1, 2, 3, 4, 5, 0xff, 0x9f, 1, 2, 3, 4, 5, 0xff, 5, 0xff]))+ Metadata.toMetadatum encoded @?= value+ nativeAgreement False (Metadata.encodeMetadatumCbor value) >>= (@?= True)+ nativeAgreement True (Metadata.encodeCbor (Metadata.singleton 725 value)) >>= (@?= True)+ _ -> assertFailure "fixture assembly"++checkJson :: IO ()+checkJson = do+ traverse_ (assertLeft . Metadata.metadatumFromDetailedJson . Json.object . pure . ("int" Json..=)) [scientific 1 minBound, scientific 1 maxBound]+ traverse_+ ( \encoded -> do+ parsed <- expectRight (Json.eitherDecode encoded :: Either String Json.Value)+ assertLeft (Metadata.metadatumFromDetailedJson parsed)+ )+ ["{\"int\":1e-9223372036854775808}", "{\"int\":1e9223372036854775807}"]+ zero <- expectRight (Json.eitherDecode "{\"int\":0e-9223372036854775808}" :: Either String Json.Value)+ Metadata.metadatumFromDetailedJson zero @?= Metadata.mkInteger 0+ let maximumInteger = 2 ^ (64 :: Int) - 1+ value <- expectRight (Metadata.mkInteger maximumInteger)+ Metadata.metadatumFromDetailedJson (Metadata.metadatumToDetailedJson value) @?= Right value+ traverse_+ (assertLeft . Metadata.metadatumFromDetailedJson)+ [ Json.object ["int" Json..= (1.5 :: Double)],+ Json.object ["int" Json..= (2 ^ (64 :: Int) :: Integer)],+ Json.object ["bytes" Json..= ("gg" :: Text.Text)],+ Json.Bool True,+ Json.object ["int" Json..= (1 :: Int), "string" Json..= ("x" :: Text.Text)]+ ]+ assertLeft (Metadata.fromDetailedJson (Json.object ["01" Json..= Metadata.metadatumToDetailedJson value]))++genValue :: Gen Metadata.Metadatum+genValue =+ Gen.recursive+ Gen.choice+ [leaf]+ [ Metadata.list <$> Gen.list (Range.linear 0 4) genValue,+ Metadata.map <$> Gen.list (Range.linear 0 4) ((,) <$> genValue <*> genValue)+ ]+ where+ leaf =+ Gen.choice+ [ Gen.mapMaybe (validated . Metadata.mkInteger) (Gen.integral (Range.linear (-100000) 100000)),+ Gen.mapMaybe (validated . Metadata.mkBytes . BS.pack) (Gen.list (Range.linear 0 64) (Gen.integral (Range.linear 0 255))),+ Gen.mapMaybe (validated . Metadata.mkText . Text.pack) (Gen.list (Range.linear 0 16) (Gen.element ['a', 'é', '🙂', '\0']))+ ]+ -- Generation and shrinking both pass through the public validators.+ validated = either (const Nothing) Just++propRoundTrip :: Property+propRoundTrip = property $ do+ value <- forAll genValue+ decoded <- evalEither (Metadata.decodeMetadatumCbor (Metadata.encodeMetadatumCbor value))+ Metadata.toMetadatum decoded === value+ json <- evalEither (Metadata.metadatumFromDetailedJson (Metadata.metadatumToDetailedJson value))+ json === value+ agreement <- evalIO (nativeAgreement False (Metadata.encodeMetadatumCbor value))+ agreement === True+ let metadata = Metadata.singleton 674 value+ restored <- evalEither (Metadata.decodeCbor (Metadata.encodeCbor metadata))+ Metadata.toMetadata restored === metadata+ Metadata.fromDetailedJson (Metadata.toDetailedJson metadata) === Right metadata++propComposition :: Property+propComposition = property $ do+ a <- forAll genValue+ b <- forAll genValue+ c <- forAll genValue+ let x = Metadata.singleton 1 a+ y = Metadata.singleton 1 b+ z = Metadata.singleton 2 c+ (x <> y) <> z === x <> (y <> z)+ Metadata.lookup 1 (x <> y) === Just a+ Metadata.toList (mempty <> x) === Metadata.toList x+ Metadata.toList (x <> mempty) === Metadata.toList x++expectRight :: (Show e) => Either e a -> IO a+expectRight (Right value) = pure value+expectRight (Left failure) = assertFailure (show failure) >> fail "unreachable"++assertLeft :: (Show a) => Either e a -> IO ()+assertLeft (Left _) = pure ()+assertLeft (Right value) = assertFailure ("unexpected success: " ++ show value)++traverse_ :: (a -> IO ()) -> [a] -> IO ()+traverse_ action = foldr ((>>) . action) (pure ())++nativeAgreement :: Bool -> BS.ByteString -> IO Bool+nativeAgreement transaction bytes = BS.useAsCStringLen bytes $ \(ptr, size) ->+ (/= 0) <$> cAgreement (castPtr ptr) (fromIntegral size) (if transaction then 1 else 0)++foreign import ccall safe "cometa_test_metadata_agreement"+ cAgreement :: Ptr Word8 -> CSize -> CInt -> IO CInt++checkPlainJson :: IO ()+checkPlainJson = do+ forM_ ["-9223372036854775808", "0", "18446744073709551615", "\"0xdead\"", "[1,\"text\",[]]", "{\"1\":1,\"a\":[2,\"0xff\"]}"] $ \encoded -> do+ json <- expectRight (Json.eitherDecodeStrict encoded)+ datum <- expectRight (Metadata.metadatumFromJson json)+ Metadata.metadatumToJson datum @?= Right json+ BS.useAsCStringLen encoded $ \(jsonPtr, jsonSize) ->+ BS.useAsCStringLen (Metadata.encodeMetadatumCbor datum) $ \(expected, size) -> do+ agrees <- cPlainJson jsonPtr (fromIntegral jsonSize) (castPtr expected) (fromIntegral size)+ agrees @?= 1+ forM_ ["null", "true", "1.5", "-9223372036854775809", "18446744073709551616"] $ \encoded -> do+ json <- expectRight (Json.eitherDecodeStrict encoded)+ assertBool "invalid plain JSON metadata" (isLeft (Metadata.metadatumFromJson json))+ key <- expectRight (Metadata.mkText "key")+ integer <- expectRight (Metadata.mkInteger 1)+ bytesValue <- expectRight (Metadata.mkBytes (BS.singleton 0))+ forM_ [bytesValue, Metadata.map [(integer, key)], Metadata.map [(key, integer), (key, integer)]] $ \datum ->+ assertBool "reject information loss" (isLeft (Metadata.metadatumToJson datum))+ -- Full CBOR negative output remains exact, although native plain input is narrower.+ low <- expectRight (Metadata.mkInteger (negate (2 ^ (64 :: Int))))+ Metadata.metadatumToJson low @?= Right (Json.Number (fromInteger (negate (2 ^ (64 :: Int)))))+ Metadata.metadatumFromJson (Json.String (Text.replicate 65 "a")) @?= Left (InvalidMetadataTextLength 65)++foreign import ccall safe "cometa_test_metadata_plain_json"+ cPlainJson :: Ptr CChar -> CSize -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,376 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Cases adapted from cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/transaction_builder/coin_selection/random_improve_coin_selector.cpp+-- (Apache-2.0): deterministic replay, insufficient funds and change shape.+-- All inputs are assembled through typed public values; accounting is checked+-- independently in Haskell and minimum Ada through the actual native oracle.+module NativeCoinSelection (tests) where++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as Name+import qualified Cometa.CoinSelection as Selection+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (InvalidSelectionRequest, NativeError))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.CoinSelection as Wire+import qualified Cometa.Internal.CoinSelection.Native as Native+import qualified Cometa.Internal.FFI.CoinSelection as FFI+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.Internal.TransactionValue as NativeValue+import qualified Cometa.NetworkId as Network+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)+import Control.Monad (forM_, replicateM, replicateM_, (>=>))+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Word (Word64)+import qualified Fixtures.ProtocolParameters as Fixture+import Foreign.Marshal.Alloc (alloca)+import Foreign.Storable (peek)+import Hedgehog (Gen, Property, PropertyT, assert, classify, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+ testGroup+ "Native coin selection"+ [ testCase "largest-first orders quantities and ignores output hints" checkLargest,+ testCase "seeded policies replay exact complete results" checkReplay,+ testCase "native round-robin change follows output shape" checkShape,+ testCase "mandatory disjoint/overlap and exact match preserve accounting" checkMandatory,+ testCase "zero target still spends an input" checkZero,+ testCase "multiasset change splits at the native value bound" checkAssets,+ testCase "insufficient target and change Ada fail and recover" checkFailure,+ testCase "aggregate native arithmetic bounds fail before selection" checkBounds,+ testCase "signed implicit surplus preserves coin and native-asset change" checkSigned,+ testCase "repeated and concurrent invocations survive GC and callback dispatch" checkLifecycle,+ testProperty "generated native strategies preserve full accounting" propAccounting,+ testProperty "upstream multiasset exact and surplus selection laws" propMultiassetSelection,+ testProperty "upstream generated insufficient coin and token supplies fail" propInsufficientSupply,+ testProperty "upstream generated splitting preserves quantities and size bounds" propSplitBundles+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "Invalid fixture") pure++requestFor :: [Value.Value] -> Value.Value -> IO Selection.SelectionRequest+requestFor values target = do+ params <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ txId <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ candidates <-+ sequence+ [ do+ output <- must (Output.mkOutput destination value Datum.NoDatum Nothing)+ pure (Utxo.utxo (Input.input txId ix) output)+ | (ix, value) <- zip ([0 ..] :: [Word64]) values+ ]+ must (Selection.mkSelectionRequest (Selection.SelectionOptions [] candidates target Nothing destination (params {Parameters.parameterAdaPerUtxoByte = Just 4310, Parameters.parameterMaxValueSize = Just 5000})))++options :: Selection.SelectionRequest -> Selection.SelectionOptions+options request = Selection.SelectionOptions (Selection.preselected request) (Selection.available request) (Selection.target request) (Selection.outputHints request) (Selection.changeAddress request) (Selection.parameters request)++algorithms :: [Selection.Selector]+algorithms = [Selection.largestFirst, Selection.randomImprove, Selection.randomImproveWithSeed 7, Selection.randomImproveWithOptions 7 Selection.Minimal]++checked :: Selection.Selector -> Selection.SelectionRequest -> IO Selection.Selection+checked selector request = do+ result <- Selection.select selector request >>= must+ Selection.validateSelection request result @?= Right ()+ foldMap (Output.value . Utxo.output) (Selection.selected result) @?= Selection.target request <> foldMap Output.value (Selection.change result)+ forM_ (Selection.change result) $ \output -> Runtime.withBytes (Output.encodeCbor output) $ \bytes size -> alloca $ \minimumSlot -> do+ code <- FFI.cMinimumAda bytes size 4310 minimumSlot+ Runtime.checkStatus "test.nativeSelection.minimumAda" code >>= must+ amount <- peek minimumSlot+ assertBool "change below native minimum Ada" (Value.quantity Asset.Ada (Output.value output) >= toInteger amount)+ pure result++checkLargest :: IO ()+checkLargest = do+ request <- requestFor (map Value.lovelace [3000000, 9000000, 2000000]) (Value.lovelace 6000000)+ result <- checked Selection.largestFirst request+ map (Value.quantity Asset.Ada . Output.value . Utxo.output) (Selection.selected result) @?= [9000000]+ hint <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 99999999) Datum.NoDatum Nothing)+ hinted <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionOutputHints = Just [hint, hint]}))+ checked Selection.largestFirst hinted >>= (@?= result)++checkReplay :: IO ()+checkReplay = do+ request <- requestFor (map (Value.lovelace . (* 1000000)) [1 .. 20]) (Value.lovelace 15000000)+ forM_ [Selection.Minimal, Selection.Optimal] $ \strategy -> do+ let selector = Selection.randomImproveWithOptions 7 strategy+ first <- checked selector request+ replicateM_ 8 (checked selector request >>= (@?= first))+ checked (Selection.randomImproveWithSeed 7) request >>= \result -> checked (Selection.randomImproveWithOptions 7 Selection.Optimal) request >>= (@?= result)++checkShape :: IO ()+checkShape = do+ request <- requestFor (replicate 20 (Value.lovelace 3000000)) (Value.lovelace 10000000)+ hint <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ hinted <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionOutputHints = Just [hint, hint]}))+ result <- checked (Selection.randomImproveWithSeed 42) hinted+ length (Selection.change result) @?= 2++checkMandatory :: IO ()+checkMandatory = do+ request <- requestFor (map Value.lovelace [3000000, 7000000, 2000000]) (Value.lovelace 10000000)+ case Selection.available request of+ mandatory : rest -> forM_ algorithms $ \selector -> forM_ [rest, mandatory : rest] $ \available -> do+ required <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionPreselected = [mandatory], Selection.selectionAvailable = available}))+ result <- checked selector required+ assertBool "mandatory input dropped" (mandatory `elem` Selection.selected result)+ [] -> assertFailure "Empty fixture"+ exact <- requestFor [Value.lovelace 10000000] (Value.lovelace 10000000)+ forM_ algorithms $ \selector -> checked selector exact >>= \result -> Selection.change result @?= []++checkZero :: IO ()+checkZero = do+ request <- requestFor (map Value.lovelace [3000000, 9000000]) mempty+ forM_ algorithms $ \selector -> checked selector request >>= \result -> assertBool "zero target produced empty selection" (not (null (Selection.selected result)))++checkAssets :: IO ()+checkAssets = do+ policy <- must (Policy.fromBytes (B.replicate 28 9))+ names <- mapM (must . Name.fromBytes . B.singleton) [1 .. 12]+ let tokens = Value.fromList [(Asset.Native policy name, 100) | name <- names]+ request <- requestFor [Value.lovelace 100000000 <> tokens] (Value.lovelace 1000000)+ small <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionParameters = (Selection.parameters request) {Parameters.parameterMaxValueSize = Just 65}}))+ forM_ algorithms $ \selector -> do+ result <- checked selector small+ assertBool "oversized bundle was not split" (length (Selection.change result) > 1)+ -- Native size assessment substitutes the maximum supply (45 billion Ada)+ -- for coin, so its final width cannot make a split map exceed the limit.+ forM_ (Selection.change result) $ \output -> do+ let boundedValue = Cbor.encode (E.encodeListLen 2 <> E.encodeInteger 45000000000000000 <> NativeValue.encodeAssets (Output.value output))+ assertBool "split value exceeds native maximum size" (B.length boundedValue <= 65)+ assertBool "native assets lost in split" (foldMap Output.value (Selection.change result) == Value.lovelace 99000000 <> tokens)++checkFailure :: IO ()+checkFailure = do+ insufficient <- requestFor [Value.lovelace 1000000] (Value.lovelace 5000000)+ dust <- requestFor [Value.lovelace 5000001] (Value.lovelace 5000000)+ empty <- requestFor [] mempty+ recovery <- requestFor [Value.lovelace 10000000] (Value.lovelace 10000000)+ forM_ algorithms $ \selector -> do+ forM_ [insufficient, dust, empty] (Selection.select selector >=> assertBool "native insufficient funds accepted" . isLeft)+ _ <- checked selector recovery+ pure ()++checkBounds :: IO ()+checkBounds = do+ overflow <- requestFor (replicate 2 (Value.lovelace (2 ^ (62 :: Int)))) (Value.lovelace 1)+ request <- requestFor [Value.lovelace 10000000] (Value.lovelace 5000000)+ excessive <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionParameters = (Selection.parameters request) {Parameters.parameterAdaPerUtxoByte = Just maxBound}}))+ hint <- must (Output.mkOutput (Selection.changeAddress request) (Value.lovelace 1) Datum.NoDatum Nothing)+ -- Each output's bound alone fits, but two shape-hinted maps exceed the signed+ -- sum consumed by largest-first. This must reject before native arithmetic.+ splitCost <- must (Selection.mkSelectionRequest ((options request) {Selection.selectionOutputHints = Just [hint, hint], Selection.selectionParameters = (Selection.parameters request) {Parameters.parameterAdaPerUtxoByte = Just (fromIntegral (maxBound :: Word64) `div` 600)}}))+ forM_ algorithms $ \selector -> forM_ [overflow, excessive, splitCost] $ \invalid -> do+ answer <- Selection.select selector invalid+ case answer of+ Left (InvalidSelectionRequest _) -> pure ()+ other -> assertFailure ("Expected preflight request failure, received " ++ show other)++checkSigned :: IO ()+checkSigned = do+ policy <- must (Policy.fromBytes (B.replicate 28 9))+ let token = Asset.Native policy Name.empty+ forM_ [Value.lovelace (-2000000), Value.lovelace 1000000 <> Value.singleton token (-100)] $ \target -> do+ request <- requestFor [Value.lovelace 3000000] target+ Wire.decodeRequest (Wire.encodeRequest request) @?= Right request+ forM_ algorithms $ \selector -> do+ result <- checked selector request+ -- Actual native callback snapshots must preserve signed target coin and+ -- assets, rather than encoding negative coin as an unsigned ledger value.+ Native.invoke selector request >>= must >>= (@?= result)+ boundary <- requestFor [Value.lovelace 3000000] (Value.lovelace (toInteger (minBound :: Int64)))+ Wire.decodeRequest (Wire.encodeRequest boundary) @?= Right boundary+ forM_ algorithms $ \selector -> do+ answer <- Selection.select selector boundary+ case answer of+ Left (InvalidSelectionRequest _) -> pure ()+ other -> assertFailure ("Expected negative-excess overflow guard: " ++ show other)++checkLifecycle :: IO ()+checkLifecycle = do+ request <- requestFor (replicate 10 (Value.lovelace 3000000)) (Value.lovelace 5000000)+ baseline <- Runtime.liveContexts+ forM_ algorithms $ \selector -> do+ replicateM_ 16 (performGC >> checked selector request)+ result <- checked selector request+ Native.invoke selector request >>= must >>= \roundtrip -> Selection.validateSelection request roundtrip @?= Right ()+ assertBool "native result empty" (not (null (Selection.selected result)))+ slots <- replicateM 4 newEmptyMVar+ forM_ slots $ \slot -> do+ _ <- forkFinally (checked selector request) (putMVar slot)+ pure ()+ forM_ slots (takeMVar >=> either (assertFailure . show) (const (pure ())))+ Runtime.liveContexts >>= (@?= baseline)++propAccounting :: Property+propAccounting = property $ do+ amounts <- forAll (Gen.list (Range.linear 1 20) (Gen.integral (Range.linear 2000000 20000000)))+ seed <- forAll (Gen.word64 Range.constantBounded)+ request <- evalIO (requestFor (map Value.lovelace amounts) (Value.lovelace 1000000))+ forM_ [Selection.largestFirst, Selection.randomImproveWithSeed seed, Selection.randomImproveWithOptions seed Selection.Minimal] $ \selector -> do+ result <- evalIO (Selection.select selector request) >>= evalEither+ Selection.validateSelection request result === Right ()++-- The following properties adapt BalanceSpec's exact/surplus/insufficient supply+-- and bundle-splitting laws, using small positive bundle generators with+-- integrated shrinking. See Fixtures/COIN_SELECTION.md for the pinned source,+-- upstream notices, and differences from its unbounded mock constraints.+-- Expected accounting uses Integer maps, never Value's arithmetic or a C oracle.+type Quantities = Map.Map Asset.AssetId Integer++quantitySum :: [[(Asset.AssetId, Integer)]] -> Quantities+quantitySum = Map.filter (/= 0) . Map.fromListWith (+) . concat++selectionLaws :: Selection.SelectionRequest -> Selection.Selection -> PropertyT IO ()+selectionLaws request result = do+ let selected = Selection.selected result+ references = map Utxo.input selected+ eligible = Selection.preselected request ++ Selection.available request+ selectedAmounts = quantitySum (map (Value.toList . Output.value . Utxo.output) selected)+ spentAndChange = quantitySum (Value.toList (Selection.target request) : map (Value.toList . Output.value) (Selection.change result))+ remainingReferences = Set.fromList (map Utxo.input (Selection.remaining result))+ selectedReferences = Set.fromList references+ assert (all (`elem` eligible) selected)+ length references === Set.size selectedReferences+ assert (all (`elem` selected) (Selection.preselected request))+ remainingReferences === Set.difference (Set.fromList (map Utxo.input (Selection.available request))) selectedReferences+ length (Selection.remaining result) === Set.size remainingReferences+ selectedAmounts === spentAndChange+ forM_ (Selection.change result) $ \output -> do+ Output.address output === Selection.changeAddress request+ assert (all ((>= 0) . snd) (Value.toList (Output.value output)))+ -- All generated outputs have minimum Ada in the 5-byte CBOR coin range.+ -- Calculate its Babbage UTxO cost with a fixed-width placeholder, so no+ -- native minimum-Ada call or native arithmetic supplies the expectation.+ placeholder <- evalEither (Output.mkOutput (Output.address output) (Value.fromList ((Asset.Ada, 1000000) : filter ((/= Asset.Ada) . fst) (Value.toList (Output.value output)))) Datum.NoDatum Nothing)+ let minimumAda = (160 + toInteger (B.length (Output.encodeCbor placeholder))) * 4310+ assert (minimumAda >= 65536 && minimumAda <= 4294967295)+ assert (Map.findWithDefault 0 Asset.Ada (quantitySum [Value.toList (Output.value output)]) >= minimumAda)++fixtureAssets :: IO [Asset.AssetId]+fixtureAssets = do+ policies <- mapM (must . Policy.fromBytes . B.replicate 28) [9, 10]+ names <- mapM (must . Name.fromBytes . B.singleton) [1 .. 8]+ pure [Asset.Native policy name | name <- names, policy <- policies]++genBundles :: [Asset.AssetId] -> Gen [[(Asset.AssetId, Integer)]]+genBundles assets = do+ count <- Gen.int (Range.linear 1 8)+ assetCount <- Gen.int (Range.linear 1 6)+ Gen.list (Range.singleton count) $ do+ coin <- Gen.integral (Range.linear 30000000 100000000)+ amounts <- Gen.list (Range.singleton assetCount) (Gen.integral (Range.linear 1 10000))+ pure ((Asset.Ada, coin) : zip assets amounts)++seededAlgorithms :: Word64 -> [Selection.Selector]+seededAlgorithms seed = [Selection.largestFirst, Selection.randomImproveWithSeed seed, Selection.randomImproveWithOptions seed Selection.Minimal]++propMultiassetSelection :: Property+propMultiassetSelection = property $ do+ assets <- evalIO fixtureAssets+ bundles <- forAll (genBundles assets)+ seed <- forAll (Gen.word64 Range.constantBounded)+ exact <- forAll Gen.bool+ overlap <- forAll Gen.bool+ mandatory <- forAll Gen.bool+ classify "exact supply" exact+ classify "surplus supply" (not exact)+ classify "overlapping mandatory input" (mandatory && overlap)+ classify "multiple policies" (any ((> 2) . length) bundles)+ let total = quantitySum bundles+ requested = if exact then total else Map.map (`div` 2) total+ base <- evalIO (requestFor (map Value.fromList bundles) (Value.fromList (Map.toList requested)))+ request <- case Selection.available base of+ first : rest | mandatory -> evalEither (Selection.mkSelectionRequest ((options base) {Selection.selectionPreselected = [first], Selection.selectionAvailable = if overlap then first : rest else rest}))+ _ -> pure base+ forM_ (seededAlgorithms seed) $ \selector -> do+ result <- evalIO (Selection.select selector request) >>= evalEither+ selectionLaws request result+ -- Check marshaled snapshots against the generated quantities as well as+ -- conservation: altered input quantities must not satisfy the oracle.+ forM_ (Selection.selected result) $ \selected ->+ assert (Value.toList (Output.value (Utxo.output selected)) `elem` map (Map.toAscList . quantitySum . (: [])) bundles)+ if exact then Selection.change result === [] else assert (not (null (Selection.change result)))++propInsufficientSupply :: Property+propInsufficientSupply = property $ do+ assets <- evalIO fixtureAssets+ bundles <- forAll (genBundles assets)+ seed <- forAll (Gen.word64 Range.constantBounded)+ missingCoin <- forAll Gen.bool+ deficit <- forAll (Gen.integral (Range.linear 1 10000))+ classify "insufficient Ada" missingCoin+ classify "insufficient native asset" (not missingCoin)+ let total = quantitySum bundles+ missingAsset <- if missingCoin then pure Asset.Ada else forAll (Gen.element (Map.keys (Map.delete Asset.Ada total)))+ let requested = Map.insertWith (+) missingAsset deficit total+ request <- evalIO (requestFor (map Value.fromList bundles) (Value.fromList (Map.toList requested)))+ forM_ (seededAlgorithms seed) $ \selector -> do+ result <- evalIO (Selection.select selector request)+ case result of+ Left (NativeError _ code _) -> Code.toNumber code === 1100+ _ -> assert False++propSplitBundles :: Property+propSplitBundles = property $ do+ assets <- evalIO fixtureAssets+ count <- forAll (Gen.int (Range.linear 4 16))+ limit <- forAll (Gen.int (Range.linear 65 80))+ amount <- forAll (Gen.element [1, 23, 24, 255, 256, 65535, 65536, 4294967295, 4294967296, toInteger (maxBound :: Int64)])+ seed <- forAll (Gen.word64 Range.constantBounded)+ classify "signed int64 quantity endpoint" (amount == toInteger (maxBound :: Int64))+ classify "quantity above word32" (amount > 4294967295)+ let raw = (Asset.Ada, 500000000) : [(asset, amount) | asset <- take count assets]+ base <- evalIO (requestFor [Value.fromList raw] (Value.lovelace 1000000))+ request <- evalEither (Selection.mkSelectionRequest ((options base) {Selection.selectionParameters = (Selection.parameters base) {Parameters.parameterMaxValueSize = Just (fromIntegral limit)}}))+ forM_ (seededAlgorithms seed) $ \selector -> do+ result <- evalIO (Selection.select selector request) >>= evalEither+ selectionLaws request result+ assert (length (Selection.change result) > 1)+ forM_ (Selection.change result) $ \output -> do+ let quantities = Value.toList (Output.value output)+ assert (all (\(_, quantity) -> quantity <= toInteger (maxBound :: Int64)) quantities)+ -- The native bundle assessment reserves the total Ada supply width.+ -- Public CBOR encoding independently measures the resulting ledger value.+ bytes <- evalEither (Value.encodeCbor (Value.fromList ((Asset.Ada, 45000000000000000) : filter ((/= Asset.Ada) . fst) quantities)))+ assert (B.length bytes <= limit)
@@ -0,0 +1,239 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++module NativeEvaluation (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.AssetId as AssetId+import qualified Cometa.AssetName as AssetName+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Evaluation.Native as Native+import qualified Cometa.Internal.Evaluation.Native as Internal+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SlotConfig as Slots+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException)+import Control.Monad (forM_, replicateM_)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Text (Text)+import qualified Data.Text as Text+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Native evaluation"+ [ testCase "V1 through V4 execute without changing exact transaction bytes" successes,+ testCase "phase-2 and deserialisation failures retain status and diagnostics" failures,+ testCase "subtargets evaluate all levels with a global budget" subtargets,+ testCase "cost models determine consumed units" costModels,+ testCase "complete resolution and validity bounds are checked" validation,+ testCase "sublevel resolution and schedule endpoints are checked" subValidation,+ testCase "partial transport failures and repeated calls release resources" lifecycle,+ testCase "concurrent requests own independent evaluator state" concurrency+ ]++config :: Native.Config+config = Native.Config Slots.preview 12 Models.empty++run :: Native.Config -> Evaluation.Target -> Tx.Transaction -> IO (Either Error Evaluation.Budgets)+run context target tx = Evaluation.evaluate (Native.evaluator context) target tx []++-- Derived from Apache-2.0 cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1+-- lib/tests/uplc/native_tx_evaluator.cpp build_succeeds_program_cbor,+-- build_v3_script and build_v4_script. These are single-CBOR-wrapped Flat+-- lambda/unit and lambda/error programs, assembled below through public values.+program :: Plutus.Version -> Bool -> Text+program language succeeds = case (language, succeeds) of+ (Plutus.V1, True) -> "46010000224981"+ (Plutus.V1, False) -> "450100002261"+ (Plutus.V2, True) -> "46010000224981"+ (Plutus.V2, False) -> "450100002261"+ (Plutus.V4, True) -> "450101002499"+ (Plutus.V4, False) -> "450101002601"+ (_, True) -> "450100002499"+ (_, False) -> "450100002601"++mintLevel :: Plutus.Version -> Text -> IO (Either Error (Fields.Fields, Witnesses.EncodedWitnesses))+mintLevel language code = runExceptT $ do+ bytes <- except (maybe (Left InvalidHex) Right (Hex.decodeHex code))+ script <- except (Plutus.fromBytes language bytes)+ digest <- ExceptT (Plutus.hash script)+ mint <- except (Fields.mkMint (Value.singleton (AssetId.Native (Policy.fromScriptHash digest) AssetName.empty) 1))+ argument <- except (Data.decodeCbor (B.pack [0x18, 0]))+ witnesses <- except (Witnesses.mkWitnesses [] [] [Script.Plutus script] [] [Redeemer.Redeemer Redeemer.Minting 0 argument (ExUnits 9 11)])+ pure ((Fields.fields [] []) {Fields.fieldMint = Just mint}, Witnesses.fromWitnesses witnesses)++transaction :: Plutus.Version -> Text -> IO Tx.Transaction+transaction language code = do+ (fields, witnesses) <- mintLevel language code >>= require+ body <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = fields})+ pure (Tx.assemble body witnesses Nothing)++successes :: IO ()+successes = forM_ [minBound .. maxBound] $ \language -> do+ original <- transaction language (program language True)+ let bytes = B.singleton 0x9f <> B.drop 1 (Tx.encodeCbor original) <> B.singleton 0xff+ tx <- require (Tx.decodeCbor bytes)+ result <- run config Evaluation.TopLevel tx >>= require+ case Evaluation.budgets result of+ [(Evaluation.RedeemerId Redeemer.Minting 0, ExUnits consumedMemory consumedSteps)] -> assertBool "positive consumed units" (consumedMemory > 0 && consumedSteps > 0)+ other -> assertFailure (show other)+ Tx.encodeCbor tx @?= bytes+ map Redeemer.executionUnits (Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses tx))) @?= [ExUnits 9 11]++failures :: IO ()+failures = do+ forM_ [minBound .. maxBound] $ \language -> do+ tx <- transaction language (program language False)+ run config Evaluation.TopLevel tx >>= expectNative Code.ScriptEvaluationFailure+ malformed <- transaction Plutus.V4 "41ff"+ run config Evaluation.TopLevel malformed >>= expectNative Code.DecodingFailure+ unavailable <- transaction Plutus.V4 (program Plutus.V4 True)+ run config {Native.protocolMajor = 10} Evaluation.TopLevel unavailable >>= expectNative Code.DecodingFailure++withSub :: Tx.Transaction -> Plutus.Version -> Bool -> IO Tx.Transaction+withSub tx language succeeds = do+ (fields, witnesses) <- mintLevel language (program language succeeds) >>= require+ subBody <- require (SubBody.fromBody (SubBody.fromFields fields))+ body <- require (Body.fromBody (Body.toBody (Tx.body tx)) {Body.bodySubTransactions = Just [Sub.assemble subBody witnesses Nothing]})+ pure (Tx.assemble body (Tx.witnesses tx) Nothing)++subtargets :: IO ()+subtargets = do+ top <- transaction Plutus.V4 (program Plutus.V4 True)+ tx <- withSub top Plutus.V4 True+ expected <- run config Evaluation.TopLevel tx >>= require+ run config (Evaluation.SubTransaction 0) tx >>= (@?= Right expected)+ run config (Evaluation.SubTransaction maxBound) tx >>= assertBool "target bounds" . isLeft+ bad <- withSub top Plutus.V4 False+ run config Evaluation.TopLevel bad >>= expectNative Code.ScriptEvaluationFailure+ run config (Evaluation.SubTransaction 0) bad >>= expectNative Code.ScriptEvaluationFailure+ old <- withSub top Plutus.V3 True+ run config Evaluation.TopLevel old >>= expectNative Code.InvalidScriptLanguage+ expensive <- require (Models.mkCostModel 3 (replicate 251 12000000))+ let limited = config {Native.costModels = Models.fromList [expensive]}+ run limited Evaluation.TopLevel top >>= require >>= \units -> assertBool "one expensive script fits" (not (null (Evaluation.budgets units)))+ run limited Evaluation.TopLevel tx >>= expectNative Code.ScriptEvaluationFailure++costModels :: IO ()+costModels = do+ tx <- transaction Plutus.V4 (program Plutus.V4 True)+ actual <- run config Evaluation.TopLevel tx >>= require+ map snd (Evaluation.budgets actual) @?= [ExUnits 500 64100]+ model <- require (Models.mkCostModel 3 (replicate 251 200))+ custom <- run config {Native.costModels = Models.fromList [model]} Evaluation.TopLevel tx >>= require+ map snd (Evaluation.budgets custom) @?= [ExUnits 1000 1000]+ invalid <- require (Models.mkCostModel 3 [1])+ run config {Native.costModels = Models.fromList [invalid]} Evaluation.TopLevel tx >>= assertBool "invalid model rejected" . isLeft++validation :: IO ()+validation = do+ resolved <- require (maybe (Left InvalidHex) Utxo.decodeCbor (Hex.decodeHex "8282582000000000000000000000000000000000000000000000000000000000000000000082581d600000000000000000000000000000000000000000000000000000000001"))+ let input = Utxo.input resolved+ body <- require (Body.fromBody (Body.body [input] [] 0))+ let tx = Tx.fromBody body+ run config Evaluation.TopLevel tx >>= assertBool "missing spending input" . isLeft+ empty <- require (Evaluation.mkBudgets [])+ Evaluation.evaluate (Native.evaluator config) Evaluation.TopLevel tx [resolved] >>= (@?= Right empty)+ Evaluation.evaluate (Native.evaluator config) Evaluation.TopLevel tx [resolved, resolved] >>= assertBool "duplicate resolution" . isLeft+ let fields = (Fields.fields [] []) {Fields.fieldReferenceInputs = Just [input]}+ refBody <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = fields})+ run config Evaluation.TopLevel (Tx.fromBody refBody) >>= assertBool "missing reference input" . isLeft+ forM_ [fields {Fields.fieldInvalidAfter = Just maxBound}, fields {Fields.fieldInvalidBefore = Just maxBound}] $ \bounds -> do+ bounded <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = bounds {Fields.fieldReferenceInputs = Nothing}})+ run config Evaluation.TopLevel (Tx.fromBody bounded) >>= assertBool "slot overflow" . isLeft++subValidation :: IO ()+subValidation = do+ resolved <- require (maybe (Left InvalidHex) Utxo.decodeCbor (Hex.decodeHex "8282582000000000000000000000000000000000000000000000000000000000000000000082581d600000000000000000000000000000000000000000000000000000000001"))+ empty <- require (Evaluation.mkBudgets [])+ top <- require (Body.fromBody (Body.body [] [] 0))+ Evaluation.evaluate (Native.evaluator config) Evaluation.TopLevel (Tx.fromBody top) [resolved] >>= (@?= Right empty)+ let reference = Utxo.input resolved+ incomplete = (Fields.fields [reference] []) {Fields.fieldReferenceInputs = Just [reference]}+ subBody <- require (SubBody.fromBody (SubBody.fromFields incomplete))+ body <- require (Body.fromBody (Body.body [] [] 0) {Body.bodySubTransactions = Just [Sub.assemble subBody (Witnesses.fromWitnesses Witnesses.empty) Nothing]})+ let tx = Tx.fromBody body+ run config Evaluation.TopLevel tx >>= assertBool "missing sublevel resolution" . isLeft+ Evaluation.evaluate (Native.evaluator config) (Evaluation.SubTransaction 0) tx [resolved] >>= (@?= Right empty)+ belowReference <- require (SubBody.fromBody (SubBody.fromFields ((Fields.fields [] []) {Fields.fieldInvalidBefore = Just 0})))+ earlyBody <- require (Body.fromBody (Body.body [] [] 0) {Body.bodySubTransactions = Just [Sub.assemble belowReference (Witnesses.fromWitnesses Witnesses.empty) Nothing]})+ run config {Native.slotConfig = Slots.mainnet} Evaluation.TopLevel (Tx.fromBody earlyBody) >>= assertBool "sublevel slot before reference" . isLeft+ extreme <- require (Slots.mkSlotConfig maxBound 0 1)+ endBody <- require (Body.fromBody (Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldInvalidAfter = Just 0}})+ run config {Native.slotConfig = extreme} Evaluation.TopLevel (Tx.fromBody endBody) >>= (@?= Right empty)++lifecycle :: IO ()+lifecycle = do+ tx <- transaction Plutus.V4 (program Plutus.V4 True)+ replicateM_ 20 $ do+ run config Evaluation.TopLevel tx >>= require >>= \units -> assertBool "repeat" (not (null (Evaluation.budgets units)))+ Internal.runUnchecked config Evaluation.TopLevel (Tx.encodeCbor tx <> B.singleton 0) (B.singleton 0x80) >>= assertBool "trailing tx" . isLeft+ Internal.runUnchecked config Evaluation.TopLevel (Tx.encodeCbor tx) (B.pack [0x81, 0]) >>= assertBool "partial UTxO" . isLeft++concurrency :: IO ()+concurrency = do+ tx <- transaction Plutus.V4 (program Plutus.V4 True)+ first <- newEmptyMVar+ second <- newEmptyMVar+ let execute slot = do+ _ <- forkFinally (run config Evaluation.TopLevel tx) (putMVar slot)+ pure ()+ execute first+ execute second+ left <- takeMVar first >>= joined+ right <- takeMVar second >>= joined+ left @?= right+ where+ joined :: Either SomeException (Either Error Evaluation.Budgets) -> IO Evaluation.Budgets+ joined = either (\failure -> assertFailure (show failure) >> fail "unreachable") require++expectNative :: Code.ErrorCode -> Either Error a -> IO ()+expectNative expected result = case result of+ Left (NativeError operation status diagnostic) -> do+ operation @?= "evaluation.native"+ status @?= expected+ assertBool "copied native diagnostic" (not (Text.null diagnostic))+ other -> case other of+ Left failure -> assertFailure (show failure)+ Right _ -> assertFailure "expected native failure"++require :: Either Error a -> IO a+require = either (\failure -> assertFailure (show failure) >> fail "unreachable") pure
@@ -0,0 +1,348 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Complete native-example flows with actual native building/VM/signing and+-- an in-memory provider. The provider is not a consensus ledger emulator.+module NativeWorkflows (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import Cometa.Error (Error (..))+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.Provider as Provider+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Signer as Signer+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Builder as SubBuilder+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (unless)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (atomicModifyIORef', modifyIORef', newIORef, readIORef)+import Data.List (find)+import qualified DeferredRedeemerBatch as Workflow (runDeferredBatch)+import qualified DeferredRedeemerSelfIndex as Workflow (runDeferredSelf)+import qualified Fixtures.Swap as Swap+import qualified Fixtures.TransactionWorkflows as Workflow hiding (runDeferredBatch, runDeferredSelf, runGuardedSub, runLockSpend, runSignedBatch)+import qualified Fixtures.Workflow as Fixture+import qualified PlutusV4GuardedSubTransaction as Workflow (runGuardedSub, runSignedBatch)+import qualified SpendFromValidator as Workflow (runLockSpend)+import qualified Support.Scripts as Scripts+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Native end-to-end examples"+ [ testCase "payment queries, signs, submits and confirms" payment,+ testCase "native mint then burn" nativeMint,+ testCase "Plutus mint then burn" plutusMint,+ testCase "native script funding then spend" nativeSpend,+ testCase "validator reference-script funding then spend" plutusSpend,+ testCase "actual Aiken self index and order pairing" deferredSpends,+ testCase "actual self-index validator rejects a wrong index" invalidIndex,+ testCase "key reward account registration and cleanup" keyRewards,+ testCase "script reward account registration and cleanup" scriptRewards,+ testCase "zero withdrawal forwards canonical input indices" withdrawZero,+ testCase "key and script DRep lifecycles" dreps,+ testCase "key and script governance voting lifecycles" votes,+ testCase "treasury withdrawal policy and donation" treasury,+ testCase "signed local intent reaches a complete batch" batch,+ testCase "buyer/seller token exchange preserves both independent signatures" swap,+ testCase "actual V4 validator and guard compose in a signed batch" guardedBatch,+ testCase "confirmation timeout prevents dependent stages" confirmation,+ testCase "confirmed wallet indexing waits for created and consumed outputs" indexLag,+ testCase "wallet indexing timeout stops without resubmitting" indexTimeout,+ testCase "invalid signatures refuse fixture submission without changing state" invalidSignature+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++execute :: Int -> (Workflow.Context -> Fixture.Fixture -> IO (Either Error a)) -> IO ()+execute expected action = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ _ <- ExceptT (action context fixture)+ transactions <- ExceptT (Right <$> Fixture.submitted fixture)+ except (unless (length transactions == expected) (Left (InvalidBuildingRequest "Unexpected workflow stage count")))+ _ <- must result+ pure ()++payment :: IO ()+payment = execute 1 (\context _ -> Workflow.runPayment context (Workflow.wallet context) 2000000)++nativeMint :: IO ()+nativeMint = execute 2 $ \context fixture ->+ Workflow.runMintBurn context (Script.Native (Native.signature (Fixture.paymentHash fixture))) Nothing AssetName.empty 3++plutusMint :: IO ()+plutusMint = execute 3 $ \context _ -> runExceptT $ do+ script <- ExceptT Scripts.alwaysSucceedsV3+ output <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 30000000) Datum.NoDatum (Just (Script.Plutus script)))+ funded <- ExceptT (Workflow.runStage context (Plan.payTo output))+ identifier <- ExceptT (Tx.transactionId funded)+ references <- ExceptT (Provider.resolveInputs (Workflow.provider context) [Input.input identifier 0])+ reference <- except $ case references of+ [value] -> Right value+ _ -> Left (InvalidBuildingRequest "Reference script did not resolve exactly once")+ ExceptT (Workflow.runMintBurn context (Script.Plutus script) (Just reference) AssetName.empty 3)++nativeSpend :: IO ()+nativeSpend = execute 2 $ \context fixture ->+ Workflow.runLockSpend context (Script.Native (Native.signature (Fixture.paymentHash fixture))) 4000000++plutusSpend :: IO ()+plutusSpend = execute 2 $ \context _ -> do+ script <- Scripts.alwaysSucceedsV3 >>= must+ Workflow.runLockSpend context (Script.Plutus script) 4000000++deferredSpends :: IO ()+deferredSpends = do+ execute 2 $ \context _ -> runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.selfIndex+ transactions <- ExceptT (Workflow.runDeferredSelf context script)+ except (checkDeferredTransactions script [1000000] transactions)+ execute 3 $ \context _ -> runExceptT $ do+ script <- Script.Plutus <$> ExceptT Scripts.orderPairing+ transactions <- ExceptT (Workflow.runDeferredBatch context script)+ except (checkDeferredTransactions script [1200000, 1500000] transactions)++checkDeferredTransactions :: Script.Script -> [Integer] -> [Tx.Transaction] -> Either Error ()+checkDeferredTransactions script payouts transactions = case reverse transactions of+ settled : funding -> do+ let fields = Body.bodyFields . Body.toBody . Tx.body+ outputs = Fields.fieldOutputs . fields+ fundedAmounts = map (map Output.value . take 1 . outputs) funding+ paidAmounts = map Output.value (take (length payouts) (outputs settled))+ noReferences = all (maybe True null . Fields.fieldReferenceInputs . fields) transactions+ noDeployments = all (all ((== Nothing) . Output.referenceScript) . outputs) transactions+ inlineWitness = script `elem` Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses settled))+ unless (length funding == length payouts && all (== [Value.lovelace 2000000]) fundedAmounts) (Left (InvalidBuildingRequest "Deferred funding must match the source's two-ADA orders"))+ unless (paidAmounts == map Value.lovelace payouts) (Left (InvalidBuildingRequest "Deferred explicit payouts differ from the source"))+ unless (noReferences && noDeployments && inlineWitness) (Left (InvalidBuildingRequest "Deferred settlement must attach its script inline without reference deployments"))+ [] -> Left (InvalidBuildingRequest "Missing deferred workflow transactions")++invalidIndex :: IO ()+invalidIndex = execute 1 $ \context fixture -> runExceptT $ do+ script <- ExceptT Scripts.selfIndex+ digest <- ExceptT (Script.hash (Script.Plutus script))+ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.ScriptCredential digest))+ output <- except (Output.mkOutput address (Value.lovelace 4000000) (Datum.InlineDatum Workflow.voidArgument) Nothing)+ _ <- ExceptT (Workflow.runStage context (Plan.payTo output))+ values <- ExceptT (Right <$> Fixture.currentUtxos fixture)+ locked <- except (maybe (Left (InvalidBuildingRequest "Missing funded script")) Right (find ((== address) . Output.address . Utxo.output) values))+ let wrong = Data.fromData (Data.Constr 0 [Data.Integer 999])+ result <- ExceptT (Right <$> Workflow.runStage context (Plan.spendWith locked (Just wrong) Nothing <> Plan.attachScript (Script.Plutus script)))+ except (unless (isLeft result) (Left (InvalidBuildingRequest "Actual self-index validator accepted an invalid argument")))++pool :: IO (Credential.KeyHash Credential.StakePool)+pool = must (Credential.keyHashFromBytes (B.replicate 28 10))++metadata :: IO Anchor.Anchor+metadata = do+ url <- must (Anchor.mkUrl "https://example.com/native-workflow")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 0))+ pure (Anchor.Anchor url digest)++keyRewards :: IO ()+keyRewards = execute 2 $ \context fixture -> do+ operator <- pool+ Workflow.runRewardCycle context (Fixture.stakeCredential fixture) Nothing operator 2000000++scriptRewards :: IO ()+scriptRewards = execute 2 $ \context _ -> do+ script <- Scripts.alwaysSucceedsV2 >>= must+ digest <- Script.hash (Script.Plutus script) >>= must+ operator <- pool+ Workflow.runRewardCycle context (Credential.ScriptCredential digest) (Just (Script.Plutus script)) operator 2000000++withdrawZero :: IO ()+withdrawZero = execute 2 $ \context _ -> do+ script <- Scripts.withdrawZero >>= must+ digest <- Script.hash (Script.Plutus script) >>= must+ operator <- pool+ Workflow.runWithdrawZero context (Credential.ScriptCredential digest) (Script.Plutus script) operator 2000000++dreps :: IO ()+dreps = do+ execute 4 $ \context fixture -> do+ anchor <- metadata+ Workflow.runDRepCycle context (Fixture.drepCredential fixture) Nothing 2000000 (Fixture.stakeCredential fixture) 2000000 anchor+ execute 4 $ \context fixture -> do+ script <- Scripts.alwaysSucceedsV3 >>= must+ digest <- Script.hash (Script.Plutus script) >>= must+ anchor <- metadata+ Workflow.runDRepCycle context (Credential.ScriptCredential digest) (Just (Script.Plutus script)) 2000000 (Fixture.stakeCredential fixture) 2000000 anchor++votes :: IO ()+votes = do+ previous <- must (Id.fromBytes (B.replicate 32 11))+ anchor <- metadata+ let action = ActionId.ActionId previous 0+ execute 3 $ \context fixture -> Workflow.runVoteCycle context (Fixture.drepCredential fixture) Nothing 2000000 anchor action+ execute 3 $ \context _ -> do+ script <- Scripts.alwaysSucceedsV3 >>= must+ digest <- Script.hash (Script.Plutus script) >>= must+ Workflow.runVoteCycle context (Credential.ScriptCredential digest) (Just (Script.Plutus script)) 2000000 anchor action++treasury :: IO ()+treasury = execute 2 $ \context fixture -> runExceptT $ do+ script <- ExceptT Scripts.alwaysSucceedsV3+ anchor <- ExceptT (Right <$> metadata)+ let account = Reward.fromCredential Network.testnet (Fixture.stakeCredential fixture)+ _ <- ExceptT (Workflow.runTreasuryWithdrawal context account 1000 (Script.Plutus script) anchor)+ ExceptT (Workflow.runDonation context 100000)++batch :: IO ()+batch = execute 2 $ \context fixture -> runExceptT $ do+ -- Keep separate ordinary wallet funding for the outer batcher, as the native+ -- example does; the independently signed intent spends only output zero.+ funding <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 50000000) Datum.NoDatum Nothing)+ prepared <- ExceptT (Workflow.runStage context (Plan.payTo funding))+ identifier <- ExceptT (Tx.transactionId prepared)+ inputs <- ExceptT (Provider.resolveInputs (Workflow.provider context) [Input.input identifier 0])+ input <- except $ case inputs of+ [value] -> Right value+ _ -> Left (InvalidBuildingRequest "Prepared local input did not resolve exactly once")+ params <- ExceptT (Provider.protocolParameters (Workflow.provider context))+ output <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 10000000) Datum.NoDatum Nothing)+ let intent = SubPlan.spend input <> SubPlan.payTo output+ local <- ExceptT (SubBuilder.build (SubBuilder.Config params (Workflow.slots context) Fields.Testnet) intent)+ signed <- ExceptT (Fixture.signIntent fixture local)+ transaction <- ExceptT (Workflow.runSignedBatch context [(signed, SubPlan.resolvedInputs intent)] mempty)+ let actual = fmap (map Sub.encodeCbor) (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ except (unless (actual == Just [Sub.encodeCbor signed]) (Left (InvalidBuildingRequest "Signed intent bytes changed")))+ pure transaction++confirmation :: IO ()+confirmation = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ let backend = (Workflow.provider context) {Provider.awaitTransaction = \_ _ -> pure (Right False)}+ changed = context {Workflow.provider = backend}+ attempt <- ExceptT (Right <$> Workflow.runMintBurn changed (Script.Native (Native.signature (Fixture.paymentHash fixture))) Nothing AssetName.empty 1)+ except (unless (isLeft attempt) (Left (InvalidBuildingRequest "Timeout did not abort flow")))+ transactions <- ExceptT (Right <$> Fixture.submitted fixture)+ except (unless (length transactions == 1) (Left (InvalidBuildingRequest "Dependent burn ran after timeout")))+ _ <- must result+ pure ()++guardedBatch :: IO ()+guardedBatch = execute 2 $ \context fixture -> do+ validator <- Scripts.v4Validator >>= must+ guard <- Scripts.v4Guard >>= must+ Workflow.runGuardedSub context (Script.Plutus validator) (Script.Plutus guard) (Fixture.signIntent fixture)++swap :: IO ()+swap = do+ result <- Swap.runSwap >>= must+ Fixture.verifyTransaction (Swap.transaction result) >>= must+ let subs = Body.bodySubTransactions (Body.toBody (Tx.body (Swap.transaction result)))+ fmap (map Sub.encodeCbor) subs @?= Just [Sub.encodeCbor (Swap.buyerIntent result), Sub.encodeCbor (Swap.sellerIntent result)]++invalidSignature :: IO ()+invalidSignature = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ before <- ExceptT (Right <$> Fixture.currentUtxos fixture)+ zero <- except (Signature.fromBytes (B.replicate 64 0))+ let wrongSigner = Signer.Signer $ \transaction -> runExceptT $ do+ original <- ExceptT (Signer.signTransaction (Workflow.signer context) transaction)+ let badWitnesses = [Witness.verificationWitness (Witness.publicKey witness) zero | witness <- Witnesses.verificationWitnesses (Witnesses.toWitnesses original)]+ Witnesses.fromWitnesses <$> except (Witnesses.mkWitnesses badWitnesses [] [] [] [])+ tamperedContext = context {Workflow.signer = wrongSigner}+ attempt <- ExceptT (Right <$> Workflow.runPayment tamperedContext (Workflow.wallet context) 2000000)+ except (unless (attempt == Left (InvalidBuildingRequest "Fixture verification witness does not verify against its transaction body")) (Left (InvalidBuildingRequest "Invalid fixture signature was accepted")))+ after <- ExceptT (Right <$> Fixture.currentUtxos fixture)+ history <- ExceptT (Right <$> Fixture.submitted fixture)+ except (unless (before == after && null history) (Left (InvalidBuildingRequest "Rejected signature changed fixture state")))+ _ <- must result+ pure ()++-- The address index may temporarily expose both newly created and already spent+-- outputs, or no outputs. Neither observation is a usable next-stage snapshot.+indexLag :: IO ()+indexLag = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ before <- liftIO (Fixture.currentUtxos fixture)+ queries <- liftIO (newIORef (0 :: Int))+ pauses <- liftIO (newIORef (0 :: Int))+ let original = Workflow.provider context+ backend =+ original+ { Provider.utxosAt = \address -> do+ number <- atomicModifyIORef' queries (\count -> (count + 1, count))+ current <- Provider.utxosAt original address+ pure $ case number of+ 1 -> fmap (before <>) current+ 2 -> Right []+ _ -> current+ }+ changed = context {Workflow.provider = backend}+ output <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 2000000) Datum.NoDatum Nothing)+ _ <- ExceptT (Workflow.runStageWithIndexPolling (pure 0) (modifyIORef' pauses (+ 1)) changed (Plan.payTo output))+ pauseCount <- liftIO (readIORef pauses)+ queryCount <- liftIO (readIORef queries)+ transactions <- liftIO (Fixture.submitted fixture)+ except (unless (pauseCount == 2 && queryCount == 4 && length transactions == 1) (Left (InvalidBuildingRequest "Index lag did not wait for both created and consumed output visibility")))+ _ <- must result+ pure ()++indexTimeout :: IO ()+indexTimeout = do+ result <- Fixture.withFixture $ \context fixture -> runExceptT $ do+ before <- liftIO (Fixture.currentUtxos fixture)+ ticks <- liftIO (newIORef [0, 1000000])+ pauses <- liftIO (newIORef (0 :: Int))+ let original = Workflow.provider context+ backend = original {Provider.utxosAt = \_ -> pure (Right before)}+ changed = context {Workflow.provider = backend, Workflow.confirmationTimeoutMillis = 1}+ clock = atomicModifyIORef' ticks $ \case+ value : rest -> (rest, value)+ [] -> ([], 1000000)+ output <- except (Output.mkOutput (Workflow.wallet context) (Value.lovelace 2000000) Datum.NoDatum Nothing)+ attempt <- liftIO (Workflow.runStageWithIndexPolling clock (modifyIORef' pauses (+ 1)) changed (Plan.payTo output))+ transactions <- liftIO (Fixture.submitted fixture)+ pauseCount <- liftIO (readIORef pauses)+ except (unless (attempt == Left (InvalidBuildingRequest "Confirmed transaction is not yet reflected in the wallet index; dependent stages stopped") && length transactions == 1 && pauseCount == 0) (Left (InvalidBuildingRequest "Index timeout did not stop exactly once at its monotonic deadline")))+ _ <- must result+ pure ()
@@ -0,0 +1,319 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Independent pure numeric workflows compared with the pinned native numeric+-- constructors, getters and arithmetic. Oracle inputs exclude native abort/UB+-- domains; invalid public inputs are checked without entering those operations.+module NumericConversions (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Encoding.Integer as Integer+import Cometa.Error (Error (..))+import qualified Cometa.Metadata as Metadata+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.UnitInterval as Unit+import Control.Monad (forM_, replicateM_, when)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Text (Text)+import qualified Data.Text as T+import qualified Data.Text.Encoding as T+import Data.Word (Word64, Word8)+import Foreign.C.String (CString, peekCString, withCString)+import Foreign.C.Types (CDouble (..), CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Property, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)+import Text.Read (readMaybe)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Numeric conversions"+ [ testCase "all radix alphabets, signs and NUL-inclusive sizes match native" textRadices,+ testCase "uppercase rendering and automatic prefixes retain native lexical rules" textRules,+ testCase "radix validation and malformed text return structured errors" invalidText,+ testCase "metadata and arbitrary Plutus integer text use public validated constructors" domainIntegers,+ testCase "explicit byte orders encode unsigned magnitude including zero" byteOrders,+ testCase "modular inverses and signed powers match native arithmetic" modular,+ testCase "invalid modular domains are total before native abort boundaries" invalidModular,+ testCase "unit interval doubles follow decimal-floor and separate-cast semantics" doubles,+ testCase "nonfinite and out-of-interval doubles are rejected" invalidDoubles,+ testCase "numeric snapshots survive repeated native cleanup and GC" lifetime,+ testProperty "arbitrary radix signed integers round trip and match native" propText,+ testProperty "generated unit interval doubles match native reduced pairs" propDouble+ ]++numbers :: [Integer]+numbers = [0, 1, -1, 61, -255, 2 ^ (64 :: Int), negate (2 ^ (257 :: Int) + 1)]++textRadices :: IO ()+textRadices = forM_ [2 .. 62] $ \base -> do+ radix <- must (Integer.mkRadix base)+ forM_ numbers $ \number -> do+ let encoded = Integer.toText radix number+ Integer.fromText radix encoded @?= Right number+ (status, native, size) <- textOracle 0 base 10 encoded 8192+ status @?= 0+ readMaybe (T.unpack native) @?= Just number+ (rendered, nativeText, nativeSize) <- textOracle 0 10 base (T.pack (show number)) 8192+ rendered @?= 0+ nativeText @?= encoded+ nativeSize @?= T.length encoded + 1+ size @?= length (show number) + 1++textRules :: IO ()+textRules = do+ forM_ [2 .. 36] $ \base -> do+ radix <- must (Integer.mkRadix base)+ forM_ numbers $ \number -> do+ upper <- must (Integer.toUpperText radix number)+ (status, native, _) <- textOracle 0 10 (negate base) (T.pack (show number)) 8192+ status @?= 0+ native @?= upper+ Integer.fromText radix upper @?= Right number+ forM_ [("0", 0), ("077", 63), ("0xFF", 255), ("-0B101", -5), (" \t-0x 1 f\n", -31), ("123\0ignored", 123)] $ \(text, expected) -> do+ Integer.fromTextAuto text @?= Right expected+ (status, native, _) <- textOracle 0 0 10 text 8192+ status @?= 0+ readMaybe (T.unpack native) @?= Just expected+ forM_ ["- 0x10", "08", "+1", "0x", "--1"] $ \text -> do+ assertBool "invalid auto-radix input" (isLeft (Integer.fromTextAuto text))+ (status, _, _) <- textOracle 0 0 10 text 8192+ assertBool "native rejected same malformed prefix" (status /= 0)+ Integer.fromText Integer.hexadecimal " - f F \n" @?= Right (-255)+ forM_ [-1, 0, 1] $ \nativeBase -> do+ (status, native, _) <- textOracle 0 10 nativeBase "-123" 8192+ status @?= 0+ native @?= Integer.toText Integer.decimal (-123)++invalidText :: IO ()+invalidText = do+ forM_ [minBound, -36, 0, 1, 63, maxBound] $ \base -> Integer.mkRadix base @?= Left (InvalidIntegerRadix base)+ forM_ ["", " ", "+1", "1.0", "0xff", "12", "-", "\0ignored"] $ \text ->+ assertBool "invalid decimal integer text" (isLeft (Integer.fromText Integer.decimal text))+ radix <- must (Integer.mkRadix 62)+ Integer.fromText radix "Aa" @?= Right (10 * 62 + 36)+ Integer.toUpperText radix 1 @?= Left (InvalidIntegerRadix (-62))+ (status, _, _) <- textOracle 0 10 10 "123456" 1+ assertBool "short native output storage" (status /= 0)++domainIntegers :: IO ()+domainIntegers = do+ forM_ [2, 10, 16, 36, 37, 62] $ \base -> do+ radix <- must (Integer.mkRadix base)+ forM_ [negate (2 ^ (64 :: Int)), -1, 0, 2 ^ (64 :: Int) - 1] $ \number -> do+ let text = Integer.toText radix number+ metadata <- must (Metadata.integerFromText radix text)+ Metadata.view metadata @?= Metadata.IntegerValue number+ (status, native, _) <- textOracle 1 base 10 text 8192+ status @?= 0+ readMaybe (T.unpack native) @?= Just number+ forM_ numbers $ \number -> do+ let text = Integer.toText radix number+ plutus <- must (Data.integerFromText radix text)+ Data.toData plutus @?= Data.Integer number+ (status, native, _) <- textOracle 2 base 10 text 8192+ status @?= 0+ readMaybe (T.unpack native) @?= Just number+ Metadata.integerFromText Integer.decimal "18446744073709551616" @?= Left (InvalidMetadataInteger (2 ^ (64 :: Int)))+ assertBool "invalid Plutus integer text" (isLeft (Data.integerFromText Integer.decimal "1.2"))++byteOrders :: IO ()+byteOrders = do+ forM_ [Integer.LittleEndian, Integer.BigEndian] $ \order -> do+ Integer.fromBytes order B.empty @?= 0+ forM_ numbers $ \number -> do+ let bytes = Integer.toBytes order number+ Integer.fromBytes order bytes @?= abs number+ Integer.toBytes order 0 @?= B.singleton 0+ B.useAsCStringLen bytes $ \(input, count) -> allocaBytes 1024 $ \output -> allocaBytes 1024 $ \decimal -> do+ status <- cBytes (castPtr input) (fromIntegral count) (if order == Integer.LittleEndian then 1 else 0) (if number < 0 then 1 else 0) output 1024 decimal 1024+ status @?= 0+ encoded <- B.packCStringLen (castPtr output, B.length bytes)+ encoded @?= bytes+ native <- peekCString decimal+ readMaybe native @?= Just number+ Integer.toBytes Integer.BigEndian 258 @?= B.pack [1, 2]+ Integer.toBytes Integer.LittleEndian (-258) @?= B.pack [2, 1]++modular :: IO ()+modular = do+ forM_ [-17, -3, 1, 2, 3, 5, 7, 19, 2 ^ (127 :: Int) + 1] $ \value ->+ forM_ [-257, -11, -2, 2, 11, 257, 2 ^ (127 :: Int) - 1] $ \modulus ->+ when (gcd value modulus == 1) $ do+ inverse <- must (Integer.modularInverse value modulus)+ (value * inverse) `mod` abs modulus @?= 1+ native <- modularOracle False value 0 modulus+ native @?= Right inverse++ forM_ [-7, -1, 0, 1, 7, 2 ^ (128 :: Int) + 1] $ \value ->+ forM_ [-17, -1, 0, 1, 2, 33, 2 ^ (65 :: Int) + 3] $ \power ->+ forM_ [-257, -11, -1, 1, 11, 257, 2 ^ (127 :: Int) - 1] $ \modulus ->+ if power < 0 && (abs modulus <= 1 || gcd value modulus /= 1)+ then pure ()+ else do+ expected <- must (Integer.modularPower value power modulus)+ modularOracle True value power modulus >>= (@?= Right expected)+ when (power >= 0 && power <= 33 && abs modulus > 1) $ expected @?= value ^ power `mod` abs modulus++invalidModular :: IO ()+invalidModular = do+ forM_ [0, -1, 1] $ \modulus -> Integer.modularInverse 7 modulus @?= Left (InvalidModulus modulus)+ forM_ [(0, 7), (6, 9), (-12, -18)] $ \(value, modulus) -> do+ Integer.modularInverse value modulus @?= Left (NoModularInverse value modulus)+ native <- modularOracle False value 0 modulus+ assertBool "oracle guards native inverse failure" (isLeft native)+ forM_ [-1, 0, 1] $ \power -> do+ Integer.modularPower 7 power 0 @?= Left (InvalidModulus 0)+ modularOracle True 7 power 0 >>= assertBool "oracle guards zero modulus" . isLeft+ Integer.modularPower 6 (-1) 9 @?= Left (NoModularInverse 6 9)+ modularOracle True 6 (-1) 9 >>= assertBool "oracle guards negative exponent without inverse" . isLeft+ Integer.modularPower 7 0 1 @?= Right 1+ Integer.modularPower 7 1 1 @?= Right 0++doubles :: IO ()+doubles = do+ forM_ [0, -0, 1, 0.1, 0.3, 1 / 3, 0.9999999999999999, 1e-16, 1e-15, encodeFloat 1 (-1074)] $ \value -> checkDouble value+ third <- must (Unit.fromDouble (1 / 3))+ (Unit.numerator third, Unit.denominator third) @?= (333333333333333, 1000000000000000)+ tiny <- must (Unit.fromDouble 1e-16)+ (Unit.numerator tiny, Unit.denominator tiny) @?= (0, 1)+ forM_ [1.5, 2.75, 1000.125, 2 ^ (63 :: Int), 18446744073709549568] $ \number -> do+ value <- must (Rational.fromDouble number)+ alloca $ \n -> alloca $ \d -> alloca $ \approximate -> do+ status <- cUnitDouble (CDouble number) n d approximate+ status @?= 0+ nativeNumerator <- peek n+ nativeDenominator <- peek d+ CDouble nativeApproximate <- peek approximate+ (Rational.numerator value, Rational.denominator value) @?= (nativeNumerator, nativeDenominator)+ Rational.toDouble value @?= nativeApproximate+ forM_ [(0, 1), (1, 3), (2, 3), (maxBound - 1, maxBound)] $ \(n, d) -> do+ value <- must (Unit.mkUnitInterval (toInteger n) (toInteger d))+ alloca $ \output -> do+ status <- cUnitToDouble n d output+ status @?= 0+ CDouble approximate <- peek output+ Unit.toDouble value @?= approximate++invalidDoubles :: IO ()+invalidDoubles = do+ forM_ [0 / 0, 1 / 0, negate (1 / 0), -0.1, 1.0000000000000002] $ \value ->+ Unit.fromDouble value @?= Left InvalidUnitIntervalDouble+ forM_ [0 / 0, 1 / 0, negate (1 / 0), -0.1, 18446744073709551616] $ \value ->+ Rational.fromDouble value @?= Left InvalidProtocolDouble+ assertBool "fractional numerator overflow is rejected" (isLeft (Rational.fromDouble 100000.123456789))++checkDouble :: Double -> IO ()+checkDouble value = do+ interval <- must (Unit.fromDouble value)+ alloca $ \n -> alloca $ \d -> alloca $ \approximate -> do+ status <- cUnitDouble (CDouble value) n d approximate+ status @?= 0+ numerator <- peek n+ denominator <- peek d+ CDouble rounded <- peek approximate+ (Unit.numerator interval, Unit.denominator interval) @?= (numerator, denominator)+ Unit.toDouble interval @?= rounded++lifetime :: IO ()+lifetime = do+ (_, retained, _) <- textOracle 2 16 62 "-123456789abcdef0123456789abcdef" 8192+ replicateM_ 20 $ do+ textOracle 1 10 10 "invalid" 8192 >>= (\(status, _, _) -> assertBool "native parse failure" (status /= 0))+ modularOracle False 3 0 11 >>= (@?= Right 4)+ checkDouble 0.1+ performGC+ radix <- must (Integer.mkRadix 62)+ let parsed = Integer.fromText Integer.hexadecimal "-123456789abcdef0123456789abcdef"+ fmap (Integer.toText radix) parsed @?= Right retained++propText :: Property+propText = property $ do+ base <- forAll (Gen.int (Range.linear 2 62))+ value <- forAll (Gen.integral (Range.linear (negate (2 ^ (512 :: Int))) (2 ^ (512 :: Int))))+ case Integer.mkRadix base of+ Left failure -> evalIO (assertFailure (show failure))+ Right radix -> do+ let text = Integer.toText radix value+ Integer.fromText radix text === Right value+ (status, native, _) <- evalIO (textOracle 0 base 10 text 8192)+ status === 0+ readMaybe (T.unpack native) === Just value++propDouble :: Property+propDouble = property $ do+ value <- forAll (Gen.double (Range.linearFrac 0 1))+ evalIO (checkDouble value)++-- FUNCTIONS ------------------------------------------------------------------++must :: (Show e) => Either e a -> IO a+must (Right value) = pure value+must (Left failure) = assertFailure (show failure) >> fail "unreachable"++textOracle :: Int -> Int -> Int -> Text -> Int -> IO (CInt, Text, Int)+textOracle kind parseBase renderBase text capacity =+ B.useAsCStringLen (T.encodeUtf8 text) $ \(input, size) -> allocaBytes capacity $ \output -> alloca $ \required -> do+ status <- cText (fromIntegral kind) (fromIntegral parseBase) (fromIntegral renderBase) input (fromIntegral size) output (fromIntegral capacity) required+ if status /= 0+ then pure (status, "", 0)+ else do+ native <- T.pack <$> peekCString output+ count <- peek required+ pure (status, native, fromIntegral count)++modularOracle :: Bool -> Integer -> Integer -> Integer -> IO (Either CInt Integer)+modularOracle power value exponentValue modulus =+ withCString (show value) $ \input -> withCString (show exponentValue) $ \exponentInput -> withCString (show modulus) $ \modulusInput -> allocaBytes 8192 $ \output -> do+ status <- cModular (if power then 1 else 0) input exponentInput modulusInput output 8192+ if status /= 0+ then pure (Left status)+ else do+ text <- peekCString output+ case readMaybe text of+ Just result -> pure (Right result)+ Nothing -> assertFailure "malformed native modular result" >> pure (Left status)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_numeric_text"+ cText :: CInt -> CInt -> CInt -> CString -> CSize -> CString -> CSize -> Ptr CSize -> IO CInt++foreign import ccall unsafe "cometa_test_numeric_modular"+ cModular :: CInt -> CString -> CString -> CString -> CString -> CSize -> IO CInt++foreign import ccall unsafe "cometa_test_unit_double"+ cUnitDouble :: CDouble -> Ptr Word64 -> Ptr Word64 -> Ptr CDouble -> IO CInt++foreign import ccall unsafe "cometa_test_unit_to_double"+ cUnitToDouble :: Word64 -> Word64 -> Ptr CDouble -> IO CInt++foreign import ccall unsafe "cometa_test_integer_bytes"+ cBytes :: Ptr Word8 -> CSize -> Word8 -> Word8 -> Ptr Word8 -> CSize -> CString -> CSize -> IO CInt
@@ -0,0 +1,212 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Lifecycle regression tests against real native hash allocations. Injectable+-- acquisition and release steps exercise failures around the same owned slot.+module Ownership (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Internal.FFI.Native as Native+import Cometa.Internal.Failure (NativeFailure (..))+import Cometa.Internal.Ownership (copyHashResult, withOwnedOutput)+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), IOException, bracket, fromException, throwIO, try)+import Control.Monad (replicateM_)+import qualified Data.ByteString as ByteString+import Data.IORef (IORef, modifyIORef', newIORef, readIORef, writeIORef)+import Foreign.C.Types (CSize (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr, nullPtr)+import Foreign.Storable (peek, poke)+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++-- FOREIGN IMPORTS ------------------------------------------------------------++-- These imports stay test-only: they make a second ownership obligation visible+-- without exposing reference-count operations through the public Haskell API.+foreign import capi unsafe "cardano/crypto/blake2b_hash.h cardano_blake2b_hash_ref"+ cRef :: Ptr Native.NativeHash -> IO ()++foreign import capi unsafe "cardano/crypto/blake2b_hash.h cardano_blake2b_hash_refcount"+ cRefCount :: Ptr Native.NativeHash -> IO CSize++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Owned output scopes"+ [ testCase "copied hash survives release, allocations, and GC" checkCopiedSnapshot,+ testCase "success releases exactly once after the action" checkSuccessfulRelease,+ testCase "native failure after allocation releases partial output" checkPartialFailureRelease,+ testCase "action exception releases exactly once" checkActionException,+ testCase "acquisition exception after allocation releases exactly once" checkAcquisitionException,+ testCase "asynchronous cancellation after allocation releases before propagation" checkCancellation,+ testCase "retained reference survives non-nulling unref without double release" checkRetainedReference,+ testCase "null success is rejected without invoking destructor" checkNullSuccess,+ testCase "failure before output allocation does not invoke destructor" checkFailureBeforeAllocation+ ]++checkCopiedSnapshot :: IO ()+checkCopiedSnapshot = do+ result <- copyHashResult "ownership.snapshot" allocateHash+ replicateM_ 100 $ do+ _ <- copyHashResult "ownership.churn" allocateHash+ pure ()+ performGC++ result @?= Right expectedHash++checkSuccessfulRelease :: IO ()+checkSuccessfulRelease = do+ releases <- newIORef 0+ result <- withOwnedOutput "ownership.success" (countedRelease releases) allocateHash $ \hash -> do+ readIORef releases >>= (@?= 0)+ cRefCount hash >>= (@?= 1)+ pure (Right ())+ result @?= Right ()+ readIORef releases >>= (@?= 1)++checkPartialFailureRelease :: IO ()+checkPartialFailureRelease = do+ releases <- newIORef 0+ -- CARDANO_ERROR_INVALID_ARGUMENT in the pinned cardano/error.h.+ let acquire slot = allocateHash slot >> pure 7+ result <- withOwnedOutput "ownership.failure" (countedRelease releases) acquire unexpectedAction+ case result of+ Left (NativeFailure operation code message) -> do+ operation @?= "ownership.failure"+ code @?= 7+ message @?= "Invalid argument"+ other -> assertFailure (show other)+ readIORef releases >>= (@?= 1)++checkActionException :: IO ()+checkActionException = do+ releases <- newIORef 0+ expectException $+ withOwnedOutput "ownership.action" (countedRelease releases) allocateHash $ \_ ->+ throwIO (userError "injected action failure")+ readIORef releases >>= (@?= 1)++checkAcquisitionException :: IO ()+checkAcquisitionException = do+ releases <- newIORef 0+ let acquire slot = allocateHash slot >> throwIO (userError "injected acquisition failure")+ expectException (withOwnedOutput "ownership.acquire" (countedRelease releases) acquire unexpectedAction)+ readIORef releases >>= (@?= 1)++checkCancellation :: IO ()+checkCancellation = do+ releases <- newIORef 0+ ready <- newEmptyMVar+ blocked <- newEmptyMVar+ finished <- newEmptyMVar+ let acquire slot = do+ code <- allocateHash slot+ putMVar ready ()+ _ <- takeMVar blocked+ pure code++ worker <- forkFinally (withOwnedOutput "ownership.cancel" (countedRelease releases) acquire unexpectedAction) (putMVar finished)+ started <- timeout 5000000 (takeMVar ready)+ case started of+ Nothing -> killThread worker >> assertFailure "allocation did not finish"+ Just () -> killThread worker++ completed <- timeout 5000000 (takeMVar finished)+ case completed of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "cancellation did not propagate after cleanup"+ readIORef releases >>= (@?= 1)++checkRetainedReference :: IO ()+checkRetainedReference = alloca $ \retained ->+ bracket (poke retained nullPtr) (const (Native.cUnref retained)) $ \() -> do+ releases <- newIORef 0+ leftNonNull <- newIORef False+ let acquire slot = do+ code <- allocateHash slot+ hash <- peek slot+ cRef hash+ poke retained hash+ pure code+ release slot = do+ countedRelease releases slot+ pointer <- peek slot+ writeIORef leftNonNull (pointer /= nullPtr)++ result <- withOwnedOutput "ownership.retained" release acquire (const (pure (Right ())))+ result @?= Right ()+ readIORef releases >>= (@?= 1)+ readIORef leftNonNull >>= (@?= True)+ hash <- peek retained+ cRefCount hash >>= (@?= 1)+ Native.cSize hash >>= (@?= 32)++checkNullSuccess :: IO ()+checkNullSuccess = do+ releases <- newIORef 0+ result <- withOwnedOutput "ownership.null" (countedRelease releases) (const (pure Native.success)) unexpectedAction+ result @?= Left (NativeContractFailure "ownership.null")+ readIORef releases >>= (@?= 0)++checkFailureBeforeAllocation :: IO ()+checkFailureBeforeAllocation = do+ releases <- newIORef 0+ let acquire slot = do+ peek slot >>= (@?= nullPtr)+ throwIO (userError "injected failure before allocation")+ expectException (withOwnedOutput "ownership.empty" (countedRelease releases) acquire unexpectedAction)+ readIORef releases >>= (@?= 0)++-- Allocate a real native digest only after checking the helper initialized its+-- output slot. Assertions distinguish fixture setup failures from cleanup bugs.+allocateHash :: Ptr (Ptr Native.NativeHash) -> IO Native.NativeCode+allocateHash slot = do+ peek slot >>= (@?= nullPtr)+ ByteString.useAsCStringLen "abc" $ \(input, size) -> do+ code <- Native.cCompute (castPtr input) (fromIntegral size) 32 slot+ code @?= Native.success+ pure code++-- Count release attempts independently of whether native unref nulls the slot.+countedRelease :: IORef Int -> Ptr (Ptr Native.NativeHash) -> IO ()+countedRelease releases slot = do+ modifyIORef' releases (+ 1)+ Native.cUnref slot++-- Failed acquisition must never hand a pointer to the borrowed action.+unexpectedAction :: Ptr Native.NativeHash -> IO (Either NativeFailure ())+unexpectedAction _ = assertFailure "action ran without successful acquisition" >> pure (Right ())++-- Catch only the injected IO exception; assertion failures must still escape.+expectException :: IO (Either NativeFailure ()) -> IO ()+expectException action = do+ result <- try action :: IO (Either IOException (Either NativeFailure ()))+ case result of+ Left _ -> pure ()+ Right value -> assertFailure ("expected injected exception, got " ++ show value)++-- Independently checked using Python hashlib.blake2b(b"abc", digest_size=32).+expectedHash :: ByteString.ByteString+expectedHash = ByteString.pack [189, 221, 129, 60, 99, 66, 57, 114, 49, 113, 239, 63, 238, 152, 87, 155, 148, 150, 78, 59, 177, 203, 62, 66, 114, 98, 200, 192, 104, 213, 35, 25]
@@ -0,0 +1,148 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Production full snapshot conversion, actual native getters and presence.+module ParameterSnapshot (tests) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error)+import Cometa.Internal.FFI.Native (NativeCode)+import Cometa.Internal.FFI.Runtime (Buffer)+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Parameters.Update as Update+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.Word (Word8)+import qualified Fixtures.ProtocolParameters as Fixture+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Ptr (Ptr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Parameter snapshots"+ [ testCase "all 56 fields reconstruct through production full setters/getters" checkAll,+ testCase "native mutation is observed instead of echoing template" checkMutation,+ testCase "known-origin availability and nullable states survive native conversion" checkPresence,+ testCase "native-origin snapshot uses actual stored scalar values" checkNativeOrigin,+ testCase "native-origin older snapshot omits unset positive stride" checkHistorical,+ testCase "missing required fields and signed full-setter overflow fail" checkInvalid,+ testCase "repeated native reconstruction releases all owners" checkRepeated,+ testProperty "full snapshot scalar edits reconstruct without defaulting" propSnapshot+ ]++must :: (Show e) => Either e a -> IO a+must value = case value of+ Left failure -> assertFailure (show failure) >> fail "Invalid fixture"+ Right result -> pure result++roundtrip :: CUInt -> ByteString -> IO (Either Error ByteString)+roundtrip mode bytes = Runtime.withBytes bytes $ \input size -> Runtime.withOwnedBuffer "test.parameterSnapshot" (cSnapshot input size mode)++checkAll :: IO ()+checkAll = do+ parameters <- must Fixture.parameters+ let bytes = Snapshot.encodeSnapshot parameters+ reloaded <- roundtrip 0 bytes >>= must+ Snapshot.decodeSnapshot reloaded @?= Right parameters+ assertBool "fresh output is decoded schema, not assumed bytes" (not (B.null reloaded))++checkMutation :: IO ()+checkMutation = do+ parameters <- must Fixture.parameters+ reloaded <- roundtrip 1 (Snapshot.encodeSnapshot parameters) >>= must >>= must . Snapshot.decodeSnapshot+ reloaded @?= parameters {Parameters.parameterMinFeeA = Parameters.parameterMinFeeA parameters + 1}++checkPresence :: IO ()+checkPresence = do+ full <- must Fixture.parameters+ let absent = full {Parameters.parameterAdaPerUtxoByte = Nothing, Parameters.parameterDecentralization = Nothing, Parameters.parameterExtraEntropy = Nothing, Parameters.parameterMaxPledgeLeverage = Nothing, Parameters.parameterPerasBootstrapRound = Nothing, Parameters.parameterRefInputsCostPerDatumByte = Nothing, Parameters.parameterRefScriptCostStride = Nothing}+ unbounded = full {Parameters.parameterMaxPledgeLeverage = Just Nothing, Parameters.parameterPerasBootstrapRound = Just Nothing, Parameters.parameterExtraEntropy = Just Parameters.neutralNonce}+ forM_ [absent, unbounded] $ \parameters -> do+ reloaded <- roundtrip 0 (Snapshot.encodeSnapshot parameters) >>= must+ Snapshot.decodeSnapshot reloaded @?= Right parameters++checkNativeOrigin :: IO ()+checkNativeOrigin = do+ full <- must Fixture.parameters+ let source = full {Parameters.parameterAdaPerUtxoByte = Nothing, Parameters.parameterRefInputsCostPerDatumByte = Nothing, Parameters.parameterMaxPledgeLeverage = Nothing, Parameters.parameterPerasBootstrapRound = Nothing}+ snapshot <- roundtrip 2 (Snapshot.encodeSnapshot source) >>= must >>= must . Snapshot.decodeSnapshot+ Parameters.parameterAdaPerUtxoByte snapshot @?= Just 0+ Parameters.parameterRefInputsCostPerDatumByte snapshot @?= Just 0+ Parameters.parameterMaxPledgeLeverage snapshot @?= Just Nothing+ Parameters.parameterPerasBootstrapRound snapshot @?= Just Nothing+ Parameters.parameterMinFeeA snapshot @?= Parameters.parameterMinFeeA full++checkHistorical :: IO ()+checkHistorical = do+ full <- must Fixture.parameters+ let historical = full {Parameters.parameterDecentralization = Nothing, Parameters.parameterExtraEntropy = Nothing, Parameters.parameterAdaPerUtxoByte = Nothing, Parameters.parameterCostModels = Nothing, Parameters.parameterExecutionCosts = Nothing, Parameters.parameterMaxTxExUnits = Nothing, Parameters.parameterMaxBlockExUnits = Nothing, Parameters.parameterMaxValueSize = Nothing, Parameters.parameterCollateralPercentage = Nothing, Parameters.parameterMaxCollateralInputs = Nothing, Parameters.parameterPoolVotingThresholds = Nothing, Parameters.parameterDrepVotingThresholds = Nothing, Parameters.parameterMinCommitteeSize = Nothing, Parameters.parameterCommitteeTermLimit = Nothing, Parameters.parameterGovernanceActionValidityPeriod = Nothing, Parameters.parameterGovernanceActionDeposit = Nothing, Parameters.parameterDrepDeposit = Nothing, Parameters.parameterDrepInactivityPeriod = Nothing, Parameters.parameterRefScriptCostPerByte = Nothing, Parameters.parameterMaxRefScriptSizePerBlock = Nothing, Parameters.parameterMaxRefScriptSizePerTx = Nothing, Parameters.parameterRefScriptCostStride = Nothing, Parameters.parameterRefScriptCostMultiplier = Nothing, Parameters.parameterMaxPledgeLeverage = Nothing, Parameters.parameterMinPoolMargin = Nothing, Parameters.parameterLeiosAnnouncementPeriodLength = Nothing, Parameters.parameterLeiosVotePeriodLength = Nothing, Parameters.parameterLeiosDiffusionPeriodLength = Nothing, Parameters.parameterLeiosCommitteeSize = Nothing, Parameters.parameterLeiosQuorumStakeThreshold = Nothing, Parameters.parameterMaxEndorserBlockReferencesSize = Nothing, Parameters.parameterMaxEndorserBlockTxsSize = Nothing, Parameters.parameterMaxEndorserBlockExecutionUnits = Nothing, Parameters.parameterMaxRefScriptSizePerEndorserBlock = Nothing, Parameters.parameterPerasMinCandidateBlockAge = Nothing, Parameters.parameterPerasHealingFactor = Nothing, Parameters.parameterPerasCertBoost = Nothing, Parameters.parameterPerasTargetCommitteeSize = Nothing, Parameters.parameterPerasBootstrapRound = Nothing, Parameters.parameterPerasQuorumThresholdSafetyMargin = Nothing, Parameters.parameterRefInputsCostPerMultiAssetByte = Nothing, Parameters.parameterRefInputsCostPerDatumByte = Nothing}+ encoded <- roundtrip 2 (Snapshot.encodeSnapshot historical) >>= must+ decoded <- must (Snapshot.decodeSnapshot encoded)+ Parameters.parameterRefScriptCostStride decoded @?= Nothing+ Parameters.parameterAdaPerUtxoByte decoded @?= Just 0+ Parameters.parameterPoolPledgeInfluence decoded @?= Parameters.parameterPoolPledgeInfluence historical++checkInvalid :: IO ()+checkInvalid = do+ full <- must Fixture.parameters+ let sparse = Update.fromParameters full+ missing = [sparse {Update.updateMinFeeA = Nothing}, sparse {Update.updateMaxTxSize = Nothing}, sparse {Update.updatePoolPledgeInfluence = Nothing}, sparse {Update.updateProtocolVersion = Nothing}]+ forM_ missing $ \change -> do+ let bytes = Update.encodeCbor change+ assertBool "required field missing" (isLeft (Snapshot.decodeSnapshot bytes))+ result <- roundtrip 0 bytes+ assertBool "native conversion rejects rather than inventing required field" (isLeft result)+ let overflow = full {Parameters.parameterMaxValueSize = Just (fromIntegral (maxBound :: Int64) + 1)}+ assertBool "signed setter prevalidation" (isLeft (Snapshot.validateNative overflow))+ result <- roundtrip 0 (Snapshot.encodeSnapshot overflow)+ assertBool "native signed setter overflow rejected" (isLeft result)+ malformed <- roundtrip 0 (Snapshot.encodeSnapshot full <> B.singleton 0)+ assertBool "trailing bytes rejected" (isLeft malformed)++checkRepeated :: IO ()+checkRepeated = do+ full <- must Fixture.parameters+ replicateM_ 64 (roundtrip 0 (Snapshot.encodeSnapshot full) >>= must)++propSnapshot :: Property+propSnapshot = property $ do+ fee <- forAll (Gen.word64 Range.constantBounded)+ base <- evalEither Fixture.parameters+ let parameters = base {Parameters.parameterMinFeeB = fee}+ bytes <- evalIO (roundtrip 0 (Snapshot.encodeSnapshot parameters)) >>= evalEither+ result <- evalEither (Snapshot.decodeSnapshot bytes)+ result === parameters++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_parameter_snapshot"+ cSnapshot :: Ptr Word8 -> CSize -> CUInt -> Ptr (Ptr Buffer) -> IO NativeCode
@@ -0,0 +1,324 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Complete typed snapshots, sparse changes and native semantic reconstruction.+module Parameters (tests) where++import qualified Codec.CBOR.Decoding as Decode+import qualified Codec.CBOR.Encoding as Encode+import qualified Codec.CBOR.Read as Read+import qualified Codec.CBOR.Write as Write+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import qualified Cometa.Protocol.ExUnits as Units+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Parameters.Update as U+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.UnitInterval as Unit+import Control.Monad (forM_)+import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as Lazy+import Data.Either (isLeft)+import Data.Word (Word64, Word8)+import qualified Fixtures.ProtocolParameters as Fixtures+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+ testGroup+ "Protocol parameter updates"+ [ testCase "all 56 fields roundtrip through typed native full snapshot reconstruction" checkAll,+ testCase "Conway snapshots omit future and deprecated fields" checkAvailability,+ testCase "independent pinned update vector selects the expected semantic fields" checkGolden,+ testCase "nullable fields preserve absent null and value states" checkNullable,+ testCase "exact import bytes remain distinct from normalized serialization" checkIdentity,+ testCase "invalid schema bounds duplicates unknown and trailing bytes fail" checkInvalid,+ testCase "nonce and positive stride validation reject invalid boundaries" checkBounds,+ testCase "changed parameters reduce rationals and preserve execution-unit order" checkChangedParameters,+ testCase "changed parameters distinguish absent and nullable values" checkChangedNullable,+ testCase "changed parameters cover all supported field identifiers" checkChangedFields,+ testProperty "sparse fee edits preserve other full fields and native semantics" propFees+ ]++expectRight :: (Show e) => Either e a -> IO a+expectRight = either (\failure -> assertFailure (show failure) >> fail "unreachable") pure++fixture :: IO P.Parameters+fixture = expectRight Fixtures.parameters++checkAll :: IO ()+checkAll = do+ full <- fixture+ let change = U.fromParameters full+ encoded = U.encodeCbor change+ decoded <- expectRight (U.decodeCbor encoded)+ U.toUpdate decoded @?= change+ U.apply U.empty full @?= full+ U.apply change full @?= full+ nativeAgreement encoded encoded+ -- Every individual field is exercised separately, verifying absence of the others.+ forM_ (zip ([0 .. 14] <> [16 .. 56] :: [Word64]) (individualChanges full)) $ \(expectedKey, item) -> do+ -- Independently pin the wire key for each named public field.+ case Read.deserialiseFromBytes (Decode.decodeMapLen >> Decode.decodeWord64) (Lazy.fromStrict (U.encodeCbor item)) of+ Left failure -> assertFailure (show failure)+ Right (_, actualKey) -> actualKey @?= expectedKey+ result <- expectRight (U.decodeCbor (U.encodeCbor item))+ U.toUpdate result @?= item+ nativeAgreement (U.encodeCbor item) (U.encodeCbor item)++individualChanges :: P.Parameters -> [U.Update]+individualChanges full =+ [ U.empty {U.updateMinFeeA = Just (P.parameterMinFeeA full)},+ U.empty {U.updateMinFeeB = Just (P.parameterMinFeeB full)},+ U.empty {U.updateMaxBlockBodySize = Just (P.parameterMaxBlockBodySize full)},+ U.empty {U.updateMaxTxSize = Just (P.parameterMaxTxSize full)},+ U.empty {U.updateMaxBlockHeaderSize = Just (P.parameterMaxBlockHeaderSize full)},+ U.empty {U.updateKeyDeposit = Just (P.parameterKeyDeposit full)},+ U.empty {U.updatePoolDeposit = Just (P.parameterPoolDeposit full)},+ U.empty {U.updateMaxEpoch = Just (P.parameterMaxEpoch full)},+ U.empty {U.updateDesiredPoolCount = Just (P.parameterDesiredPoolCount full)},+ U.empty {U.updatePoolPledgeInfluence = Just (P.parameterPoolPledgeInfluence full)},+ U.empty {U.updateExpansionRate = Just (P.parameterExpansionRate full)},+ U.empty {U.updateTreasuryGrowthRate = Just (P.parameterTreasuryGrowthRate full)},+ U.empty {U.updateDecentralization = P.parameterDecentralization full},+ U.empty {U.updateExtraEntropy = P.parameterExtraEntropy full},+ U.empty {U.updateProtocolVersion = Just (P.parameterProtocolVersion full)},+ U.empty {U.updateMinPoolCost = Just (P.parameterMinPoolCost full)},+ U.empty {U.updateAdaPerUtxoByte = P.parameterAdaPerUtxoByte full},+ U.empty {U.updateCostModels = P.parameterCostModels full},+ U.empty {U.updateExecutionCosts = P.parameterExecutionCosts full},+ U.empty {U.updateMaxTxExUnits = P.parameterMaxTxExUnits full},+ U.empty {U.updateMaxBlockExUnits = P.parameterMaxBlockExUnits full},+ U.empty {U.updateMaxValueSize = P.parameterMaxValueSize full},+ U.empty {U.updateCollateralPercentage = P.parameterCollateralPercentage full},+ U.empty {U.updateMaxCollateralInputs = P.parameterMaxCollateralInputs full},+ U.empty {U.updatePoolVotingThresholds = P.parameterPoolVotingThresholds full},+ U.empty {U.updateDrepVotingThresholds = P.parameterDrepVotingThresholds full},+ U.empty {U.updateMinCommitteeSize = P.parameterMinCommitteeSize full},+ U.empty {U.updateCommitteeTermLimit = P.parameterCommitteeTermLimit full},+ U.empty {U.updateGovernanceActionValidityPeriod = P.parameterGovernanceActionValidityPeriod full},+ U.empty {U.updateGovernanceActionDeposit = P.parameterGovernanceActionDeposit full},+ U.empty {U.updateDrepDeposit = P.parameterDrepDeposit full},+ U.empty {U.updateDrepInactivityPeriod = P.parameterDrepInactivityPeriod full},+ U.empty {U.updateRefScriptCostPerByte = P.parameterRefScriptCostPerByte full},+ U.empty {U.updateMaxRefScriptSizePerBlock = P.parameterMaxRefScriptSizePerBlock full},+ U.empty {U.updateMaxRefScriptSizePerTx = P.parameterMaxRefScriptSizePerTx full},+ U.empty {U.updateRefScriptCostStride = P.parameterRefScriptCostStride full},+ U.empty {U.updateRefScriptCostMultiplier = P.parameterRefScriptCostMultiplier full},+ U.empty {U.updateMaxPledgeLeverage = P.parameterMaxPledgeLeverage full},+ U.empty {U.updateMinPoolMargin = P.parameterMinPoolMargin full},+ U.empty {U.updateLeiosAnnouncementPeriodLength = P.parameterLeiosAnnouncementPeriodLength full},+ U.empty {U.updateLeiosVotePeriodLength = P.parameterLeiosVotePeriodLength full},+ U.empty {U.updateLeiosDiffusionPeriodLength = P.parameterLeiosDiffusionPeriodLength full},+ U.empty {U.updateLeiosCommitteeSize = P.parameterLeiosCommitteeSize full},+ U.empty {U.updateLeiosQuorumStakeThreshold = P.parameterLeiosQuorumStakeThreshold full},+ U.empty {U.updateMaxEndorserBlockReferencesSize = P.parameterMaxEndorserBlockReferencesSize full},+ U.empty {U.updateMaxEndorserBlockTxsSize = P.parameterMaxEndorserBlockTxsSize full},+ U.empty {U.updateMaxEndorserBlockExecutionUnits = P.parameterMaxEndorserBlockExecutionUnits full},+ U.empty {U.updateMaxRefScriptSizePerEndorserBlock = P.parameterMaxRefScriptSizePerEndorserBlock full},+ U.empty {U.updatePerasMinCandidateBlockAge = P.parameterPerasMinCandidateBlockAge full},+ U.empty {U.updatePerasHealingFactor = P.parameterPerasHealingFactor full},+ U.empty {U.updatePerasCertBoost = P.parameterPerasCertBoost full},+ U.empty {U.updatePerasTargetCommitteeSize = P.parameterPerasTargetCommitteeSize full},+ U.empty {U.updatePerasBootstrapRound = P.parameterPerasBootstrapRound full},+ U.empty {U.updatePerasQuorumThresholdSafetyMargin = P.parameterPerasQuorumThresholdSafetyMargin full},+ U.empty {U.updateRefInputsCostPerMultiAssetByte = P.parameterRefInputsCostPerMultiAssetByte full},+ U.empty {U.updateRefInputsCostPerDatumByte = P.parameterRefInputsCostPerDatumByte full}+ ]++checkGolden :: IO ()+checkGolden = do+ -- Native protocol_param_update.c map keys: min_fee_a=0, min_fee_b=1,+ -- max_ref_script_size_per_block=34, max_pledge_leverage=38.+ let bytes = BS.pack [0xa4, 0, 0x18, 44, 1, 0x1a, 0, 2, 0x5e, 0xf5, 0x18, 34, 0x19, 1, 0, 0x18, 38, 0xf6]+ expected = U.empty {U.updateMinFeeA = Just 44, U.updateMinFeeB = Just 155381, U.updateMaxRefScriptSizePerBlock = Just 256, U.updateMaxPledgeLeverage = Just Nothing}+ decoded <- expectRight (U.decodeCbor bytes)+ U.toUpdate decoded @?= expected+ U.encodeCbor expected @?= bytes+ nativeAgreement bytes bytes++checkAvailability :: IO ()+checkAvailability = do+ full <- fixture+ let conway =+ full+ { P.parameterDecentralization = Nothing,+ P.parameterExtraEntropy = Nothing,+ P.parameterMaxRefScriptSizePerBlock = Nothing,+ P.parameterMaxRefScriptSizePerTx = Nothing,+ P.parameterRefScriptCostStride = Nothing,+ P.parameterRefScriptCostMultiplier = Nothing,+ P.parameterMaxPledgeLeverage = Nothing,+ P.parameterMinPoolMargin = Nothing,+ P.parameterLeiosAnnouncementPeriodLength = Nothing,+ P.parameterLeiosVotePeriodLength = Nothing,+ P.parameterLeiosDiffusionPeriodLength = Nothing,+ P.parameterLeiosCommitteeSize = Nothing,+ P.parameterLeiosQuorumStakeThreshold = Nothing,+ P.parameterMaxEndorserBlockReferencesSize = Nothing,+ P.parameterMaxEndorserBlockTxsSize = Nothing,+ P.parameterMaxEndorserBlockExecutionUnits = Nothing,+ P.parameterMaxRefScriptSizePerEndorserBlock = Nothing,+ P.parameterPerasMinCandidateBlockAge = Nothing,+ P.parameterPerasHealingFactor = Nothing,+ P.parameterPerasCertBoost = Nothing,+ P.parameterPerasTargetCommitteeSize = Nothing,+ P.parameterPerasBootstrapRound = Nothing,+ P.parameterPerasQuorumThresholdSafetyMargin = Nothing,+ P.parameterRefInputsCostPerMultiAssetByte = Nothing,+ P.parameterRefInputsCostPerDatumByte = Nothing+ }+ change = U.fromParameters conway+ U.apply U.empty conway @?= conway+ U.apply change conway @?= conway+ U.updateMaxRefScriptSizePerBlock change @?= Nothing+ U.updateMaxPledgeLeverage change @?= Nothing+ U.updateDecentralization change @?= Nothing+ let feeEdit = U.empty {U.updateMinFeeB = Just 42}+ U.apply feeEdit conway @?= conway {P.parameterMinFeeB = 42}+ nativeAgreement (U.encodeCbor change) (U.encodeCbor change)+ decoded <- expectRight (U.decodeCbor (U.encodeCbor change))+ U.toUpdate decoded @?= change++checkNullable :: IO ()+checkNullable = do+ full <- fixture+ let changes = [U.empty, U.empty {U.updateMaxPledgeLeverage = Just Nothing}, U.empty {U.updatePerasBootstrapRound = Just Nothing}, U.empty {U.updateMaxPledgeLeverage = P.parameterMaxPledgeLeverage full, U.updatePerasBootstrapRound = P.parameterPerasBootstrapRound full}]+ forM_ changes $ \change -> do+ result <- expectRight (U.decodeCbor (U.encodeCbor change))+ U.toUpdate result @?= change+ nativeAgreement (U.encodeCbor change) (U.encodeCbor change)+ let removed = U.apply (U.empty {U.updateMaxPledgeLeverage = Just Nothing, U.updatePerasBootstrapRound = Just Nothing}) full+ P.parameterMaxPledgeLeverage removed @?= Just Nothing+ P.parameterPerasBootstrapRound removed @?= Just Nothing+ -- Neutral entropy is separate from absent entropy.+ let neutral = U.empty {U.updateExtraEntropy = Just P.neutralNonce}+ nativeAgreement (U.encodeCbor neutral) (U.encodeCbor neutral)++checkIdentity :: IO ()+checkIdentity = do+ let original = BS.pack [0xbf, 0x18, 0, 0x18, 1, 0xff]+ decoded <- expectRight (U.decodeCbor original)+ U.toCbor decoded @?= original+ U.toUpdate decoded @?= U.empty {U.updateMinFeeA = Just 1}+ U.encodeCbor (U.toUpdate decoded) @?= BS.pack [0xa1, 0, 1]+ -- Native pinned update decoding supports only definite maps.+ nativeAgreement (U.encodeCbor (U.toUpdate decoded)) (U.encodeCbor (U.toUpdate decoded))+ let definiteNonminimal = BS.pack [0xa1, 0x18, 0, 0x18, 1]+ nativeAgreement definiteNonminimal (BS.pack [0xa1, 0, 1])++checkInvalid :: IO ()+checkInvalid = do+ let encode = Write.toStrictByteString+ uint key value = Encode.encodeMapLen 1 <> Encode.encodeWord key <> Encode.encodeInteger value+ malformed =+ map BS.pack [[0xa1, 15, 0], [0xa2, 0, 1, 0, 2], [0xa1, 0, 0x20], [0xa0, 0], [0x80], [0xa1, 13, 0x81, 1], [0xa1, 13, 0x82, 1, 0x40], [0xa1, 36, 0], [0xa1, 38, 0x80], [0xa1, 53, 0x20]]+ <> [encode (uint key 4294967296) | key <- [34, 35, 36, 40, 41, 42, 45, 46, 48, 49, 53]]+ <> [encode (uint key 65536) | key <- [43, 51, 52]]+ forM_ malformed $ \bytes -> assertBool "invalid update accepted" (isLeft (U.decodeCbor bytes))++checkBounds :: IO ()+checkBounds = do+ forM_ [-1, 0, 4294967296] $ \value -> P.mkReferenceScriptCostStride value @?= Left (InvalidReferenceScriptCostStride value)+ forM_ [1, 4294967295] $ \value -> do+ stride <- expectRight (P.mkReferenceScriptCostStride value)+ toInteger (P.referenceScriptCostStride stride) @?= value+ forM_ [0, 1, 31, 33] $ \count -> P.mkNonce (BS.replicate count 0) @?= Left (InvalidProtocolNonceLength count)+ P.nonceBytes P.neutralNonce @?= Nothing+ forM_ [U.empty {U.updateMinFeeA = Just maxBound}, U.empty {U.updateMaxValueSize = Just maxBound}, U.empty {U.updateMaxRefScriptSizePerBlock = Just maxBound}, U.empty {U.updateLeiosCommitteeSize = Just maxBound}] $ \change -> do+ decoded <- expectRight (U.decodeCbor (U.encodeCbor change))+ U.toUpdate decoded @?= change+ nativeAgreement (U.encodeCbor change) (U.encodeCbor change)++propFees :: Property+propFees = property $ do+ a <- forAll (Gen.word64 Range.constantBounded)+ b <- forAll (Gen.word64 Range.constantBounded)+ full <- evalIO fixture+ let change = U.empty {U.updateMinFeeA = Just a, U.updateMinFeeB = Just b}+ result = U.apply change full+ decoded <- evalEither (U.decodeCbor (U.encodeCbor change))+ U.toUpdate decoded === change+ result === full {P.parameterMinFeeA = a, P.parameterMinFeeB = b}+ evalIO (nativeAgreement (U.encodeCbor change) (U.encodeCbor change))++nativeAgreement :: BS.ByteString -> BS.ByteString -> IO ()+nativeAgreement input expected = BS.useAsCStringLen input $ \(inputPtr, inputSize) -> BS.useAsCStringLen expected $ \(expectedPtr, expectedSize) -> do+ result <- c_agreement (castPtr inputPtr) (fromIntegral inputSize) (castPtr expectedPtr) (fromIntegral expectedSize)+ result @?= 1++-- All storage is borrowed through synchronous return; C scopes all native owners.+foreign import ccall unsafe "cometa_test_parameters_agreement"+ c_agreement :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> IO CInt++-- Adapted from cardano-c's pinned protocol_param_update.cpp+-- encodesTagsValuesAndReducesRationals; see Fixtures/PARAMETER_DATA.md.+checkChangedParameters :: IO ()+checkChangedParameters = do+ pledge <- expectRight (Rational.mkNonNegativeRational 3 10)+ treasury <- expectRight (Unit.mkUnitInterval 2 10)+ let change =+ U.empty+ { U.updateMinFeeA = Just 44,+ U.updatePoolPledgeInfluence = Just pledge,+ U.updateTreasuryGrowthRate = Just treasury,+ U.updateMaxTxExUnits = Just (Units.ExUnits 1000 2000)+ }+ expected =+ Data.Map+ [ (Data.Integer 0, Data.Integer 44),+ (Data.Integer 9, Data.List [Data.Integer 3, Data.Integer 10]),+ (Data.Integer 11, Data.List [Data.Integer 1, Data.Integer 5]),+ (Data.Integer 20, Data.List [Data.Integer 1000, Data.Integer 2000])+ ]+ U.toPlutusData change >>= (@?= Right expected)+ U.toPlutusData U.empty >>= (@?= Right (Data.Map []))++checkChangedNullable :: IO ()+checkChangedNullable = do+ let change =+ U.empty+ { U.updateMinFeeA = Just maxBound,+ U.updateMaxPledgeLeverage = Just Nothing,+ U.updatePerasBootstrapRound = Just Nothing+ }+ expected =+ Data.Map+ [ (Data.Integer 0, Data.Integer (toInteger (maxBound :: Word64))),+ (Data.Integer 38, Data.Constr 1 []),+ (Data.Integer 53, Data.Constr 1 [])+ ]+ U.toPlutusData change >>= (@?= Right expected)++checkChangedFields :: IO ()+checkChangedFields = do+ full <- fixture+ let change = U.fromParameters full+ original = U.encodeCbor change+ converted <- U.toPlutusData change >>= expectRight+ case converted of+ Data.Map entries -> map fst entries @?= map Data.Integer ([0 .. 11] ++ [16 .. 56])+ _ -> assertFailure "Changed parameters must be a data map"+ U.encodeCbor change @?= original+ forM_ [1 .. 25 :: Int] $ \_ -> U.toPlutusData change >>= (@?= Right converted)
@@ -0,0 +1,287 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Deterministic public test material only. Vector provenance is recorded in+-- Fixtures/PASSWORD_CRYPTO.md; no live keys or external service is used.+module PasswordCrypto (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Emip3 as Emip3+import qualified Cometa.Crypto.Pbkdf2 as Pbkdf2+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import Cometa.Internal.FFI.Native (success)+import qualified Cometa.Internal.FFI.PasswordCrypto as Native+import Cometa.Internal.Failure (NativeFailure (..))+import qualified Cometa.Internal.Hex as Hex+import Cometa.Internal.Ownership (withOwnedOutput)+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), IOException, evaluate, fromException, throwIO, try)+import Control.Monad (replicateM, replicateM_, void)+import Data.Bits (xor)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek, poke)+import Hedgehog (Property, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import capi unsafe "cardano/buffer.h cardano_buffer_ref"+ cRef :: Ptr Native.Buffer -> IO ()++foreign import capi unsafe "cardano/buffer.h cardano_buffer_unref"+ cUnref :: Ptr (Ptr Native.Buffer) -> IO ()++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Password crypto"+ [ testCase "PBKDF2 native password/salt vector" checkPbkdfVector,+ testCase "PBKDF2 independent binary multi-block vector" checkBinaryVector,+ testCase "PBKDF2 rejects invalid parameters before computation" checkBounds,+ testCase "EMIP3 pinned native decrypt vector" checkNativeEnvelope,+ testCase "EMIP3 independent binary envelope" checkIndependentEnvelope,+ testCase "EMIP3 supports empty plaintext and rejects short envelopes" checkEnvelopeBounds,+ testCase "EMIP3 authenticates salt, nonce, tag and ciphertext" checkTampering,+ testCase "EMIP3 encrypt round trips and copied plaintext survives GC" checkRoundTrips,+ testCase "EMIP3 concurrent operations have independent outputs" checkConcurrentEmip3,+ testCase "plaintext owner is wiped and released after success" checkCleanupSuccess,+ testCase "partial failure owner is wiped and released" checkCleanupFailure,+ testCase "copy exception wipes and releases plaintext owner" checkCleanupException,+ testCase "cancellation wipes and releases plaintext owner" checkCleanupCancellation,+ testCase "PBKDF2 evaluation cancellation unwinds before reuse" checkPbkdfCancellation,+ testCase "PBKDF2 shared concurrent result survives GC" checkSharedPbkdf,+ testProperty "PBKDF2 prefix law across SHA512 block boundary" propPrefix+ ]++checkPbkdfVector :: IO ()+checkPbkdfVector =+ fmap Hex.encodeHex (Pbkdf2.deriveBytes "password" "salt" 1 64)+ @?= Right "867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5d513554e1c8cf252c02d470a285a0501bad999bfe943c08f050235d7d68b1da55e63f73b60a57fce"++checkBinaryVector :: IO ()+checkBinaryVector =+ fmap Hex.encodeHex (Pbkdf2.deriveBytes "pass\NULword" "sa\NULlt" 2 65)+ @?= Right "b10b04b1ec0406c23faa6bc0309a13f6d520ebc223bf096e42f6eaa6b6598f5dc6643beb1f5db291e44287bbe755e281a26a93c6c04dc59017b9da06be3742bfcb"++checkBounds :: IO ()+checkBounds = do+ Pbkdf2.deriveBytes "" "" 1 32 @?= Left EmptyPbkdf2Salt+ mapM_ (\count -> Pbkdf2.deriveBytes "" "s" count 32 @?= Left (InvalidPbkdf2Iterations count)) [-1, 0, 4294967296, 2 ^ (64 :: Int)]+ mapM_ (\size -> Pbkdf2.deriveBytes "" "s" 1 size @?= Left (InvalidPbkdf2OutputLength size)) [-1, 0, 274877906881, toInteger (maxBound :: Int) + 1]+ fmap ByteString.length (Pbkdf2.deriveBytes "" "s" 1 1) @?= Right 1+ -- Validate the maximum iteration encoding without executing billions of HMACs.+ Pbkdf2.deriveBytes "" "s" 4294967295 0 @?= Left (InvalidPbkdf2OutputLength 0)++nativeEnvelope :: ByteString+nativeEnvelope = decoded "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000009ce1d7784a05efd109ad89c29fea0775bf085ac03988089b3a93"++independentEnvelope :: ByteString+independentEnvelope = decoded "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2bdbd67fe6279185e5cdcb32a669ae6bb7e9d2de22e9eebbe7f95775"++checkNativeEnvelope :: IO ()+checkNativeEnvelope = do+ Emip3.decryptBytes "password" nativeEnvelope >>= (@?= Right (ByteString.pack [0 .. 9]))+ let emptyPasswordEnvelope = decoded "0430bb0e1941fd9ec98909e766447883b4af77242a81c7ef2ba8d339f0deeae383227e257c0d6f28ad372a1bc9b87a30e3544258b21a2b576746f5fb83746c7a8e1fa37e2ca3"+ Emip3.decryptBytes "" emptyPasswordEnvelope >>= (@?= Right (ByteString.pack [0 .. 9]))++checkIndependentEnvelope :: IO ()+checkIndependentEnvelope = do+ Emip3.decryptBytes "p\NULw" independentEnvelope >>= (@?= Right "hello\NULworld")+ Emip3.decryptBytes "p\NULw" (decoded "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b5b62d7cf9c5d08c8a599f4257d36b254") >>= (@?= Right ByteString.empty)++checkEnvelopeBounds :: IO ()+checkEnvelopeBounds =+ mapM_ (\size -> Emip3.decryptBytes "" (ByteString.replicate size 0) >>= (@?= Left (InvalidEmip3EnvelopeLength size))) [0, 1, 59]++checkTampering :: IO ()+checkTampering = do+ Emip3.decryptBytes "wrong password" independentEnvelope >>= checkAuthenticationFailure+ mapM_ (\position -> Emip3.decryptBytes "p\NULw" (flipByte position independentEnvelope) >>= checkAuthenticationFailure) [0, 31, 32, 43, 44, 59, 60, 70]+ where+ flipByte position bytes = ByteString.take position bytes <> ByteString.singleton (ByteString.index bytes position `xor` 1) <> ByteString.drop (position + 1) bytes++checkAuthenticationFailure :: Either Error ByteString -> IO ()+checkAuthenticationFailure (Left (NativeError operation code _)) = do+ operation @?= "emip3.decryptBytes"+ code @?= Code.GenericFailure+checkAuthenticationFailure _ = assertFailure "authentication did not fail with native generic status"++checkRoundTrips :: IO ()+checkRoundTrips = mapM_ check [("", ""), ("", "x"), ("p\NULw", "hello\NULworld"), ("password", ByteString.pack [0 .. 255])]+ where+ check (password, plaintext) = do+ encrypted <- Emip3.encrypt password plaintext+ case encrypted of+ Left err -> assertFailure (show err)+ Right envelope -> do+ ByteString.length envelope @?= ByteString.length plaintext + 60+ result <- Emip3.decryptBytes password envelope+ replicateM_ 3 (void (Emip3.decryptBytes password envelope))+ performGC+ result @?= Right plaintext++checkConcurrentEmip3 :: IO ()+checkConcurrentEmip3 = do+ gates <- replicateM 4 newEmptyMVar+ let operation = do+ encrypted <- Emip3.encrypt "public password" "public plaintext"+ case encrypted of+ Left err -> pure (Left err)+ Right envelope -> Emip3.decryptBytes "public password" envelope+ start gate = void (forkFinally operation (putMVar gate))+ check result = case result of+ Left _ -> assertFailure "concurrent encryption raised an exception"+ Right plaintext -> plaintext @?= Right "public plaintext"+ mapM_ start gates+ results <- mapM takeMVar gates+ mapM_ check results++-- Retain a test-only alias to inspect zeroization before its final release.+-- The production release still owns exactly one reference; its slot is cleared.+checkedRelease :: IO () -> Ptr (Ptr Native.Buffer) -> IO ()+checkedRelease released slot = do+ pointer <- peek slot+ size <- Native.cSize pointer+ cRef pointer+ Native.cRelease slot+ alloca $ \retained -> do+ poke retained pointer+ bytes <- Native.cData pointer >>= \dataPtr -> ByteString.packCStringLen (castPtr dataPtr, fromIntegral size)+ cUnref retained+ bytes @?= ByteString.replicate (fromIntegral size) 0+ released++withPlaintext :: IO () -> (Ptr Native.Buffer -> IO (Either NativeFailure ())) -> IO (Either NativeFailure ())+withPlaintext released action = ByteString.useAsCStringLen nativeEnvelope $ \(input, size) ->+ ByteString.useAsCStringLen "password" $ \(password, passwordSize) ->+ withOwnedOutput+ "passwordCrypto.cleanup"+ (checkedRelease released)+ (Native.cDecrypt (castPtr input) (fromIntegral size) (castPtr password) (fromIntegral passwordSize))+ action++checkCleanupSuccess :: IO ()+checkCleanupSuccess = do+ releases <- newIORef (0 :: Int)+ result <- withPlaintext (modifyIORef' releases (+ 1)) (\_ -> pure (Right ()))+ result @?= Right ()+ readIORef releases >>= (@?= 1)++checkCleanupFailure :: IO ()+checkCleanupFailure = do+ releases <- newIORef (0 :: Int)+ ByteString.useAsCStringLen nativeEnvelope $ \(input, size) ->+ ByteString.useAsCStringLen "password" $ \(password, passwordSize) -> do+ result <-+ withOwnedOutput+ "passwordCrypto.partial"+ (checkedRelease (modifyIORef' releases (+ 1)))+ ( \slot -> do+ status <- Native.cDecrypt (castPtr input) (fromIntegral size) (castPtr password) (fromIntegral passwordSize) slot+ status @?= success+ pure 1+ )+ (\_ -> pure (Right ()))+ case result of+ Left (NativeFailure _ 1 _) -> pure ()+ _ -> assertFailure "injected failure status was lost"+ readIORef releases >>= (@?= 1)++checkCleanupException :: IO ()+checkCleanupException = do+ releases <- newIORef (0 :: Int)+ result <- try (withPlaintext (modifyIORef' releases (+ 1)) (\_ -> throwIO (userError "injected copy failure"))) :: IO (Either IOException (Either NativeFailure ()))+ case result of+ Left _ -> pure ()+ Right _ -> assertFailure "copy exception did not propagate"+ readIORef releases >>= (@?= 1)++checkCleanupCancellation :: IO ()+checkCleanupCancellation = do+ releases <- newIORef (0 :: Int)+ started <- newEmptyMVar+ blocked <- newEmptyMVar+ finished <- newEmptyMVar+ worker <-+ forkFinally+ (withPlaintext (modifyIORef' releases (+ 1)) (\_ -> putMVar started () >> takeMVar blocked))+ (putMVar finished)+ takeMVar started+ killThread worker+ result <- timeout 5000000 (takeMVar finished)+ case result of+ Just (Left exception) | Just ThreadKilled <- fromException exception -> pure ()+ _ -> assertFailure "cancellation did not propagate"+ readIORef releases >>= (@?= 1)++checkPbkdfCancellation :: IO ()+checkPbkdfCancellation = do+ started <- newEmptyMVar+ finished <- newEmptyMVar+ worker <-+ forkFinally+ (putMVar started () >> evaluate (Pbkdf2.deriveBytes "public test password" "salt" 100000 65))+ (putMVar finished)+ takeMVar started+ killThread worker+ result <- timeout 5000000 (takeMVar finished)+ case result of+ Just (Left exception) | Just ThreadKilled <- fromException exception -> pure ()+ _ -> assertFailure "PBKDF2 cancellation did not propagate"+ checkPbkdfVector++checkSharedPbkdf :: IO ()+checkSharedPbkdf = do+ let shared = Pbkdf2.deriveBytes "shared public test" "public salt" 1000 65+ gates <- replicateM 8 newEmptyMVar+ let start gate = void (forkFinally (evaluate shared) (putMVar gate))+ mapM_ start gates+ results <- mapM takeMVar gates+ performGC+ let check result = case result of+ Left _ -> assertFailure "concurrent derivation raised an exception"+ Right bytes -> fmap ByteString.length bytes @?= Right 65+ mapM_ check results++propPrefix :: Property+propPrefix = property $ do+ password <- forAll (Gen.bytes (Range.linear 0 140))+ salt <- forAll (Gen.bytes (Range.linear 1 40))+ size <- forAll (Gen.integral (Range.linear 1 130))+ let larger = Pbkdf2.deriveBytes password salt 2 130+ smaller = Pbkdf2.deriveBytes password salt 2 size+ fmap (ByteString.take (fromInteger size)) larger === smaller++decoded :: Text -> ByteString+decoded text = fromMaybe ByteString.empty (Hex.decodeHex text)
@@ -0,0 +1,221 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module PlutusData (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import Cometa.Error (Error (..))+import qualified Cometa.PlutusData as Data+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Monad (forM_, replicateM_, when)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import qualified Data.Text as Text+import Data.Word (Word64, Word8)+import Fixtures.PlutusData (integerVectors)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Gen, Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Plutus Data"+ [ testCase "pinned arbitrary integer CBOR and hashes" checkIntegerVectors,+ testCase "constructor tag transitions and maximum alternative" checkConstructors,+ testCase "bytes and bignums chunk at 64 bytes" checkChunks,+ testCase "maps retain duplicate keys and order" checkMaps,+ testCase "indefinite collections, bytes, bignums and constructors" checkIndefinite,+ testCase "original encodings retain distinct hash identity" checkIdentity,+ testCase "malformed, wrong type and trailing encodings are rejected" checkInvalid,+ testCase "typed native traversal and cache-free serialization" checkNative,+ testCase "hash lifecycle supports repeated calls and cancellation" checkLifecycle,+ testProperty "all semantic alternatives round trip" propRoundTrip,+ testProperty "native typed conversion agrees with semantic trees" propNative+ ]++checkIntegerVectors :: IO ()+checkIntegerVectors = forM_ integerVectors $ \(number, encoded, digest) -> do+ let value = Data.Integer number+ Data.encodeCbor value @?= hex encoded+ decoded <- expectRight (Data.decodeCbor (hex encoded))+ Data.toData decoded @?= value+ hashed <- Data.hash decoded >>= expectRight+ Blake2b.toHex hashed @?= Text.pack digest++checkConstructors :: IO ()+checkConstructors = forM_ [(0, "d87980"), (6, "d87f80"), (7, "d9050080"), (127, "d9057880"), (128, "d86682188080"), (maxBound, "d866821bffffffffffffffff80")] $ \(alternative, encoded) -> do+ let value = Data.Constr alternative []+ Data.encodeCbor value @?= hex encoded+ decoded <- expectRight (Data.decodeCbor (hex encoded))+ Data.toData decoded @?= value++checkChunks :: IO ()+checkChunks = do+ forM_ [0, 1, 63, 64, 65, 128, 129, 1024] $ \size -> do+ let bytes = ByteString.replicate size 171+ value = Data.Bytes bytes+ decoded <- expectRight (Data.decodeCbor (Data.encodeCbor value))+ Data.toData decoded @?= value+ when (size > 64) $ ByteString.take 1 (Data.encodeCbor value) @?= ByteString.singleton 95+ forM_ [1, -1] $ \sign -> do+ let value = Data.Integer (sign * 2 ^ (1024 :: Int))+ decoded <- expectRight (Data.decodeCbor (Data.encodeCbor value))+ Data.toData decoded @?= value+ let malformed = ByteString.pack [88, 65] <> ByteString.replicate 65 0+ assertInvalid malformed+ assertInvalid (ByteString.pack [95] <> malformed <> ByteString.singleton 255)+ assertInvalid (ByteString.pack [194] <> malformed)++checkMaps :: IO ()+checkMaps = do+ let entries = [(Data.Integer 1, Data.Bytes "a"), (Data.Integer 1, Data.Bytes "b"), (Data.Bytes "", Data.List [])]+ value = Data.Map entries+ decoded <- expectRight (Data.decodeCbor (Data.encodeCbor value))+ Data.toData decoded @?= value+ (Data.Map (reverse entries) == value) @?= False+ checkNativeValue value++checkIndefinite :: IO ()+checkIndefinite = forM_ [("bf01020103ff", Data.Map [(Data.Integer 1, Data.Integer 2), (Data.Integer 1, Data.Integer 3)]), ("9f0140ff", Data.List [Data.Integer 1, Data.Bytes ByteString.empty]), ("5f41014102ff", Data.Bytes (ByteString.pack [1, 2])), ("c25f41014100ff", Data.Integer 256), ("c35f41014100ff", Data.Integer (-257)), ("d8669f18809f01ffff", Data.Constr 128 [Data.Integer 1]), ("d8799f01ff", Data.Constr 0 [Data.Integer 1])] $ \(encoded, value) -> do+ decoded <- expectRight (Data.decodeCbor (hex encoded))+ Data.toData decoded @?= value+ Data.toCbor decoded @?= hex encoded++checkIdentity :: IO ()+checkIdentity = do+ short <- expectRight (Data.decodeCbor (hex "8101"))+ indefinite <- expectRight (Data.decodeCbor (hex "9f1801ff"))+ Data.toData short @?= Data.toData indefinite+ (short == indefinite) @?= False+ Data.toCbor indefinite @?= hex "9f1801ff"+ Data.toCbor (Data.fromData (Data.toData indefinite)) @?= hex "8101"+ shortHash <- Data.hash short >>= expectRight+ indefiniteHash <- Data.hash indefinite >>= expectRight+ (shortHash == indefiniteHash) @?= False+ expected <- Blake2b.compute 32 (hex "9f1801ff") >>= expectRight+ indefiniteHash @?= expected++checkInvalid :: IO ()+checkInvalid = forM_ ["", "00ff", "ff", "f6", "f5", "6161", "c001", "c241", "c401", "d87900", "d9057980", "d8668100", "d86683008000", "d866823080", "9f01", "bf0102", "bf01ff", "5f5f40ffff", "1c", "1b00", "d8669f008000ff", "9bffffffffffffffff", "bbffffffffffffffff"] (assertInvalid . hex)++checkNative :: IO ()+checkNative = forM_ [Data.Constr 0 [Data.Integer (negate (2 ^ (64 :: Int)) - 1), Data.List [Data.Bytes (ByteString.replicate 129 0)]], Data.Map [(Data.Integer 1, Data.Integer 2), (Data.Integer 1, Data.Integer 3)], Data.Constr maxBound []] checkNativeValue++checkLifecycle :: IO ()+checkLifecycle = do+ let datum = Data.fromData (Data.List [Data.Integer 123, Data.Bytes (ByteString.replicate 129 171)])+ expected <- Data.hash datum >>= expectRight+ replicateM_ 100 $ do+ result <- Data.hash datum >>= expectRight+ result @?= expected+ done <- newEmptyMVar+ started <- newEmptyMVar+ worker <- forkFinally (putMVar started () >> replicateM_ 1000 (Data.hash datum)) (putMVar done)+ takeMVar started+ killThread worker+ completed <- timeout 5000000 (takeMVar done)+ case completed of+ Nothing -> assertFailure "Cancelled datum hashing worker did not finish"+ Just _ -> pure ()+ actual <- Data.hash datum >>= expectRight+ actual @?= expected++propRoundTrip :: Property+propRoundTrip = property $ do+ value <- forAll genData+ decoded <- evalEither (Data.decodeCbor (Data.encodeCbor value))+ Data.toData decoded === value+ Data.toCbor decoded === Data.encodeCbor value++propNative :: Property+propNative = property $ do+ value <- forAll genData+ evalIO (checkNativeValue value)++genData :: Gen Data.PlutusData+genData =+ Gen.recursive+ Gen.choice+ [Data.Integer <$> Gen.integral (Range.linearFrom 0 (negate (2 ^ (600 :: Int))) (2 ^ (600 :: Int))), Data.Bytes <$> Gen.bytes (Range.linear 0 150)]+ [Data.Constr <$> Gen.word64 Range.constantBounded <*> Gen.list (Range.linear 0 4) genData, Data.List <$> Gen.list (Range.linear 0 4) genData, Data.Map <$> Gen.list (Range.linear 0 4) ((,) <$> genData <*> genData)]++checkNativeValue :: Data.PlutusData -> IO ()+checkNativeValue value = do+ let bytes = Data.encodeCbor value+ capacity = ByteString.length bytes * 2 + 1024+ ByteString.useAsCStringLen bytes $ \(input, size) -> allocaArray capacity $ \output -> alloca $ \outputSize -> allocaArray 8 $ \counts -> do+ status <- cOracle (castPtr input) (fromIntegral size) output (fromIntegral capacity) outputSize counts+ status @?= 0+ actualSize <- peek outputSize+ encoded <- ByteString.packCStringLen (castPtr output, fromIntegral actualSize)+ decoded <- expectRight (Data.decodeCbor encoded)+ Data.toData decoded @?= value+ actualCounts <- peekArray 8 counts+ actualCounts @?= nodeCounts value++nodeCounts :: Data.PlutusData -> [Word64]+nodeCounts value = case value of+ Data.Constr alternative fields -> add [1, 0, 0, 0, 0, alternative, 0, 0] (children fields)+ Data.Map pairs -> add [0, 1, 0, 0, 0, 0, 0, 0] (children (concatMap (\(key, item) -> [key, item]) pairs))+ Data.List values -> add [0, 0, 1, 0, 0, 0, 0, 0] (children values)+ Data.Integer number -> [0, 0, 0, 1, 0, 0, bitLength (abs number), 0]+ Data.Bytes bytes -> [0, 0, 0, 0, 1, 0, 0, fromIntegral (ByteString.length bytes)]+ where+ add = zipWith (+)+ children = foldr (add . nodeCounts) (replicate 8 0)+ bitLength 0 = 1+ bitLength number = magnitudeBits number+ magnitudeBits 0 = 0+ magnitudeBits number = 1 + magnitudeBits (number `div` 2)++assertInvalid :: ByteString -> IO ()+assertInvalid bytes = case Data.decodeCbor bytes of+ Left (InvalidPlutusDataCbor _) -> pure ()+ result -> assertFailure ("Expected InvalidPlutusDataCbor, received " <> show result)++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Right value -> pure value+ Left failure -> assertFailure (show failure)++hex :: String -> ByteString+hex text = ByteString.pack (go text)+ where+ go (a : b : rest) = fromIntegral (digit a * 16 + digit b) : go rest+ go _ = []+ digit character+ | character <= '9' = fromEnum character - fromEnum '0'+ | otherwise = fromEnum character - fromEnum 'a' + 10++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_plutus_data_oracle"+ cOracle :: Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> Ptr Word64 -> IO CUInt
@@ -0,0 +1,260 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Typed pool workflows, pinned native vectors and reconstruction properties.+module Pool (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.NetworkId as Network+import qualified Cometa.Pool.BlsKey as Bls+import qualified Cometa.Pool.Metadata as Metadata+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Pool.Relay as Relay+import qualified Cometa.UnitInterval as Unit+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Either (isLeft)+import Data.Maybe (isNothing)+import qualified Data.Set as Set+import qualified Data.Text as Text+import Data.Word (Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Pools"+ [ testCase "owner witness comparison ignores only BLS changes" checkOwnerWitnesses,+ testCase "public fields reconstruct pinned native registration variants" checkPinned,+ testCase "all relay alternatives and optional IP/port combinations" checkRelays,+ testCase "byte, UTF-8, hash, URL and DNS boundaries" checkValidation,+ testCase "malformed CBOR, duplicate owners and trailing data" checkInvalid,+ testCase "semantic update independence and collection semantics" checkIndependence,+ testCase "repeated native reconstruction releases getter references" checkRepeated,+ testProperty "generated typed pool values agree with native field reconstruction" propParameters,+ testProperty "IPv4 and IPv6 text round trips preserve network bytes" propIpText+ ]++sample :: Either Error Pool.PoolParameters+sample = do+ poolOperator <- Credential.keyHashFromBytes =<< hex "d85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef92"+ vrf <- Pool.vrfKeyHashFromBytes =<< hex "8dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0"+ stake <- Credential.keyHashFromBytes =<< hex "cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f"+ proportion <- Unit.mkUnitInterval 1 5+ dns <- Relay.mkDnsName "example.com"+ ipv4 <- Relay.ipv4FromText "127.0.0.1"+ Pool.PoolParameters poolOperator vrf Nothing 10000 1000 proportion (Reward.fromCredential Network.mainnet (Credential.KeyCredential stake)) (Set.singleton stake) [Relay.SingleHostName (Just 5000) dns, Relay.SingleHostAddress (Just 6000) (Just ipv4) Nothing, Relay.MultiHostName dns] . Just <$> sampleMetadata++sampleMetadata :: Either Error Metadata.Metadata+sampleMetadata = do+ location <- Metadata.mkUrl "https://example.com"+ digest <- Metadata.metadataHashFromBytes =<< hex "0f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"+ pure (Metadata.Metadata location digest)++sampleBls :: Either Error Bls.BlsKey+sampleBls = Bls.mkBlsKey (ByteString.pack [0 .. 95]) (ByteString.pack [96 .. 143])++checkPinned :: IO ()+checkPinned = do+ value <- expectRight sample+ bls <- expectRight sampleBls+ forM_ [(value, nativeParameters), (value {Pool.metadata = Nothing}, nativeNoMetadata), (value {Pool.blsKey = Just bls}, nativeWithBls)] $ \(parameters, vector) -> do+ golden <- expectRight (hex vector)+ Pool.encodeCbor parameters @?= ByteString.cons (if isNothing (Pool.blsKey parameters) then 0x89 else 0x8a) golden+ Pool.decodeCbor (Pool.encodeCbor parameters) @?= Right parameters+ nativeAgreement 0 (Pool.encodeCbor parameters)+ reference <- expectRight sampleMetadata+ goldenMetadata <- expectRight (hex nativeMetadata)+ Metadata.encodeCbor reference @?= goldenMetadata+ nativeAgreement 2 goldenMetadata+ goldenBls <- expectRight (hex nativeBls)+ Bls.encodeCbor bls @?= goldenBls+ nativeAgreement 3 goldenBls+ nullBls <- expectRight (hex nativeNullBls)+ Pool.decodeCbor (ByteString.cons 0x8a nullBls) @?= Right value+ let indefinite = ByteString.cons 0x9f (ByteString.snoc (ByteString.drop 1 (Pool.encodeCbor value)) 0xff)+ Pool.decodeCbor indefinite @?= Right value++checkRelays :: IO ()+checkRelays = do+ ipv4 <- expectRight (Relay.ipv4FromText "10.3.2.10")+ ipv6 <- expectRight (Relay.ipv6FromText "0102:0304:0102:0304:0102:0304:0102:0304")+ dns <- expectRight (Relay.mkDnsName "example.com")+ let values = [Relay.SingleHostAddress port v4 v6 | port <- [Nothing, Just 0, Just maxBound], v4 <- [Nothing, Just ipv4], v6 <- [Nothing, Just ipv6]] ++ [Relay.SingleHostName Nothing dns, Relay.SingleHostName (Just 10) dns, Relay.MultiHostName dns]+ forM_ values $ \value -> do+ Relay.decodeCbor (Relay.encodeCbor value) @?= Right value+ nativeAgreement 1 (Relay.encodeCbor value)+ forM_ [(Relay.SingleHostName (Just 10) dns, "83010a6b6578616d706c652e636f6d"), (Relay.MultiHostName dns, "82026b6578616d706c652e636f6d"), (Relay.SingleHostAddress (Just 10) (Just ipv4) (Just ipv6), "84000a440a03020a5001020304010203040102030401020304")] $ \(value, vector) -> do+ golden <- expectRight (hex vector)+ Relay.encodeCbor value @?= golden++checkValidation :: IO ()+checkValidation = do+ expectedDigest <- expectRight (hex "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319")+ hashResult <- Metadata.hashData "abc"+ fmap Metadata.metadataHashBytes hashResult @?= Right expectedDigest+ forM_ [0, 1, 27, 29, 31, 33, 96] $ \size -> do+ assertBool "VRF hash length" (isLeft (Pool.vrfKeyHashFromBytes (ByteString.replicate size 0)))+ assertBool "metadata hash length" (isLeft (Metadata.metadataHashFromBytes (ByteString.replicate size 0)))+ forM_ [0, 3, 5, 16] $ \size -> assertBool "IPv4 exact length" (isLeft (Relay.ipv4FromBytes (ByteString.replicate size 0)))+ forM_ [0, 4, 15, 17] $ \size -> assertBool "IPv6 exact length" (isLeft (Relay.ipv6FromBytes (ByteString.replicate size 0)))+ forM_ ["1.2.3", "1.2.3.256", "+1.2.3.4", "1.2.3. 4", "1.2.3.٤"] $ \text -> assertBool "IPv4 malformed text" (isLeft (Relay.ipv4FromText text))+ forM_ [":::1", "1::2::3", "0000:0000:0000:0000:0000:0000:0000:zzzz", "1:2:3:4:5:6:7", "1:2:3:4:5:6:7:8:9", "1:2:3:4:5:6:7:8::", "::ffff:256.1.2.3", "1.2.3.4::"] $ \text -> assertBool "IPv6 malformed text" (isLeft (Relay.ipv6FromText text))+ forM_ [("::", "0000:0000:0000:0000:0000:0000:0000:0000"), ("::1", "0000:0000:0000:0000:0000:0000:0000:0001"), ("1::", "0001:0000:0000:0000:0000:0000:0000:0000"), ("1:2:3:4:5:6:7:8", "0001:0002:0003:0004:0005:0006:0007:0008"), ("::FFFF:192.0.2.1", "0000:0000:0000:0000:0000:ffff:c000:0201"), ("1:2:3:4:5:6:192.0.2.1", "0001:0002:0003:0004:0005:0006:c000:0201")] $ \(input, expanded) -> do+ address <- expectRight (Relay.ipv6FromText input)+ Relay.ipv6Text address @?= expanded+ assertBool "empty DNS" (isLeft (Relay.mkDnsName ""))+ assertBool "NUL DNS" (isLeft (Relay.mkDnsName "a\0b"))+ assertBool "UTF8 DNS limit" (isLeft (Relay.mkDnsName (Text.replicate 33 "é")))+ dns <- expectRight (Relay.mkDnsName (Text.replicate 32 "é"))+ nativeAgreement 1 (Relay.encodeCbor (Relay.MultiHostName dns))+ _ <- expectRight (Metadata.mkUrl "")+ _ <- expectRight (Metadata.mkUrl (Text.replicate 64 "é"))+ assertBool "URL UTF8 limit" (isLeft (Metadata.mkUrl (Text.replicate 65 "é")))+ assertBool "NUL URL" (isLeft (Metadata.mkUrl "a\0b"))+ Bls.mkBlsKey ByteString.empty ByteString.empty @?= Left (InvalidPoolBlsKeyLength 0 0)+ assertBool "short proof" (isLeft (Bls.mkBlsKey (ByteString.replicate 96 0) (ByteString.replicate 47 0)))++checkInvalid :: IO ()+checkInvalid = do+ value <- expectRight sample+ forM_ [ByteString.empty, "\xff", ByteString.snoc (Pool.encodeCbor value) 0, ByteString.cons 0x88 (ByteString.drop 1 (Pool.encodeCbor value)), ByteString.init (Pool.encodeCbor value)] $ \bytes -> assertBool "pool invalid" (isLeft (Pool.decodeCbor bytes))+ forM_ ["820300", "84001a00010000f6f6", "84000043000000f6", "8301f660", "82026100", "820261ff", "9f02ff", "82020000"] $ \vector -> do+ bytes <- expectRight (hex vector)+ assertBool "relay malformed" (isLeft (Relay.decodeCbor bytes))+ forM_ ["80", "820040", "826000", "8260581f00000000000000000000000000000000000000000000000000000000000000"] $ \vector -> do+ bytes <- expectRight (hex vector)+ assertBool "metadata malformed" (isLeft (Metadata.decodeCbor bytes))+ assertBool "BLS malformed" (isLeft (Bls.decodeCbor "\x82\x40\x40"))+ let owner = Set.findMin (Pool.owners value)+ ownerBytes = Credential.keyHashBytes owner+ marker = ByteString.pack [0xd9, 1, 2, 0x81, 0x58, 0x1c] <> ownerBytes+ duplicate = ByteString.pack [0xd9, 1, 2, 0x82, 0x58, 0x1c] <> ownerBytes <> ByteString.pack [0x58, 0x1c] <> ownerBytes+ (prefix, suffix) = ByteString.breakSubstring marker (Pool.encodeCbor value)+ assertBool "duplicate owners rejected" (isLeft (Pool.decodeCbor (prefix <> duplicate <> ByteString.drop (ByteString.length marker) suffix)))++checkIndependence :: IO ()+checkIndependence = do+ original <- expectRight sample+ let changed = original {Pool.pledge = maxBound, Pool.cost = maxBound, Pool.relays = Pool.relays original ++ Pool.relays original, Pool.owners = Set.empty, Pool.metadata = Nothing}+ Pool.pledge original @?= 10000+ length (Pool.relays original) @?= 3+ Pool.decodeCbor (Pool.encodeCbor changed) @?= Right changed+ nativeAgreement 0 (Pool.encodeCbor changed)++checkRepeated :: IO ()+checkRepeated = do+ value <- expectRight sample+ bls <- expectRight sampleBls+ replicateM_ 100 (nativeAgreement 0 (Pool.encodeCbor value {Pool.blsKey = Just bls}))++propParameters :: Property+propParameters = property $ do+ keyBytes <- forAll (Gen.bytes (Range.singleton 28))+ vrfBytes <- forAll (Gen.bytes (Range.singleton 32))+ ipBytes <- forAll (Gen.bytes (Range.singleton 4))+ ip6Bytes <- forAll (Gen.bytes (Range.singleton 16))+ pledge <- forAll (Gen.word64 Range.constantBounded)+ cost <- forAll (Gen.word64 Range.constantBounded)+ numerator <- forAll (Gen.integral (Range.linear 0 1000))+ withBls <- forAll Gen.bool+ withMetadata <- forAll Gen.bool+ port <- forAll (Gen.maybe (Gen.word16 Range.constantBounded))+ base <- evalEither sample+ poolOperator <- evalEither (Credential.keyHashFromBytes keyBytes)+ owner <- evalEither (Credential.keyHashFromBytes keyBytes)+ vrf <- evalEither (Pool.vrfKeyHashFromBytes vrfBytes)+ proportion <- evalEither (Unit.mkUnitInterval numerator 1000)+ ipv4 <- evalEither (Relay.ipv4FromBytes ipBytes)+ ipv6 <- evalEither (Relay.ipv6FromBytes ip6Bytes)+ bls <- evalEither sampleBls+ let value = base {Pool.operator = poolOperator, Pool.vrfKeyHash = vrf, Pool.pledge = pledge, Pool.cost = cost, Pool.margin = proportion, Pool.blsKey = if withBls then Just bls else Nothing, Pool.metadata = if withMetadata then Pool.metadata base else Nothing, Pool.owners = Set.insert owner (Pool.owners base), Pool.relays = Relay.SingleHostAddress port (Just ipv4) (Just ipv6) : Pool.relays base}+ Pool.decodeCbor (Pool.encodeCbor value) === Right value+ evalIO (nativeAgreement 0 (Pool.encodeCbor value))++propIpText :: Property+propIpText = property $ do+ ipv4 <- evalEither . Relay.ipv4FromBytes =<< forAll (Gen.bytes (Range.singleton 4))+ ipv6 <- evalEither . Relay.ipv6FromBytes =<< forAll (Gen.bytes (Range.singleton 16))+ Relay.ipv4FromText (Relay.ipv4Text ipv4) === Right ipv4+ Relay.ipv6FromText (Relay.ipv6Text ipv6) === Right ipv6++nativeAgreement :: CUInt -> ByteString -> IO ()+nativeAgreement mode encoded = ByteString.useAsCStringLen encoded $ \(input, size) -> do+ agrees <- cAgreement mode (castPtr input) (fromIntegral size)+ agrees @?= 1++hex :: String -> Either Error ByteString+hex text = maybe (Left InvalidHex) Right (Hex.decodeHex (Text.pack text))++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Left failure -> assertFailure (show failure) >> fail "unreachable assertion"+ Right value -> pure value++-- Native vectors: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/pool_params/{pool_params,pool_metadata,bls_key,relay}.cpp.+-- Copyright Biglup Labs, Apache-2.0. Groups below lack the public array framing.++nativeParameters :: String+nativeParameters = "581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db01927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"++nativeNoMetadata :: String+nativeNoMetadata = "581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db01927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6df6"++nativeWithBls :: String+nativeWithBls = "581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0825860000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f5830606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f1927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"++nativeNullBls :: String+nativeNullBls = "581cd85087c646951407198c27b1b950fd2e99f28586c000ce39f6e6ef9258208dd154228946bd12967c12bedb1cb6038b78f8b84a1760b1a788fa72a4af3db0f61927101903e8d81e820105581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810fd9010281581ccb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8383011913886b6578616d706c652e636f6d8400191770447f000001f682026b6578616d706c652e636f6d827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"++nativeMetadata :: String+nativeMetadata = "827368747470733a2f2f6578616d706c652e636f6d58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5"++nativeBls :: String+nativeBls = "825860000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f5830606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f"++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_pool_agreement"+ cAgreement :: CUInt -> Ptr Word8 -> CSize -> IO CInt++checkOwnerWitnesses :: IO ()+checkOwnerWitnesses = do+ latest <- expectRight sample+ bls <- expectRight sampleBls+ equivalentMargin <- expectRight (Unit.mkUnitInterval 2 10)+ Pool.requiresOwnerWitnesses latest Nothing @?= True+ Pool.requiresOwnerWitnesses latest (Just latest) @?= False+ Pool.requiresOwnerWitnesses (latest {Pool.blsKey = Just bls}) (Just latest) @?= False+ Pool.requiresOwnerWitnesses (latest {Pool.margin = equivalentMargin}) (Just latest) @?= False+ Pool.requiresOwnerWitnesses (latest {Pool.cost = Pool.cost latest + 1}) (Just latest) @?= True
@@ -0,0 +1,284 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Pure proposal workflows and pinned native fresh-construction differential tests.+-- Imported CBOR constants: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/proposal_procedures/{hard_fork_initiation_action,treasury_withdrawals_action,+-- no_confidence_action,update_committee_action,new_constitution_action,info_action}.cpp.+-- Copyright Biglup Labs, Apache-2.0. Properties and generators are original Cometa tests.+module Proposals (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.NetworkId as Network+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.ProposedUpdates as Legacy+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.TransactionId as TxId+import qualified Cometa.UnitInterval as Interval+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Either (isLeft)+import qualified Data.Text as Text+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Governance proposals"+ [ testCase "all seven actions reconstruct freshly with optional fields" checkActions,+ testCase "proposals preserve order, duplicates, and unsigned amount bounds" checkProposals,+ testCase "committee and constitution reconstruct fields" checkCommittee,+ testCase "legacy maps and envelopes reconstruct sorted updates" checkLegacy,+ testCase "invalid schemas and duplicate map keys are rejected" checkInvalid,+ testCase "exact wrappers preserve nonminimal and indefinite encodings" checkExact,+ testCase "pinned native corpus decodes through public semantic values" checkPinned,+ testCase "repeated retained-getter reconstruction releases all local owners" checkRepeated,+ testProperty "amount and policy boundaries round trip and agree with native" propRoundTrip,+ testProperty "ordered proposal append is associative with empty identity" propAppend+ ]++sampleAnchor :: Either Error Anchor.Anchor+sampleAnchor = Anchor.Anchor <$> Anchor.mkUrl "https://www.someurl.io" <*> Anchor.dataHashFromBytes (BS.replicate 32 0)++sampleAccount :: Word8 -> Either Error Reward.RewardAddress+sampleAccount prefix =+ Reward.fromCredential Network.testnet . Credential.KeyCredential+ <$> Credential.keyHashFromBytes (BS.replicate 28 prefix)++sampleActions :: Word64 -> Either Error [Action.Action]+sampleActions amount = do+ anchor <- sampleAnchor+ account <- sampleAccount 2+ secondAccount <- sampleAccount 1+ cold <- Credential.KeyCredential <$> Credential.keyHashFromBytes (BS.replicate 28 1)+ script <- Credential.ScriptCredential <$> Credential.scriptHashFromBytes (BS.replicate 28 2)+ policy <- Credential.scriptHashFromBytes (BS.replicate 28 3)+ tx <- TxId.fromBytes (BS.replicate 32 0)+ let previous = ActionId.ActionId tx maxBound+ members <- Committee.membersFromList [(script, amount), (cold, 0)]+ withdrawals <- Action.withdrawalsFromList [(account, amount), (secondAccount, 0)]+ quorum <- Interval.mkUnitInterval 2 3+ let changes = Update.empty {Update.updateMinFeeA = Just amount}+ pure+ [ Action.ParameterChange Nothing changes Nothing,+ Action.ParameterChange (Just previous) changes (Just policy),+ Action.HardForkInitiation Nothing (Version.ProtocolVersion maxBound maxBound),+ Action.HardForkInitiation (Just previous) (Version.ProtocolVersion 9 0),+ Action.TreasuryWithdrawals withdrawals Nothing,+ Action.TreasuryWithdrawals withdrawals (Just policy),+ Action.NoConfidence Nothing,+ Action.NoConfidence (Just previous),+ Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers quorum,+ Action.UpdateCommittee (Just previous) (Action.removalsFromList [script, cold, cold]) members quorum,+ Action.NewConstitution Nothing (Constitution.Constitution anchor Nothing),+ Action.NewConstitution (Just previous) (Constitution.Constitution anchor (Just policy)),+ Action.InfoAction+ ]++modeOf :: Action.Action -> CUInt+modeOf action = case action of+ Action.ParameterChange {} -> 0+ Action.HardForkInitiation {} -> 1+ Action.TreasuryWithdrawals {} -> 2+ Action.NoConfidence {} -> 3+ Action.UpdateCommittee {} -> 4+ Action.NewConstitution {} -> 5+ Action.InfoAction -> 6++checkActions :: IO ()+checkActions = forM_ [0, 1, maxBound] $ \amount -> do+ actions <- expectRight (sampleActions amount)+ forM_ actions $ \action -> do+ let encoded = Action.encodeCbor action+ fmap Action.toAction (Action.decodeCbor encoded) @?= Right action+ nativeAgreement (modeOf action) encoded++sampleProposal :: Word64 -> Action.Action -> Either Error Proposal.Proposal+sampleProposal amount action = Proposal.Proposal amount <$> sampleAccount 1 <*> pure action <*> sampleAnchor++checkProposals :: IO ()+checkProposals = do+ actions <- expectRight (sampleActions maxBound)+ proposals <- traverse (expectRight . sampleProposal maxBound) actions+ forM_ proposals $ \proposal -> do+ fmap Proposal.toProposal (Proposal.decodeCbor (Proposal.encodeCbor proposal)) @?= Right proposal+ nativeAgreement 10 (Proposal.encodeCbor proposal)+ let collection = Proposal.fromList (proposals <> proposals)+ Proposal.toList collection @?= proposals <> proposals+ fmap Proposal.toProposals (Proposal.decodeProposals (Proposal.encodeProposals collection)) @?= Right collection+ nativeAgreement 11 (Proposal.encodeProposals collection)+ nativeAgreement 11 (Proposal.encodeProposals Proposal.empty)++checkCommittee :: IO ()+checkCommittee = do+ anchor <- expectRight sampleAnchor+ policy <- expectRight (Credential.scriptHashFromBytes (BS.replicate 28 5))+ forM_ [Nothing, Just policy] $ \script -> do+ let constitution = Constitution.Constitution anchor script+ Constitution.decodeCbor (Constitution.encodeCbor constitution) @?= Right constitution+ nativeAgreement 7 (Constitution.encodeCbor constitution)+ cold <- Credential.KeyCredential <$> expectRight (Credential.keyHashFromBytes (BS.replicate 28 0))+ script <- Credential.ScriptCredential <$> expectRight (Credential.scriptHashFromBytes (BS.replicate 28 1))+ members <- expectRight (Committee.membersFromList [(script, maxBound), (cold, 0)])+ quorum <- expectRight (Interval.mkUnitInterval 1 1)+ let committee = Committee.Committee members quorum+ Committee.decodeCbor (Committee.encodeCbor committee) @?= Right committee+ nativeAgreement 8 (Committee.encodeCbor committee)+ nativeAgreement 9 (Committee.encodeMembers members)+ Committee.membersFromList [(cold, 0), (cold, 1)] @?= Left DuplicateCommitteeMember++checkLegacy :: IO ()+checkLegacy = do+ high <- expectRight (Credential.keyHashFromBytes (BS.replicate 28 255))+ low <- expectRight (Credential.keyHashFromBytes (BS.replicate 28 0))+ let changes = Update.empty {Update.updateMinFeeB = Just maxBound}+ entries <- expectRight (Legacy.fromList [(high, changes), (low, Update.empty)])+ fmap fst (Legacy.toList entries) @?= [low, high]+ fmap Legacy.toUpdates (Legacy.decodeCbor (Legacy.encodeCbor entries)) @?= Right entries+ nativeAgreement 12 (Legacy.encodeCbor entries)+ forM_ [0, maxBound] $ \epoch -> do+ let proposal = Legacy.UpdateProposal epoch entries+ fmap Legacy.toProposal (Legacy.decodeProposal (Legacy.encodeProposal proposal)) @?= Right proposal+ nativeAgreement 13 (Legacy.encodeProposal proposal)+ Legacy.fromList [(low, changes), (low, Update.empty)] @?= Left DuplicateProtocolUpdate++checkInvalid :: IO ()+checkInvalid = do+ forM_ ["", "00", "8107", "8206f6", "810600", "9f06f6ff", "820321", "8203f5"] $ \hex -> do+ bytes <- hexBytes hex+ assertBool "invalid action rejected" (isLeft (Action.decodeCbor bytes))+ account <- expectRight (sampleAccount 1)+ Action.withdrawalsFromList [(account, 0), (account, 1)] @?= Left DuplicateTreasuryWithdrawal+ let invalidProposal = BS.pack [0x84, 0, 0x40, 0x81, 6, 0x80]+ assertBool "reward account schema enforced" (isLeft (Proposal.decodeCbor invalidProposal))+ let key = "581c" <> replicate 56 '0'+ duplicate <- hexBytes ("a2" <> key <> "a0" <> key <> "a0")+ assertBool "legacy duplicate map rejected" (isLeft (Legacy.decodeCbor duplicate))+ badEpoch <- hexBytes "82a020"+ assertBool "negative epoch rejected" (isLeft (Legacy.decodeProposal badEpoch))++checkExact :: IO ()+checkExact = do+ bytes <- hexBytes "9f1806ff"+ action <- expectRight (Action.decodeCbor bytes)+ Action.toAction action @?= Action.InfoAction+ Action.toCbor action @?= bytes+ Action.encodeCbor (Action.toAction action) @?= BS.pack [0x81, 6]+ proposal <- expectRight (sampleProposal 0 Action.InfoAction)+ let freshProposal = Proposal.encodeCbor proposal+ nonminimalProposal = BS.take 1 freshProposal <> BS.pack [0x18, 0] <> BS.drop 2 freshProposal+ importedProposal <- expectRight (Proposal.decodeCbor nonminimalProposal)+ Proposal.toCbor importedProposal @?= nonminimalProposal+ Proposal.toProposal importedProposal @?= proposal+ listBytes <- hexBytes "9fff"+ collection <- expectRight (Proposal.decodeProposals listBytes)+ Proposal.proposalsCbor collection @?= listBytes+ Proposal.toProposals collection @?= Proposal.empty+ legacyBytes <- hexBytes "9fbfff1800ff"+ legacy <- expectRight (Legacy.decodeProposal legacyBytes)+ Legacy.proposalCbor legacy @?= legacyBytes+ Legacy.toProposal legacy @?= Legacy.UpdateProposal 0 Legacy.empty++checkPinned :: IO ()+checkPinned = forM_ pinnedVectors $ \(mode, hex) -> do+ bytes <- hexBytes hex+ encoded <- expectRight (Action.decodeCbor bytes)+ -- Inspection and fresh reassembly exercise public semantic payloads.+ let semantic = Action.toAction encoded+ Action.toCbor encoded @?= bytes+ nativeAgreement mode (Action.encodeCbor semantic)++checkRepeated :: IO ()+checkRepeated = replicateM_ 30 (checkProposals >> checkLegacy >> checkCommittee)++propRoundTrip :: Property+propRoundTrip = property $ do+ amount <- forAll (Gen.word64 Range.constantBounded)+ actions <- evalEither (sampleActions amount)+ forM_ actions $ \action -> do+ let encoded = Action.encodeCbor action+ fmap Action.toAction (Action.decodeCbor encoded) === Right action+ result <- evalIO (nativeResult (modeOf action) encoded)+ result === 1++propAppend :: Property+propAppend = property $ do+ amounts <- forAll (Gen.list (Range.linear 0 8) (Gen.word64 Range.constantBounded))+ proposals <- evalEither (traverse (`sampleProposal` Action.InfoAction) amounts)+ let a = Proposal.fromList proposals+ b = Proposal.fromList (reverse proposals)+ c = Proposal.fromList (take 1 proposals)+ Proposal.append a Proposal.empty === a+ Proposal.append Proposal.empty a === a+ Proposal.append (Proposal.append a b) c === Proposal.append a (Proposal.append b c)++expectRight :: (Show error) => Either error value -> IO value+expectRight value = case value of+ Left failure -> assertFailure (show failure)+ Right result -> pure result++hexBytes :: String -> IO ByteString+hexBytes value = case Hex.decodeHex (Text.pack value) of+ Nothing -> assertFailure "Invalid test hexadecimal"+ Just result -> pure result++nativeAgreement :: CUInt -> ByteString -> IO ()+nativeAgreement mode bytes = do+ result <- nativeResult mode bytes+ assertBool ("native fresh reconstruction failed, mode " <> show mode) (result == 1)++nativeResult :: CUInt -> ByteString -> IO CInt+nativeResult mode bytes = BS.useAsCStringLen bytes $ \(ptr, size) -> c_agreement mode (castPtr ptr) (fromIntegral size)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_proposals_agreement"+ c_agreement :: CUInt -> Ptr Word8 -> CSize -> IO CInt++-- DEFINITIONS ----------------------------------------------------------------++pinnedVectors :: [(CUInt, String)]+pinnedVectors =+ [ (1, "8301825820000000000000000000000000000000000000000000000000000000000000000003820103"),+ (2, "8302a1581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f01581c8293d319ef5b3ac72366dd28006bd315b715f7e7cfcbd3004129b80d"),+ (3, "8203825820000000000000000000000000000000000000000000000000000000000000000003"),+ (4, "8504825820000000000000000000000000000000000000000000000000000000000000000003d90102828200581c000000000000000000000000000000000000000000000000000000008200581c20000000000000000000000000000000000000000000000000000000a28200581c30000000000000000000000000000000000000000000000000000000018200581c4000000000000000000000000000000000000000000000000000000002d81e820105"),+ (5, "830582582000000000000000000000000000000000000000000000000000000000000000000382827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000f6"),+ (6, "8106")+ ]
@@ -0,0 +1,211 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module ProtocolValues (tests) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import qualified Cometa.Protocol.CostModels as Costs+import qualified Cometa.Protocol.DRepVotingThresholds as DRep+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as ExUnits+import qualified Cometa.Protocol.PoolVotingThresholds as Pool+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.UnitInterval as Unit+import Data.Bits (testBit)+import Data.ByteString (ByteString)+import qualified Data.ByteString as BS+import Data.Either (isLeft)+import Data.Foldable (traverse_)+import Data.Ratio ((%))+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Protocol values"+ [ testCase "fraction bounds, numeric comparison and pair retention" checkRationals,+ testCase "tuple bounds and malformed CBOR" checkBounds,+ testCase "pinned native corpus values and invalid rational regression" checkCorpus,+ testCase "future cost language, signed costs and replacement" checkCosts,+ testCase "language views preserve V1 encoding and match native subsets" checkLanguageViews,+ testCase "typed native construction agrees with all foundational codecs" checkNative,+ testProperty "exact fractions preserve pairs and numeric order" propFractions,+ testProperty "full-width budgets agree with typed native construction" propBudgets+ ]++checkRationals :: IO ()+checkRationals = do+ half <- expectRight (Rational.mkNonNegativeRational 1 2)+ unreduced <- expectRight (Rational.mkNonNegativeRational 2 4)+ half @?= unreduced+ compare half unreduced @?= EQ+ Rational.toRational unreduced @?= (1 % 2)+ Rational.numerator unreduced @?= 2+ Rational.denominator unreduced @?= 4+ assertBool "wire pairs retained" (Rational.encodeCbor half /= Rational.encodeCbor unreduced)+ traverse_+ (\(n, d) -> Rational.mkNonNegativeRational n d @?= Left (InvalidProtocolRational n d))+ [(-1, 1), (1, 0), (1, -1), (2 ^ (64 :: Int), 1), (1, 2 ^ (64 :: Int))]+ Unit.mkUnitInterval 2 1 @?= Left (InvalidUnitInterval 2 1)+ traverse_ (expectRight . uncurry Unit.mkUnitInterval) [(0, 1), (1, 1), (2, 4)]+ large <- expectRight (Rational.mkNonNegativeRational 2 1)+ Prices.decodeCbor (Prices.encodeCbor (Prices.ExUnitPrices large half)) @?= Right (Prices.ExUnitPrices large half)++checkBounds :: IO ()+checkBounds = do+ ExUnits.mkExUnits (-1) 0 @?= Left (InvalidExUnits (-1) 0)+ ExUnits.mkExUnits 0 (2 ^ (64 :: Int)) @?= Left (InvalidExUnits 0 (2 ^ (64 :: Int)))+ Version.mkProtocolVersion 0 (2 ^ (32 :: Int)) @?= Left (InvalidProtocolVersion 0 (2 ^ (32 :: Int)))+ Version.decodeCbor (Version.encodeCbor (Version.ProtocolVersion maxBound maxBound)) @?= Right (Version.ProtocolVersion maxBound maxBound)+ traverse_+ (assertBool "reject malformed rational" . isLeft . Rational.decodeCbor . BS.pack)+ [[0x82, 1, 2], [0xd8, 30, 0x82, 1, 0], [0xd8, 30, 0x81, 1], [0xd8, 30, 0x83, 1, 2, 3], [0xd8, 30, 0x82, 1, 2, 0]]+ Unit.decodeCbor (BS.pack [0xd8, 30, 0x82, 2, 1]) `assertLeft` "unit upper bound"+ ExUnits.decodeCbor (BS.pack [0x9f, 1, 2, 0xff]) @?= Right (ExUnits.ExUnits 1 2)+ ExUnits.decodeCbor (BS.pack [0x9f, 1, 2, 3, 0xff]) `assertLeft` "extra indefinite field"+ Version.decodeCbor (BS.pack [0x82, 0, 0x1b, 0, 0, 0, 1, 0, 0, 0, 0]) `assertLeft` "minor u32 bound"++-- Native vectors: cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/common/{unit_interval,ex_units,protocol_version}.cpp and+-- lib/tests/protocol_params/{ex_unit_prices,pool_voting_thresholds}.cpp;+-- Apache-2.0. Bytes below transcribe the named CBOR constants.+checkCorpus :: IO ()+checkCorpus = do+ fraction <- expectRight (Rational.decodeCbor (BS.pack [0xd8, 30, 0x82, 1, 5]))+ Rational.numerator fraction @?= 1+ Rational.denominator fraction @?= 5+ Version.decodeCbor (BS.pack [0x82, 1, 3]) @?= Right (Version.ProtocolVersion 1 3)+ budget <- expectRight (ExUnits.decodeCbor (BS.pack [0x82, 0x1b, 0, 0, 0x86, 0x78, 0x8f, 0xfc, 0x4e, 0x83, 0x1b, 0, 1, 0x50, 0x60, 0xe9, 0xe4, 0x64, 0x51]))+ ExUnits.memory budget @?= 0x86788ffc4e83+ ExUnits.steps budget @?= 0x15060e9e46451+ prices <- expectRight (Prices.decodeCbor (BS.pack [0x82, 0xd8, 30, 0x82, 1, 2, 0xd8, 30, 0x82, 1, 3]))+ Rational.toRational (Prices.memoryPrice prices) @?= (1 % 2)+ Rational.toRational (Prices.stepPrice prices) @?= (1 % 3)+ -- Native pool fixture starts with 0/0; a proportion cannot have denominator 0.+ Pool.decodeCbor (BS.pack [0x85, 0xd8, 30, 0x82, 0, 0, 0xd8, 30, 0x82, 1, 1, 0xd8, 30, 0x82, 2, 2, 0xd8, 30, 0x82, 3, 3, 0xd8, 30, 0x82, 4, 4]) `assertLeft` "undefined native proportion"++checkCosts :: IO ()+checkCosts = do+ future <- expectRight (Costs.mkCostModel 255 [minBound, 0, maxBound])+ replacement <- expectRight (Costs.mkCostModel 255 [7])+ original <- expectRight (Costs.mkCostModel 0 [])+ let models = Costs.fromList [future, original, replacement]+ Costs.lookup 255 models @?= Just replacement+ fmap Costs.languageId (Costs.toList models) @?= [0, 255]+ Costs.decodeCbor (Costs.encodeCbor models) @?= Right models+ Costs.decodeCostModelCbor 255 (Costs.encodeCostModelCbor future) @?= Right future+ Costs.mkCostModel 0 (replicate 2049 0) @?= Left (InvalidCostModelLength 2049)+ full <- expectRight (Costs.mkCostModel 0 (replicate 2048 0))+ Costs.decodeCostModelCbor 0 (Costs.encodeCostModelCbor full) @?= Right full+ Costs.decodeCbor (BS.pack [0xa2, 0, 0x80, 0, 0x80]) `assertLeft` "duplicate language"+ Costs.decodeCbor (BS.pack [0xa1, 0x19, 1, 0, 0x80]) `assertLeft` "language u8 bound"+ Costs.decodeCostModelCbor 0 (BS.pack ([0x9f] ++ replicate 2049 0 ++ [0xff])) `assertLeft` "indefinite vector bound"+ indefinite <- expectRight (Costs.decodeCostModelCbor 255 (BS.pack [0x9f, 0x20, 0, 0xff]))+ Costs.costs indefinite @?= [-1, 0]+ Costs.decodeCostModelCbor 0 (BS.pack [0x81, 0x1b, 0x80, 0, 0, 0, 0, 0, 0, 0]) `assertLeft` "int64 overflow"++checkNative :: IO ()+checkNative = do+ r <- expectRight (Rational.mkNonNegativeRational 2 4)+ u <- expectRight (Unit.mkUnitInterval 2 4)+ otherR <- expectRight (Rational.mkNonNegativeRational 4 6)+ otherU <- expectRight (Unit.mkUnitInterval 4 6)+ let prices = Prices.ExUnitPrices r otherR+ pool = Pool.PoolVotingThresholds u otherU u otherU u+ drep = DRep.DRepVotingThresholds u otherU u otherU u otherU u otherU u otherU+ m <- expectRight (Costs.mkCostModel 0 [-1, 0, maxBound])+ let cases = [(0, Rational.encodeCbor r), (1, ExUnits.encodeCbor (ExUnits.ExUnits 2 4)), (2, Version.encodeCbor (Version.ProtocolVersion 2 4)), (3, Prices.encodeCbor prices), (4, Pool.encodeCbor pool), (5, DRep.encodeCbor drep), (6, Costs.encodeCbor (Costs.fromList [m]))]+ traverse_ (\(kind, bytes) -> oracle kind 2 4 >>= (@?= bytes)) cases+ Pool.decodeCbor (Pool.encodeCbor pool) @?= Right pool+ DRep.decodeCbor (DRep.encodeCbor drep) @?= Right drep++propFractions :: Property+propFractions = property $ do+ n <- forAll (Gen.word64 Range.constantBounded)+ d <- forAll (Gen.word64 (Range.constant 1 maxBound))+ r <- evalEither (Rational.mkNonNegativeRational (toInteger n) (toInteger d))+ decoded <- evalEither (Rational.decodeCbor (Rational.encodeCbor r))+ Rational.numerator decoded === n+ Rational.denominator decoded === d+ Rational.toRational decoded === (toInteger n % toInteger d)+ otherN <- forAll (Gen.word64 Range.constantBounded)+ otherD <- forAll (Gen.word64 (Range.constant 1 maxBound))+ other <- evalEither (Rational.mkNonNegativeRational (toInteger otherN) (toInteger otherD))+ compare r other === compare (toInteger n % toInteger d) (toInteger otherN % toInteger otherD)+ native <- evalIO (oracle 0 n d)+ Rational.encodeCbor r === native++propBudgets :: Property+propBudgets = property $ do+ m <- forAll (Gen.word64 Range.constantBounded)+ s <- forAll (Gen.word64 Range.constantBounded)+ let budget = ExUnits.ExUnits m s+ ExUnits.decodeCbor (ExUnits.encodeCbor budget) === Right budget+ native <- evalIO (oracle 1 m s)+ ExUnits.encodeCbor budget === native++assertLeft :: Either a b -> String -> IO ()+assertLeft value label = assertBool label (isLeft value)++expectRight :: (Show e) => Either e a -> IO a+expectRight (Right value) = pure value+expectRight (Left failure) = assertFailure (show failure) >> fail "unreachable"++oracle :: Word8 -> Word64 -> Word64 -> IO ByteString+oracle kind first second = allocaBytes 1024 $ \output -> alloca $ \size -> do+ status <- cOracle kind first second (castPtr output) 1024 size+ status @?= 0+ count <- peek size+ BS.packCStringLen (castPtr output, fromIntegral count)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_protocol_values_oracle"+ cOracle :: Word8 -> Word64 -> Word64 -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt++-- Native oracle: pinned costmdls.c, known language views; exact V1 bytes are+-- independently stated below, including the historical indefinite-array defect.+checkLanguageViews :: IO ()+checkLanguageViews = do+ Costs.encodeLanguageViews Costs.empty @?= BS.singleton 0xa0+ one <- expectRight (Costs.mkCostModel 0 [1, -2])+ Costs.encodeLanguageViews (Costs.fromList [one])+ @?= BS.pack [0xa1, 0x41, 0, 0x44, 0x9f, 1, 0x21, 0xff]+ forEachMask [0 .. 31]+ where+ forEachMask = traverse_ $ \mask -> do+ models <-+ traverse+ (\language -> expectRight (Costs.mkCostModel language [minBound, -1, 0, maxBound]))+ [if bit == 4 then 255 else fromIntegral bit | bit <- [0 .. 4], testBit mask bit]+ native <- oracle 7 mask 0+ Costs.encodeLanguageViews (Costs.fromList models) @?= native
@@ -0,0 +1,307 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Every provider callback is exercised through actual typed native dispatch.+module Provider (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import Cometa.AssetId (AssetId (..))+import qualified Cometa.AssetName as AssetName+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import Cometa.Internal.FFI.Native (NativeCode)+import qualified Cometa.Internal.FFI.ProviderRuntime as FFI+import qualified Cometa.Internal.ProviderRuntime as Native+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionCbor+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Provider as Provider+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, bracket_, fromException, try)+import Control.Monad (forM_, replicateM_, void)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.Text as Text+import qualified Data.Text.Encoding as Text+import Data.Word (Word32, Word8)+import qualified Fixtures.ProtocolParameters as Parameters+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- TYPES ----------------------------------------------------------------------++data Fixture = Fixture Address.Address Reward.RewardAddress AssetId Utxo.Utxo Datum.Hash32 Tx.Transaction TxId.TransactionId Evaluation.Budgets++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Provider injection"+ [ testCase "all ten callbacks marshal typed values through native provider methods" correspondence,+ testCase "unsupported capabilities preserve exact errors through native failures" unsupported,+ testCase "missing datum and NFT remain successful Nothing, and empty queries remain empty" missing,+ testCase "name byte bounds reject before acquiring registrations" metadata,+ testCase "typed snapshots outlive native cleanup and repeated GC" lifetime,+ testCase "lazy query results and callback exceptions unwind before releasing owners" exceptions,+ testCase "native confirmation cancellation joins callback cleanup and recovers" cancellation,+ testCase "trailing requests avoid handlers and partial malformed replies release typed owners" malformed+ ]++fixture :: Either Error Fixture+fixture = do+ address <- Address.fromBytes (B.cons 0x61 (B.replicate 28 1))+ reward <- Reward.fromBytes (B.cons 0xe1 (B.replicate 28 2))+ policy <- Policy.fromBytes (B.replicate 28 3)+ token <- AssetName.fromBytes "token"+ identifier <- TxId.fromBytes (B.replicate 32 4)+ output <- Output.mkOutput address (Cometa.Value.lovelace 2000000) Datum.NoDatum Nothing+ hash <- Datum.hashFromBytes (B.replicate 32 5)+ let reference = Input.input identifier maxBound+ resolved = Utxo.utxo reference output+ redeemer = Redeemer.Redeemer Redeemer.Spending 0 (Data.fromData (Data.Integer 42)) (ExUnits 1 2)+ encodedBody <- Body.fromBody (Body.body [] [] 10)+ witnesses <- Witnesses.mkWitnesses [] [] [] [] [redeemer]+ let transaction = Tx.assemble encodedBody (Witnesses.fromWitnesses witnesses) Nothing+ budgets <- Evaluation.mkBudgets [(Evaluation.RedeemerId Redeemer.Spending 0, ExUnits 100 200)]+ pure (Fixture address reward (Native policy token) resolved hash transaction identifier budgets)++backend :: Fixture -> Provider.Provider+backend (Fixture address reward asset resolved hash transaction identifier budgets) =+ (Provider.unavailable "Fixture provider" 42)+ { Provider.protocolParameters = pure Parameters.parameters,+ Provider.utxosAt = \actual -> do+ actual @?= address+ pure (Right [resolved]),+ Provider.rewardBalance = \actual -> do+ actual @?= reward+ pure (Right maxBound),+ Provider.utxosWithAsset = \actual selected -> do+ actual @?= address+ selected @?= asset+ pure (Right [resolved]),+ Provider.utxoWithAsset = \selected -> do+ selected @?= asset+ pure (Right (Just resolved)),+ Provider.resolveInputs = \references -> do+ references @?= [Utxo.input resolved]+ pure (Right [resolved]),+ Provider.resolveDatum = \actual -> do+ actual @?= hash+ pure (Right (Just (Data.fromData (Data.Integer 42)))),+ Provider.awaitTransaction = \actual timeoutMillis -> do+ actual @?= identifier+ timeoutMillis @?= maxBound+ pure (Right True),+ Provider.submitTransaction = \actual -> do+ Tx.body actual @?= Tx.body transaction+ pure (Right identifier),+ Provider.evaluateTransaction = \actual additional -> do+ Tx.body actual @?= Tx.body transaction+ additional @?= [resolved]+ pure (Right budgets)+ }++correspondence :: IO ()+correspondence = do+ values@(Fixture address reward asset resolved hash transaction identifier budgets) <- requirePure fixture+ expectedParameters <- requirePure Parameters.parameters+ result <- Native.withProvider (backend values) $ \adapter -> do+ let provider = Native.nativeProvider adapter+ Provider.name provider @?= "Fixture provider"+ Provider.networkMagic provider @?= 42+ Provider.protocolParameters provider >>= (@?= Right expectedParameters)+ Provider.utxosAt provider address >>= (@?= Right [resolved])+ Provider.rewardBalance provider reward >>= (@?= Right maxBound)+ Provider.utxosWithAsset provider address asset >>= (@?= Right [resolved])+ Provider.utxoWithAsset provider asset >>= (@?= Right (Just resolved))+ Provider.resolveInputs provider [Utxo.input resolved] >>= (@?= Right [resolved])+ Provider.resolveDatum provider hash >>= (@?= Right (Just (Data.fromData (Data.Integer 42))))+ Provider.awaitTransaction provider identifier maxBound >>= (@?= Right True)+ Provider.submitTransaction provider transaction >>= (@?= Right identifier)+ Provider.evaluateTransaction provider transaction [resolved] >>= (@?= Right budgets)+ pure (Right ())+ result @?= Right ()++unsupported :: IO ()+unsupported = do+ Fixture address reward asset resolved hash transaction identifier _ <- requirePure fixture+ result <- Native.withProvider (Provider.unavailable "Unavailable" 7) $ \adapter -> do+ let provider = Native.nativeProvider adapter+ unit :: IO (Either Error a) -> IO (Either Error ())+ unit = fmap void+ operations =+ [ ("protocolParameters", unit (Provider.protocolParameters provider)),+ ("utxosAt", unit (Provider.utxosAt provider address)),+ ("rewardBalance", unit (Provider.rewardBalance provider reward)),+ ("utxosWithAsset", unit (Provider.utxosWithAsset provider address asset)),+ ("utxoWithAsset", unit (Provider.utxoWithAsset provider asset)),+ ("resolveInputs", unit (Provider.resolveInputs provider [Utxo.input resolved])),+ ("resolveDatum", unit (Provider.resolveDatum provider hash)),+ ("awaitTransaction", unit (Provider.awaitTransaction provider identifier 0)),+ ("submitTransaction", unit (Provider.submitTransaction provider transaction)),+ ("evaluateTransaction", unit (Provider.evaluateTransaction provider transaction [resolved]))+ ]+ forM_ operations $ \(operation, action) -> action >>= (@?= Left (UnsupportedOperation ("provider." <> operation)))+ pure (Right ())+ result @?= Right ()++missing :: IO ()+missing = do+ Fixture address _ asset resolved hash _ _ _ <- requirePure fixture+ let provider =+ (Provider.unavailable "Empty" 8)+ { Provider.utxosAt = \_ -> pure (Right []),+ Provider.resolveInputs = \_ -> pure (Right []),+ Provider.utxoWithAsset = \_ -> pure (Right Nothing),+ Provider.resolveDatum = \_ -> pure (Right Nothing)+ }+ result <- Native.withProvider provider $ \adapter -> do+ let native = Native.nativeProvider adapter+ Provider.utxosAt native address >>= (@?= Right [])+ Provider.resolveInputs native [Utxo.input resolved] >>= (@?= Right [])+ Provider.utxoWithAsset native asset >>= (@?= Right Nothing)+ Provider.resolveDatum native hash >>= (@?= Right Nothing)+ pure (Right ())+ result @?= Right ()++metadata :: IO ()+metadata = do+ baseline <- Runtime.liveContexts+ forM_ [Text.replicate 256 "a", Text.replicate 128 "é", "bad\0name"] $ \backendName -> do+ result <- Native.withProvider (Provider.unavailable backendName 1) (\_ -> assertFailure "invalid metadata acquired a callback" >> pure (Right ()))+ assertBool "invalid name accepted" (isLeft result)+ let validName = Text.replicate 127 "é" <> "a"+ nativeMetadata <- Native.withProvider (Provider.unavailable validName maxBound) $ \adapter -> Native.withNative adapter $ \pointer ->+ allocaBytes 256 $ \nameOutput -> alloca $ \magicOutput -> do+ status <- cMetadata pointer nameOutput 256 magicOutput+ status @?= 0+ actualName <- B.packCString (castPtr nameOutput)+ actualMagic <- peek magicOutput+ actualName @?= Text.encodeUtf8 validName+ actualMagic @?= maxBound+ pure (Right ())+ nativeMetadata @?= Right ()+ Runtime.liveContexts >>= (@?= baseline)++lifetime :: IO ()+lifetime = do+ values@(Fixture address _ _ resolved _ _ _ _) <- requirePure fixture+ baseline <- Runtime.liveContexts+ result <- Native.withProvider (backend values) $ \adapter -> do+ let provider = Native.nativeProvider adapter+ replicateM_ 20 (performGC >> Provider.utxosAt provider address >>= (@?= Right [resolved]))+ Provider.utxosAt provider address+ performGC+ result @?= Right [resolved]+ Runtime.liveContexts >>= (@?= baseline)++exceptions :: IO ()+exceptions = do+ Fixture address _ _ _ _ _ _ _ <- requirePure fixture+ baseline <- Runtime.liveContexts+ forM_ [pure (Right (error "lazy UTxO list")), ioError (userError "query exception")] $ \query -> do+ let provider = (Provider.unavailable "Throwing" 42) {Provider.utxosAt = const query}+ outcome <- try (Native.withProvider provider (\adapter -> Provider.utxosAt (Native.nativeProvider adapter) address)) :: IO (Either SomeException (Either Error [Utxo.Utxo]))+ assertBool "query exception swallowed" (isLeft outcome)+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ Fixture _ _ _ _ _ _ identifier _ <- requirePure fixture+ started <- newEmptyMVar+ finalized <- newEmptyMVar+ hold <- newEmptyMVar+ count <- newIORef (0 :: Int)+ let await _ _ = do+ calls <- readIORef count+ modifyIORef' count (+ 1)+ if calls == 0+ then bracket_ (putMVar started ()) (putMVar finalized ()) (takeMVar hold)+ else pure (Right True)+ provider = (Provider.unavailable "Cancelable" 42) {Provider.awaitTransaction = await}+ result <- Native.withProvider provider $ \adapter -> do+ let native = Native.nativeProvider adapter+ finished <- newEmptyMVar+ worker <- forkFinally (Provider.awaitTransaction native identifier 10) (putMVar finished)+ takeMVar started+ Provider.awaitTransaction native identifier 10 >>= (@?= Left RuntimeBusy)+ joined <- timeout 5000000 (killThread worker >> takeMVar finished)+ case joined of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "provider cancellation failed to join"+ takeMVar finalized+ Provider.awaitTransaction native identifier 10+ result @?= Right True++malformed :: IO ()+malformed = do+ Fixture address _ _ resolved _ _ _ _ <- requirePure fixture+ baseline <- Runtime.liveContexts+ calls <- newIORef (0 :: Int)+ reply <- newIORef (B.singleton 0x80)+ let handler _ _ = modifyIORef' calls (+ 1) >> Right <$> readIORef reply+ request = Cometa.Internal.TransactionCbor.encode (Codec.CBOR.Encoding.encodeBytes (Address.toBytes address))+ result <- Runtime.withRuntime handler $ \owner -> do+ badRequest <- rawCall owner 1 (request <> B.singleton 0)+ assertBool "trailing native request accepted" (isLeft badRequest)+ readIORef calls >>= (@?= 0)+ writeIORef reply (B.singleton 0x82 <> Utxo.encodeCbor resolved <> B.singleton 0)+ replicateM_ 10 $ do+ partial <- rawCall owner 1 request+ assertBool "partial malformed reply accepted" (isLeft partial)+ writeIORef reply (B.singleton 0x80)+ rawCall owner 1 request+ result @?= Right (B.singleton 0x80)+ Runtime.liveContexts >>= (@?= baseline)++rawCall :: Runtime.Runtime -> Word32 -> B.ByteString -> IO (Either Error B.ByteString)+rawCall owner operation request = Runtime.withOperation owner $ \context ->+ Runtime.withBytes "Malformed fixture" $ \backendName nameSize -> Runtime.withBytes request $ \bytes size ->+ Runtime.withOwnedBuffer "test.provider.raw" (FFI.cCall context backendName nameSize 42 operation bytes size)++requirePure :: (Show failure) => Either failure a -> IO a+requirePure = either (\failure -> assertFailure (show failure) >> fail "provider fixture") pure++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_provider_metadata"+ cMetadata :: Ptr FFI.NativeProvider -> Ptr Word8 -> CSize -> Ptr Word32 -> IO NativeCode
@@ -0,0 +1,351 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module PublicTransaction (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PrivateKey as Private+import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.Crypto.Ed25519.PublicKey as Public+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.KeyHandler.Software as Software+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), IOException, bracket_, fromException, try)+import Control.Monad (forM_, replicateM_, void, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Text+import Data.Word (Word64, Word8)+import qualified Fixtures.Transaction as Fixture+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Public transaction workflows"+ [ testCase "pinned signed corpus exact bytes, typed fee and native ID agreement" corpus,+ testCase "all field orders and nonminimal/indefinite outer arrays preserve identity" framing,+ testCase "same-value body edits are exact no-ops and changed fees clear only outer signatures" edits,+ testCase "partial signatures preserve original body and wrapper and agree with native signing" signing,+ testCase "invalid complete envelopes and trailing bytes fail" invalid,+ testCase "software normal and extended handlers return partial witnesses without mutating input" software,+ testCase "hierarchical handler signs typed nonempty paths" hierarchical,+ testCase "closed, wrong-password and callback failures preserve the input and release resources" failures,+ testCase "signing callback cancellation joins cleanup and handler remains usable" cancellation,+ testCase "sub-transaction signs its own body and retains exact framing" subTransaction+ ]++corpus :: IO ()+corpus = forM_ Fixture.allFixtures $ \fixture -> do+ bytes <- hex (Fixture.transactionHex fixture)+ transaction <- requirePure (Tx.decodeCbor bytes)+ Tx.encodeCbor transaction @?= bytes+ Hex.encodeHex (Body.toCbor (Tx.body transaction)) @?= Fixture.bodyHex fixture+ Hex.encodeHex (Witnesses.toCbor (Tx.witnesses transaction)) @?= Fixture.witnessHex fixture+ Body.fee (Body.toBody (Tx.body transaction)) @?= Fixture.expectedFee fixture+ digest <- require (Tx.transactionId transaction)+ TxId.toHex digest @?= Fixture.hashHex fixture+ (nativeFee, nativeHash, counts) <- nativeSnapshot bytes+ nativeFee @?= Fixture.expectedFee fixture+ nativeHash @?= TxId.toBytes digest+ counts @?= Fixture.expectedCounts fixture+ Tx.hasScriptData transaction @?= (Fixture.fixtureName fixture == Fixture.fixtureName Fixture.rich)++framing :: IO ()+framing = do+ original <- fixtureTransaction Fixture.noncanonical+ rich <- fixtureTransaction Fixture.rich+ let components = Body.toCbor (Tx.body original) <> Witnesses.toCbor (Tx.witnesses original)+ layouts =+ [ (Tx.Historical, B.singleton 0x83 <> components <> B.singleton 0xf6),+ (Tx.Mempool, B.singleton 0x84 <> components <> B.pack [0xf5, 0xf6]),+ (Tx.Mempool, B.singleton 0x84 <> components <> B.pack [0xf4, 0xf6]),+ (Tx.Block, B.singleton 0x84 <> components <> B.pack [0xf6, 0xf5]),+ (Tx.Block, B.singleton 0x84 <> components <> B.pack [0xf6, 0xf4])+ ]+ variants (layout, bytes) =+ [ (layout, bytes),+ (layout, B.singleton 0x9f <> B.drop 1 bytes <> B.singleton 0xff),+ (layout, B.pack [0x98, B.head bytes - 0x80] <> B.drop 1 bytes)+ ]+ forM_ (concatMap variants layouts) $ \(layout, bytes) -> do+ transaction <- requirePure (Tx.decodeCbor bytes)+ Tx.encodeCbor transaction @?= bytes+ Tx.frame transaction @?= layout+ let attached = Tx.setAuxiliaryData (Tx.auxiliaryData rich) transaction+ Tx.body attached @?= Tx.body transaction+ Tx.witnesses attached @?= Tx.witnesses transaction+ Tx.setAuxiliaryData Nothing attached @?= transaction+ requirePure (Tx.decodeCbor (Tx.encodeCbor attached)) >>= (@?= attached)+ let fresh = Tx.assemble (Tx.body transaction) (Tx.witnesses transaction) (Tx.auxiliaryData rich)+ requirePure (Tx.decodeCbor (Tx.encodeCbor fresh)) >>= (@?= fresh)+ let changedClaim = Tx.setScriptValidity (not (Tx.scriptValidity transaction)) transaction+ Tx.setScriptValidity (Tx.scriptValidity transaction) transaction @?= transaction+ Tx.body changedClaim @?= Tx.body transaction+ Tx.witnesses changedClaim @?= Tx.witnesses transaction+ Tx.scriptValidity changedClaim @?= not (Tx.scriptValidity transaction)+ requirePure (Tx.decodeCbor (Tx.encodeCbor changedClaim)) >>= (@?= changedClaim)+ nativeSnapshot (Tx.encodeCbor changedClaim) >>= \(_, digest, _) -> Hex.encodeHex digest @?= Fixture.hashHex Fixture.noncanonical+ nativeSnapshot bytes >>= \(_, digest, _) -> Hex.encodeHex digest @?= Fixture.hashHex Fixture.noncanonical+ Tx.encodeCbor (Tx.setFee 10 transaction) @?= bytes+ signed <- require (Key.withNormalKey seed (`Signing.sign` transaction))+ Body.toCbor (Tx.body signed) @?= Body.toCbor (Tx.body transaction)+ Tx.frame signed @?= layout+ assertBool "outer header changed" (B.take (if B.head bytes == 0x98 then 2 else 1) (Tx.encodeCbor signed) == B.take (if B.head bytes == 0x98 then 2 else 1) bytes)+ assertBool "outer indefinite ending changed" (B.last (Tx.encodeCbor signed) == B.last bytes)++edits :: IO ()+edits = forM_ Fixture.allFixtures $ \fixture -> do+ transaction <- fixtureTransaction fixture+ normalized <- requirePure (Body.fromBody (Body.toBody (Tx.body transaction)))+ let unchanged = Tx.setBody normalized transaction+ changed = Tx.setFee 42 transaction+ changedAgain = Tx.setFee 43 transaction+ unchanged @?= transaction+ Tx.setFee (Fixture.expectedFee fixture) transaction @?= transaction+ Body.fee (Body.toBody (Tx.body changed)) @?= 42+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses changed)) @?= []+ Witnesses.bootstrapWitnesses (Witnesses.toWitnesses (Tx.witnesses changed)) @?= []+ before <- witnessFields transaction+ after <- witnessFields changed+ after @?= filter (\(key, _) -> key /= 0 && key /= 2) before+ Tx.auxiliaryData changed @?= Tx.auxiliaryData transaction+ first <- require (Tx.transactionId changed)+ second <- require (Tx.transactionId changedAgain)+ assertBool "independent fee edits share an ID" (first /= second)+ expected <- hex (Fixture.transactionHex fixture)+ Tx.encodeCbor transaction @?= expected+ requirePure (Tx.decodeCbor (Tx.encodeCbor changed)) >>= (@?= changed)++signing :: IO ()+signing = do+ transaction <- fixtureTransaction Fixture.noncanonical+ witness <- require (Key.withNormalKey seed (`Signing.verificationWitness` transaction))+ expected <- nativeSign 0 (Tx.encodeCbor transaction)+ Public.toBytes (Witness.publicKey witness) <> Signature.toBytes (Witness.signature witness) @?= expected+ signed <- require (Key.withNormalKey seed (`Signing.sign` transaction))+ twice <- require (Key.withNormalKey seed (`Signing.sign` signed))+ twice @?= signed+ Tx.body signed @?= Tx.body transaction+ Tx.transactionId signed >>= (\digest -> Tx.transactionId transaction >>= (@?= digest))+ digest <- require (Tx.transactionId signed)+ Public.verify (Witness.publicKey witness) (TxId.toBytes digest) (Witness.signature witness) >>= (@?= Right True)+ (_, _, counts) <- nativeSnapshot (Tx.encodeCbor signed)+ assertBool "new signature not verified by native oracle" (last counts > last (Fixture.expectedCounts Fixture.noncanonical))+ let invalidated = Tx.setFee 42 signed+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses invalidated)) @?= []+ before <- witnessFields transaction+ after <- witnessFields signed+ filter ((/= 0) . fst) before @?= filter ((/= 0) . fst) after++invalid :: IO ()+invalid = do+ transaction <- fixtureTransaction Fixture.noncanonical+ forM_ [B.empty, B.singleton 0, B.take 1 (Tx.encodeCbor transaction), B.init (Tx.encodeCbor transaction), Tx.encodeCbor transaction <> B.singleton 0] $ \bytes ->+ assertBool "invalid envelope accepted" (isLeft (Tx.decodeCbor bytes))+ forM_ ["82a0a0", "84a0a0f5f6", "84a3008001800220a0f5f6", "84a3008001800200a0f6f6", "9fa3008001800200a0f6f5f5ff"] $ hex >=> (assertBool "invalid schema accepted" . isLeft . Tx.decodeCbor)++software :: IO ()+software = do+ transaction <- fixtureTransaction Fixture.rich+ forM_ [False, True] $ \extended -> do+ let withKey action = if extended then Key.withExtendedKey (B.replicate 64 1) action else Key.withNormalKey seed action+ witness <- require (withKey (`Signing.verificationWitness` transaction))+ partial <- require (withKey (\key -> Software.withSigningKey key password (pure password) (`Software.signTransaction` transaction)))+ Witnesses.verificationWitnesses (Witnesses.toWitnesses partial) @?= [witness]+ signed <- requirePure (Tx.addWitnesses partial transaction)+ Tx.body signed @?= Tx.body transaction+ requirePure (Tx.decodeCbor (Tx.encodeCbor signed)) >>= (@?= signed)+ replicateM_ 5 (void (require (withKey (\key -> Software.withSigningKey key password (performGC >> pure password) (`Software.signTransaction` transaction)))))++hierarchical :: IO ()+hierarchical = do+ transaction <- fixtureTransaction Fixture.noncanonical+ let entropy = B.replicate 16 0+ path = Path.derivationPath (Path.standardAccountPath minBound) Path.externalRole minBound+ witness <- require (Private.withEntropy "" entropy (\root -> Private.withDerived root (Path.toIndices path) (\child -> Private.withSigningKey child (`Signing.verificationWitness` transaction))))+ partial <- require (Software.withEntropy entropy password (pure password) (\handler -> Software.signTransactionAt handler (path :| [path]) transaction))+ Witnesses.verificationWitnesses (Witnesses.toWitnesses partial) @?= [witness]++failures :: IO ()+failures = do+ transaction <- fixtureTransaction Fixture.noncanonical+ escaped <- newEmptyMVar+ _ <- require (Key.withNormalKey seed (\key -> putMVar escaped key >> pure (Right ())))+ closed <- takeMVar escaped+ Signing.sign closed transaction >>= (@?= Left SigningKeyClosed)+ handlerSlot <- newEmptyMVar+ _ <- require (withHandler (pure password) (\handler -> putMVar handlerSlot handler >> pure (Right ())))+ handler <- takeMVar handlerSlot+ Software.signTransaction handler transaction >>= (@?= Left KeyHandlerClosed)+ wrong <- withHandler (pure "wrong-password") (`Software.signTransaction` transaction)+ assertBool "wrong password accepted" (isLeft wrong)+ invalidPassword <- withHandler (pure B.empty) (`Software.signTransaction` transaction)+ invalidPassword @?= Left (InvalidKeyHandlerPasswordLength 0)+ ref <- newIORef Nothing+ callbackResult <- newIORef Nothing+ let request = do+ active <- readIORef ref+ case active of+ Nothing -> assertFailure "missing handler" >> pure password+ Just value -> do+ result <- Software.signTransaction value transaction+ modifyIORef' callbackResult (const (Just result))+ pure password+ _ <- require (withHandler request (\active -> modifyIORef' ref (const (Just active)) >> Software.signTransaction active transaction))+ readIORef callbackResult >>= (@?= Just (Left KeyHandlerBusy))+ failureCount <- newIORef (0 :: Int)+ let sometimesFails = do+ n <- readIORef failureCount+ modifyIORef' failureCount (+ 1)+ if n == 0 then ioError (userError "password action failed") else pure password+ _ <-+ require+ ( withHandler sometimesFails $ \active -> do+ first <- try (Software.signTransaction active transaction) :: IO (Either IOException (Either Error Witnesses.EncodedWitnesses))+ assertBool "callback exception swallowed" (isLeft first)+ Software.signTransaction active transaction+ )+ expected <- hex (Fixture.transactionHex Fixture.noncanonical)+ Tx.encodeCbor transaction @?= expected++cancellation :: IO ()+cancellation = do+ transaction <- fixtureTransaction Fixture.noncanonical+ started <- newEmptyMVar+ finalized <- newEmptyMVar+ hold <- newEmptyMVar+ count <- newIORef (0 :: Int)+ let request = do+ n <- readIORef count+ modifyIORef' count (+ 1)+ if n == 0 then bracket_ (putMVar started ()) (putMVar finalized ()) (takeMVar hold) else pure password+ result <- withHandler request $ \handler -> do+ finished <- newEmptyMVar+ worker <- forkFinally (Software.signTransaction handler transaction) (putMVar finished)+ takeMVar started+ Software.signTransaction handler transaction >>= (@?= Left KeyHandlerBusy)+ joined <- timeout 5000000 (killThread worker >> takeMVar finished)+ case joined of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "signing cancellation failed to join"+ takeMVar finalized+ Software.signTransaction handler transaction+ assertBool "handler failed after cancellation" (not (isLeft result))++subTransaction :: IO ()+subTransaction = do+ transaction <- requirePure (Sub.decodeCbor (B.pack [0x9f, 0xa2, 0, 0x80, 1, 0x80, 0xa0, 0xf6, 0xff]))+ signed <- require (Key.withNormalKey seed (`Signing.signSubTransaction` transaction))+ Sub.body signed @?= Sub.body transaction+ B.head (Sub.encodeCbor signed) @?= 0x9f+ B.last (Sub.encodeCbor signed) @?= 0xff+ witness <- require (Key.withNormalKey seed (`Signing.subTransactionWitness` transaction))+ expected <- nativeSign 1 (Sub.encodeCbor transaction)+ Public.toBytes (Witness.publicKey witness) <> Signature.toBytes (Witness.signature witness) @?= expected+ generated <- require (withHandler (pure password) (`Software.signSubTransaction` transaction))+ Witnesses.verificationWitnesses (Witnesses.toWitnesses generated) @?= [witness]+ normalized <- requirePure (SubBody.fromBody (SubBody.toBody (Sub.body signed)))+ Sub.setBody normalized signed @?= signed+ let enclosingBody = (Body.body [] [] 10) {Body.bodySubTransactions = Just [signed]}+ encodedOuter <- requirePure (Body.fromBody enclosingBody)+ let outer = Tx.fromBody encodedOuter+ outerSigned <- require (Key.withNormalKey seed (`Signing.sign` outer))+ let edited = Tx.setFee 42 outerSigned+ Body.bodySubTransactions (Body.toBody (Tx.body edited)) @?= Just [signed]+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses edited)) @?= []+ reloaded <- requirePure (Tx.decodeCbor (Tx.encodeCbor edited))+ Body.bodySubTransactions (Body.toBody (Tx.body reloaded)) @?= Just [signed]+ let path = Path.derivationPath (Path.standardAccountPath minBound) Path.externalRole minBound+ hierarchicalPartial <- require (Software.withEntropy (B.replicate 16 0) password (pure password) (\handler -> Software.signSubTransactionAt handler (path :| []) transaction))+ digest <- require (Sub.transactionId transaction)+ forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses hierarchicalPartial)) $ \value ->+ Public.verify (Witness.publicKey value) (TxId.toBytes digest) (Witness.signature value) >>= (@?= Right True)++seed :: ByteString+seed = B.replicate 32 42++password :: ByteString+password = "transaction-fixture"++withHandler :: IO ByteString -> (Software.Handler Software.Ed25519 -> IO (Either Error value)) -> IO (Either Error value)+withHandler request action = Key.withNormalKey seed (\key -> Software.withSigningKey key password request action)++fixtureTransaction :: Fixture.Fixture -> IO Tx.Transaction+fixtureTransaction fixture = hex (Fixture.transactionHex fixture) >>= requirePure . Tx.decodeCbor++hex :: Data.Text.Text -> IO ByteString+hex text = maybe (assertFailure "invalid fixture hex" >> fail "fixture") pure (Hex.decodeHex text)++require :: (Show failure) => IO (Either failure value) -> IO value+require action = action >>= requirePure++requirePure :: (Show failure) => Either failure value -> IO value+requirePure = either (\failure -> assertFailure (show failure) >> fail "fixture operation") pure++witnessFields :: Tx.Transaction -> IO [(Integer, ByteString)]+witnessFields transaction = do+ encoded <- require (Cbor.fromBytes (Witnesses.toCbor (Tx.witnesses transaction)))+ pairs <- require (Cbor.decodeMap encoded)+ mapM (\(key, value) -> do number <- require (Cbor.decodeInteger key); pure (number, Cbor.toBytes value)) pairs++nativeSnapshot :: ByteString -> IO (Word64, ByteString, [Word64])+nativeSnapshot bytes = B.useAsCStringLen bytes $ \(input, size) ->+ alloca $ \fee -> allocaBytes 32 $ \digest -> allocaArray 6 $ \counts -> do+ status <- cOracle (castPtr input) (fromIntegral size) fee digest counts+ status @?= 0+ (,,) <$> peek fee <*> B.packCStringLen (castPtr digest, 32) <*> peekArray 6 counts++nativeSign :: CUInt -> ByteString -> IO ByteString+nativeSign sub bytes = B.useAsCStringLen bytes $ \(input, size) -> B.useAsCString seed $ \key -> allocaBytes 96 $ \output -> do+ status <- cNativeSign (castPtr input) (fromIntegral size) sub (castPtr key) output+ status @?= 0+ B.packCStringLen (castPtr output, 96)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_transaction_oracle"+ cOracle :: Ptr Word8 -> CSize -> Ptr Word64 -> Ptr Word8 -> Ptr Word64 -> IO CUInt++foreign import ccall safe "cometa_test_transaction_sign"+ cNativeSign :: Ptr Word8 -> CSize -> CUInt -> Ptr Word8 -> Ptr Word8 -> IO CUInt
@@ -0,0 +1,223 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Shared callback ownership, retry, grouped cancellation and alias evidence.+module Runtime (tests) where++-- IMPORTS --------------------------------------------------------------------++import Cometa.Error (Error (..))+import Cometa.Internal.FFI.Native (NativeCode)+import qualified Cometa.Internal.Runtime as Runtime+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Concurrent.MVar (tryPutMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, bracket_, displayException, fromException, try, uninterruptibleMask_)+import Control.Monad (forM_, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (isInfixOf)+import Foreign.C.Types (CUInt (..))+import Foreign.Ptr (Ptr, nullPtr)+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Shared callback runtime"+ [ testCase "native failure preserves exact Error; handled failure and retry can recover" retries,+ testCase "native last-owner aliases and closed handles retain correct registration lifetime" aliases,+ testCase "duplicate contexts activate once and partial group acquisition rolls back" groups,+ testCase "callback reentry and overlap fail promptly without losing independent gates" reentry,+ testCase "lazy success, lazy failure and callback exceptions rethrow after native unwind" exceptions,+ testCase "group cancellation reaches the second callback and joins its finalizer" cancellation,+ testCase "group cancellation fans out past a masked dependent callback" dependentCancellation+ ]++probe :: Runtime.Runtime -> CUInt -> IO (Either Error ByteString)+probe runtime mode = Runtime.withOperation runtime $ \context ->+ Runtime.withOwnedBuffer "test.runtime" (cProbe context nullPtr mode)++retries :: IO ()+retries = do+ let expected = InvalidTransactionOutputValue (-42)+ handler operation _ = pure (if operation == 0 then Left expected else Right "recovered")+ before <- Runtime.liveContexts+ result <- Runtime.withRuntime handler $ \runtime -> do+ probe runtime 0 >>= (@?= Left expected)+ probe runtime 1 >>= (@?= Right (B.singleton 0x80))+ probe runtime 2 >>= (@?= Right "recovered")+ probe runtime 0 >>= (@?= Left expected)+ pure (Right ())+ result @?= Right ()+ Runtime.liveContexts >>= (@?= before)++aliases :: IO ()+aliases = do+ baseline <- Runtime.liveContexts+ escaped <- newEmptyMVar+ result <- Runtime.withRuntime (\_ bytes -> performGC >> pure (Right bytes)) $ \original -> do+ Runtime.liveContexts >>= (@?= baseline + 1)+ Runtime.withRetained original $ \alias -> do+ Runtime.close original >>= (@?= Right ())+ probe original 0 >>= (@?= Left RuntimeClosed)+ putMVar escaped alias+ replicateM_ 10 (probe alias 0 >>= (@?= Right (B.singleton 0x80)))+ pure (Right ())+ result @?= Right ()+ alias <- takeMVar escaped+ probe alias 0 >>= (@?= Left RuntimeClosed)+ Runtime.close alias >>= (@?= Right ())+ Runtime.liveContexts >>= (@?= baseline)++groups :: IO ()+groups = do+ result <- Runtime.withRuntime (\_ bytes -> pure (Right bytes)) $ \first ->+ Runtime.withRuntime (\_ bytes -> pure (Right bytes)) $ \second -> do+ Runtime.close second >>= (@?= Right ())+ Runtime.withOperations [first, second] (\_ -> pure (Right ())) >>= (@?= Left RuntimeClosed)+ probe first 0 >>= (@?= Right (B.singleton 0x80))+ lazyGroup <- try (Runtime.withOperations [first, error "lazy group handle"] (\_ -> pure (Right ()))) :: IO (Either SomeException (Either Error ()))+ assertBool "lazy group argument did not throw" (isLeft lazyGroup)+ probe first 0 >>= (@?= Right (B.singleton 0x80))+ Runtime.withRetained first $ \alias -> do+ both <- Runtime.withOperations [first, alias] $ \case+ [one, two] -> Runtime.withOwnedBuffer "test.runtime.group" (cProbe one two 3)+ _ -> pure (Left (InvalidCallbackResult "Incorrect context count"))+ both @?= Right (B.singleton 0x80)+ pure (Right ())+ result @?= Right ()++reentry :: IO ()+reentry = do+ current <- newIORef Nothing+ reentered <- newIORef Nothing+ let handler _ bytes = do+ selected <- readIORef current+ case selected of+ Nothing -> pure (Left (InvalidCallbackResult "Missing test runtime"))+ Just runtime -> do+ nested <- probe runtime 0+ writeIORef reentered (Just nested)+ Runtime.close runtime >>= (@?= Left RuntimeBusy)+ pure (Right bytes)+ result <- Runtime.withRuntime handler $ \runtime -> do+ writeIORef current (Just runtime)+ probe runtime 0+ result @?= Right (B.singleton 0x80)+ readIORef reentered >>= (@?= Just (Left RuntimeBusy))++exceptions :: IO ()+exceptions = do+ baseline <- Runtime.liveContexts+ forM_ [\_ _ -> pure (Right (error "lazy reply")), \_ _ -> pure (Left (UnsupportedOperation (error "lazy error"))), \_ _ -> ioError (userError "callback failed")] $ \handler -> do+ outcome <- try (Runtime.withRuntime handler (`probe` 0)) :: IO (Either SomeException (Either Error ByteString))+ assertBool "callback exception escaped as expected Error" (isLeft outcome)+ case outcome of+ Left failure -> assertBool "unexpected exception" (any (`isInfixOf` displayException failure) ["lazy reply", "lazy error", "callback failed"])+ Right _ -> assertFailure "callback unexpectedly succeeded"+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ baseline <- Runtime.liveContexts+ started <- newEmptyMVar+ finalized <- newEmptyMVar+ hold <- newEmptyMVar+ count <- newIORef (0 :: Int)+ let secondHandler _ bytes = do+ calls <- readIORef count+ modifyIORef' count (+ 1)+ if calls == 0+ then bracket_ (putMVar started ()) (putMVar finalized ()) (takeMVar hold)+ else pure (Right bytes)+ result <- Runtime.withRuntime (\_ bytes -> pure (Right bytes)) $ \first ->+ Runtime.withRuntime secondHandler $ \second -> do+ finished <- newEmptyMVar+ worker <-+ forkFinally+ ( Runtime.withOperations [first, second] $ \case+ [one, two] -> Runtime.withOwnedBuffer "test.runtime.cancelGroup" (cProbe one two 3)+ _ -> pure (Left (InvalidCallbackResult "Incorrect context count"))+ )+ (putMVar finished)+ takeMVar started+ Runtime.withOperations [second, first] (\_ -> pure (Right ())) >>= (@?= Left RuntimeBusy)+ joined <- timeout 5000000 (killThread worker >> takeMVar finished)+ case joined of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "group cancellation did not join"+ takeMVar finalized+ probe first 0 >>= (@?= Right (B.singleton 0x80))+ probe second 0 >>= (@?= Right (B.singleton 0x80))+ pure (Right ())+ result @?= Right ()+ Runtime.liveContexts >>= (@?= baseline)++-- A serial throwTo implementation deadlocks here: the first callback masks+-- cancellation until the second callback's finalizer has run. The C probe invokes+-- both callbacks concurrently and does not return until both native threads join.+dependentCancellation :: IO ()+dependentCancellation = do+ baseline <- Runtime.liveContexts+ firstReady <- newEmptyMVar+ secondReady <- newEmptyMVar+ secondFinalized <- newEmptyMVar+ hold <- newEmptyMVar+ let firstHandler _ bytes = do+ putMVar firstReady ()+ uninterruptibleMask_ (takeMVar secondFinalized)+ pure (Right bytes)+ secondHandler _ _ = do+ takeMVar firstReady+ bracket_ (putMVar secondReady ()) (putMVar secondFinalized ()) (takeMVar hold)+ result <- Runtime.withRuntime firstHandler $ \first ->+ Runtime.withRuntime secondHandler $ \second -> do+ finished <- newEmptyMVar+ worker <-+ forkFinally+ ( Runtime.withOperations [first, second] $ \case+ [one, two] -> Runtime.withOwnedBuffer "test.runtime.dependentCancellation" (cProbe one two 4)+ _ -> pure (Left (InvalidCallbackResult "Incorrect context count"))+ )+ (putMVar finished)+ takeMVar secondReady+ joined <- timeout 5000000 (killThread worker >> takeMVar finished)+ case joined of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> do+ -- Unblock even a regressed serial cancellation path before failing,+ -- so the test never strands native threads or callback registrations.+ _ <- tryPutMVar secondFinalized ()+ _ <- takeMVar finished+ assertFailure "group cancellation did not fan out"+ pure (Right ())+ result @?= Right ()+ Runtime.liveContexts >>= (@?= baseline)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_runtime_probe"+ cProbe :: Ptr Runtime.Context -> Ptr Runtime.Context -> CUInt -> Ptr (Ptr Runtime.Buffer) -> IO NativeCode
@@ -0,0 +1,74 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.++module Main (main) where++-- IMPORTS --------------------------------------------------------------------++import qualified AdditionalProviders+import qualified BalancingScriptLanguages+import qualified BlockfrostHttp+import qualified BlockfrostJson+import qualified BlockfrostProtocol+import qualified BlockfrostProvider+import qualified CoinSelection+import qualified ContextualTransaction+import qualified DeferredRedeemer+import qualified DijkstraBuilder+import qualified EncodingNormalization+import qualified Evaluation+import qualified NativeCoinSelection+import qualified NativeEvaluation+import qualified ParameterSnapshot+import qualified Provider+import qualified Runtime+import qualified SubTransactionBuilder+import Test.Tasty (defaultMain, localOption, testGroup)+import Test.Tasty.Runners (NumThreads (..))+import qualified TransactionBalancing+import qualified TransactionBuilder+import qualified TransactionBuilding+import qualified TransactionIndices+import qualified TransactionInspection++-- DEFINITIONS ----------------------------------------------------------------++main :: IO ()+main =+ defaultMain $+ localOption (NumThreads 1) $+ testGroup+ "Runtime extension points"+ [ testGroup "Blockfrost" [BlockfrostProtocol.tests, BlockfrostHttp.tests, BlockfrostJson.tests, BlockfrostProvider.tests],+ AdditionalProviders.tests,+ EncodingNormalization.tests,+ TransactionInspection.tests,+ Runtime.tests,+ Provider.tests,+ ParameterSnapshot.tests,+ CoinSelection.tests,+ NativeCoinSelection.tests,+ TransactionBuilding.tests,+ TransactionBuilder.tests,+ NativeEvaluation.tests,+ DeferredRedeemer.tests,+ TransactionBalancing.tests,+ BalancingScriptLanguages.tests,+ TransactionIndices.tests,+ ContextualTransaction.tests,+ SubTransactionBuilder.tests,+ DijkstraBuilder.tests,+ Evaluation.tests+ ]
@@ -0,0 +1,318 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Typed script construction, exact identity, native conformance and VM goldens.+module Scripts (tests, nativeValues) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.PlutusData as Data+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar, throwTo)+import Control.Exception (AsyncException (ThreadKilled), fromException)+import Control.Monad (forM_, forever, replicateM_)+import qualified Data.Aeson as Aeson+import qualified Data.ByteString as ByteString+import qualified Data.ByteString.Lazy as Lazy+import Data.Either (isLeft)+import qualified Data.Text as Text+import Data.Word (Word64, Word8)+import qualified Fixtures.Scripts as Fixtures+import Foreign.C.Types (CChar, CInt (..), CSize (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Scripts"+ [ testCase "native script construction JSON validates every alternative" checkJson,+ testCase "all native alternatives assemble to pinned bytes and agree with native hash" checkNative,+ testCase "threshold and slot extrema retain full unsigned range" checkBounds,+ testCase "native imported encodings and child identity remain exact" checkIdentity,+ testCase "native parser rejects malformed alternatives, credentials and trailing input" checkInvalidNative,+ testCase "all Plutus versions have independent hash vectors and native agreement" checkPlutus,+ testCase "Plutus outer encodings are exact while hashes use compiled bytes" checkPlutusIdentity,+ testCase "combined envelopes normalize without changing payload identity" checkEnvelope,+ testCase "combined and Plutus parsers reject invalid framing" checkInvalidEnvelope,+ testCase "typed VM parameter application matches pinned golden corpus" checkApply,+ testCase "VM errors, result snapshots and original values survive repeated cleanup" checkLifetime,+ testCase "cancellation unwinds VM calls and leaves independent operations usable" checkCancellation,+ testProperty "assembled native scripts round trip without loss" propNative+ ]++nativeValues :: IO [Native.NativeScript]+nativeValues = do+ keyBytes <- bytes "00112233445566778899aabbccddeeff00112233445566778899aabb"+ scriptBytes <- bytes "aabbccddeeff00112233445566778899aabbccddeeff001122334455"+ key <- expectRight (Credential.keyHashFromBytes keyBytes)+ guardKey <- expectRight (Credential.keyHashFromBytes keyBytes)+ guardHash <- expectRight (Credential.scriptHashFromBytes scriptBytes)+ let signed = Native.signature key+ guarded = Native.requireGuard (Credential.KeyCredential guardKey)+ scriptGuard = Native.requireGuard (Credential.ScriptCredential guardHash)+ pure+ [ signed,+ Native.allOf [],+ Native.anyOf [],+ Native.atLeast 0 [],+ Native.invalidBefore 0,+ Native.invalidAfter maxBound,+ guarded,+ scriptGuard,+ Native.allOf [signed, guarded],+ Native.anyOf [scriptGuard],+ Native.atLeast 1 [guarded]+ ]++checkNative :: IO ()+checkNative = do+ values <- nativeValues+ forM_ (zip values Fixtures.nativeVectors) $ \(script, golden) -> do+ expected <- bytes golden+ Native.encodeCbor script @?= expected+ decoded <- expectRight (Native.decodeCbor expected)+ decoded @?= script+ Native.view decoded @?= Native.view script+ nativeAgreement (Script.Native script)+ digest <- Native.hash (Native.allOf []) >>= expectRight+ expected <- bytes "d441227553a0f1a965fee7d60a0f724b368dd1bddbc208730fccebcf"+ Credential.scriptHashBytes digest @?= expected++checkBounds :: IO ()+checkBounds = do+ forM_ [0, 1, maxBound :: Word64] $ \count -> do+ let script = Native.atLeast count []+ Native.view script @?= Native.RequireAtLeast count []+ Native.decodeCbor (Native.encodeCbor script) @?= Right script+ nativeAgreement (Script.Native script)+ forM_ [0, 1, maxBound :: Word64] $ \slot -> forM_ [Native.invalidBefore slot, Native.invalidAfter slot] $ \script -> do+ Native.decodeCbor (Native.encodeCbor script) @?= Right script+ nativeAgreement (Script.Native script)++checkIdentity :: IO ()+checkIdentity = do+ encoded <- bytes "9f18041801ff"+ script <- expectRight (Native.decodeCbor encoded)+ Native.view script @?= Native.InvalidBefore 1+ Native.encodeCbor script @?= encoded+ digest <- Native.hash script >>= expectRight+ expectedDigest <- bytes "39ba2bf155ed91d0af8648e127e7def677e9b9f2dcad79c987c83b53"+ Credential.scriptHashBytes digest @?= expectedDigest+ assertBool "representation-sensitive equality" (script /= Native.invalidBefore 1)+ Native.encodeCbor (Native.allOf [script]) @?= ByteString.pack [0x82, 1, 0x81] <> encoded+ reparsed <- expectRight (Native.decodeCbor (Native.encodeCbor (Native.allOf [script])))+ Native.view reparsed @?= Native.RequireAll [script]++checkInvalidNative :: IO ()+checkInvalidNative = forM_ ["", "80", "8100", "83040000", "820700", "820020", "8200581b000000000000000000000000000000000000000000000000000000", "82061b00", "8206820200", "8206820040", "83032080", "82041b", "82040000", "9f040001ff"] $ \hex -> do+ encoded <- bytes hex+ assertBool ("reject native " <> hex) (isLeft (Native.decodeCbor encoded))++checkPlutus :: IO ()+checkPlutus = forM_ (zip [Plutus.V1 .. Plutus.V4] hashes) $ \(language, golden) -> do+ script <- expectRight (Plutus.fromBytes language Fixtures.compiledScript)+ Plutus.version script @?= language+ Plutus.toBytes script @?= Fixtures.compiledScript+ Plutus.encodeCbor script @?= ByteString.cons 0x46 Fixtures.compiledScript+ Plutus.decodeCbor language (Plutus.encodeCbor script) @?= Right script+ digest <- Plutus.hash script >>= expectRight+ expected <- bytes golden+ Credential.scriptHashBytes digest @?= expected+ nativeAgreement (Script.Plutus script)+ where+ hashes =+ [ "83497f63170b2119e6100fcd767a28894a250f577ba0418b1d43f084",+ "b003687053ba29e4e9667d34839714a53138140fe7b929363bd2bb2f",+ "7fb5e4100a4521d55108c5a193f25691547cbdfe676deae925042ae1",+ "1fd0190f1816f66a28208ce5836f64f54d99bdc2a088fee8e14547ed"+ ]++checkPlutusIdentity :: IO ()+checkPlutusIdentity = do+ canonical <- expectRight (Plutus.fromBytes Plutus.V3 Fixtures.compiledScript)+ forM_+ [ ByteString.pack [0x58, 6] <> Fixtures.compiledScript,+ ByteString.pack [0x5f, 0x42, 0x45, 1, 0x44, 0, 0, 0x24, 0x99, 0xff]+ ]+ $ \encoded -> do+ script <- expectRight (Plutus.decodeCbor Plutus.V3 encoded)+ Plutus.encodeCbor script @?= encoded+ Plutus.toBytes script @?= Fixtures.compiledScript+ assertBool "outer representation participates in equality" (script /= canonical)+ left <- Plutus.hash script+ right <- Plutus.hash canonical+ left @?= right+ Plutus.fromBytes Plutus.V1 ByteString.empty @?= Left EmptyPlutusScript+ opaque <- expectRight (Plutus.fromBytes Plutus.V1 (ByteString.singleton 255))+ Plutus.toBytes opaque @?= ByteString.singleton 255++checkEnvelope :: IO ()+checkEnvelope = do+ original <- bytes "9f18009f18041801ffff"+ script <- expectRight (Script.decodeCbor original)+ normalized <- bytes "82009f18041801ff"+ Script.encodeCbor script @?= normalized+ Script.decodeCbor normalized @?= Right script+ forM_ [Plutus.V1 .. Plutus.V4] $ \language -> do+ plutus <- expectRight (Plutus.fromBytes language Fixtures.compiledScript)+ let combined = Script.Plutus plutus+ Script.decodeCbor (Script.encodeCbor combined) @?= Right combined+ combinedHash <- Script.hash combined+ plutusHash <- Plutus.hash plutus+ combinedHash @?= plutusHash++checkInvalidEnvelope :: IO ()+checkInvalidEnvelope = do+ forM_ ["", "80", "8100", "830082018000", "8205820180", "820100", "820082018000", "9f0082018000ff"] $ \hex -> do+ encoded <- bytes hex+ assertBool ("reject envelope " <> hex) (isLeft (Script.decodeCbor encoded))+ forM_ ["", "80", "41", "410000", "5f0100ff"] $ \hex -> do+ encoded <- bytes hex+ assertBool ("reject Plutus " <> hex) (isLeft (Plutus.decodeCbor Plutus.V1 encoded))+ empty <- bytes "40"+ Plutus.decodeCbor Plutus.V1 empty @?= Left EmptyPlutusScript++checkApply :: IO ()+checkApply = do+ let parameters = [[], [Data.Integer 0], [Data.Integer (2 ^ (64 :: Int))], [Data.Integer 0, Data.Bytes (ByteString.singleton 255)]]+ forM_ [Plutus.V1 .. Plutus.V4] $ \language -> do+ original <- expectRight (Plutus.fromBytes language Fixtures.compiledScript)+ forM_ (zip parameters Fixtures.applyVectors) $ \(params, (encodedParams, expectedCode)) -> do+ expectedParams <- bytes encodedParams+ Data.encodeCbor (Data.List params) @?= expectedParams+ expected <- bytes expectedCode+ applied <- Plutus.applyParams original params >>= expectRight+ Plutus.toBytes applied @?= expected+ Plutus.version applied @?= language+ Plutus.toBytes original @?= Fixtures.compiledScript+ nativeAgreement (Script.Plutus applied)+ first <- Plutus.applyParams original [Data.Integer 0] >>= expectRight+ sequential <- Plutus.applyParams first [Data.Bytes (ByteString.singleton 255)] >>= expectRight+ simultaneous <- Plutus.applyParams original [Data.Integer 0, Data.Bytes (ByteString.singleton 255)] >>= expectRight+ sequential @?= simultaneous++checkLifetime :: IO ()+checkLifetime = do+ original <- expectRight (Plutus.fromBytes Plutus.V2 Fixtures.compiledScript)+ result <- Plutus.applyParams original [Data.Integer 0] >>= expectRight+ invalid <- expectRight (Plutus.fromBytes Plutus.V2 (ByteString.singleton 255))+ replicateM_ 32 $ do+ failure <- Plutus.applyParams invalid [Data.Map [(Data.Integer 1, Data.Bytes ByteString.empty)]]+ assertBool "malformed Flat returns a native error" (case failure of Left NativeError {} -> True; _ -> False)+ _ <- Plutus.applyParams original [Data.Constr 0 [Data.Integer (-1)]] >>= expectRight+ performGC+ expected <- bytes "4b0100003249930101000001"+ Plutus.toBytes result @?= expected+ Plutus.toBytes original @?= Fixtures.compiledScript+ nativeAgreement (Script.Plutus result)++checkCancellation :: IO ()+checkCancellation = do+ original <- expectRight (Plutus.fromBytes Plutus.V3 Fixtures.compiledScript)+ invalid <- expectRight (Plutus.fromBytes Plutus.V3 (ByteString.singleton 255))+ forM_ [False, True] $ \malformed -> do+ started <- newEmptyMVar+ done <- newEmptyMVar+ let invoke = if malformed then Plutus.applyParams invalid [] else Plutus.applyParams original [Data.Bytes (ByteString.replicate 1024 7)]+ worker <-+ forkFinally+ ( do+ _ <- invoke+ putMVar started ()+ forever invoke+ )+ (putMVar done)+ began <- timeout 5000000 (takeMVar started)+ began @?= Just ()+ throwTo worker ThreadKilled+ stopped <- timeout 5000000 (takeMVar done)+ case stopped of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "VM worker failed to unwind cancellation"+ after <- Plutus.applyParams original [] >>= expectRight+ Plutus.toBytes after @?= Fixtures.compiledScript+ nativeAgreement (Script.Plutus after)++propNative :: Property+propNative = property $ do+ slots <- forAll (Gen.list (Range.linear 0 20) (Gen.word64 Range.constantBounded))+ required <- forAll (Gen.word64 Range.constantBounded)+ let script = Native.allOf [Native.anyOf (map Native.invalidBefore slots), Native.atLeast required (map Native.invalidAfter slots)]+ decoded <- evalEither (Native.decodeCbor (Native.encodeCbor script))+ decoded === script+ Native.view decoded === Native.view script+ evalIO (nativeAgreement (Script.Native script))++nativeAgreement :: Script.Script -> IO ()+nativeAgreement script = do+ digest <- Script.hash script >>= expectRight+ let encoded = Script.encodeCbor script+ ByteString.useAsCStringLen encoded $ \(input, inputSize) ->+ ByteString.useAsCString (Credential.scriptHashBytes digest) $ \hashBytes -> do+ agrees <- cAgreement (castPtr input) (fromIntegral inputSize) (castPtr hashBytes) (castPtr input) (fromIntegral inputSize)+ agrees @?= 1++bytes :: String -> IO ByteString.ByteString+bytes encoded = case Hex.decodeHex (Text.pack encoded) of+ Nothing -> assertFailure "invalid test fixture hex" >> pure ByteString.empty+ Just value -> pure value++expectRight :: (Show failure) => Either failure value -> IO value+expectRight result = case result of+ Left failure -> assertFailure (show failure) >> fail "unreachable assertion"+ Right value -> pure value++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_script_agreement"+ cAgreement :: Ptr Word8 -> CSize -> Ptr Word8 -> Ptr Word8 -> CSize -> IO CInt++checkJson :: IO ()+checkJson = do+ key <- expectRight (Credential.keyHashFromBytes (ByteString.replicate 28 7))+ guardKey <- expectRight (Credential.keyHashFromBytes (ByteString.replicate 28 8))+ guardScript <- expectRight (Credential.scriptHashFromBytes (ByteString.replicate 28 9))+ let sig = Native.signature key+ scripts = [sig, Native.allOf [], Native.anyOf [sig, sig], Native.atLeast maxBound [sig], Native.invalidBefore maxBound, Native.invalidAfter 0, Native.requireGuard (Credential.KeyCredential guardKey), Native.requireGuard (Credential.ScriptCredential guardScript)]+ forM_ (Native.allOf scripts : scripts) $ \script -> do+ let json = Native.toJson script+ Native.fromJson json @?= Right script+ ByteString.useAsCStringLen (Lazy.toStrict (Aeson.encode json)) $ \(jsonPtr, jsonSize) ->+ ByteString.useAsCStringLen (Native.encodeCbor script) $ \(expected, expectedSize) -> do+ agrees <- cScriptJson jsonPtr (fromIntegral jsonSize) (castPtr expected) (fromIntegral expectedSize)+ agrees @?= 1+ forM_ ["{}", "[]", "{\"type\":\"unknown\"}", "{\"type\":\"before\",\"slot\":-1}", "{\"type\":\"after\",\"slot\":18446744073709551616}", "{\"type\":\"atLeast\",\"required\":1.5,\"scripts\":[]}", "{\"type\":\"guard\",\"keyHash\":\"00\",\"scriptHash\":\"00\"}", "{\"type\":\"sig\",\"keyHash\":\"zz\"}", "{\"type\":\"all\",\"scripts\":[{}]}"] $ \encoded -> do+ json <- expectRight (Aeson.eitherDecodeStrict encoded)+ assertBool "invalid script construction JSON" (isLeft (Native.fromJson json))++foreign import ccall safe "cometa_test_native_script_json"+ cScriptJson :: Ptr CChar -> CSize -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,220 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Original selection properties inspired by cardano-coin-selection+-- 57efda2eda720b9e793a6f907319cc84aa02058c BalanceSpec (Apache-2.0).+-- Sparse incidence and signed funding extend the existing positive-bundle laws.+-- Expected balances use Integer arithmetic, never selection validation or a+-- second native call. Choice/order of random selections is deliberately free.+module SelectionReliability (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as Name+import qualified Cometa.CoinSelection as Selection+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (forM_, zipWithM)+import qualified Data.ByteString as B+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Word (Word64)+import qualified Fixtures.ProtocolParameters as Fixture+import Hedgehog (Property, PropertyT, assert, classify, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Selection reliability"+ [ testProperty "sparse signed requirements conserve assets and exact heterogeneous snapshots" propSignedSparse,+ testProperty "single-input token change succeeds at its independently derived minimum Ada" propMinimumBoundary+ ]++addresses :: Either Error (Address.Address, Address.Address)+addresses = do+ key <- Credential.keyHashFromBytes (B.replicate 28 7)+ stake <- Credential.keyHashFromBytes (B.replicate 28 8)+ script <- Credential.scriptHashFromBytes (B.replicate 28 9)+ pure (Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key)), Address.ShelleyAddress (Shelley.base Network.testnet (Credential.ScriptCredential script) (Credential.KeyCredential stake)))++-- The five input assets exclude mintedAsset by construction. Return the hint+-- asset explicitly as well, so fixture access remains total on every compiler.+assets :: Either Error ([Asset.AssetId], Asset.AssetId, Asset.AssetId)+assets = do+ policyA <- Policy.fromBytes (B.replicate 28 10)+ policyB <- Policy.fromBytes (B.replicate 28 11)+ short <- Name.fromBytes (B.singleton 0)+ long <- Name.fromBytes (B.replicate 32 255)+ let hintAsset = Asset.Native policyA Name.empty+ mintedAsset = Asset.Native policyB long+ inputAssets = [hintAsset, Asset.Native policyA short, Asset.Native policyA long, Asset.Native policyB Name.empty, Asset.Native policyB short]+ pure (inputAssets, mintedAsset, hintAsset)++quantities :: [Value.Value] -> Map.Map Asset.AssetId Integer+quantities = Map.filter (/= 0) . Map.fromListWith (+) . concatMap Value.toList++selectors :: Word64 -> [Selection.Selector]+selectors seed = [Selection.largestFirst, Selection.randomImproveWithSeed seed, Selection.randomImproveWithOptions seed Selection.Minimal]++-- Solve the independent Babbage size equation at its least fixed point, instead+-- of assuming that the minimum coin always uses the same CBOR width. Encoding+-- uses the public Haskell output codec; no native minimum-Ada oracle is called.+minimumAda :: Word64 -> Output.Output -> Either Error Integer+minimumAda cost output = go (0 :: Int) 0+ where+ tokens = filter ((/= Asset.Ada) . fst) (Value.toList (Output.value output))+ go iterations coin = do+ candidate <- Output.mkOutput (Output.address output) (Value.fromList ((Asset.Ada, coin) : tokens)) (Output.datum output) (Output.referenceScript output)+ let required = toInteger cost * (160 + toInteger (B.length (Output.encodeCbor candidate)))+ if required == coin+ then Right required+ else+ if iterations >= 10+ then Left (InvalidSelection "Independent minimum-Ada fixed point did not converge")+ else go (iterations + 1) required++assertLaws :: Word64 -> Selection.SelectionRequest -> Selection.Selection -> PropertyT IO ()+assertLaws cost request result = do+ let chosen = Selection.selected result+ remaining = Selection.remaining result+ refs = map Utxo.input+ chosenRefs = Set.fromList (refs chosen)+ remainingRefs = Set.fromList (refs remaining)+ candidates = Map.fromList [(Utxo.input item, item) | item <- Selection.available request]+ eligible = Map.union (Map.fromList [(Utxo.input item, item) | item <- Selection.preselected request]) candidates+ delta =+ Map.filter+ (/= 0)+ ( Map.unionsWith+ (+)+ [quantities (map (Output.value . Utxo.output) chosen), Map.map negate (quantities [Selection.target request]), Map.map negate (quantities (map Output.value (Selection.change result)))]+ )+ length chosen === Set.size chosenRefs+ length remaining === Set.size remainingRefs+ assert (Set.null (Set.intersection chosenRefs remainingRefs))+ remainingRefs === Set.difference (Map.keysSet candidates) chosenRefs+ assert (Set.fromList (refs (Selection.preselected request)) `Set.isSubsetOf` chosenRefs)+ forM_ (chosen <> remaining) $ \item -> do+ expected <- evalEither (maybe (Left (InvalidSelection "Ineligible input")) Right (Map.lookup (Utxo.input item) eligible))+ -- Identity and every resolved output field, including datum/script bytes,+ -- must survive both the selected and remaining paths.+ Output.encodeCbor (Utxo.output item) === Output.encodeCbor (Utxo.output expected)+ delta === Map.empty+ forM_ (Selection.change result) $ \output -> do+ Output.address output === Selection.changeAddress request+ assert (all ((>= 0) . snd) (Value.toList (Output.value output)))+ Output.datum output === Datum.NoDatum+ Output.referenceScript output === Nothing+ required <- evalEither (minimumAda cost output)+ assert (Value.quantity Asset.Ada (Output.value output) >= required)++propSignedSparse :: Property+propSignedSparse = property $ do+ (tokens, mintedAsset, hintAsset) <- evalEither assets+ (enterprise, base) <- evalEither addresses+ params <- evalEither Fixture.parameters+ count <- forAll (Gen.int (Range.linear 1 10))+ rows <- forAll (Gen.list (Range.singleton count) (Gen.list (Range.singleton 5) (Gen.integral (Range.linear 0 1000))))+ signs <- forAll (Gen.list (Range.singleton 5) Gen.bool)+ seed <- forAll (Gen.word64 Range.constantBounded)+ cost <- forAll (Gen.element [0, 1, 24, 100, 4310, 10000])+ coinTarget <- forAll (Gen.integral (Range.linear (-5000000) 5000000))+ mandatoryCount <- forAll (Gen.int (Range.linear 0 count))+ overlap <- forAll Gen.bool+ baseChange <- forAll Gen.bool+ hintMode <- forAll (Gen.int (Range.linear 0 2))+ identifier <- evalEither (Id.fromBytes (B.replicate 32 42))+ retained <- evalEither (Data.decodeCbor (B.pack [24, 1]))+ let destination = if baseChange then base else enterprise+ resolved index amounts = do+ let datum = case index `mod` 3 of 0 -> Datum.NoDatum; 1 -> Datum.InlineDatum retained; _ -> Datum.InlineDatum (Data.fromData (Data.List [Data.Integer (toInteger index)]))+ reference = if odd index then Just (Script.Native (Native.invalidBefore (fromIntegral index))) else Nothing+ output <- Output.mkOutput (if odd index then base else enterprise) (Value.fromList ((Asset.Ada, 50000000) : zip tokens amounts)) datum reference+ pure (Utxo.utxo (Input.input identifier (fromIntegral index)) output)+ pool <- evalEither (zipWithM resolved [0 :: Int ..] rows)+ let totalTokens = Map.delete Asset.Ada (quantities (map (Output.value . Utxo.output) pool))+ signed = [(token, if negative then negate (1 + Map.findWithDefault 0 token totalTokens `div` 2) else Map.findWithDefault 0 token totalTokens `div` 2) | (token, negative) <- zip tokens signs]+ target = Value.fromList ((Asset.Ada, coinTarget) : (mintedAsset, -1000) : signed)+ mandatory = take mandatoryCount pool+ available = if overlap then pool else drop mandatoryCount pool+ hint <- evalEither (Output.mkOutput destination (Value.fromList [(Asset.Ada, 1000000000), (hintAsset, 1000000)]) Datum.NoDatum Nothing)+ let hints = case hintMode of 0 -> Nothing; 1 -> Just []; _ -> Just [hint, hint]+ request <- evalEither (Selection.mkSelectionRequest (Selection.SelectionOptions mandatory available target hints destination (params {Parameters.parameterAdaPerUtxoByte = Just cost, Parameters.parameterMaxValueSize = Just 5000})))+ classify "mandatory only" (mandatoryCount == count && not overlap)+ classify "overlapping mandatory" (mandatoryCount > 0 && overlap)+ classify "implicit Ada source" (coinTarget < 0)+ classify "base change address" baseChange+ classify "hint amount exceeds available funding" (hintMode == 2)+ classify "sparse input bundle" (any (elem 0) rows)+ forM_ (selectors seed) $ \selector -> do+ result <- evalIO (Selection.select selector request) >>= evalEither+ assertLaws cost request result+ -- This asset occurs in no input: negative net requirements must materialize+ -- as token change, even when no optional input remains to select.+ Map.findWithDefault 0 mintedAsset (quantities (map Output.value (Selection.change result))) === 1000++propMinimumBoundary :: Property+propMinimumBoundary = property $ do+ (_, token, _) <- evalEither assets+ (enterprise, base) <- evalEither addresses+ params <- evalEither Fixture.parameters+ quantity <- forAll (Gen.element [1, 23, 24, 255, 256, 65535, 65536, 4294967296])+ cost <- forAll (Gen.element [1, 24, 100, 4310, 10000])+ baseChange <- forAll Gen.bool+ seed <- forAll (Gen.word64 Range.constantBounded)+ identifier <- evalEither (Id.fromBytes (B.replicate 32 43))+ let destination = if baseChange then base else enterprise+ inputCoin = 50000000+ inputOutput <- evalEither (Output.mkOutput enterprise (Value.fromList [(Asset.Ada, inputCoin), (token, quantity)]) Datum.NoDatum Nothing)+ changeShape <- evalEither (Output.mkOutput destination (Value.singleton token quantity) Datum.NoDatum Nothing)+ minimumCoin <- evalEither (minimumAda cost changeShape)+ let mandatory = Utxo.utxo (Input.input identifier maxBound) inputOutput+ request coin = Selection.mkSelectionRequest (Selection.SelectionOptions [mandatory] [] (Value.lovelace (inputCoin - coin)) Nothing destination (params {Parameters.parameterAdaPerUtxoByte = Just cost, Parameters.parameterMaxValueSize = Just 5000}))+ adequate <- evalEither (request minimumCoin)+ inadequate <- evalEither (request (minimumCoin - 1))+ classify "one-byte minimum coin" (minimumCoin < 24)+ classify "three-byte minimum coin" (minimumCoin >= 256 && minimumCoin < 65536)+ classify "five-byte minimum coin" (minimumCoin >= 65536)+ forM_ (selectors seed) $ \selector -> do+ failed <- evalIO (Selection.select selector inadequate)+ case failed of+ Left (NativeError _ code _) -> Code.toNumber code === 1100+ _ -> assert False+ result <- evalIO (Selection.select selector adequate) >>= evalEither+ assertLaws cost adequate result+ quantities (map Output.value (Selection.change result)) === quantities [Value.fromList [(Asset.Ada, minimumCoin), (token, quantity)]]
@@ -0,0 +1,158 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Encoding controls over the existing native body corpus and typed witnesses.+module SetEncoding (tests) where++import Cometa.Encoding.Set (SetEncoding (..))+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Witnesses as Witnesses+import Control.Monad (forM_, when)+import Data.Either (isLeft)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import qualified TransactionBody as Bodies+import qualified TransactionWitnesses as WitnessCorpus++tests :: TestTree+tests =+ testGroup+ "Set encoding controls"+ [ testCase "body corpus supports per-field tags without semantic changes" checkBodies,+ testCase "subbody corpus supports only its own set fields" checkSubBodies,+ testCase "every witness collection retains exact values and native tags" checkWitnesses,+ testCase "nonminimal tags and indefinite payloads preserve exact bytes" checkExact,+ testCase "encoding-only body edits invalidate signatures at both levels" checkSignatures,+ testCase "fresh encoders choose tags explicitly" checkFresh+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "Invalid fixture") pure++checkBodies :: IO ()+checkBodies = forM_ Bodies.bodyVectors $ \(_, hex) -> do+ original <- Bodies.bytes hex >>= must . Body.decodeCbor+ forM_ [minBound .. maxBound] $ \field -> forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ let changed = Body.withSetEncoding field requested original+ Body.toBody changed @?= Body.toBody original+ Body.decodeCbor (Body.toCbor changed) @?= Right changed+ Body.withSetEncoding field requested changed @?= changed+ case Body.setEncoding field original of+ Nothing -> changed @?= original+ Just previous -> do+ Body.setEncoding field changed @?= Just requested+ when (previous == requested) (changed @?= original)++checkSubBodies :: IO ()+checkSubBodies = forM_ Bodies.subBodyVectors $ \(_, hex) -> do+ original <- Bodies.bytes hex >>= must . SubBody.decodeCbor+ forM_ [minBound .. maxBound] $ \field -> forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ let changed = SubBody.withSetEncoding field requested original+ SubBody.toBody changed @?= SubBody.toBody original+ SubBody.decodeCbor (SubBody.toCbor changed) @?= Right changed+ SubBody.withSetEncoding field requested changed @?= changed+ case SubBody.setEncoding field original of+ Nothing -> changed @?= original+ Just previous -> do+ SubBody.setEncoding field changed @?= Just requested+ when (previous == requested) (changed @?= original)++checkWitnesses :: IO ()+checkWitnesses = do+ (_, _, _, values, _) <- must (WitnessCorpus.sample 7 42)+ let original = Witnesses.fromWitnesses values+ forM_ [minBound .. maxBound] $ \field -> forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ let changed = Witnesses.withSetEncoding field requested original+ semantic = Witnesses.toWitnesses changed+ Witnesses.setEncoding field changed @?= Just requested+ Witnesses.decodeCbor (Witnesses.toCbor changed) @?= Right changed+ Witnesses.verificationWitnesses semantic @?= Witnesses.verificationWitnesses values+ Witnesses.bootstrapWitnesses semantic @?= Witnesses.bootstrapWitnesses values+ Witnesses.scripts semantic @?= Witnesses.scripts values+ Witnesses.datums semantic @?= Witnesses.datums values+ Witnesses.redeemers semantic @?= Witnesses.redeemers values+ Witnesses.withSetEncoding field requested changed @?= changed+ WitnessCorpus.agree 3 (Witnesses.toCbor changed)+ let absent = Witnesses.fromWitnesses Witnesses.empty+ Witnesses.withSetEncoding Witnesses.Datums TaggedSet absent @?= absent++checkExact :: IO ()+checkExact = do+ forM_ ["d90102", "da00000102", "db0000000000000102"] $ \tag -> do+ raw <- Bodies.bytes ("bf00" ++ tag ++ "9fff0180021800ff")+ original <- must (Body.decodeCbor raw)+ Body.setEncoding Body.Inputs original @?= Just TaggedSet+ Body.withSetEncoding Body.Inputs TaggedSet original @?= original+ let untagged = Body.withSetEncoding Body.Inputs UntaggedSet original+ expected <- Bodies.bytes "a3009fff0180021800"+ Body.toCbor untagged @?= expected+ Body.toBody untagged @?= Body.toBody original+ witnessRaw <- Bodies.bytes ("bf04" ++ tag ++ "9f1801ffff")+ witness <- must (Witnesses.decodeCbor witnessRaw)+ Witnesses.withSetEncoding Witnesses.Datums TaggedSet witness @?= witness+ witnessExpected <- Bodies.bytes "a1049f1801ff"+ Witnesses.toCbor (Witnesses.withSetEncoding Witnesses.Datums UntaggedSet witness) @?= witnessExpected+ forM_ ["a300d901038001800200", "a300d90102d901028001800200"] $ \hex -> do+ raw <- Bodies.bytes hex+ assertBool "invalid outer set tag" (isLeft (Body.decodeCbor raw))++checkSignatures :: IO ()+checkSignatures = do+ (_, _, _, values, _) <- must (WitnessCorpus.sample 7 42)+ original <- must (Body.fromBody (Body.body [] [] 0))+ let witness = Witnesses.fromWitnesses values+ transaction = Tx.assemble original witness Nothing+ changed = Tx.setBodySetEncoding Body.Inputs UntaggedSet transaction+ remaining = Witnesses.toWitnesses (Tx.witnesses changed)+ Tx.setBodySetEncoding Body.Inputs TaggedSet transaction @?= transaction+ Tx.setBodySetEncoding Body.Proposals UntaggedSet transaction @?= transaction+ Body.setEncoding Body.Inputs (Tx.body changed) @?= Just UntaggedSet+ Witnesses.verificationWitnesses remaining @?= []+ Witnesses.bootstrapWitnesses remaining @?= []+ Witnesses.scripts remaining @?= Witnesses.scripts values+ Witnesses.datums remaining @?= Witnesses.datums values+ Witnesses.redeemers remaining @?= Witnesses.redeemers values+ before <- Tx.transactionId transaction >>= must+ after <- Tx.transactionId changed >>= must+ assertBool "body encoding changes transaction id" (before /= after)+ subBody <- must (SubBody.fromBody (SubBody.body [] []))+ let intent = Sub.assemble subBody witness Nothing+ edited = Sub.setBodySetEncoding SubBody.Inputs UntaggedSet intent+ Sub.setBodySetEncoding SubBody.Inputs TaggedSet intent @?= intent+ SubBody.setEncoding SubBody.Inputs (Sub.body edited) @?= Just UntaggedSet+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Sub.witnesses edited)) @?= []+ Witnesses.bootstrapWitnesses (Witnesses.toWitnesses (Sub.witnesses edited)) @?= []+ Witnesses.scripts (Witnesses.toWitnesses (Sub.witnesses edited)) @?= Witnesses.scripts values++checkFresh :: IO ()+checkFresh = do+ forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ bytes <- must (Body.encodeCborWith requested (Body.body [] [] 7))+ encoded <- must (Body.decodeCbor bytes)+ Body.setEncoding Body.Inputs encoded @?= Just requested+ Bodies.nativeResult 0 bytes >>= (@?= if requested == TaggedSet then 0 else 9001)+ subBytes <- must (SubBody.encodeCborWith requested (SubBody.body [] []))+ subEncoded <- must (SubBody.decodeCbor subBytes)+ SubBody.setEncoding SubBody.Inputs subEncoded @?= Just requested+ Bodies.nativeResult 1 subBytes >>= (@?= if requested == TaggedSet then 0 else 9001)+ (_, _, _, witnesses, _) <- must (WitnessCorpus.sample 7 42)+ let witnessBytes = Witnesses.encodeCborWith requested witnesses+ witnessEncoded <- must (Witnesses.decodeCbor witnessBytes)+ forM_ [minBound .. maxBound] $ \field -> Witnesses.setEncoding field witnessEncoded @?= Just requested+ WitnessCorpus.agree 3 witnessBytes
@@ -0,0 +1,90 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++module SlotConfig (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.SlotConfig as Slots+import Data.Either (isLeft)+import Data.Word (Word64)+import Foreign.C.Types (CUInt (..))+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Slot configuration"+ [ testCase "network schedules match native constants" presets,+ testCase "zero duration, earlier periods and unsigned overflow are rejected" bounds,+ testProperty "slot starts and enclosing instants agree with native arithmetic" conversions+ ]++presets :: IO ()+presets = mapM_ check (zip [0 ..] [Slots.mainnet, Slots.preview, Slots.preprod])+ where+ check (network, config) = do+ actualTime <- cPreset network 0+ actualSlot <- cPreset network 1+ actualLength <- cPreset network 2+ (Slots.zeroTime config, Slots.zeroSlot config, Slots.slotLength config) @?= (actualTime, actualSlot, actualLength)++bounds :: IO ()+bounds = do+ assertBool "zero duration" (isLeft (Slots.mkSlotConfig 0 0 0))+ assertBool "historical slot" (isLeft (Slots.slotToTime Slots.mainnet (Slots.zeroSlot Slots.mainnet - 1)))+ assertBool "historical time" (isLeft (Slots.timeToSlot Slots.preprod (Slots.zeroTime Slots.preprod - 1)))+ let checked config action = either (const False) (isLeft . action) config+ assertBool "time overflow" (checked (Slots.mkSlotConfig maxBound 0 1) (`Slots.slotToTime` 1))+ assertBool "slot overflow" (checked (Slots.mkSlotConfig 0 maxBound 1) (`Slots.timeToSlot` 1))+ (Slots.mkSlotConfig maxBound maxBound maxBound >>= (`Slots.slotToTime` maxBound)) @?= Right maxBound+ (Slots.mkSlotConfig maxBound maxBound maxBound >>= (`Slots.timeToSlot` maxBound)) @?= Right maxBound++conversions :: Property+conversions = property $ do+ time <- forAll (Gen.word64 (Range.linear 0 10000000000000))+ slot <- forAll (Gen.word64 (Range.linear 0 100000000))+ duration <- forAll (Gen.word64 (Range.linear 1 100000))+ offset <- forAll (Gen.word64 (Range.linear 0 100000000))+ within <- forAll (Gen.word64 (Range.linear 0 (duration - 1)))+ config <- evalEither (Slots.mkSlotConfig time slot duration)+ start <- evalEither (Slots.slotToTime config (slot + offset))+ nativeStart <- evalIO (cSlot time slot duration (slot + offset))+ start === nativeStart+ Slots.timeToSlot config start === Right (slot + offset)+ Slots.timeToSlot config (start + within) === Right (slot + offset)+ nativeSlot <- evalIO (cTime time slot duration (start + within))+ nativeSlot === slot + offset+ Slots.slotToTime config (slot + offset + 1) === Right (start + duration)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_slot_preset"+ cPreset :: CUInt -> CUInt -> IO Word64++foreign import ccall unsafe "cometa_test_slot_begin"+ cSlot :: Word64 -> Word64 -> Word64 -> Word64 -> IO Word64++foreign import ccall unsafe "cometa_test_slot_enclosing"+ cTime :: Word64 -> Word64 -> Word64 -> Word64 -> IO Word64
@@ -0,0 +1,339 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Public storage, typed derivation and exception/lifetime regression scenarios.+module SoftwareKeyHandler (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Bip32.PrivateKey as Private+import qualified Cometa.Crypto.Bip32.PublicKey as Bip32Public+import qualified Cometa.Crypto.DerivationPath as Path+import qualified Cometa.Crypto.Ed25519.PublicKey as EdPublic+import qualified Cometa.Crypto.Ed25519.SigningKey as Signing+import Cometa.Error (Error (..))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.KeyHandler.Software as Software+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (AsyncException (ThreadKilled), SomeException, bracket_, fromException, throw, throwIO, try)+import Control.Monad (forM_, replicateM_, void, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Text (Text)+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Software key handlers"+ [ testCase "pinned native BIP32 storage and account public key known answer" checkNativeFixture,+ testCase "normal and extended Ed25519 encryption agree with pinned keys" checkEd25519,+ testCase "every supported entropy length derives the same typed account as BIP32" checkEntropy,+ testCase "constructor validation avoids callback and continuation" checkBounds,+ testCase "storage framing bounds prevent excessive allocation and trailing data" checkStorageBounds,+ testCase "native checksum verification rejects corrupted storage" checkChecksum,+ testCase "encrypted serialization round trip does not request a password" checkStorage,+ testCase "wrong password fails authentication after deferred loading" checkWrongPassword,+ testCase "password boundary128 and embedded NUL round trip" checkPasswords,+ testCase "invalid callback password lengths preserve structured errors" checkCallbackBounds,+ testCase "escaped and explicitly closed handles reject all operations" checkClosed,+ testCase "source key closure is independent and closed source fails" checkSource,+ testCase "continuation failure and exception close escaped handles" checkScopeFailure,+ testCase "callback exception and lazy password failure unwind safely" checkCallbackFailure,+ testCase "callback reentry returns busy without deadlock" checkReentry,+ testCase "callback failures recover on the same handle and name snapshots outlive close" checkRecovery,+ testCase "concurrent use and close are busy while callback is active" checkBusy,+ testCase "cancellation joins callback finalizer and permits later operation" checkCancellation,+ testCase "scope exit joins escaped in-flight operation" checkScopeJoin,+ testCase "independent handlers retain independent callback registrations through GC" checkIndependent+ ]++entropy :: ByteString+entropy = ByteString.pack [0 .. 31]++password :: ByteString+password = "password"++withNormal :: IO ByteString -> (Software.Handler Software.Ed25519 -> IO (Either Error value)) -> IO (Either Error value)+withNormal request action = Signing.withNormalKey (ByteString.replicate 32 1) $ \key -> Software.withSigningKey key password request action++accountPath :: IO Path.AccountPath+accountPath = Path.standardAccountPath <$> requirePure (Path.mkIndex 0)++checkNativeFixture :: IO ()+checkNativeFixture = do+ bytes <- hexBytes "0a0a0a0a01010000005c97db5e09b3a4919ec75ed1126056241a1e5278731c2e0b01bea0a5f42c22db4131e0a4bbe75633677eb0e60e2ecd3520178f85c7e0d4be77a449087fe9674ee52f946b07c1b56d228c496ec0d36dd44212ba8af0f6eed1a82194dd69f479c603"+ path <- accountPath+ result <- require $ Software.withSerialized bytes (pure password) $ \case+ Software.Bip32Handler handler -> do+ Software.serialize handler >>= (@?= Right bytes)+ fmap (fmap Bip32Public.toHex) (Software.accountPublicKey handler path)+ Software.Ed25519Handler _ -> assertFailure "wrong loaded capability" >> pure (Left InvalidKeyHandlerStorage)+ result @?= "1b39889a420374e41917cf420d88a84d9b40d7eeef533ac37f323076c5f7106a15ef170481a5c4333be2b4cf498525512ac4a3427e1a0e9c9f42cfcb42ba6deb"++checkEd25519 :: IO ()+checkEd25519 = forM_ cases $ \(importKey, keyHex, publicHex) -> do+ result <- require $ importKey keyHex $ \key -> Software.withSigningKey key password (pure password) $ \handler -> fmap (fmap EdPublic.toHex) (Software.publicKey handler)+ result @?= publicHex+ where+ cases =+ [ (Signing.withNormalKeyHex, "f04462421183d227bbc0fa60799ef338169c05eed7aa6aac19bc4db20557df51", "bbdafd1393fffa82352b9792e7e8ff66fa05877a79a2486965e28049380c2cac"),+ (Signing.withExtendedKeyHex, "f04462421183d227bbc0fa60799ef338169c05eed7aa6aac19bc4db20557df51e154255decce80ae4ab8a61af6abde05e7fbc049861cc040a7afe4fb0a875899", "07473467683e6a30a13d471a68641f311a14e2b37a38ea592e5d6efc2b446bce")+ ]++checkEntropy :: IO ()+checkEntropy = do+ index <- requirePure (Path.mkIndex 2147483647)+ let path = Path.accountPath index Path.cardanoCoinType index+ forM_ [16, 20, 24, 28, 32] $ \size -> do+ let bytes = ByteString.take size entropy+ expected <- require $ Private.withEntropy ByteString.empty bytes $ \root -> Private.withDerived root (Path.accountIndices path) Private.publicKey+ actual <- require $ Software.withEntropy bytes password (pure password) $ \handler -> Software.accountPublicKey handler path+ actual @?= expected++checkBounds :: IO ()+checkBounds = do+ let invoked = assertFailure "validation invoked user code" >> pure (Right ())+ forM_ [0, 1, 15, 17, 31, 33] $ \size -> Software.withEntropy (ByteString.replicate size 1) password (pure password) (const invoked) >>= (@?= Left (InvalidBip39EntropyLength size))+ forM_ [0, 129] $ \size -> Software.withEntropy entropy (ByteString.replicate size 1) (pure password) (const invoked) >>= (@?= Left (InvalidKeyHandlerPasswordLength size))++checkStorageBounds :: IO ()+checkStorageBounds = forM_ inputs $ \bytes -> Software.withSerialized bytes (throwIO (userError "callback")) (const (assertFailure "invalid storage reached scope" >> pure (Right ()))) >>= (@?= Left InvalidKeyHandlerStorage)+ where+ inputs = [ByteString.empty, ByteString.pack [10, 10, 10, 10, 1, 1, 255, 255, 255, 255], ByteString.pack [10, 10, 10, 10, 2, 1, 0, 0, 0, 76] <> ByteString.replicate 80 0, ByteString.pack [10, 10, 10, 10, 1, 2, 0, 0, 0, 92] <> ByteString.replicate 96 0, ByteString.pack [10, 10, 10, 10, 1, 0, 0, 0, 0, 91] <> ByteString.replicate 95 0]++checkChecksum :: IO ()+checkChecksum = do+ bytes <- require $ withNormal (pure password) Software.serialize+ let corrupted = ByteString.init bytes <> ByteString.singleton (ByteString.last bytes + 1)+ result <- Software.withSerialized corrupted (pure password) (const (pure (Right ())))+ case result of+ Left (NativeError _ Code.ChecksumMismatch _) -> pure ()+ other -> assertFailure (show other)+ Software.withSerialized (bytes <> "x") (pure password) (const (pure (Right ()))) >>= (@?= Left InvalidKeyHandlerStorage)++checkStorage :: IO ()+checkStorage = do+ count <- newIORef (0 :: Int)+ bytes <- require $ withNormal (modifyIORef' count (+ 1) >> pure password) $ \handler -> do+ first <- Software.serialize handler+ Software.serialize handler >>= (@?= first)+ pure first+ readIORef count >>= (@?= 0)+ Software.withSerialized+ bytes+ (modifyIORef' count (+ 1) >> pure password)+ ( \case+ Software.Ed25519Handler handler -> void (Software.publicKey handler >>= requirePure) >> pure (Right ())+ Software.Bip32Handler _ -> assertFailure "wrong mode" >> pure (Right ())+ )+ >>= (@?= Right ())+ readIORef count >>= (@?= 1)++checkWrongPassword :: IO ()+checkWrongPassword = do+ bytes <- require $ withNormal (pure password) Software.serialize+ result <- Software.withSerialized bytes (pure "wrong") $ \case+ Software.Ed25519Handler handler -> voidResult <$> Software.publicKey handler+ Software.Bip32Handler _ -> pure (Left InvalidKeyHandlerStorage)+ case result of Left (NativeError {}) -> pure (); other -> assertFailure (show other)++checkPasswords :: IO ()+checkPasswords = forM_ ["a\0b", ByteString.replicate 128 9] $ \pass -> do+ result <- Signing.withNormalKey (ByteString.replicate 32 1) $ \key -> Software.withSigningKey key pass (pure pass) (fmap voidResult . Software.publicKey)+ result @?= Right ()++checkCallbackBounds :: IO ()+checkCallbackBounds = forM_ [0, 129] $ \size -> do+ result <- withNormal (pure (ByteString.replicate size 1)) (fmap voidResult . Software.publicKey)+ result @?= Left (InvalidKeyHandlerPasswordLength size)++checkClosed :: IO ()+checkClosed = do+ escaped <- require $ withNormal (pure password) (pure . Right)+ Software.close escaped >>= (@?= Right ())+ Software.serialize escaped >>= (@?= Left KeyHandlerClosed)+ Software.publicKey escaped >>= (@?= Left KeyHandlerClosed)+ result <- withNormal (pure password) $ \handler -> do+ Software.close handler >>= (@?= Right ())+ Software.close handler >>= (@?= Right ())+ voidResult <$> Software.publicKey handler+ result @?= Left KeyHandlerClosed++checkSource :: IO ()+checkSource = do+ result <- Signing.withNormalKey (ByteString.replicate 32 1) $ \source -> Software.withSigningKey source password (pure password) $ \handler -> do+ expected <- require (Signing.publicKey source)+ Signing.close source+ Software.publicKey handler >>= (@?= Right expected)+ pure (Right ())+ result @?= Right ()+ Signing.withNormalKey (ByteString.replicate 32 1) (\source -> Signing.close source >> Software.withSigningKey source password (pure password) (const (pure (Right ())))) >>= (@?= Left SigningKeyClosed)++checkScopeFailure :: IO ()+checkScopeFailure = do+ escaped <- newEmptyMVar+ withNormal (pure password) (\handler -> putMVar escaped handler >> pure (Left InvalidKeyHandlerStorage :: Either Error ())) >>= (@?= Left InvalidKeyHandlerStorage)+ handler <- takeMVar escaped+ Software.publicKey handler >>= (@?= Left KeyHandlerClosed)+ outcome <- try $ withNormal (pure password) (\key -> putMVar escaped key >> throwIO (userError "scope")) :: IO (Either SomeException (Either Error ()))+ assertBool "scope exception propagated" (case outcome of Left _ -> True; _ -> False)+ takeMVar escaped >>= (Software.publicKey >=> (@?= Left KeyHandlerClosed))++checkCallbackFailure :: IO ()+checkCallbackFailure = forM_ [throwIO (userError "password"), pure (throw (userError "lazy password"))] $ \request -> do+ result <- try (withNormal request (fmap voidResult . Software.publicKey)) :: IO (Either SomeException (Either Error ()))+ assertBool "callback exception escaped only after native unwind" (case result of Left _ -> True; _ -> False)++checkRecovery :: IO ()+checkRecovery = do+ state <- newIORef (0 :: Int)+ let request = do+ index <- readIORef state+ modifyIORef' state (+ 1)+ case index of+ 0 -> pure ByteString.empty+ 1 -> throwIO (userError "callback recovery")+ _ -> pure password+ snapshot <- require $ withNormal request $ \handler -> do+ Software.publicKey handler >>= (@?= Left (InvalidKeyHandlerPasswordLength 0))+ outcome <- try (Software.publicKey handler) :: IO (Either SomeException (Either Error EdPublic.PublicKey))+ assertBool "callback exception propagated" (case outcome of Left _ -> True; _ -> False)+ void (Software.publicKey handler >>= requirePure)+ name <- Software.name handler+ Software.close handler >>= (@?= Right ())+ Software.name handler >>= (@?= Left KeyHandlerClosed)+ pure name+ snapshot @?= "Ed25519 Software Secure Key Handler"+ readIORef state >>= (@?= 3)++checkReentry :: IO ()+checkReentry = do+ slot <- newEmptyMVar+ let request = do+ handler <- takeMVar slot+ Software.publicKey handler >>= (@?= Left KeyHandlerBusy)+ Software.serialize handler >>= (@?= Left KeyHandlerBusy)+ Software.name handler >>= (@?= Left KeyHandlerBusy)+ Software.close handler >>= (@?= Left KeyHandlerBusy)+ pure password++ result <- withNormal request $ \handler -> do+ putMVar slot handler+ voidResult <$> Software.publicKey handler+ result @?= Right ()++checkBusy :: IO ()+checkBusy = do+ started <- newEmptyMVar+ release <- newEmptyMVar+ result <- withNormal (putMVar started () >> takeMVar release >> pure password) $ \handler -> do+ finished <- newEmptyMVar+ _ <- forkFinally (Software.publicKey handler) (putMVar finished)+ takeMVar started+ Software.close handler >>= (@?= Left KeyHandlerBusy)+ Software.publicKey handler >>= (@?= Left KeyHandlerBusy)+ Software.serialize handler >>= (@?= Left KeyHandlerBusy)+ Software.name handler >>= (@?= Left KeyHandlerBusy)+ putMVar release ()+ outcome <- takeMVar finished+ case outcome of Right (Right _) -> pure (); _ -> assertFailure "operation failed"+ pure (Right ())+ result @?= Right ()++checkCancellation :: IO ()+checkCancellation = do+ started <- newEmptyMVar+ finalized <- newEmptyMVar+ hold <- newEmptyMVar+ count <- newIORef (0 :: Int)+ result <- withNormal+ ( do+ n <- readIORef count+ modifyIORef' count (+ 1)+ if n == 0 then bracket_ (putMVar started ()) (putMVar finalized ()) (takeMVar hold) else pure password+ )+ $ \handler -> do+ finished <- newEmptyMVar+ thread <- forkFinally (Software.publicKey handler) (putMVar finished)+ takeMVar started+ ended <- timeout 5000000 (killThread thread >> takeMVar finished)+ case ended of+ Just (Left exception) -> fromException exception @?= Just ThreadKilled+ _ -> assertFailure "cancellation failed to join"+ takeMVar finalized+ voidResult <$> Software.publicKey handler+ result @?= Right ()++checkScopeJoin :: IO ()+checkScopeJoin = do+ started <- newEmptyMVar+ release <- newEmptyMVar+ operationFinished <- newEmptyMVar+ scopeFinished <- newEmptyMVar+ ready <- newEmptyMVar+ escaped <- newEmptyMVar+ _ <-+ forkFinally+ ( withNormal (putMVar started () >> takeMVar release >> pure password) $ \handler -> do+ putMVar escaped handler+ _ <- forkFinally (Software.publicKey handler) (putMVar operationFinished)+ takeMVar started+ putMVar ready ()+ pure (Right ())+ )+ (putMVar scopeFinished)+ handler <- takeMVar escaped+ takeMVar ready+ -- The operation keeps the pointer alive even after the user continuation exits.+ Software.close handler >>= (@?= Left KeyHandlerBusy)+ putMVar release ()+ takeMVar operationFinished >>= \case Right (Right _) -> pure (); _ -> assertFailure "operation failed"+ takeMVar scopeFinished >>= \case Right (Right ()) -> pure (); _ -> assertFailure "scope failed"+ Software.publicKey handler >>= (@?= Left KeyHandlerClosed)++checkIndependent :: IO ()+checkIndependent = replicateM_ 3 $ do+ first <- newEmptyMVar+ second <- newEmptyMVar+ done <- newEmptyMVar+ let run signal other pass = Signing.withNormalKey (ByteString.replicate 32 1) $ \source -> Software.withSigningKey source pass (putMVar signal () >> takeMVar other >> performGC >> pure pass) (fmap voidResult . Software.publicKey)+ _ <- forkFinally (run first second "first") (putMVar done)+ run second first "second" >>= (@?= Right ())+ takeMVar done >>= \case Right (Right ()) -> pure (); _ -> assertFailure "independent callback failed"++voidResult :: Either error value -> Either error ()+voidResult = void++require :: IO (Either Error value) -> IO value+require action = action >>= requirePure++requirePure :: (Show error) => Either error value -> IO value+requirePure = either (\failure -> assertFailure (show failure) >> fail "unreachable") pure++hexBytes :: Text -> IO ByteString+hexBytes text = case Hex.decodeHex text of+ Just bytes -> pure bytes+ Nothing -> assertFailure "invalid fixture hex" >> fail "fixture"
@@ -0,0 +1,172 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Standalone set representation choices preserve exact nested payloads.+-- Tests are original Cometa fixtures; native comparisons reuse the existing+-- certificate, proposal and pool reconstruction oracles.+module StandaloneSetEncoding (tests) where++import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Encoding.Set (SetEncoding (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.NetworkId as Network+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.UnitInterval as Unit+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified Data.Set as Set+import Data.Word (Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Standalone set encoding"+ [ testCase "certificate tags retain indefinite arrays and nonminimal nested bytes" checkCertificates,+ testCase "proposal tags retain ordering, duplicates and exact nested bytes" checkProposals,+ testCase "pool owner encoding is an explicit fresh serialization choice" checkPool,+ testCase "committee removal tags retain imported credential order and bytes" checkRemovals+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "Invalid fixture") pure++tags :: [ByteString]+tags = [B.pack [217, 1, 2], B.pack [218, 0, 0, 1, 2], B.pack [219, 0, 0, 0, 0, 0, 0, 1, 2]]++checkCertificates :: IO ()+checkCertificates = do+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ let value = Certificate.StakeRegistration (Credential.KeyCredential stake)+ collection = Certificates.fromList [value, value]+ -- Deliberately nonminimal certificate kind, inside an indefinite collection.+ item = B.pack [130, 24, 0] <> B.drop 2 (Certificate.encodeCbor value)+ payload = B.singleton 159 <> item <> item <> B.singleton 255+ nativeAgreement cCertificates 1 (Certificates.encodeCborWith TaggedSet collection)+ forM_ tags $ \tag -> do+ original <- must (Certificates.decodeCbor (tag <> payload))+ Certificates.setEncoding original @?= TaggedSet+ Certificates.withSetEncoding TaggedSet original @?= original+ let changed = Certificates.withSetEncoding UntaggedSet original+ Certificates.toCbor changed @?= payload+ Certificates.toCertificates changed @?= collection+ Certificates.decodeCbor payload @?= Right changed+ Certificates.withSetEncoding UntaggedSet changed @?= changed+ Certificates.toCbor original @?= tag <> payload+ forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ encoded <- must (Certificates.decodeCbor (Certificates.encodeCborWith requested collection))+ Certificates.setEncoding encoded @?= requested+ Certificates.toCertificates encoded @?= collection+ assertBool "wrong set tag" (isLeft (Certificates.decodeCbor (B.pack [217, 1, 3, 128])))++checkProposals :: IO ()+checkProposals = do+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ url <- must (Anchor.mkUrl "https://example.com")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 2))+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ value = Proposal.Proposal 0 account Action.InfoAction (Anchor.Anchor url digest)+ collection = Proposal.fromList [value, value]+ -- Deliberately nonminimal deposit, preserved below the outer collection.+ item = B.pack [132, 24, 0] <> B.drop 2 (Proposal.encodeCbor value)+ payload = B.singleton 159 <> item <> item <> B.singleton 255+ nativeAgreement cProposals 11 (Proposal.encodeProposalsWith TaggedSet collection)+ forM_ tags $ \tag -> do+ original <- must (Proposal.decodeProposals (tag <> payload))+ Proposal.withSetEncoding TaggedSet original @?= original+ let changed = Proposal.withSetEncoding UntaggedSet original+ Proposal.proposalsCbor changed @?= payload+ Proposal.toProposals changed @?= collection+ Proposal.decodeProposals payload @?= Right changed+ Proposal.withSetEncoding UntaggedSet changed @?= changed+ Proposal.proposalsCbor original @?= tag <> payload+ forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ encoded <- must (Proposal.decodeProposals (Proposal.encodeProposalsWith requested collection))+ Proposal.setEncoding encoded @?= requested+ Proposal.toProposals encoded @?= collection+ assertBool "wrong set tag" (isLeft (Proposal.decodeProposals (B.pack [217, 1, 3, 128])))++checkPool :: IO ()+checkPool = do+ operator <- must (Credential.keyHashFromBytes (B.replicate 28 3))+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 4))+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 5))+ margin <- must (Unit.mkUnitInterval 1 2)+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ value = Pool.PoolParameters operator vrf Nothing 0 0 margin account (Set.singleton stake) [] Nothing+ Pool.encodeCborWith TaggedSet value @?= Pool.encodeCbor value+ let tagged = Pool.encodeCbor value+ untagged = Pool.encodeCborWith UntaggedSet value+ (prefix, suffix) = B.breakSubstring (B.pack [217, 1, 2]) tagged+ assertBool "owner tag exists" (not (B.null suffix))+ untagged @?= prefix <> B.drop 3 suffix+ Pool.decodeCbor untagged @?= Right value+ Pool.decodeCbor tagged @?= Right value+ nativeAgreement cPool 0 tagged+ forM_ tags $ \tag -> Pool.decodeCbor (prefix <> tag <> B.drop 3 suffix) @?= Right value++checkRemovals :: IO ()+checkRemovals = do+ first <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ second <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ let credential hash = B.pack [130, 24, 0, 88, 28] <> Credential.keyHashBytes hash+ -- Retain unsorted input order and repeated credentials in the exact bytes.+ payload = B.singleton 159 <> credential first <> credential second <> credential first <> B.singleton 255+ values = Action.removalsFromList (map Credential.KeyCredential [first, second, first])+ forM_ tags $ \tag -> do+ original <- must (Action.decodeRemovals (tag <> payload))+ Action.removalsSetEncoding original @?= TaggedSet+ Action.withRemovalsSetEncoding TaggedSet original @?= original+ let changed = Action.withRemovalsSetEncoding UntaggedSet original+ Action.removalsCbor changed @?= payload+ Action.toRemovals changed @?= values+ Action.decodeRemovals payload @?= Right changed+ Action.withRemovalsSetEncoding UntaggedSet changed @?= changed+ forM_ [TaggedSet, UntaggedSet] $ \requested -> do+ encoded <- must (Action.decodeRemovals (Action.encodeRemovalsWith requested values))+ Action.removalsSetEncoding encoded @?= requested+ Action.toRemovals encoded @?= values+ forM_ [B.pack [217, 1, 3, 128], B.pack [128, 0], B.pack [129, 128]] $ \invalid ->+ assertBool "invalid credential set" (isLeft (Action.decodeRemovals invalid))++nativeAgreement :: (CUInt -> Ptr Word8 -> CSize -> IO CInt) -> CUInt -> ByteString -> IO ()+nativeAgreement oracle mode bytes = B.useAsCStringLen bytes $ \(pointer, size) -> do+ result <- oracle mode (castPtr pointer) (fromIntegral size)+ result @?= 1++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_certificates_agree"+ cCertificates :: CUInt -> Ptr Word8 -> CSize -> IO CInt++foreign import ccall unsafe "cometa_test_proposals_agreement"+ cProposals :: CUInt -> Ptr Word8 -> CSize -> IO CInt++foreign import ccall safe "cometa_test_pool_agreement"+ cPool :: CUInt -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,486 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Offline sub-transaction intent construction and scoped callback evidence.+module SubTransactionBuilder (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.SigningKey as Key+import Cometa.Error (Error (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.SubTransactionBuilder as Internal+import qualified Cometa.Internal.SubTransactionPlan as InternalPlan+import qualified Cometa.Internal.TransactionPlan as Common+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as NativeScript+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SlotConfig as Slots+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.SubTransaction.Builder as Builder+import qualified Cometa.SubTransaction.Indices as Indices+import qualified Cometa.SubTransaction.Plan as Plan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as TopBuilder+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as TopIndices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as TopPlan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Interval+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, displayException, throw, try)+import Control.Monad (forM_, replicateM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (elemIndex, isInfixOf, sort)+import Data.Maybe (isJust)+import qualified Fixtures.ProtocolParameters as Fixture+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Sub-transaction builder"+ [ testCase "intent preserves exact inputs/outputs without balancing" intent,+ testCase "actual V4 execution commits immediate and deferred arguments" scripts,+ testCase "composed script attachments preserve first identity and language failures" uniqueScripts,+ testCase "datum witnesses are shared across explicit attachments and local inputs" uniqueDatums,+ testCase "outer evaluation rejects underbudget signed intents and retains adequate bytes" attachedBudgets,+ testCase "reference scripts resolve from explicit reference inputs" references,+ testCase "guards, account operations and treasury donation survive building" dijkstraFields,+ testCase "all seven proposal constructors use protocol deposits" proposals,+ testCase "proposals support explicit and deferred local arguments" proposalArguments,+ testCase "grouped voting redeemers run once per local voter" voting,+ testCase "deferred snapshots and indices are local and invoked once" localDraft,+ testCase "conflicts, invalid language and schedule errors are total" invalid,+ testCase "aggregate values and protocol result limits are checked" bounds,+ testCase "expected failures, lazy exceptions and partial parses clean up" failures,+ testCase "cancellation joins the pure deferred worker" cancellation+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++fixture :: IO (Builder.Config, Output.Output, Utxo.Utxo)+fixture = do+ raw <- must Fixture.parameters+ model <- must (Models.mkCostModel 3 (replicate 251 200))+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ previous <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ params = raw {P.parameterProtocolVersion = Version.ProtocolVersion 12 0, P.parameterCostModels = Just (Models.fromList [model]), P.parameterMaxTxSize = 16384, P.parameterMaxTxExUnits = Just (ExUnits 100000000 100000000000)}+ funding <- must (Output.mkOutput destination (Value.lovelace 1) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput destination (Value.lovelace 100000000) Datum.NoDatum Nothing)+ pure (Builder.Config params Slots.preview Fields.Testnet, output, Utxo.utxo (Input.input previous 0) funding)++fieldsOf :: Sub.SubTransaction -> Fields.Fields+fieldsOf = SubBody.fields . SubBody.toBody . Sub.body++redeemers :: Sub.SubTransaction -> [Redeemer.Redeemer]+redeemers = Witnesses.redeemers . Witnesses.toWitnesses . Sub.witnesses++scriptFixture :: IO (Plutus.PlutusScript, Policy.PolicyId)+scriptFixture = do+ -- Apache-2.0 cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+ -- lib/tests/uplc/native_tx_evaluator.cpp build_v4_script: lambda returning unit.+ script <- must (Plutus.fromBytes Plutus.V4 (B.pack [0x45, 1, 1, 0, 0x24, 0x99]))+ policy <- Policy.fromScriptHash <$> (Plutus.hash script >>= must)+ pure (script, policy)++intent :: IO ()+intent = do+ (config, output, input) <- fixture+ let plan = Plan.spend input <> Plan.payTo output <> Plan.validFrom 10 <> Plan.validUntil 20+ sub <- Builder.build config plan >>= must+ Fields.fieldInputs (fieldsOf sub) @?= [Utxo.input input]+ Fields.fieldOutputs (fieldsOf sub) @?= [output]+ Fields.fieldInvalidBefore (fieldsOf sub) @?= Just 10+ Fields.fieldInvalidAfter (fieldsOf sub) @?= Just 20+ Fields.fieldNetworkId (fieldsOf sub) @?= Just Fields.Testnet+ Plan.resolvedInputs plan @?= [input]+ Builder.build config (Plan.spend input <> Plan.spend input <> Plan.payTo output) >>= must >>= \same -> Fields.fieldInputs (fieldsOf same) @?= [Utxo.input input]+ Sub.decodeCbor (Sub.encodeCbor sub) @?= Right sub++scripts :: IO ()+scripts = do+ (config, _, _) <- fixture+ (script, policy) <- scriptFixture+ let argument = Data.fromData (Data.Integer 42)+ attached = Plan.attachScript (Script.Plutus script)+ immediate = attached <> attached <> Plan.mintWithRedeemer (asset policy) 1 argument+ deferred = attached <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] (\_ _ -> Right argument)+ first <- Builder.build config immediate >>= must+ second <- Builder.build config deferred >>= must+ first @?= second+ map Redeemer.argument (redeemers first) @?= [argument]+ map Redeemer.executionUnits (redeemers first) @?= [ExUnits 1000 1000]+ assertBool "script-data hash absent" (isJust (Fields.fieldScriptDataHash (fieldsOf first)))+ where+ asset policy = Asset.Native policy AssetName.empty++localDraft :: IO ()+localDraft = do+ (config, output, keyInput) <- fixture+ (script, _) <- scriptFixture+ digest <- Plutus.hash script >>= must+ previous <- must (Id.fromBytes (B.replicate 32 9))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.ScriptCredential digest))+ datum = Data.fromData (Data.Integer 7)+ locked <- must (Output.mkOutput destination (Value.lovelace 1) (Datum.InlineDatum datum) Nothing)+ let scriptInput = Utxo.utxo (Input.input previous 0) locked+ callback draft inputs = do+ let localInputs = Fields.fieldInputs (Body.bodyFields (Body.toBody (Tx.body draft)))+ if Body.fee (Body.toBody (Tx.body draft)) /= 0 || map Utxo.input inputs /= sort localInputs+ then Left (InvalidTransactionPlan "Expected local fee-zero canonical draft")+ else case elemIndex (Utxo.input scriptInput) localInputs of+ Nothing -> Left (InvalidTransactionPlan "Missing local input")+ Just index -> Right (Data.fromData (Data.Integer (toInteger index)))+ plan = Plan.attachDatum datum <> Plan.spendWithDeferredRedeemer scriptInput callback (Just datum) <> Plan.spend keyInput <> Plan.payTo output <> Plan.attachScript (Script.Plutus script) <> Plan.attachDatum datum+ count <- newIORef (0 :: Int)+ let observed operation bytes = modifyIORef' count (+ 1) >> Internal.dispatch plan operation bytes+ bytes <- Internal.runWithDispatch config observed (encoded plan) >>= must+ sub <- must (Sub.decodeCbor bytes)+ map Redeemer.argument (redeemers sub) @?= [Data.fromData (Data.Integer 1)]+ readIORef count >>= (@?= 1)+ Witnesses.datums (Witnesses.toWitnesses (Sub.witnesses sub)) @?= [datum]++encoded :: Plan.Plan -> B.ByteString+encoded = Common.encodePlan 0 . InternalPlan.toPlan++invalid :: IO ()+invalid = do+ (config, output, input) <- fixture+ let argument = Data.fromData (Data.Integer 1)+ one = Plan.spendWithDeferredRedeemer input (\_ _ -> Right argument) Nothing+ Builder.build config (one <> one <> Plan.payTo output) >>= assertBool "duplicate deferred input" . isLeft+ Builder.build config (Plan.validFrom 10 <> Plan.validUntil 10) >>= assertBool "empty validity" . isLeft+ Builder.build config (Plan.validUntil maxBound) >>= assertBool "time overflow" . isLeft+ (script, policy) <- scriptFixture+ old <- must (Plutus.fromBytes Plutus.V3 (Plutus.toBytes script))+ oldPolicy <- Policy.fromScriptHash <$> (Plutus.hash old >>= must)+ Builder.build config (Plan.attachScript (Script.Plutus old) <> Plan.mintWithDeferredRedeemer oldPolicy [(AssetName.empty, 1)] (\_ _ -> Right argument)) >>= assertBool "old language executed locally" . isLeft+ let grouped = Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] (\_ _ -> Right argument)+ Builder.build config (grouped <> grouped) >>= assertBool "repeated policy" . isLeft++failures :: IO ()+failures = do+ baseline <- Runtime.liveContexts+ (config, _, _) <- fixture+ (script, policy) <- scriptFixture+ let plan callback = Plan.attachScript (Script.Plutus script) <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] callback+ expected = InvalidTransactionPlan "Refused local draft"+ Builder.build config (plan (\_ _ -> Left expected)) >>= (@?= Left expected)+ let lazyFailure _ _ = Right (Data.fromData (Data.Integer (throw (userError "lazy sub payload"))))+ outcome <- try (Builder.build config (plan lazyFailure))+ case outcome of+ Left (failure :: SomeException) -> assertBool "lost lazy failure" ("lazy sub payload" `isInfixOf` displayException failure)+ Right result -> assertFailure (show result)+ replicateM_ 5 $ do+ Internal.runUnchecked config mempty (B.pack [0x81, 0x80]) >>= assertBool "malformed instruction accepted" . isLeft+ Internal.runWithDispatch config (\_ _ -> pure (Right (B.pack [0, 0]))) (encoded (plan (\_ _ -> Right (Data.fromData (Data.Integer 0))))) >>= assertBool "trailing payload accepted" . isLeft+ performGC+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ baseline <- Runtime.liveContexts+ (config, _, _) <- fixture+ (script, policy) <- scriptFixture+ entered <- newEmptyMVar+ finished <- newEmptyMVar+ let never _ _ = Right (Data.fromData (Data.Integer (sum [1 ..])))+ plan = Plan.attachScript (Script.Plutus script) <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] never+ observed operation bytes = putMVar entered () >> Internal.dispatch plan operation bytes+ worker <- forkFinally (Internal.runWithDispatch config observed (encoded plan)) (putMVar finished)+ takeMVar entered+ killThread worker+ outcome <- timeout 5000000 (takeMVar finished)+ case outcome of+ Just (Left _) -> pure ()+ _ -> assertFailure "cancelled sub-builder did not join its callback"+ Runtime.liveContexts >>= (@?= baseline)++references :: IO ()+references = do+ (config, _, input) <- fixture+ (script, policy) <- scriptFixture+ let funding = Utxo.output input+ argument = Data.fromData (Data.Integer 3)+ referenced <- must (Output.mkOutput (Output.address funding) (Output.value funding) Datum.NoDatum (Just (Script.Plutus script)))+ let reference = Utxo.utxo (Utxo.input input) referenced+ plan = Plan.referenceInput reference <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] (\_ _ -> Right argument)+ sub <- Builder.build config plan >>= must+ Fields.fieldReferenceInputs (fieldsOf sub) @?= Just [Utxo.input input]+ Fields.fieldInputs (fieldsOf sub) @?= []+ map Redeemer.argument (redeemers sub) @?= [argument]+ Plan.resolvedInputs plan @?= [reference]++accountFixture :: IO (Reward.RewardAddress, Anchor.Anchor)+accountFixture = do+ key <- must (Credential.keyHashFromBytes (B.replicate 28 5))+ url <- must (Anchor.mkUrl "https://example.com/governance")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 6))+ pure (Reward.fromCredential Network.testnet (Credential.KeyCredential key), Anchor.Anchor url digest)++dijkstraFields :: IO ()+dijkstraFields = do+ (config, _, _) <- fixture+ (account, _) <- accountFixture+ (script, _) <- scriptFixture+ digest <- Plutus.hash script >>= must+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ let credential = Credential.KeyCredential key+ argument = Data.fromData (Data.Integer 99)+ plan =+ Plan.requireGuard credential+ <> Plan.guardWithRedeemer digest argument+ <> Plan.attachScript (Script.Plutus script)+ <> Plan.requireTopLevelGuard credential Nothing+ <> Plan.directDeposit account 2+ <> Plan.directDeposit account 3+ <> Plan.accountBalance account (Fields.BalanceRange (Just 1) (Just 9))+ <> Plan.donate 1+ <> Plan.donate 2+ sub <- Builder.build config plan >>= must+ Fields.fieldGuards (fieldsOf sub) @?= Just [credential, Credential.ScriptCredential digest]+ fmap Fields.entries (Fields.fieldRequiredTopLevelGuards (fieldsOf sub)) @?= Just [(credential, Nothing)]+ fmap Fields.entries (Fields.fieldDirectDeposits (fieldsOf sub)) @?= Just [(account, 5)]+ fmap Fields.entries (Fields.fieldAccountBalanceIntervals (fieldsOf sub)) @?= Just [(account, Fields.BalanceRange (Just 1) (Just 9))]+ Fields.fieldDonation (fieldsOf sub) @?= Just 3+ map Redeemer.purpose (redeemers sub) @?= [Redeemer.Guarding]+ map Redeemer.index (redeemers sub) @?= [1]+ map Redeemer.argument (redeemers sub) @?= [argument]++proposals :: IO ()+proposals = do+ (config, _, _) <- fixture+ (account, anchor) <- accountFixture+ (policyScript, _) <- scriptFixture+ policy <- Plutus.hash policyScript >>= must+ withdrawals <- must (Action.withdrawalsFromList [(account, 5)])+ quorum <- must (Interval.mkUnitInterval 1 2)+ let changes = Update.empty {Update.updateMinFeeA = Just 1}+ actions =+ [ Action.ParameterChange Nothing changes (Just policy),+ Action.HardForkInitiation Nothing (Version.ProtocolVersion 13 0),+ Action.TreasuryWithdrawals withdrawals (Just policy),+ Action.NoConfidence Nothing,+ Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers quorum,+ Action.NewConstitution Nothing (Constitution.Constitution anchor Nothing),+ Action.InfoAction+ ]+ configured = config {Builder.parameters = (Builder.parameters config) {P.parameterGovernanceActionDeposit = Just 500}}+ forM_ actions $ \action -> do+ sub <- Builder.build configured (Plan.attachScript (Script.Plutus policyScript) <> Plan.propose account action anchor) >>= must+ fmap Proposal.toList (Fields.fieldProposalProcedures (fieldsOf sub)) @?= Just [Proposal.Proposal 500 account action anchor]++voting :: IO ()+voting = do+ (config, _, _) <- fixture+ (script, _) <- scriptFixture+ digest <- Plutus.hash script >>= must+ previous <- must (Id.fromBytes (B.replicate 32 2))+ let voter = Voting.DRepVoter (Credential.ScriptCredential digest)+ choices = [(ActionId.ActionId previous 0, Voting.VotingProcedure Voting.Yes Nothing), (ActionId.ActionId previous 1, Voting.VotingProcedure Voting.Abstain Nothing)]+ argument = Data.fromData (Data.Integer 55)+ plan = Plan.attachScript (Script.Plutus script) <> Plan.voteWithDeferredRedeemer voter choices (\_ _ -> Right argument)+ count <- newIORef (0 :: Int)+ let observed operation bytes = modifyIORef' count (+ 1) >> Internal.dispatch plan operation bytes+ bytes <- Internal.runWithDispatch config observed (encoded plan) >>= must+ sub <- must (Sub.decodeCbor bytes)+ map Redeemer.purpose (redeemers sub) @?= [Redeemer.Voting]+ map Redeemer.argument (redeemers sub) @?= [argument]+ fmap Voting.toList (Fields.fieldVotingProcedures (fieldsOf sub)) @?= Just [(voter, fst choice, snd choice) | choice <- choices]+ readIORef count >>= (@?= 1)++bounds :: IO ()+bounds = do+ (config, output, _) <- fixture+ huge <- must (Output.mkOutput (Output.address output) (Value.lovelace 9223372036854775807) Datum.NoDatum Nothing)+ Builder.build config (Plan.payTo huge <> Plan.payTo huge) >>= assertBool "aggregate output overflow" . isLeft+ let withParams change = config {Builder.parameters = change (Builder.parameters config)}+ Builder.build (withParams (\params -> params {P.parameterKeyDeposit = maxBound})) mempty >>= assertBool "deposit narrowing" . isLeft+ Builder.build (withParams (\params -> params {P.parameterMaxTxSize = 0})) (Plan.payTo output) >>= assertBool "sub serialization size" . isLeft+ Builder.build (withParams (\params -> params {P.parameterMaxValueSize = Just 0})) (Plan.payTo output) >>= assertBool "output value size" . isLeft+ (script, policy) <- scriptFixture+ let mint = Plan.attachScript (Script.Plutus script) <> Plan.mintWithDeferredRedeemer policy [(AssetName.empty, 1)] (\_ _ -> Right (Data.fromData (Data.Integer 1)))+ Builder.build (withParams (\params -> params {P.parameterMaxTxExUnits = Just (ExUnits 999 1000)})) mint >>= assertBool "execution units exceed cap" . isLeft+ Builder.build (withParams (\params -> params {P.parameterMaxTxExUnits = Nothing})) mint >>= assertBool "missing execution cap" . isLeft++attachedBudgets :: IO ()+attachedBudgets = do+ (localConfig, _, input) <- fixture+ (script, policy) <- scriptFixture+ let address = Output.address (Utxo.output input)+ params =+ (Builder.parameters localConfig)+ { P.parameterMinFeeA = 0,+ P.parameterMinFeeB = 0,+ P.parameterMaxValueSize = Just 5000,+ P.parameterAdaPerUtxoByte = Just 4310,+ P.parameterCollateralPercentage = Just 150,+ P.parameterMaxCollateralInputs = Just 3+ }+ argument = Data.fromData (Data.Integer 1)+ mintIntent = Plan.attachScript (Script.Plutus script) <> Plan.mintWithRedeemer (Asset.Native policy AssetName.empty) 1 argument+ adequate <- Builder.build localConfig mintIntent >>= must+ models <- maybe (assertFailure "missing fixture cost models" >> fail "fixture") pure (P.parameterCostModels params)+ insufficient <- replaceBudget models (ExUnits 0 0) adequate+ wallet <- must (Output.mkOutput address (Value.lovelace 10000000) Datum.NoDatum Nothing)+ payment <- must (Output.mkOutput address (Value.lovelace 2000000) Datum.NoDatum Nothing)+ collateral <- must (Output.mkOutput address (Value.lovelace 5000000) Datum.NoDatum Nothing)+ collateralReference <- must (Id.fromBytes (B.replicate 32 10))+ let config =+ (TopBuilder.defaultConfig params Slots.preview address)+ { TopBuilder.availableUtxos = [Utxo.utxo (Utxo.input input) wallet],+ TopBuilder.collateralUtxos = [Utxo.utxo (Input.input collateralReference 0) collateral],+ TopBuilder.minimumFee = 200000+ }+ parent sub = TopPlan.payTo payment <> TopPlan.attachSubTransaction sub []+ signed <- Key.withNormalKey (B.replicate 32 7) $ \key -> do+ low <- Signing.signSubTransaction key insufficient+ enough <- Signing.signSubTransaction key adequate+ pure ((,) <$> low <*> enough)+ (signedLow, signedEnough) <- must signed+ TopBuilder.build config (parent signedLow) >>= (@?= Left (InvalidBuildingRequest "Attached subtransaction execution exceeds its declared budget"))+ batch <- TopBuilder.build config (parent signedEnough) >>= must+ fmap (map Sub.encodeCbor) (Body.bodySubTransactions (Body.toBody (Tx.body batch))) @?= Just [Sub.encodeCbor signedEnough]++replaceBudget :: Models.CostModels -> ExUnits -> Sub.SubTransaction -> IO Sub.SubTransaction+replaceBudget models units transaction = do+ let original = Witnesses.toWitnesses (Sub.witnesses transaction)+ updated = [value {Redeemer.executionUnits = units} | value <- Witnesses.redeemers original]+ witnesses <- must (Witnesses.mkWitnesses (Witnesses.verificationWitnesses original) (Witnesses.bootstrapWitnesses original) (Witnesses.scripts original) (Witnesses.datums original) updated)+ let encodedWitnesses = Witnesses.fromWitnesses witnesses+ commitment <- Building.scriptDataHash models encodedWitnesses >>= must+ let fields = (fieldsOf transaction) {Fields.fieldScriptDataHash = commitment}+ body <- must (SubBody.fromBody (SubBody.fromFields fields))+ pure (Sub.assemble body encodedWitnesses (Sub.auxiliaryData transaction))++uniqueScripts :: IO ()+uniqueScripts = do+ (config, output, input) <- fixture+ let nativeA = Script.Native (NativeScript.allOf [])+ nativeB = Script.Native (NativeScript.anyOf [])+ nativePlan = Plan.attachScript nativeB <> Plan.attachScript nativeA+ payment = Plan.spend input <> Plan.payTo output+ nativeSub <- Builder.build config (nativePlan <> nativePlan <> payment) >>= must+ Witnesses.scripts (Witnesses.toWitnesses (Sub.witnesses nativeSub)) @?= [nativeB, nativeA]+ first <- Script.Plutus <$> must (Plutus.decodeCbor Plutus.V4 (B.pack [0x58, 3, 1, 2, 3]))+ canonical <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V4 (B.pack [1, 2, 3]))+ distinct <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V4 (B.pack [4, 5, 6]))+ let once = Plan.attachScript first <> Plan.attachScript distinct <> payment+ repeated = Plan.attachScript first <> Plan.attachScript distinct <> Plan.attachScript canonical <> Plan.attachScript first <> payment+ encoded repeated @?= encoded once+ expected <- Builder.build config once >>= must+ actual <- Builder.build config repeated >>= must+ Sub.encodeCbor actual @?= Sub.encodeCbor expected+ length (Witnesses.scripts (Witnesses.toWitnesses (Sub.witnesses actual))) @?= 2+ -- Deduplication never turns an unsupported language into an accepted plan.+ forM_ [Plutus.V1 .. Plutus.V3] $ \version -> do+ old <- Script.Plutus <$> must (Plutus.fromBytes version (B.pack [1, 2, 3]))+ let attachment = Plan.attachScript old+ single <- Builder.build config (attachment <> payment)+ duplicate <- Builder.build config (attachment <> attachment <> payment)+ assertBool "unsupported sub-level script accepted" (isLeft single)+ duplicate @?= single++uniqueDatums :: IO ()+uniqueDatums = do+ (config, output, first) <- fixture+ let second = Utxo.utxo (Input.input (Input.transactionId (Utxo.input first)) 1) (Utxo.output first)+ canonical = Data.fromData (Data.Integer 0)+ imported <- must (Data.decodeCbor (B.pack [0x18, 0]))+ Data.toData imported @?= Data.toData canonical+ let attachments = Plan.attachDatum imported <> Plan.attachDatum canonical <> Plan.attachDatum imported <> Plan.attachDatum canonical+ explicit <- Builder.build config (attachments <> Plan.payTo output) >>= must+ Witnesses.datums (Witnesses.toWitnesses (Sub.witnesses explicit)) @?= [imported, canonical]+ forM_ [False, True] $ \attachFirst -> do+ let spends = Plan.spendWith first Nothing (Just imported) <> Plan.spendWith second Nothing (Just imported)+ plan = if attachFirst then attachments <> spends <> Plan.payTo output else spends <> attachments <> Plan.payTo output+ sub <- Builder.build config plan >>= must+ Fields.fieldInputs (fieldsOf sub) @?= [Utxo.input first, Utxo.input second]+ Witnesses.datums (Witnesses.toWitnesses (Sub.witnesses sub)) @?= [imported, canonical]+ Builder.build config (Plan.spendWith first Nothing (Just imported) <> Plan.spendWith first Nothing (Just canonical) <> Plan.payTo output)+ >>= (@?= Left (InvalidTransactionPlan "Conflicting requirements for one spending input"))++proposalArguments :: IO ()+proposalArguments = do+ baseline <- Runtime.liveContexts+ (config, _, _) <- fixture+ (account, anchor) <- accountFixture+ (script, _) <- scriptFixture+ policy <- Plutus.hash script >>= must+ let deposit = 100000+ configured = config {Builder.parameters = (Builder.parameters config) {P.parameterGovernanceActionDeposit = Just deposit}}+ action = Action.ParameterChange Nothing Update.empty (Just policy)+ proposal = Proposal.Proposal deposit account action anchor+ immediate = Data.fromData (Data.Integer 17)+ callback draft _ = case TopIndices.findProposal proposal draft of+ Nothing -> Left (InvalidTransactionPlan "Local proposal absent from draft")+ Just index -> Right (Data.fromData (Data.Integer (toInteger index)))+ prefix = Plan.attachScript (Script.Plutus script) <> Plan.propose account Action.InfoAction anchor+ sub <- Builder.build configured (prefix <> Plan.proposeWithDeferredRedeemer account action anchor callback) >>= must+ map Redeemer.purpose (redeemers sub) @?= [Redeemer.Proposing]+ map Redeemer.index (redeemers sub) @?= [1]+ map Redeemer.argument (redeemers sub) @?= [Data.fromData (Data.Integer 1)]+ Indices.findProposal proposal sub @?= Just 1+ explicit <- Builder.build configured (prefix <> Plan.proposeWithRedeemer account action anchor immediate) >>= must+ map Redeemer.argument (redeemers explicit) @?= [immediate]+ policyless <- Builder.build configured (Plan.propose account (Action.ParameterChange Nothing Update.empty Nothing) anchor) >>= must+ redeemers policyless @?= []+ let failure = InvalidTransactionPlan "Local proposal callback refused draft"+ Builder.build configured (prefix <> Plan.proposeWithDeferredRedeemer account action anchor (\_ _ -> Left failure)) >>= (@?= Left failure)+ Runtime.liveContexts >>= (@?= baseline)
@@ -0,0 +1,274 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Private transaction representation evidence, not a public transaction API.+-- Imported and synthetic signed bytes have independent hashes and signature+-- verification provenance in test/Fixtures/TRANSACTIONS.md.+module Transaction (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Crypto.Blake2b as Blake2b+import qualified Cometa.Encoding.Cbor as Cbor+import Cometa.Internal.Hex (decodeHex, encodeHex)+import qualified Cometa.Internal.Transaction as Tx+import Control.Monad (replicateM_, (>=>))+import Data.ByteString (ByteString)+import qualified Data.ByteString as ByteString+import Data.Either (isLeft)+import Data.Text (Text)+import Data.Word (Word64, Word8)+import Fixtures.Transaction (Fixture (..))+import qualified Fixtures.Transaction as Fixture+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Marshal.Array (allocaArray, peekArray)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Property, evalEither, evalIO, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Private transaction encoding prototype"+ [ testCase "historical and noncanonical signed encodings retain exact identity" $ mapM_ checkIdentity Fixture.allFixtures,+ testCase "native oracle verifies signed digests and decoded field snapshots" $ mapM_ checkNativeAgreement Fixture.allFixtures,+ testCase "typed body inspection retains fee and field order" checkBodyFields,+ testCase "setting the same fee is an exact no-op" $ mapM_ checkSameFee Fixture.allFixtures,+ testCase "changed fee invalidates body bytes and removes signatures" checkChangedFee,+ testCase "fee edit retains native scripts, datums and redeemers" checkWitnessRetention,+ testCase "sibling edits and copied snapshots remain independent" checkEditIndependence,+ testCase "malformed, incomplete and trailing transactions are rejected" checkInvalidTransactions,+ testCase "legacy, block and indefinite frames retain exact identity" checkFrameLayouts,+ testCase "repeated decode/edit snapshots survive native cleanup and GC" checkLifecycle,+ testProperty "fee edit round trips without changing its source" propFeeEdit+ ]++checkIdentity :: Fixture -> IO ()+checkIdentity fixture = do+ bytes <- hexBytes (transactionHex fixture)+ tx <- requireRight (Tx.decodeCbor bytes)+ Tx.encodeCbor tx @?= bytes+ encodeHex (Tx.bodyCbor tx) @?= bodyHex fixture+ encodeHex (Tx.witnessCbor tx) @?= witnessHex fixture+ encodeHex (Tx.bodyHash tx) @?= hashHex fixture+ Tx.fee tx @?= expectedFee fixture+ -- The hash expectation was computed independently; this additionally checks+ -- agreement with the public hashing operation on the exact body snapshot.+ digest <- requireRight (Blake2b.compute 32 (Tx.bodyCbor tx))+ Blake2b.toBytes digest @?= Tx.bodyHash tx++checkNativeAgreement :: Fixture -> IO ()+checkNativeAgreement fixture = do+ bytes <- hexBytes (transactionHex fixture)+ tx <- requireRight (Tx.decodeCbor bytes)+ (nativeFee, nativeHash, counts) <- nativeSnapshot bytes+ nativeFee @?= Tx.fee tx+ nativeHash @?= Tx.bodyHash tx+ counts @?= expectedCounts fixture+ -- The oracle verifies each retained verification-key signature over precisely+ -- the body digest whose independent value is pinned in the fixture.+ encodeHex nativeHash @?= hashHex fixture++checkBodyFields :: IO ()+checkBodyFields = do+ bytes <- hexBytes (transactionHex Fixture.noncanonical)+ tx <- requireRight (Tx.decodeCbor bytes)+ body <- requireRight (Cbor.fromBytes (Tx.bodyCbor tx))+ entries <- requireRight (Cbor.decodeMap body)+ map (Cbor.toHex . fst) entries @?= ["02", "01", "00"]+ case entries of+ [(_, feeValue), (_, outputs), (_, inputs)] -> do+ Cbor.decodeInteger feeValue >>= (@?= Right 10)+ Cbor.decodeArray outputs >>= (@?= Right [])+ Cbor.toHex inputs @?= "d9010280"+ _ -> assertFailure "unexpected noncanonical body fields"++checkSameFee :: Fixture -> IO ()+checkSameFee fixture = do+ bytes <- hexBytes (transactionHex fixture)+ tx <- requireRight (Tx.decodeCbor bytes)+ edited <- requireRight (Tx.setFee (Tx.fee tx) tx)+ edited @?= tx+ Tx.encodeCbor edited @?= bytes+ Tx.bodyHash edited @?= Tx.bodyHash tx+ Tx.witnessCbor edited @?= Tx.witnessCbor tx++checkChangedFee :: IO ()+checkChangedFee = do+ original <- decodeFixture Fixture.noncanonical+ edited <- requireRight (Tx.setFee 42 original)+ Tx.fee edited @?= 42+ encodeHex (Tx.bodyCbor edited) @?= "a300d9010280018002182a"+ encodeHex (Tx.bodyHash edited) @?= "a5412fe55fd15ed71f2e55fdb9c4f8a3105f8e41cb770e2ed848f73f0382a38b"+ encodeHex (Tx.witnessCbor edited) @?= "a0"+ assertBool "body change retained its old hash" (Tx.bodyHash edited /= Tx.bodyHash original)+ reparsed <- requireRight (Tx.decodeCbor (Tx.encodeCbor edited))+ reparsed @?= edited+ (nativeFee, nativeHash, counts) <- nativeSnapshot (Tx.encodeCbor edited)+ nativeFee @?= 42+ nativeHash @?= Tx.bodyHash edited+ counts @?= [0, 0, 0, 0, 0, 0]++checkWitnessRetention :: IO ()+checkWitnessRetention = do+ original <- decodeFixture Fixture.rich+ before <- witnessEntries original+ edited <- requireRight (Tx.setFee 42 original)+ after <- witnessEntries edited+ map fst before @?= [0, 1, 2, 4, 5]+ map fst after @?= [1, 4, 5]+ after @?= filter (\(key, _) -> key /= 0 && key /= 2) before+ (_, _, counts) <- nativeSnapshot (Tx.encodeCbor edited)+ counts @?= [0, 0, 1, 1, 1, 0]+ encodeHex (Tx.witnessCbor original) @?= witnessHex Fixture.rich+ auxiliaryHex original >>= (@?= "a1017803617578")+ auxiliaryHex edited >>= (@?= "a1017803617578")++checkEditIndependence :: IO ()+checkEditIndependence = do+ original <- decodeFixture Fixture.rich+ let body = Tx.bodyCbor original+ witness = Tx.witnessCbor original+ digest = Tx.bodyHash original+ first <- requireRight (Tx.setFee 42 original)+ second <- requireRight (Tx.setFee 43 original)+ performGC+ Tx.fee original @?= 10+ Tx.bodyCbor original @?= body+ Tx.witnessCbor original @?= witness+ Tx.bodyHash original @?= digest+ map Tx.fee [first, second] @?= [42, 43]+ assertBool "sibling edits share a stale body hash" (Tx.bodyHash first /= Tx.bodyHash second)++checkInvalidTransactions :: IO ()+checkInvalidTransactions = do+ valid <- hexBytes (transactionHex Fixture.noncanonical)+ let malformed = [ByteString.empty, ByteString.singleton 0, ByteString.take 1 valid, ByteString.init valid, valid <> ByteString.singleton 0]+ mapM_ check malformed+ mapM_ (hexBytes >=> check) ["82a0a0", "84a0a0f5f6", "84a200800180a0f5f6", "84a3008001800220a0f5f6", "84a400d9010280018002010202a0f5f6", "84a300d90102800180020aa200800080f5f6"]+ where+ check bytes = Tx.decodeCbor bytes >>= assertBool "malformed transaction accepted" . isLeft++checkFrameLayouts :: IO ()+checkFrameLayouts = do+ original <- hexBytes (transactionHex Fixture.noncanonical)+ let fields = ByteString.take (ByteString.length original - 2) original+ legacyFalse = fields <> ByteString.pack [0xf4, 0xf6]+ blockTrue = fields <> ByteString.pack [0xf6, 0xf5]+ blockFalse = fields <> ByteString.pack [0xf6, 0xf4]+ indefinite bytes = ByteString.singleton 0x9f <> ByteString.drop 1 bytes <> ByteString.singleton 0xff+ mapM_ (uncurry check) [(original, ["f5", "f6"]), (legacyFalse, ["f4", "f6"]), (blockTrue, ["f6", "f5"]), (blockFalse, ["f6", "f4"]), (indefinite original, ["f5", "f6"]), (indefinite blockTrue, ["f6", "f5"])]+ where+ check bytes suffix = do+ tx <- requireRight (Tx.decodeCbor bytes)+ Tx.encodeCbor tx @?= bytes+ encodeHex (Tx.bodyHash tx) @?= hashHex Fixture.noncanonical+ same <- requireRight (Tx.setFee 10 tx)+ Tx.encodeCbor same @?= bytes+ edited <- requireRight (Tx.setFee 42 tx)+ frame <- requireRight (Cbor.fromBytes (Tx.encodeCbor edited))+ fields <- requireRight (Cbor.decodeArray frame)+ map Cbor.toHex (drop 2 fields) @?= suffix++checkLifecycle :: IO ()+checkLifecycle = do+ original <- decodeFixture Fixture.rich+ edited <- requireRight (Tx.setFee 42 original)+ replicateM_ 100 $ do+ temporary <- decodeFixture Fixture.historical+ _ <- requireRight (Tx.setFee 42 temporary)+ _ <- decodeFixture Fixture.rich+ pure ()+ performGC+ encodeHex (Tx.bodyHash original) @?= hashHex Fixture.rich+ encodeHex (Tx.witnessCbor original) @?= witnessHex Fixture.rich+ Tx.fee edited @?= 42+ checkIdentity Fixture.historical++propFeeEdit :: Property+propFeeEdit = withTests 300 $ property $ do+ fee <- forAll (Gen.word64 Range.constantBounded)+ original <- evalIO (decodeFixture Fixture.rich)+ edited <- evalIO (Tx.setFee fee original) >>= evalEither+ Tx.fee edited === fee+ Tx.fee original === 10+ encodeHex (Tx.bodyHash original) === hashHex Fixture.rich+ encodeHex (Tx.witnessCbor original) === witnessHex Fixture.rich+ decoded <- evalIO (Tx.decodeCbor (Tx.encodeCbor edited)) >>= evalEither+ Tx.fee decoded === fee+ Tx.bodyHash decoded === Tx.bodyHash edited+ Tx.bodyCbor decoded === Tx.bodyCbor edited+ Tx.witnessCbor decoded === Tx.witnessCbor edited++witnessEntries :: Tx.Transaction -> IO [(Integer, ByteString)]+witnessEntries tx = do+ value <- requireRight (Cbor.fromBytes (Tx.witnessCbor tx))+ pairs <- requireRight (Cbor.decodeMap value)+ mapM+ ( \(key, item) -> do+ number <- requireRight (Cbor.decodeInteger key)+ pure (number, Cbor.toBytes item)+ )+ pairs++auxiliaryHex :: Tx.Transaction -> IO Text+auxiliaryHex tx = do+ frame <- requireRight (Cbor.fromBytes (Tx.encodeCbor tx))+ fields <- requireRight (Cbor.decodeArray frame)+ case fields of+ [_, _, _, auxiliary] -> pure (Cbor.toHex auxiliary)+ _ -> assertFailure "expected a legacy four-element fixture" >> fail "invalid frame"++decodeFixture :: Fixture -> IO Tx.Transaction+decodeFixture fixture = hexBytes (transactionHex fixture) >>= requireRight . Tx.decodeCbor++hexBytes :: Text -> IO ByteString+hexBytes text = case decodeHex text of+ Just bytes -> pure bytes+ Nothing -> assertFailure "invalid hexadecimal fixture" >> fail "invalid fixture"++requireRight :: (Show failure) => IO (Either failure value) -> IO value+requireRight action = do+ result <- action+ case result of+ Right value -> pure value+ Left failure -> assertFailure (show failure) >> fail "transaction fixture operation failed"++nativeSnapshot :: ByteString -> IO (Word64, ByteString, [Word64])+nativeSnapshot bytes =+ ByteString.useAsCStringLen bytes $ \(input, size) ->+ alloca $ \fee -> allocaArray 32 $ \hash -> allocaArray 6 $ \counts -> do+ status <- cTransactionOracle (castPtr input) (fromIntegral size) fee hash counts+ status @?= 0+ nativeFee <- peek fee+ nativeHash <- ByteString.packCStringLen (castPtr hash, 32)+ nativeCounts <- peekArray 6 counts+ pure (nativeFee, nativeHash, nativeCounts)++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_transaction_oracle"+ cTransactionOracle :: Ptr Word8 -> CSize -> Ptr Word64 -> Ptr Word8 -> Ptr Word64 -> IO CUInt
@@ -0,0 +1,348 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Independent accounting equations exercised through native building calls.+-- Primary-source provenance and limits: Fixtures/TRANSACTION_ACCOUNTING.md.+module TransactionAccountingProperties (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as Name+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Encoding.Set (SetEncoding (..))+import Cometa.Error (Error)+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.NetworkId as Network+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Value+import Control.Monad (forM_, when)+import qualified Data.ByteString as B+import Data.Map.Strict (Map)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import Data.Word (Word64, Word8)+import qualified Fixtures.ProtocolParameters as ProtocolFixture+import Hedgehog (Gen, Property, PropertyT, classify, evalEither, evalIO, forAll, property, withTests, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++data Event+ = LegacyRegistration+ | LegacyDeregistration+ | Registration Word64+ | Unregistration Word64+ | DRepRegistration Word64+ | DRepUnregistration Word64+ | StakeRegistrationDelegation Word64+ | VoteRegistrationDelegation Word64+ | StakeVoteRegistrationDelegation Word64+ | Retirement+ deriving (Eq, Show)++data Fixture = Fixture+ { fixtureAddress :: Address.Address,+ fixtureStake :: Credential.Credential Credential.Stake,+ fixtureDRep :: Credential.Credential Credential.DRep,+ fixturePool :: Credential.KeyHash Credential.StakePool,+ fixtureAccount :: Reward.RewardAddress,+ fixtureAnchor :: Anchor.Anchor+ }++data Scenario = Scenario+ { scenarioWithdrawal :: Word64,+ scenarioDeposit :: Word64,+ scenarioRefund :: Word64,+ scenarioDonation :: Word64,+ scenarioDirectDeposit :: Word64,+ scenarioFee :: Word64,+ scenarioMint :: Integer,+ scenarioPerturbation :: Integer+ }+ deriving (Show)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Native transaction accounting properties"+ [ testProperty "mixed implicit deposits, refunds and withdrawals follow independent totals" propImplicit,+ testProperty "top-level, local and batch conservation includes signed mint and account flows" propConservation,+ testProperty "zero mint is absent in the shrunk accounting regression" zeroMintRegression,+ testProperty "pool deposit deduplication is local and global at the appropriate scope" propPoolDeposits+ ]++smallAmount :: Gen Word64+smallAmount = Gen.choice [Gen.element [0, 1, 23, 24, 255, 256, 65535, 65536], Gen.integral (Range.linear 0 1000000)]++genEvent :: Gen Event+genEvent =+ Gen.choice+ [ pure LegacyRegistration,+ pure LegacyDeregistration,+ Registration <$> smallAmount,+ Unregistration <$> smallAmount,+ DRepRegistration <$> smallAmount,+ DRepUnregistration <$> smallAmount,+ StakeRegistrationDelegation <$> smallAmount,+ VoteRegistrationDelegation <$> smallAmount,+ StakeVoteRegistrationDelegation <$> smallAmount,+ pure Retirement+ ]++fixture :: Either Error Fixture+fixture = do+ payment <- Credential.keyHashFromBytes (B.replicate 28 1)+ staking <- Credential.keyHashFromBytes (B.replicate 28 2)+ representative <- Credential.keyHashFromBytes (B.replicate 28 3)+ pool <- Credential.keyHashFromBytes (B.replicate 28 4)+ url <- Anchor.mkUrl "https://example.com/accounting"+ digest <- Anchor.dataHashFromBytes (B.replicate 32 5)+ let stake = Credential.KeyCredential staking+ pure (Fixture (Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential payment))) stake (Credential.KeyCredential representative) pool (Reward.fromCredential Network.testnet stake) (Anchor.Anchor url digest))++certificate :: Fixture -> Event -> Certificate.Certificate+certificate f event = case event of+ LegacyRegistration -> Certificate.StakeRegistration (fixtureStake f)+ LegacyDeregistration -> Certificate.StakeDeregistration (fixtureStake f)+ Registration amount -> Certificate.Registration (fixtureStake f) amount+ Unregistration amount -> Certificate.Unregistration (fixtureStake f) amount+ DRepRegistration amount -> Certificate.RegisterDRep (fixtureDRep f) amount Nothing+ DRepUnregistration amount -> Certificate.UnregisterDRep (fixtureDRep f) amount+ StakeRegistrationDelegation amount -> Certificate.StakeRegistrationDelegation (fixtureStake f) (fixturePool f) amount+ VoteRegistrationDelegation amount -> Certificate.VoteRegistrationDelegation (fixtureStake f) DRep.AlwaysAbstain amount+ StakeVoteRegistrationDelegation amount -> Certificate.StakeVoteRegistrationDelegation (fixtureStake f) (fixturePool f) DRep.AlwaysAbstain amount+ Retirement -> Certificate.PoolRetirement (fixturePool f) 42++-- These expectations consume generated events, never decoded certificates or+-- native results. All arithmetic remains unbounded until the final comparison.+eventTotals :: Word64 -> [Event] -> (Integer, Integer)+eventTotals keyDeposit events = (sum (map paid events), sum (map refunded events))+ where+ paid event = case event of+ LegacyRegistration -> toInteger keyDeposit+ Registration amount -> toInteger amount+ DRepRegistration amount -> toInteger amount+ StakeRegistrationDelegation amount -> toInteger amount+ VoteRegistrationDelegation amount -> toInteger amount+ StakeVoteRegistrationDelegation amount -> toInteger amount+ _ -> 0+ refunded event = case event of+ LegacyDeregistration -> toInteger keyDeposit+ Unregistration amount -> toInteger amount+ DRepUnregistration amount -> toInteger amount+ _ -> 0++withdrawalEntries :: [Word64] -> Either Error (Fields.Entries Reward.RewardAddress Word64)+withdrawalEntries amounts = do+ accounts <- traverse account [1 .. length amounts]+ Fields.mkEntries (zip accounts amounts)+ where+ account index = Reward.fromCredential Network.testnet . Credential.KeyCredential <$> Credential.keyHashFromBytes (B.replicate 28 (fromIntegral index))++propImplicit :: Property+propImplicit = property $ do+ events <- forAll (Gen.list (Range.linear 0 20) genEvent)+ proposals <- forAll (Gen.list (Range.linear 0 6) smallAmount)+ withdrawals <- forAll (Gen.list (Range.linear 1 5) smallAmount)+ keyDeposit <- forAll smallAmount+ f <- evalEither fixture+ raw <- evalEither ProtocolFixture.parameters+ entries <- evalEither (withdrawalEntries withdrawals)+ let parameters = raw {Parameters.parameterKeyDeposit = keyDeposit}+ (paid, refunded) = eventTotals keyDeposit events+ expected = Building.ImplicitCoin (fromInteger (sum (map toInteger withdrawals))) (fromInteger (paid + sum (map toInteger proposals))) (fromInteger refunded)+ fields =+ (Fields.fields [] [])+ { Fields.fieldCertificates = Just (Certificates.fromList (map (certificate f) events)),+ Fields.fieldProposalProcedures = Just (Proposal.fromList [Proposal.Proposal amount (fixtureAccount f) Action.InfoAction (fixtureAnchor f) | amount <- proposals]),+ Fields.fieldWithdrawals = Just entries+ }+ -- Top-level empty collections are representable; the subtransaction+ -- grammar requires those optional fields to be absent when empty.+ localFields =+ fields+ { Fields.fieldCertificates = if null events then Nothing else Fields.fieldCertificates fields,+ Fields.fieldProposalProcedures = if null proposals then Nothing else Fields.fieldProposalProcedures fields+ }+ classify "legacy deposits/refunds" (LegacyRegistration `elem` events || LegacyDeregistration `elem` events)+ classify "governance proposal deposits" (not (null proposals))+ classify "retirement has no immediate refund" (Retirement `elem` events)+ forM_ [TaggedSet, UntaggedSet] $ \encoding -> do+ bodyBytes <- evalEither (Body.encodeCborWith encoding ((Body.body [] [] 0) {Body.bodyFields = fields}))+ encodedBody <- evalEither (Body.decodeCbor bodyBytes)+ let transaction = Tx.fromBody encodedBody+ before = Tx.encodeCbor transaction+ actual <- evalIO (Building.implicitCoin parameters transaction) >>= evalEither+ actual === expected+ localBytes <- evalEither (SubBody.encodeCborWith encoding (SubBody.fromFields localFields))+ localBody <- evalEither (SubBody.decodeCbor localBytes)+ local <- evalIO (Building.subTransactionImplicitCoin parameters (Sub.fromBody localBody)) >>= evalEither+ local === expected+ Tx.encodeCbor transaction === before++scenario :: Gen Scenario+scenario = Scenario <$> smallAmount <*> smallAmount <*> smallAmount <*> smallAmount <*> smallAmount <*> smallAmount <*> Gen.integral (Range.linear (-1000) 1000) <*> Gen.element [-100, 0, 100]++-- A generated perturbation changes both coin and one asset's outputs. Zero is+-- exactly balanced; the other choices are deliberate componentwise deficits or+-- surpluses. Burn shrinkage cannot make outputs negative because funding is ample.+scenarioFields :: Fixture -> Word8 -> Word64 -> Scenario -> Either Error (Fields.Fields, Utxo.Utxo, Map Asset.AssetId Integer)+scenarioFields f salt chargedFee value = do+ policy <- Policy.fromBytes (B.replicate 28 37)+ identifier <- Id.fromBytes (B.replicate 32 salt)+ let asset = Asset.Native policy Name.empty+ perturbation = scenarioPerturbation value+ inputCoin = 2000000000+ outputCoin = inputCoin + toInteger (scenarioWithdrawal value) + toInteger (scenarioRefund value) - toInteger (scenarioDeposit value) - toInteger chargedFee - toInteger (scenarioDonation value) - toInteger (scenarioDirectDeposit value) + perturbation+ tokenSupply = 10000+ tokenOutput = tokenSupply + scenarioMint value + perturbation+ inputReference = Input.input identifier 0+ funding <- Output.mkOutput (fixtureAddress f) (Value.fromList [(Asset.Ada, inputCoin), (asset, tokenSupply)]) Datum.NoDatum Nothing+ output <- Output.mkOutput (fixtureAddress f) (Value.fromList [(Asset.Ada, outputCoin), (asset, tokenOutput)]) Datum.NoDatum Nothing+ mint <- Fields.mkMint (Value.singleton asset (scenarioMint value))+ withdrawals <- Fields.mkEntries [(fixtureAccount f, scenarioWithdrawal value)]+ direct <- Fields.mkEntries [(fixtureAccount f, scenarioDirectDeposit value)]+ let fields =+ (Fields.fields [inputReference] [output])+ { Fields.fieldMint = if scenarioMint value == 0 then Nothing else Just mint,+ Fields.fieldWithdrawals = Just withdrawals,+ Fields.fieldDirectDeposits = Just direct,+ Fields.fieldDonation = Just (scenarioDonation value),+ Fields.fieldCertificates = Just (Certificates.fromList [Certificate.Registration (fixtureStake f) (scenarioDeposit value), Certificate.Unregistration (fixtureStake f) (scenarioRefund value)])+ }+ expected = Map.fromList [(Asset.Ada, negate perturbation), (asset, negate perturbation)]+ pure (fields, Utxo.utxo inputReference funding, normalize expected)++normalize :: Map Asset.AssetId Integer -> Map Asset.AssetId Integer+normalize = Map.filter (/= 0)++observed :: Value.Value -> Map Asset.AssetId Integer+observed = Map.fromList . Value.toList++propConservation :: Property+propConservation = property $ do+ outerCase <- forAll scenario+ localCase <- forAll scenario+ checkConservation outerCase localCase++-- The CI failure shrank to zero local mint and a top-level burn. Retain this+-- exact case independently of random seeds, then cover zero at either level.+zeroMintRegression :: Property+zeroMintRegression = withTests 1 . property $ do+ let zero = Scenario 0 0 0 0 0 0 0 (-100)+ checkConservation zero {scenarioMint = -1000} zero+ forM_ [-1, 0, 1] $ \amount -> do+ checkConservation zero {scenarioMint = amount} zero+ checkConservation zero zero {scenarioMint = amount}++checkConservation :: Scenario -> Scenario -> PropertyT IO ()+checkConservation outerCase localCase = do+ f <- evalEither fixture+ parameters <- evalEither ProtocolFixture.parameters+ (outerFields, outerInput, outerExpected) <- evalEither (scenarioFields f 17 (scenarioFee outerCase) outerCase)+ (localFields, localInput, localExpected) <- evalEither (scenarioFields f 18 0 localCase)+ when (scenarioMint localCase == 0) $ Fields.fieldMint localFields === Nothing+ extraIdentifier <- evalEither (Id.fromBytes (B.replicate 32 19))+ let extra = Utxo.utxo (Input.input extraIdentifier 0) (Utxo.output outerInput)+ expected = normalize (Map.unionWith (+) outerExpected localExpected)+ resolved = [localInput, extra, outerInput]+ classify "minting" (scenarioMint outerCase > 0 || scenarioMint localCase > 0)+ classify "burning" (scenarioMint outerCase < 0 || scenarioMint localCase < 0)+ classify "complete balance" (Map.null expected)+ classify "opposing intent imbalances cancel" (scenarioPerturbation outerCase /= 0 && scenarioPerturbation outerCase == negate (scenarioPerturbation localCase))+ classify "coin surplus" (Map.findWithDefault 0 Asset.Ada expected > 0)+ classify "coin deficit" (Map.findWithDefault 0 Asset.Ada expected < 0)+ forM_ [TaggedSet, UntaggedSet] $ \encoding -> do+ localBytes <- evalEither (SubBody.encodeCborWith encoding (SubBody.fromFields (localFields {Fields.fieldReferenceInputs = Just [Utxo.input extra]})))+ localBody <- evalEither (SubBody.decodeCbor localBytes)+ let local = Sub.fromBody localBody+ outer = (Body.body [] [] (scenarioFee outerCase)) {Body.bodyFields = outerFields {Fields.fieldReferenceInputs = Just [Utxo.input extra]}, Body.bodyCollateral = Just [Utxo.input extra], Body.bodySubTransactions = Just [local]}+ bytes <- evalEither (Body.encodeCborWith encoding outer)+ body <- evalEither (Body.decodeCbor bytes)+ let transaction = Tx.fromBody body+ before = Tx.encodeCbor transaction+ top <- evalIO (Building.imbalance parameters resolved transaction) >>= evalEither+ observed top === outerExpected+ sub <- evalIO (Building.subTransactionImbalance parameters resolved local) >>= evalEither+ observed sub === localExpected+ batch <- evalIO (Building.batchImbalance parameters resolved transaction) >>= evalEither+ observed batch === expected+ balanced <- evalIO (Building.isBalanced parameters resolved transaction) >>= evalEither+ balanced === Map.null expected+ Tx.encodeCbor transaction === before++poolParameters :: Fixture -> Word8 -> Either Error Pool.PoolParameters+poolParameters f identifier = do+ operator <- Credential.keyHashFromBytes (B.replicate 28 identifier)+ vrf <- Pool.vrfKeyHashFromBytes (B.replicate 32 identifier)+ margin <- Unit.mkUnitInterval 0 1+ pure (Pool.PoolParameters operator vrf Nothing 0 0 margin (fixtureAccount f) Set.empty [] Nothing)++propPoolDeposits :: Property+propPoolDeposits = property $ do+ outerPools <- forAll (Gen.list (Range.linear 1 8) (Gen.integral (Range.linear 1 4)))+ localPools <- forAll (Gen.list (Range.linear 1 8) (Gen.integral (Range.linear 1 4)))+ deposit <- forAll smallAmount+ f <- evalEither fixture+ raw <- evalEither ProtocolFixture.parameters+ outerParameters <- evalEither (traverse (poolParameters f) outerPools)+ localParameters <- evalEither (traverse (poolParameters f) localPools)+ let parameters = raw {Parameters.parameterPoolDeposit = deposit}+ fields values = (Fields.fields [] []) {Fields.fieldCertificates = Just (Certificates.fromList (map Certificate.PoolRegistration values))}+ outerCount = toInteger (Set.size (Set.fromList outerPools))+ localCount = toInteger (Set.size (Set.fromList localPools))+ totalCount = toInteger (Set.size (Set.fromList (outerPools <> localPools)))+ paid count = count * toInteger deposit+ classify "within-body repeat" (length outerPools > Set.size (Set.fromList outerPools))+ classify "cross-body repeat" (outerCount + localCount > totalCount)+ localBody <- evalEither (SubBody.fromBody (SubBody.fromFields (fields localParameters)))+ let local = Sub.fromBody localBody+ encoded <- evalEither (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = fields outerParameters, Body.bodySubTransactions = Just [local]}))+ let transaction = Tx.fromBody encoded+ top <- evalIO (Building.implicitCoin parameters transaction) >>= evalEither+ top === Building.ImplicitCoin 0 (fromInteger (paid outerCount)) 0+ sub <- evalIO (Building.subTransactionImplicitCoin parameters local) >>= evalEither+ sub === Building.ImplicitCoin 0 (fromInteger (paid localCount)) 0+ batch <- evalIO (Building.batchImbalance parameters [] transaction) >>= evalEither+ observed batch === normalize (Map.singleton Asset.Ada (negate (paid totalCount)))
@@ -0,0 +1,540 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Offline rebalancing of imported transaction snapshots through public values.+module TransactionBalancing (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.CoinSelection as Selection+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Ed25519.PublicKey as Key+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Crypto.Ed25519.SigningKey as SigningKey+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Metadata as Metadata+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.CostModels as Models+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Balancing as Balancing+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Signing as Signing+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, readMVar, threadDelay)+import Control.Exception (AsyncException (ThreadKilled), SomeException, displayException, fromException, throw, try)+import Control.Monad (forM_, replicateM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Int (Int64)+import Data.List (elemIndex, isInfixOf, sort)+import qualified Data.Map.Strict as Map+import Data.Word (Word8)+import qualified DeferredRedeemer as Fixture+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Contextual transaction balancing"+ [ testCase "payment snapshots retain original outputs and strip obsolete outer signatures" payment,+ testCase "change destination does not overwrite the imported body network" network,+ testCase "selected inputs remap immediate redeemers while retaining nonminimal argument CBOR" immediate,+ testCase "deferred spending payloads see final indices and selected snapshots" deferred,+ testCase "missing and stale script-data hashes use final redeemers and only required V2 views" scriptCommitments,+ testCase "datum-only script-data commitments use empty language views" datumCommitments,+ testCase "numeric balancing bounds fail before selector callbacks" numericBounds,+ testCase "callback errors and lazy exceptions retain identity and release contexts" failures,+ testCase "cancellation propagates ThreadKilled and joins deferred balancing contexts" cancellation,+ testCase "max-int64 token transfers bound spending and production independently" maximumTokenTransfer,+ testCase "missing and conflicting resolved snapshots fail before selection" invalidSnapshots,+ testCase "reference and collateral snapshots are mandatory" contextualInputs,+ testCase "resolved and collateral snapshots do not authorize extra spending" fundingAuthority,+ testCase "selector candidates exclude outer spending and reference inputs" selectorCandidates,+ testCase "malformed and unmatched redeemer identifiers fail before callbacks" invalidRedeemers,+ testCase "nested signed content and reference snapshots survive outer balancing" nested,+ testCase "indefinite nested envelope retains signed body and witnesses without requiring full-frame identity" nestedIndefinite+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++semantic :: Tx.Transaction -> Body.Body+semantic = Body.toBody . Tx.body++fields :: Tx.Transaction -> Fields.Fields+fields = Body.bodyFields . semantic++redeemers :: Tx.Transaction -> [Redeemer.Redeemer]+redeemers = Witnesses.redeemers . Witnesses.toWitnesses . Tx.witnesses++funding :: Builder.Config -> Word8 -> Integer -> IO Utxo.Utxo+funding configured seed amount = do+ identifier <- must (Id.fromBytes (B.replicate 32 seed))+ output <- must (Output.mkOutput (Builder.changeAddress configured) (Value.lovelace amount) Datum.NoDatum Nothing)+ pure (Utxo.utxo (Input.input identifier 0) output)++spendAll :: Selection.Selector+spendAll = Selection.Selector $ \request -> pure $ do+ let selected = Map.elems (Map.fromList [(Utxo.input input, input) | input <- Selection.preselected request <> Selection.available request])+ total = foldMap (Output.value . Utxo.output) selected+ excess = Value.difference total (Selection.target request)+ change <- if Value.isZero excess then pure [] else (: []) <$> Output.mkOutput (Selection.changeAddress request) excess Datum.NoDatum Nothing+ pure (Selection.Selection selected [] change)++payment :: IO ()+payment = do+ (configured, output, wallet) <- Fixture.fixture+ original <- Builder.build configured (Plan.payTo output) >>= must+ key <- must (Key.fromBytes (B.replicate 32 7))+ signature <- must (Signature.fromBytes (B.replicate 64 9))+ bootstrap <- must (Witness.mkBootstrapWitness key signature (B.replicate 32 10) "\160")+ signed <- must (Witnesses.mkWitnesses [Witness.verificationWitness key signature] [bootstrap] [] [] [])+ let imported = Tx.setWitnesses (Witnesses.fromWitnesses signed) original+ bytes = Tx.encodeCbor imported+ originalOutputs = Fields.fieldOutputs (fields imported)+ extra <- funding configured 1 3000000+ balanced <- Balancing.balance configured {Builder.minimumFee = 400000, Builder.availableUtxos = [extra], Builder.selector = Just spendAll} [wallet] imported >>= must+ Tx.encodeCbor imported @?= bytes+ take (length originalOutputs) (Fields.fieldOutputs (fields balanced)) @?= originalOutputs+ -- Existing change is an ordinary imported output, so additional funding is+ -- needed to raise the fee; that output must not be silently spent or reduced.+ Body.fee (semantic balanced) @?= 400000+ Fields.fieldInputs (fields balanced) @?= sort [Utxo.input extra, Utxo.input wallet]+ foldMap Output.value (drop (length originalOutputs) (Fields.fieldOutputs (fields balanced))) @?= Value.lovelace 2800000+ Witnesses.verificationWitnesses (Witnesses.toWitnesses (Tx.witnesses balanced)) @?= []+ Witnesses.bootstrapWitnesses (Witnesses.toWitnesses (Tx.witnesses balanced)) @?= []+ Tx.decodeCbor (Tx.encodeCbor balanced) @?= Right balanced++network :: IO ()+network = do+ (configured, output, wallet) <- Fixture.fixture+ key <- must (Credential.keyHashFromBytes (B.replicate 28 3))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.mainnet (Credential.KeyCredential key))+ body = (Body.body [Utxo.input wallet] [output] 0) {Body.bodyFields = (Fields.fields [Utxo.input wallet] [output]) {Fields.fieldNetworkId = Just Fields.Testnet}}+ imported <- Tx.fromBody <$> must (Body.fromBody body)+ balanced <- Balancing.balance configured {Builder.changeAddress = destination, Builder.availableUtxos = []} [wallet] imported >>= must+ Fields.fieldNetworkId (fields balanced) @?= Just Fields.Testnet+ take 1 (Fields.fieldOutputs (fields balanced)) @?= [output]+ map Output.address (drop 1 (Fields.fieldOutputs (fields balanced))) @?= [destination]++scriptDraft :: IO (Builder.Config, Utxo.Utxo, Utxo.Utxo, Tx.Transaction)+scriptDraft = do+ (configured, output, locked, script) <- Fixture.scriptFixture+ let argument = Data.fromData (Data.Integer 77)+ original <- Builder.build configured (Plan.spendWith locked (Just argument) Nothing <> Plan.attachScript script <> Plan.payTo output) >>= must+ extra <- funding configured 1 3000000+ pure (configured {Builder.minimumFee = 400000, Builder.availableUtxos = [extra], Builder.selector = Just spendAll}, locked, extra, original)++immediate :: IO ()+immediate = do+ (configured, locked, extra, canonical) <- scriptDraft+ argument <- must (Data.decodeCbor (B.pack [0x18, 0x01]))+ let oldWitnesses = Witnesses.toWitnesses (Tx.witnesses canonical)+ importedWitnesses <-+ must+ ( Witnesses.mkWitnesses+ (Witnesses.verificationWitnesses oldWitnesses)+ (Witnesses.bootstrapWitnesses oldWitnesses)+ (Witnesses.scripts oldWitnesses)+ (Witnesses.datums oldWitnesses)+ [redeemer {Redeemer.argument = argument} | redeemer <- Witnesses.redeemers oldWitnesses]+ )+ let original = Tx.setWitnesses (Witnesses.fromWitnesses importedWitnesses) canonical+ calls <- newIORef (0 :: Int)+ selections <- newIORef (0 :: Int)+ let selected = Selection.Selector $ \request -> do+ modifyIORef' selections (+ 1)+ Selection.select spendAll request+ checked = Evaluation.Evaluator $ \_ draft resolvedInputs -> do+ modifyIORef' calls (+ 1)+ map Redeemer.index (redeemers draft) @?= [1]+ map (Data.toCbor . Redeemer.argument) (redeemers draft) @?= [B.pack [0x18, 0x01]]+ assertBool "evaluator receives newly selected snapshot" (extra `elem` resolvedInputs)+ pure (Evaluation.mkBudgets [(Evaluation.RedeemerId Redeemer.Spending 1, ExUnits 100 200)])+ bytes = Tx.encodeCbor original+ balanced <- Balancing.balance configured {Builder.evaluator = Just checked, Builder.selector = Just selected} (locked : Builder.collateralUtxos configured) original >>= must+ Fields.fieldInputs (fields balanced) @?= sort [Utxo.input extra, Utxo.input locked]+ map Redeemer.index (redeemers balanced) @?= [1]+ map (Data.toCbor . Redeemer.argument) (redeemers balanced) @?= [B.pack [0x18, 0x01]]+ map Redeemer.executionUnits (redeemers balanced) @?= [ExUnits 100 200]+ readIORef calls >>= assertBool "injected evaluator was called" . (> 0)+ readIORef selections >>= assertBool "injected selector was called" . (> 0)+ Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses balanced)) @?= Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses original))+ Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses balanced)) @?= Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses original))+ required <- v2Models configured+ assertCommitment required balanced+ Tx.encodeCbor original @?= bytes++deferred :: IO ()+deferred = do+ baseline <- Runtime.liveContexts+ (configured, locked, _, original) <- scriptDraft+ let callback draft selected = do+ let canonical = Fields.fieldInputs (fields draft)+ if map Utxo.input selected /= sort canonical+ then Left (InvalidTransactionPlan "noncanonical selected rebalancing snapshots")+ else case elemIndex (Utxo.input locked) canonical of+ Nothing -> Left (InvalidTransactionPlan "original script input disappeared")+ Just index -> Right (Data.fromData (Data.Constr 0 [Data.Integer (toInteger index)]))+ overrides = Map.singleton (Evaluation.RedeemerId Redeemer.Spending 0) callback+ balanced <- Balancing.balanceWithRedeemers configured (locked : Builder.collateralUtxos configured) overrides original >>= must+ map Redeemer.index (redeemers balanced) @?= [1]+ map Redeemer.argument (redeemers balanced) @?= [Data.fromData (Data.Constr 0 [Data.Integer 1])]+ required <- v2Models configured+ assertCommitment required balanced+ Runtime.liveContexts >>= (@?= baseline)++v2Models :: Builder.Config -> IO Models.CostModels+v2Models configured = case Parameters.parameterCostModels (Builder.parameters configured) >>= Models.lookup 1 of+ Just model -> pure (Models.fromList [model])+ Nothing -> assertFailure "V2 fixture model missing" >> fail "fixture"++assertCommitment :: Models.CostModels -> Tx.Transaction -> IO ()+assertCommitment models transaction = do+ expected <- Building.scriptDataHash models (Tx.witnesses transaction) >>= must+ Fields.fieldScriptDataHash (fields transaction) @?= expected++unusedLanguages :: IO ([Script.Script], [Models.CostModel])+unusedLanguages = do+ v1 <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V1 (B.pack [7, 8, 9]))+ v3 <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V3 (B.pack [10, 11, 12]))+ v1Model <- must (Models.mkCostModel 0 (replicate 166 0))+ v3Model <- must (Models.mkCostModel 2 (replicate 297 0))+ pure ([v1, v3], [v1Model, v3Model])++scriptCommitments :: IO ()+scriptCommitments = do+ (configured, locked, _, original) <- scriptDraft+ required <- v2Models configured+ (unusedScripts, unusedModels) <- unusedLanguages+ referenceId <- must (Id.fromBytes (B.replicate 32 44))+ referenceScript <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V3 (B.pack [15, 16, 17]))+ referenceOutput <- must (Output.mkOutput (Builder.changeAddress configured) (Value.lovelace 3000000) Datum.NoDatum (Just referenceScript))+ stale <- must (Datum.hashFromBytes (B.replicate 32 255))+ let reference = Utxo.utxo (Input.input referenceId 0) referenceOutput+ models = Models.fromList (Models.toList required <> unusedModels)+ context = configured {Builder.parameters = (Builder.parameters configured) {Parameters.parameterCostModels = Just models}}+ oldWitnesses = Witnesses.toWitnesses (Tx.witnesses original)+ changed = [redeemer {Redeemer.argument = Data.fromData (Data.Integer 999), Redeemer.executionUnits = ExUnits 7 11} | redeemer <- Witnesses.redeemers oldWitnesses]+ witnessSet <- must (Witnesses.mkWitnesses [] [] (Witnesses.scripts oldWitnesses <> unusedScripts) (Witnesses.datums oldWitnesses) changed)+ forM_ [Nothing, Just stale] $ \commitment -> do+ let replacement =+ (semantic original)+ { Body.bodyFields =+ (fields original)+ { Fields.fieldReferenceInputs = Just [Utxo.input reference],+ Fields.fieldScriptDataHash = commitment+ }+ }+ encoded <- must (Body.fromBody replacement)+ let imported = Tx.setWitnesses (Witnesses.fromWitnesses witnessSet) (Tx.setBody encoded original)+ bytes = Tx.encodeCbor imported+ balanced <- Balancing.balance context (locked : reference : Builder.collateralUtxos context) imported >>= must+ map Redeemer.index (redeemers balanced) @?= [1]+ map Redeemer.argument (redeemers balanced) @?= [Data.fromData (Data.Integer 999)]+ map Redeemer.executionUnits (redeemers balanced) @?= [ExUnits 100 200]+ assertCommitment required balanced+ allViews <- Building.scriptDataHash models (Tx.witnesses balanced) >>= must+ assertBool "unused witness/reference languages entered the commitment" (Fields.fieldScriptDataHash (fields balanced) /= allViews)+ Tx.encodeCbor imported @?= bytes++datumCommitments :: IO ()+datumCommitments = do+ (configured, output, wallet) <- Fixture.fixture+ datum <- must (Data.decodeCbor (B.pack [0x18, 0x01]))+ (unusedScripts, unusedModels) <- unusedLanguages+ witnesses <- must (Witnesses.mkWitnesses [] [] unusedScripts [datum] [])+ encoded <- must (Body.fromBody (Body.body [Utxo.input wallet] [output] 0))+ let imported = Tx.assemble encoded (Witnesses.fromWitnesses witnesses) Nothing+ models = Models.fromList unusedModels+ context = configured {Builder.availableUtxos = [], Builder.parameters = (Builder.parameters configured) {Parameters.parameterCostModels = Just models}}+ balanced <- Balancing.balance context [wallet] imported >>= must+ assertCommitment Models.empty balanced+ Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses balanced)) @?= [datum]+ allViews <- Building.scriptDataHash models (Tx.witnesses balanced) >>= must+ -- Datum-only commitments have empty views even when models were supplied.+ Fields.fieldScriptDataHash (fields balanced) @?= allViews++-- A transfer consumes and produces the same token units. These opposing sides+-- each fit Int64; adding their absolute magnitudes is not a native accumulator.+maximumTokenTransfer :: IO ()+maximumTokenTransfer = do+ (configured, _, wallet) <- Fixture.fixture+ policy <- must (Policy.fromBytes (B.replicate 28 46))+ referenceId <- must (Id.fromBytes (B.replicate 32 47))+ let asset = Asset.Native policy AssetName.empty+ quantity = toInteger (maxBound :: Int64)+ address = Builder.changeAddress configured+ fundingOutput <- must (Output.mkOutput address (Value.fromList [(Asset.Ada, 10000000), (asset, quantity)]) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput address (Value.fromList [(Asset.Ada, 2000000), (asset, quantity)]) Datum.NoDatum Nothing)+ referenceOutput <- must (Output.mkOutput address (Value.fromList [(Asset.Ada, 3000000), (asset, quantity)]) Datum.NoDatum Nothing)+ let fundingInput = Utxo.utxo (Utxo.input wallet) fundingOutput+ reference = Utxo.utxo (Input.input referenceId 0) referenceOutput+ -- Neither an extra resolution snapshot nor a reference input authorizes+ -- spending its tokens, so neither contributes to consumed-value bounds.+ cases = [(Nothing, [fundingInput]), (Nothing, [fundingInput, reference]), (Just [Utxo.input reference], [fundingInput, reference])]+ context = configured {Builder.availableUtxos = [], Builder.collateralUtxos = [], Builder.minimumFee = 200000, Builder.selector = Nothing}+ forM_ cases $ \(references, resolved) -> do+ let common = (Fields.fields [Utxo.input fundingInput] [output]) {Fields.fieldReferenceInputs = references}+ imported <- Tx.fromBody <$> must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = common}))+ let before = Tx.encodeCbor imported+ balanced <- Balancing.balance context resolved imported >>= must+ Fields.fieldInputs (fields balanced) @?= [Utxo.input fundingInput]+ Fields.fieldReferenceInputs (fields balanced) @?= references+ take 1 (Fields.fieldOutputs (fields balanced)) @?= [output]+ sum [Value.quantity asset (Output.value item) | item <- Fields.fieldOutputs (fields balanced)] @?= quantity+ Body.fee (semantic balanced) @?= 200000+ Building.isBalanced (Builder.parameters context) resolved balanced >>= (@?= Right True)+ Tx.encodeCbor imported @?= before++numericBounds :: IO ()+numericBounds = do+ (configured, output, wallet) <- Fixture.fixture+ original <- Tx.fromBody <$> must (Body.fromBody (Body.body [Utxo.input wallet] [output] 0))+ huge <- funding configured 45 (2 ^ (63 :: Int) - 1)+ calls <- newIORef (0 :: Int)+ let selected = Selection.Selector $ \_ -> modifyIORef' calls (+ 1) >> pure (Left (InvalidTransactionPlan "numeric preflight must precede selection"))+ context = configured {Builder.availableUtxos = [], Builder.selector = Just selected}+ cases =+ [ (context {Builder.minimumFee = maxBound}, [wallet]),+ (context {Builder.extraSigners = maxBound}, [wallet]),+ (context {Builder.parameters = (Builder.parameters context) {Parameters.parameterAdaPerUtxoByte = Just maxBound}}, [wallet]),+ (context {Builder.availableUtxos = [huge]}, [wallet])+ ]+ forM_ cases $ \(options, resolved) ->+ Balancing.balance options resolved original >>= assertBool "numeric native-bound overflow accepted" . isLeft+ readIORef calls >>= (@?= 0)++failures :: IO ()+failures = do+ baseline <- Runtime.liveContexts+ (configured, locked, _, original) <- scriptDraft+ let expected = InvalidTransactionPlan "rebalancing callback refused draft"+ run callback = Balancing.balanceWithRedeemers configured (locked : Builder.collateralUtxos configured) (Map.singleton (Evaluation.RedeemerId Redeemer.Spending 0) callback) original+ lazyFailure _ _ = Right (Data.fromData (Data.List [Data.Integer (throw (userError "lazy rebalancing payload"))]))+ replicateM_ 3 (run (\_ _ -> Left expected) >>= (@?= Left expected))+ outcome <- try (run lazyFailure)+ case outcome of+ Left (failure :: SomeException) -> assertBool "lazy callback exception retained" ("lazy rebalancing payload" `isInfixOf` displayException failure)+ Right result -> assertFailure ("lazy callback returned normally: " <> show result)+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ baseline <- Runtime.liveContexts+ (configured, locked, _, original) <- scriptDraft+ finished <- newEmptyMVar+ cancelled <- newEmptyMVar+ let never _ _ = Right (Data.fromData (Data.Integer (sum [1 ..])))+ overrides = Map.singleton (Evaluation.RedeemerId Redeemer.Spending 0) never+ worker <- forkFinally (Balancing.balanceWithRedeemers configured (locked : Builder.collateralUtxos configured) overrides original) (putMVar finished)+ -- Match the existing deferred-construction cancellation fixture: the payload+ -- never materializes, and cancellation must unwind its joined native scope.+ threadDelay 200000+ _ <- forkFinally (killThread worker) (putMVar cancelled)+ -- Use the builder fixtures' five-second join bound: full Valgrind runs also+ -- charge callback scheduling and native finalization to this deadline.+ outcome <- timeout 5000000 ((,) <$> readMVar finished <*> readMVar cancelled)+ case outcome of+ Just (Left failure, Right ()) -> fromException failure @?= Just ThreadKilled+ Just other -> assertFailure ("cancellation returned normally or lost its exception: " <> show other)+ Nothing -> assertFailure "deferred balancing cancellation did not join within its deadline"+ Runtime.liveContexts >>= (@?= baseline)++invalidSnapshots :: IO ()+invalidSnapshots = do+ (configured, output, wallet) <- Fixture.fixture+ original <- Tx.fromBody <$> must (Body.fromBody (Body.body [Utxo.input wallet] [output] 0))+ conflictingOutput <- must (Output.mkOutput (Builder.changeAddress configured) (Value.lovelace 11000000) Datum.NoDatum Nothing)+ calls <- newIORef (0 :: Int)+ let selected = Selection.Selector $ \_ -> modifyIORef' calls (+ 1) >> pure (Left (InvalidTransactionPlan "selection must not run"))+ checked = configured {Builder.availableUtxos = [], Builder.selector = Just selected}+ conflicting = Utxo.utxo (Utxo.input wallet) conflictingOutput+ forM_ [[], [wallet, conflicting]] $ \resolved ->+ Balancing.balance checked resolved original >>= assertBool "invalid snapshot accepted" . isLeft+ Balancing.balance checked {Builder.availableUtxos = [conflicting]} [wallet] original >>= assertBool "conflicting wallet and resolved snapshots accepted" . isLeft+ readIORef calls >>= (@?= 0)++contextualInputs :: IO ()+contextualInputs = do+ (configured, output, wallet) <- Fixture.fixture+ reference <- funding configured 40 3000000+ collateral <- funding configured 41 5000000+ let body =+ (Body.body [Utxo.input wallet] [output] 0)+ { Body.bodyFields = (Fields.fields [Utxo.input wallet] [output]) {Fields.fieldReferenceInputs = Just [Utxo.input reference]},+ Body.bodyCollateral = Just [Utxo.input collateral]+ }+ imported <- Tx.fromBody <$> must (Body.fromBody body)+ forM_ [[wallet], [wallet, reference], [wallet, collateral]] $ \resolved ->+ Balancing.balance configured {Builder.availableUtxos = []} resolved imported >>= assertBool "missing contextual input accepted" . isLeft+ balanced <- Balancing.balance configured {Builder.availableUtxos = []} [wallet, reference, collateral] imported >>= must+ Fields.fieldInputs (fields balanced) @?= [Utxo.input wallet]+ Fields.fieldReferenceInputs (fields balanced) @?= Just [Utxo.input reference]+ take 1 (Fields.fieldOutputs (fields balanced)) @?= [output]++fundingAuthority :: IO ()+fundingAuthority = do+ (configured, _, wallet) <- Fixture.fixture+ eligible <- funding configured 1 1000000+ reserve <- funding configured 2 10000000+ paymentOutput <- must (Output.mkOutput (Builder.changeAddress configured) (Value.lovelace 12000000) Datum.NoDatum Nothing)+ original <- Tx.fromBody <$> must (Body.fromBody (Body.body [Utxo.input wallet] [paymentOutput] 0))+ let bytes = Tx.encodeCbor original+ -- The explicit wallet plus mandatory input holds only 11 ADA. A snapshot+ -- supplied for inspection/resolution or collateral must not fund 12 ADA.+ options = configured {Builder.availableUtxos = [eligible]}+ cases =+ [ (options, [wallet, reserve]),+ (options {Builder.collateralUtxos = [reserve]}, [wallet]),+ (options {Builder.collateralUtxos = [reserve]}, [wallet, reserve])+ ]+ forM_ cases $ \(context, resolved) -> do+ result <- Balancing.balance context resolved original+ assertBool "resolution or collateral silently expanded wallet authority" (isLeft result)+ Tx.encodeCbor original @?= bytes++selectorCandidates :: IO ()+selectorCandidates = do+ (configured, _, wallet) <- Fixture.fixture+ eligible <- funding configured 1 5000000+ reference <- funding configured 2 10000000+ collateral <- funding configured 3 5000000+ paymentOutput <- must (Output.mkOutput (Builder.changeAddress configured) (Value.lovelace 12000000) Datum.NoDatum Nothing)+ let originalFields = (Fields.fields [Utxo.input wallet] [paymentOutput]) {Fields.fieldReferenceInputs = Just [Utxo.input reference]}+ body = (Body.body [Utxo.input wallet] [paymentOutput] 0) {Body.bodyFields = originalFields}+ original <- Tx.fromBody <$> must (Body.fromBody body)+ calls <- newIORef (0 :: Int)+ let checked = Selection.Selector $ \request -> do+ modifyIORef' calls (+ 1)+ let candidates = map Utxo.input (Selection.available request)+ required = map Utxo.input (Selection.preselected request)+ assertBool "outer spending input was exposed as an additional candidate" (Utxo.input wallet `notElem` candidates)+ assertBool "outer reference input was exposed as an additional candidate" (Utxo.input reference `notElem` candidates)+ assertBool "collateral-only snapshot was exposed as an additional candidate" (Utxo.input collateral `notElem` candidates)+ assertBool "selector received an unauthorized candidate" (all (== Utxo.input eligible) candidates)+ assertBool "mandatory outer input was not preselected" (Utxo.input wallet `elem` required)+ Selection.select spendAll request+ context =+ configured+ { Builder.availableUtxos = [wallet, reference, eligible],+ Builder.collateralUtxos = [collateral],+ Builder.selector = Just checked+ }+ balanced <- Balancing.balance context [wallet, reference] original >>= must+ readIORef calls >>= assertBool "selector was not invoked" . (> 0)+ Fields.fieldInputs (fields balanced) @?= sort [Utxo.input wallet, Utxo.input eligible]+ Fields.fieldReferenceInputs (fields balanced) @?= Just [Utxo.input reference]++invalidRedeemers :: IO ()+invalidRedeemers = do+ (configured, output, wallet) <- Fixture.fixture+ imported <- Tx.fromBody <$> must (Body.fromBody (Body.body [Utxo.input wallet] [output] 0))+ let argument = Data.fromData (Data.Integer 0)+ forM_ [minBound .. maxBound] $ \purpose -> do+ let index = if purpose == Redeemer.Spending then maxBound else 0+ witnesses <- must (Witnesses.mkWitnesses [] [] [] [] [Redeemer.Redeemer purpose index argument (ExUnits 0 0)])+ let malformed = Tx.setWitnesses (Witnesses.fromWitnesses witnesses) imported+ Balancing.balance configured {Builder.availableUtxos = []} [wallet] malformed >>= assertBool "out-of-range redeemer accepted" . isLeft+ let never _ _ = throw (userError "unmatched rebalancing callback ran")+ Balancing.balanceWithRedeemers configured [wallet] (Map.singleton (Evaluation.RedeemerId Redeemer.Spending 99) never) imported >>= assertBool "unmatched callback identifier accepted" . isLeft++nested :: IO ()+nested = nestedWithEnvelope False++nestedIndefinite :: IO ()+nestedIndefinite = nestedWithEnvelope True++nestedWithEnvelope :: Bool -> IO ()+nestedWithEnvelope indefinite = do+ (configured, output, wallet) <- Fixture.fixture+ nestedInput <- funding configured 40 5000000+ reference <- funding configured 41 3000000+ message <- must (Metadata.mkText "signed nested content")+ metadata <- must (Metadata.decodeCbor (Metadata.encodeCbor (Metadata.singleton 674 message)))+ let auxiliary = Auxiliary.fromAuxiliaryData (Auxiliary.auxiliaryData (Just metadata) Nothing [])+ auxiliaryHash <- Auxiliary.hash auxiliary >>= must+ commitment <- must (Datum.hashFromBytes (Auxiliary.hashBytes auxiliaryHash))+ let subFields =+ (Fields.fields [Utxo.input nestedInput] [output])+ { Fields.fieldReferenceInputs = Just [Utxo.input reference],+ Fields.fieldAuxiliaryDataHash = Just commitment+ }+ encodedBody <- must (SubBody.fromBody (SubBody.fromFields subFields))+ let unsigned = Sub.assemble encodedBody (Witnesses.fromWitnesses Witnesses.empty) (Just auxiliary)+ signed <- SigningKey.withNormalKey (B.replicate 32 11) (`Signing.signSubTransaction` unsigned) >>= must+ let canonicalFrame = Sub.encodeCbor signed+ B.take 1 canonicalFrame @?= B.singleton 0x83+ intent <-+ if indefinite+ then must (Sub.decodeCbor (B.singleton 0x9f <> B.drop 1 canonicalFrame <> B.singleton 0xff))+ else pure signed+ let body = (Body.body [Utxo.input wallet] [output] 0) {Body.bodySubTransactions = Just [intent]}+ dijkstra = configured {Builder.availableUtxos = [], Builder.parameters = (Builder.parameters configured) {Parameters.parameterProtocolVersion = Version.ProtocolVersion 12 0}}+ originalEnvelope = Sub.encodeCbor intent+ bodyBytes = SubBody.toCbor (Sub.body intent)+ witnessBytes = Witnesses.toCbor (Sub.witnesses intent)+ auxiliaryBytes = Auxiliary.toCbor <$> Sub.auxiliaryData intent+ originalId <- Sub.transactionId intent >>= must+ imported <- Tx.fromBody <$> must (Body.fromBody body)+ Balancing.balance dijkstra [wallet, nestedInput] imported >>= assertBool "missing nested reference accepted" . isLeft+ balanced <- Balancing.balance dijkstra [wallet, nestedInput, reference] imported >>= must+ case Body.bodySubTransactions (semantic balanced) of+ Just [actual] -> do+ -- Native code may rewrite the containing three-field envelope. Exact signed+ -- body, witnesses and auxiliary data define the retained nested content.+ SubBody.toCbor (Sub.body actual) @?= bodyBytes+ Witnesses.toCbor (Sub.witnesses actual) @?= witnessBytes+ (Auxiliary.toCbor <$> Sub.auxiliaryData actual) @?= auxiliaryBytes+ Sub.transactionId actual >>= (@?= Right originalId)+ forM_ (Witnesses.verificationWitnesses (Witnesses.toWitnesses (Sub.witnesses actual))) $ \witness ->+ Key.verify (Witness.publicKey witness) (Id.toBytes originalId) (Witness.signature witness) >>= (@?= Right True)+ other -> assertFailure ("nested intent disappeared: " <> show other)+ Sub.encodeCbor intent @?= originalEnvelope
@@ -0,0 +1,342 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Body fixtures originate in cardano-c eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1,+-- lib/tests/transaction_body/*.cpp, Apache-2.0. Source filenames and constant+-- names are retained below. Tests rebuild fresh public semantic values before+-- separate native getter/constructor reconstruction, never a source body cache.+module TransactionBody (tests, bodyVectors, subBodyVectors, bytes, agree, nativeResult) where++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Int (Int64)+import qualified Data.Text as Text+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Ptr (Ptr, castPtr)+import Hedgehog (Property, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++tests :: TestTree+tests =+ testGroup+ "Transaction bodies"+ [ testCase "pinned complete ordinary and Dijkstra body schemas reconstruct" checkBodies,+ testCase "pinned maximal Dijkstra subbody reconstructs all fields" checkSubBodies,+ testCase "legacy, inline datum, reference script and bounded pointer outputs reconstruct" checkOutputs,+ testCase "uint64 input references and exact bytes" checkInputs,+ testCase "exact nonminimal body hash and controlled fee edit" checkIdentity,+ testCase "datum identity inside nested guard and inline output slices" checkNestedIdentity,+ testCase "output quantity, hash, mint and association boundaries" checkBoundaries,+ testCase "malformed and unknown body fields fail without dropping data" checkMalformed,+ testCase "resolved UTxO snapshot uses typed input and output" checkUtxo,+ testCase "asset names, mixed-network associations and input sets use native ordering" checkOrdering,+ testProperty "fee edits are independent and fresh native bodies agree" propFee,+ testProperty "typed output quantities reconstruct across native int64 range" propOutput+ ]++must :: (Show e) => Either e a -> IO a+must value = case value of+ Left err -> assertFailure (show err) >> fail "Fixture validation failed"+ Right result -> pure result++bytes :: String -> IO ByteString+bytes text = maybe (assertFailure "Invalid fixture hex" >> fail "Invalid fixture hex") pure (Hex.decodeHex (Text.pack text))++agree :: CUInt -> ByteString -> IO ()+agree kind payload = nativeResult kind payload >>= (@?= 0)++-- | Native reconstruction status; 9001 means successful reconstruction with a+-- different encoding, such as native input sets emitting tag 258.+nativeResult :: CUInt -> ByteString -> IO CInt+nativeResult kind payload = B.useAsCStringLen payload $ \(ptr, size) ->+ cAgreement kind (castPtr ptr) (fromIntegral size)++checkBodies :: IO ()+checkBodies = forM_ bodyVectors $ \(name, hex) -> do+ payload <- bytes hex+ encoded <- must (Body.decodeCbor payload)+ Body.toCbor encoded @?= payload+ let semantic = Body.toBody encoded+ -- Empty historical guards remain exact imports but fresh assembly rejects+ -- them instead of silently deleting field presence.+ if "EMPTY" `Text.isInfixOf` Text.pack name+ then assertBool name (isLeft (Body.encodeCbor semantic))+ else do+ fresh <- must (Body.encodeCbor semantic)+ decoded <- must (Body.decodeCbor fresh)+ assertBool name (Body.toBody decoded == semantic)+ agree 0 fresh++checkSubBodies :: IO ()+checkSubBodies = forM_ subBodyVectors $ \(name, hex) -> do+ payload <- bytes hex+ encoded <- must (SubBody.decodeCbor payload)+ SubBody.toCbor encoded @?= payload+ case name of+ "sub_transaction_body.cpp/MINIMAL_CBOR" -> do+ digest <- SubBody.hash encoded >>= must+ Id.toHex digest @?= "da4603f4488d798af667794ab542f130a4bd1c20c7ed950c4648aaa95d0be4f4"+ "sub_transaction_body.cpp/MAXIMAL_CBOR" -> do+ digest <- SubBody.hash encoded >>= must+ Id.toHex digest @?= "29f569946d1ad32690effd3c74cfe3d437fae9bdf2797b6afa5d6d46e291da9e"+ _ -> pure ()+ fresh <- must (SubBody.encodeCbor (SubBody.toBody encoded))+ decoded <- must (SubBody.decodeCbor fresh)+ SubBody.toBody decoded @?= SubBody.toBody encoded+ agree 1 fresh++checkOutputs :: IO ()+checkOutputs = do+ forM_ outputVectors $ \(_, hex) -> do+ payload <- bytes hex+ encoded <- must (Output.decodeCbor payload)+ Output.toCbor encoded @?= payload+ let fresh = Output.encodeCbor (Output.toOutput encoded)+ decoded <- must (Output.decodeCbor fresh)+ Output.toOutput decoded @?= Output.toOutput encoded+ agree 2 fresh+ -- The pinned native pointer fixture has slot 16,292,793,057. Native address+ -- reconstruction truncates pointer fields to uint32; reject this overflow+ -- explicitly instead of presenting a lossy semantic snapshot.+ overflow <- bytes "825826412813b99a80cfb4024374bd0f502959485aa56e0648564ff805f2e51bbcd9819561bddc66141a02faf080"+ assertBool "pinned pointer slot overflow rejected" (isLeft (Output.decodeCbor overflow))+ key <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ let pointer = Shelley.pointer Network.mainnet (Credential.KeyCredential key) (Shelley.StakePointer maxBound maxBound maxBound)+ bounded <- must (Output.mkOutput (Address.ShelleyAddress pointer) (Value.lovelace 1) Datum.NoDatum Nothing)+ agree 2 (Output.encodeCbor bounded)++checkInputs :: IO ()+checkInputs = do+ txId <- must (Id.fromBytes (B.replicate 32 11))+ forM_ [0, 1, maxBound] $ \ix -> do+ let reference = Input.input txId ix+ Input.decodeCbor (Input.encodeCbor reference) @?= Right reference+ Input.index reference @?= ix+ agree 3 (Input.encodeCbor reference)++checkIdentity :: IO ()+checkIdentity = do+ payload <- bytes "bf18009fff18019fff18021800ff"+ encoded <- must (Body.decodeCbor payload)+ Body.toCbor encoded @?= payload+ digest <- Body.hash encoded >>= must+ -- Independent BLAKE2b-256 vector generated with Python hashlib, recorded here.+ Id.toHex digest @?= "60b9f97f0685ea6efefa4cf9c7fbae7ff953ae4ea907fa65804f8131c25c873a"+ let original = Body.toBody encoded+ edited = Body.setFee maxBound original+ Body.bodyFields edited @?= Body.bodyFields original+ Body.fee original @?= 0+ Body.fee edited @?= maxBound+ fresh <- must (Body.encodeCbor original)+ assertBool "fresh semantic reassembly changes nonminimal identity" (fresh /= payload)+ Body.toCbor (Body.setFeeEncoded 0 encoded) @?= payload+ changed <- must (Body.decodeCbor (Body.toCbor (Body.setFeeEncoded maxBound encoded)))+ Body.fee (Body.toBody changed) @?= maxBound++checkNestedIdentity :: IO ()+checkNestedIdentity = do+ -- Nonminimal constructor/integer encoding must survive two nested wrappers.+ inline <- must (Data.decodeCbor (B.pack [0x18, 0x01]))+ destination <- destinationAddress+ out <- must (Output.mkOutput destination (Value.lovelace 2) (Datum.InlineDatum inline) Nothing)+ fresh <- must (Body.encodeCbor (Body.body [] [out] 0))+ encoded <- must (Body.decodeCbor fresh)+ case Fields.fieldOutputs (Body.bodyFields (Body.toBody encoded)) of+ [value] -> case Output.datum value of+ Datum.InlineDatum dat -> Data.toCbor dat @?= B.pack [0x18, 0x01]+ _ -> assertFailure "Lost inline datum alternative"+ _ -> assertFailure "Lost output"+ guard <- Credential.ScriptCredential <$> must (Credential.scriptHashFromBytes (B.replicate 28 7))+ required <- must (Fields.mkEntries [(guard, Just inline)])+ let minimal = Body.body [] [] 0+ body = minimal {Body.bodyFields = (Body.bodyFields minimal) {Fields.fieldRequiredTopLevelGuards = Just required}}+ bodyBytes <- must (Body.encodeCbor body)+ reloaded <- must (Body.decodeCbor bodyBytes)+ Fields.fieldRequiredTopLevelGuards (Body.bodyFields (Body.toBody reloaded)) @?= Just required++checkBoundaries :: IO ()+checkBoundaries = do+ destination <- destinationAddress+ assertBool "negative output" (isLeft (Output.mkOutput destination (Value.lovelace (-1)) Datum.NoDatum Nothing))+ assertBool "native int64 output overflow" (isLeft (Output.mkOutput destination (Value.lovelace (2 ^ (63 :: Int))) Datum.NoDatum Nothing))+ _ <- must (Output.mkOutput destination (Value.lovelace (toInteger (maxBound :: Int64))) Datum.NoDatum Nothing)+ forM_ [0, 31, 33] $ \size -> assertBool "digest size" (isLeft (Datum.hashFromBytes (B.replicate size 0)))+ let minimal = Body.body [] [] 0+ assertBool "present empty nested set rejected" (isLeft (Body.encodeCbor (minimal {Body.bodySubTransactions = Just []})))+ let duplicateGuard = Credential.KeyCredential <$> Credential.keyHashFromBytes (B.replicate 28 4)+ guard <- must duplicateGuard+ let invalidGuards = minimal {Body.bodyFields = (Body.bodyFields minimal) {Fields.fieldGuards = Just [guard, guard]}}+ assertBool "repeated fresh guards rejected" (isLeft (Body.fromBody invalidGuards))+ assertBool "mint Ada rejected" (isLeft (Fields.mkMint (Value.lovelace 1)))+ assertBool "empty association rejected" (isLeft (Fields.mkEntries ([] :: [(Word64, Word64)])))+ assertBool "equal duplicate association rejected" (isLeft (Fields.mkEntries [(1 :: Word64, 0 :: Word64), (1, 0)]))++checkMalformed :: IO ()+checkMalformed = do+ forM_ ["a0", "a200800180", "a40080018002000201", "a4008001800200181c00", "a3008001800220", "a300800180020000", "a40080018002001818a0"] $ \hex -> do+ payload <- bytes hex+ assertBool hex (isLeft (Body.decodeCbor payload))+ forM_ malformedSubVectors $ \(name, hex) -> do+ payload <- bytes hex+ assertBool name (isLeft (SubBody.decodeCbor payload))+ forM_ ["80", "a10040", "a3004001000101", "a300581d600000000000000000000000000000000000000000000000000000000001000400"] $ \hex -> do+ payload <- bytes hex+ assertBool hex (isLeft (Output.decodeCbor payload))++destinationAddress :: IO Address.Address+destinationAddress = do+ key <- must (Credential.keyHashFromBytes (B.replicate 28 3))+ pure (Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key)))++checkUtxo :: IO ()+checkUtxo = do+ destination <- destinationAddress+ txId <- must (Id.fromBytes (B.replicate 32 3))+ out <- must (Output.mkOutput destination (Value.lovelace 1) Datum.NoDatum Nothing)+ let snapshot = Utxo.utxo (Input.input txId maxBound) out+ Utxo.decodeCbor (Utxo.encodeCbor snapshot) @?= Right snapshot++checkOrdering :: IO ()+checkOrdering = do+ destination <- destinationAddress+ policy <- must (Policy.fromBytes (B.replicate 28 8))+ shortName <- must (AssetName.fromBytes (B.singleton 97))+ longName <- must (AssetName.fromBytes (B.pack [0, 0]))+ let bundle = Value.lovelace 1 <> Value.singleton (Asset.Native policy longName) 3 <> Value.singleton (Asset.Native policy shortName) 4+ output <- must (Output.mkOutput destination bundle Datum.NoDatum Nothing)+ agree 2 (Output.encodeCbor output)++ key <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ script <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ let mainKey = Reward.fromCredential Network.mainnet (Credential.KeyCredential key)+ testScript = Reward.fromCredential Network.testnet (Credential.ScriptCredential script)+ deposits <- must (Fields.mkEntries [(testScript, maxBound), (mainKey, 0)])+ txId <- must (Id.fromBytes (B.replicate 32 3))+ let low = Input.input txId 0+ high = Input.input txId maxBound+ minimal = Body.body [high, low, high] [output] 0+ transaction = minimal {Body.bodyFields = (Body.bodyFields minimal) {Fields.fieldDirectDeposits = Just deposits}}+ encoded <- must (Body.fromBody transaction)+ Fields.fieldInputs (Body.bodyFields (Body.toBody encoded)) @?= [low, high, high]+ agree 0 (Body.toCbor encoded)++propFee :: Property+propFee = property $ do+ amount <- forAll (Gen.word64 Range.constantBounded)+ replacement <- forAll (Gen.word64 Range.constantBounded)+ let original = Body.body [] [] amount+ changed = Body.setFee replacement original+ Body.fee original === amount+ Body.bodyFields changed === Body.bodyFields original+ fresh <- evalEither (Body.encodeCbor changed)+ decoded <- evalEither (Body.decodeCbor fresh)+ Body.toBody decoded === changed+ evalIO (agree 0 fresh)++propOutput :: Property+propOutput = property $ do+ amount <- forAll (Gen.integral (Range.constant 0 (toInteger (maxBound :: Int64))))+ destination <- evalIO destinationAddress+ output <- evalEither (Output.mkOutput destination (Value.lovelace amount) Datum.NoDatum Nothing)+ encoded <- evalEither (Output.decodeCbor (Output.encodeCbor output))+ Output.toOutput encoded === output+ evalIO (agree 2 (Output.encodeCbor output))++bodyVectors :: [(String, String)]+bodyVectors =+ [ ("transaction_body.cpp/MINIMAL_DIJKSTRA_BODY", "a300d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a"),+ ("transaction_body.cpp/GUARDS_KEY_HASH_FORM_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0e81581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d39"),+ ("transaction_body.cpp/GUARDS_UNTAGGED_INPUTS_BODY", "a400818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0e81581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d39"),+ ("transaction_body.cpp/GUARDS_TAGGED_KEY_HASH_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0ed9010282581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d39581c966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c37"),+ ("transaction_body.cpp/GUARDS_EMPTY_TAGGED_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0ed9010280"),+ ("transaction_body.cpp/GUARDS_EMPTY_BARE_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0e80"),+ ("transaction_body.cpp/GUARDS_CREDENTIAL_FORM_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0e828200581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d398201581c966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c37"),+ ("transaction_body.cpp/GUARDS_CREDENTIAL_TAGGED_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0ed90102828200581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d398201581c966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c37"),+ ("transaction_body.cpp/GUARDS_SCRIPT_ONLY_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a0e818201581c966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c37"),+ ("transaction_body.cpp/SUB_TRANSACTIONS_TAGGED_BODY", "a400d9010281825820ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e25000180020017d901028283a300d90102800180031864a0a101647465737483a200d90102800180a0f6"),+ ("transaction_body.cpp/SUB_TRANSACTIONS_BARE_BODY", "a400d9010281825820ee155ace9c40292074cb6aff8c9ccdd273c81648ff1149ef36bcea6ebb8a3e250001800200178283a300d90102800180031864a0a101647465737483a200d90102800180a0f6"),+ ("transaction_body.cpp/REQUIRED_TOP_LEVEL_GUARDS_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a1818a18200581c00112233445566778899aabbccddeeff00112233445566778899aabbf6"),+ ("transaction_body.cpp/DIRECT_DEPOSITS_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a1819a2581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d01903e8581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce725701907d0"),+ ("transaction_body.cpp/ACCOUNT_BALANCE_INTERVALS_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a181aa3581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821864191388581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce72570821901f4f6581df0aabbccddeeff00112233445566778899aabbccddeeff00112233445582f6192710"),+ ("transaction_body.cpp/STARTING_ACCOUNT_BALANCE_INTERVALS_BODY", "a400d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a181ba2581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce7257082f6192710581df0aabbccddeeff00112233445566778899aabbccddeeff001122334455182a"),+ ("transaction_body.cpp/BOTH_ACCOUNT_BALANCE_INTERVALS_BODY", "a500d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a181aa3581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821864191388581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce72570821901f4f6581df0aabbccddeeff00112233445566778899aabbccddeeff00112233445582f6192710181ba2581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce7257082f6192710581df0aabbccddeeff00112233445566778899aabbccddeeff001122334455182a"),+ ("transaction_body.cpp/ALL_TOP_LEVEL_KEYS_BODY", "b81900d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000180020a031903e804d90102828304581c26b17b78de4f035dc0bfce60d1d3c3a8085c38dcce5fb8767e518bed1901f48405581c0d94e174732ef9aae73f395ab44507bfa983d65023c11a951f0c32e4581ca646474b8f5431261506b6c273d307c7569a4eb6c96b42dd4a29520a582003170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131405a2581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d005581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce72570030758202ceb364d93225b4a0f004a0975a13eb50c3cc6348474b4fe9121f8dc72ca0cfa08186409a3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c413831581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e0b58206199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d38abc123de0dd90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5010e828200581c6199186adb51974690d7247d2646097d2c62763b16fb7ed3f9f55d398201581c966e394a544f242081e41d1965137b1bb412ac230d40ed5407821c370f0110a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc01820aa3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c411832581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e11186412d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d50013a28202581c10000000000000000000000000000000000000000000000000000000a38258201000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258202000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258203000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008203581c20000000000000000000000000000000000000000000000000000000a28258201000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f582000000000000000000000000000000000000000000000000000000000000000008258203000000000000000000000000000000000000000000000000000000000000000038200827668747470733a2f2f7777772e736f6d6575726c2e696f5820000000000000000000000000000000000000000000000000000000000000000014d9010281841a000f4240581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f830582582000000000000000000000000000000000000000000000000000000000000000000382827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000f6827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000151907d0161903e817d901028283a300d90102800180031864a0a101647465737483a200d90102800180a0f61818a18200581c00112233445566778899aabbccddeeff00112233445566778899aabbf61819a2581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d01903e8581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce725701907d0181aa3581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821864191388581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce72570821901f4f6581df0aabbccddeeff00112233445566778899aabbccddeeff00112233445582f6192710181ba2581de0404b5a4088ae9abcf486a7e7b8f82069e6fcfe1bf226f1851ce7257082f6192710581df0aabbccddeeff00112233445566778899aabbccddeeff001122334455182a")+ ]++subBodyVectors :: [(String, String)]+subBodyVectors =+ [ ("sub_transaction_body.cpp/MINIMAL_CBOR", "a200d90102800180"),+ ("sub_transaction_body.cpp/MAXIMAL_CBOR", "b300d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000181825839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc820aa3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c411832581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e031903e804d90102818304581c26b17b78de4f035dc0bfce60d1d3c3a8085c38dcce5fb8767e518bed1901f405a1581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f050758200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d508186409a3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c413831581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e0b58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d50ed90102828200581c00112233445566778899aabbccddeeff00112233445566778899aabb8201581caabbccddeeff00112233445566778899aabbccddeeff0011223344550f0112d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d50013a18202581c00112233445566778899aabbccddeeff00112233445566778899aabba18258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5038201f614d9010281841a000f4240581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8106827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000151907d0161903e81818a28200581c00112233445566778899aabbccddeeff00112233445566778899aabbf68201581caabbccddeeff00112233445566778899aabbccddeeff001122334455d879801819a1581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f1a000f4240181aa1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821864191388"),+ ("sub_transaction_body.cpp/MAXIMAL_FRESH_CBOR", "b300d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5000181a2005839009493315cd92eb5d8c4304e67b7e16ae36d61d34502694657811a2c8e32c728d3861e164cab28cb8f006448139c8f1740ffb8e7aa9e5232dc01820aa3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c411832581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e031903e804d90102818304581c26b17b78de4f035dc0bfce60d1d3c3a8085c38dcce5fb8767e518bed1901f405a1581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f050758200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d508186409a3581c2a286ad895d091f2b3d168a6091ad2627d30a72761a5bc36eef00740a14014581c659f2917fb63f12b33667463ee575eeac1845bbc736b9c0bbc40ba82a14454534c413831581c7eae28af2208be856f7a119668ae52a49b73725e326dc16579dcc373a240182846504154415445181e0b58200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d50ed90102828200581c00112233445566778899aabbccddeeff00112233445566778899aabb8201581caabbccddeeff00112233445566778899aabbccddeeff0011223344550f0112d90102818258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d50013a18202581c00112233445566778899aabbccddeeff00112233445566778899aabba18258200f3abbc8fc19c2e61bab6059bf8a466e6e754833a08a62a6c56fe0e78f19d9d5038201f614d9010281841a000f4240581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f8106827668747470733a2f2f7777772e736f6d6575726c2e696f58200000000000000000000000000000000000000000000000000000000000000000151907d0161903e81818a28200581c00112233445566778899aabbccddeeff00112233445566778899aabbf68201581caabbccddeeff00112233445566778899aabbccddeeff001122334455d879801819a1581de1cb0ec2692497b458e46812c8a5bfa2931d1a2d965a99893828ec810f1a000f4240181aa1581de013cf55d175ea848b87deb3e914febd7e028e2bf6534475d52fb9c3d0821864191388")+ ]++outputVectors :: [(String, String)]+outputVectors =+ [ ("transaction_output.cpp/CBOR", "a400583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa801821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a028201d81849d8799f0102030405ff03d8185182014e4d01000033222220051200120011"),+ ("transaction_output.cpp/LEGACY_OUTPUT_CBOR", "83583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa8821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a58200000000000000000000000000000000000000000000000000000000000000000"),+ ("transaction_output.cpp/LEGACY_OUTPUT_NO_DATUM_CBOR", "82583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa8821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a"),+ ("transaction_output.cpp/BABBAGE_INLINE_DATUM_CBOR", "a300583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa801821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a028201d81849d8799f0102030405ff"),+ ("transaction_output.cpp/BABBAGE_DATUM_HASH_CBOR", "a400583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa801821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a0282005820000000000000000000000000000000000000000000000000000000000000000003d8185182014e4d01000033222220051200120011"),+ ("transaction_output.cpp/BABBAGE_REF_SCRIPT_CBOR", "a300583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa801821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a03d8185182014e4d01000033222220051200120011"),+ ("transaction_output.cpp/BABBAGE_NO_OPTIONAL_FIELD_SCRIPT_CBOR", "82583900537ba48a023f0a3c65e54977ffc2d78c143fb418ef6db058e006d78a7c16240714ea0e12b41a914f2945784ac494bb19573f0ca61a08afa8821a000f4240a2581c00000000000000000000000000000000000000000000000000000000a3443031323218644433343536186344404142420a581c11111111111111111111111111111111111111111111111111111111a3443031323218644433343536186344404142420a")+ ]++malformedSubVectors :: [(String, String)]+malformedSubVectors =+ [ ("sub_transaction_body.cpp/FEE_KEY_CBOR", "a300d90102800180020a"),+ ("sub_transaction_body.cpp/COLLATERAL_KEY_CBOR", "a300d901028001800d00"),+ ("sub_transaction_body.cpp/COLLATERAL_RETURN_KEY_CBOR", "a300d901028001801000"),+ ("sub_transaction_body.cpp/TOTAL_COLLATERAL_KEY_CBOR", "a300d901028001801100"),+ ("sub_transaction_body.cpp/NESTED_SUB_TX_KEY_CBOR", "a300d901028001801700"),+ ("sub_transaction_body.cpp/STARTING_INTERVALS_KEY_CBOR", "a300d90102800180181ba0"),+ ("sub_transaction_body.cpp/UNKNOWN_KEY_CBOR", "a300d90102800180186300"),+ ("sub_transaction_body.cpp/MISSING_INPUTS_CBOR", "a10180"),+ ("sub_transaction_body.cpp/MISSING_OUTPUTS_CBOR", "a100d9010280"),+ ("sub_transaction_body.cpp/EMPTY_WITHDRAWALS_CBOR", "a300d9010280018005a0"),+ ("sub_transaction_body.cpp/EMPTY_REQUIRED_GUARDS_CBOR", "a300d901028001801818a0")+ ]++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_transaction_body_agree"+ cAgreement :: CUInt -> Ptr Word8 -> CSize -> IO CInt
@@ -0,0 +1,454 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Offline native-builder tests. Expected balances use independent integer+-- accounting; inputs are synthetic and never query or submit to a network.+module TransactionBuilder (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.CoinSelection as Selection+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (..))+import qualified Cometa.Evaluation as Evaluation+import qualified Cometa.Internal.Runtime as Runtime+import qualified Cometa.Internal.TransactionPlan as InternalPlan+import qualified Cometa.Metadata as Metadata+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Pool.Relay as Relay+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import Cometa.Protocol.ExUnits (ExUnits (..))+import qualified Cometa.Protocol.Parameters as P+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SlotConfig as Slot+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Balancing as Balancing+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Builder as Builder+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Value+import Control.Concurrent (forkFinally, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, displayException, finally, throwIO, try)+import Control.Monad (forM_, replicateM_, (>=>))+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (isInfixOf)+import qualified Data.Map.Strict as Map+import qualified Data.Set as Set+import qualified Fixtures.ProtocolParameters as Fixture+import Hedgehog (Property, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import System.Mem (performGC)+import System.Timeout (timeout)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Transaction building"+ [ testCase "pool-state snapshots refine witness fees and reject duplicates" poolWitnesses,+ testCase "payment order, multiplicity and independent balance oracle" payment,+ testCase "many mandatory inputs sharing one key keep one witness reserve" sharedKey,+ testCase "injected selection crosses actual balancing callbacks repeatedly" callbacks,+ testCase "native script minting, metadata, certificates and withdrawal" fields,+ testCase "composed script attachments are unique by language and exact program" uniqueScripts,+ testCase "datum witnesses are shared across explicit attachments and inputs" uniqueDatums,+ testCase "injected evaluator installs budgets in a complete script spend" scripts,+ testCase "preflight conflicts and native insufficient funds" invalid,+ testCase "surplus withdrawals and minted change cross injected selection" surplus,+ testCase "aggregate native arithmetic and witness padding fail before callbacks" bounds,+ testCase "expected callback error and thrown exceptions preserve identity" failures,+ testCase "cancellation joins callback cleanup and restores allocation baseline" cancellation,+ testProperty "plan associativity and identity" laws+ ]++must :: (Show e) => Either e a -> IO a+must = either (\e -> assertFailure (show e) >> fail "fixture") pure++fixture :: IO (Builder.Config, Output.Output, Utxo.Utxo)+fixture = do+ raw <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ previous <- must (Id.fromBytes (B.replicate 32 8))+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ params =+ raw+ { P.parameterMinFeeA = 0,+ P.parameterMinFeeB = 0,+ P.parameterMaxTxSize = 16384,+ P.parameterMaxValueSize = Just 5000,+ P.parameterAdaPerUtxoByte = Just 4310,+ P.parameterProtocolVersion = Version.ProtocolVersion 10 0,+ P.parameterCollateralPercentage = Just 150,+ P.parameterMaxCollateralInputs = Just 3,+ P.parameterKeyDeposit = 2000000,+ P.parameterMaxTxExUnits = Just (ExUnits 10000000 10000000000)+ }+ funding <- must (Output.mkOutput destination (Value.lovelace 10000000) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput destination (Value.lovelace 2000000) Datum.NoDatum Nothing)+ let utxo = Utxo.utxo (Input.input previous 0) funding+ config =+ (Builder.defaultConfig params Slot.preview destination)+ { Builder.availableUtxos = [utxo],+ Builder.minimumFee = 200000+ }+ pure (config, output, utxo)++semantic :: Tx.Transaction -> Fields.Fields+semantic = Body.bodyFields . Body.toBody . Tx.body++payment :: IO ()+payment = do+ (config, output, input) <- fixture+ let plan = Plan.payTo output <> Plan.payTo output <> Plan.validFrom 10 <> Plan.validFrom 20 <> Plan.validUntil 100 <> Plan.validUntil 80+ tx <- Builder.build config plan >>= must+ let actual = semantic tx+ Fields.fieldInputs actual @?= [Utxo.input input]+ take 2 (Fields.fieldOutputs actual) @?= [output, output]+ foldMap Output.value (drop 2 (Fields.fieldOutputs actual)) @?= Value.lovelace 5800000+ Body.fee (Body.toBody (Tx.body tx)) @?= 200000+ Fields.fieldInvalidBefore actual @?= Just 20+ Fields.fieldInvalidAfter actual @?= Just 80+ Fields.fieldNetworkId actual @?= Just Fields.Testnet+ Tx.decodeCbor (Tx.encodeCbor tx) @?= Right tx+ overlap <- Builder.build config (Plan.spend input <> Plan.payTo output) >>= must+ Fields.fieldInputs (semantic overlap) @?= [Utxo.input input]+ foldMap Output.value (Fields.fieldOutputs (semantic overlap)) @?= Value.lovelace 9800000++sharedKey :: IO ()+sharedKey = do+ (config, output, wallet) <- fixture+ let previous = Input.transactionId (Utxo.input wallet)+ tiny <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 1000000) Datum.NoDatum Nothing)+ let inputs = [Utxo.utxo (Input.input previous ix) tiny | ix <- [0 .. 299]]+ plan = foldMap Plan.spend inputs <> Plan.payTo output+ tx <- Builder.build config {Builder.availableUtxos = []} plan >>= must+ length (Fields.fieldInputs (semantic tx)) @?= 300+ assertBool "fixture transaction should fit16KiB" (B.length (Tx.encodeCbor tx) + 101 < 16384)++spendAll :: Selection.Selector+spendAll = Selection.Selector $ \request -> pure $ do+ let selected = Map.elems (Map.fromList [(Utxo.input u, u) | u <- Selection.preselected request <> Selection.available request])+ total = foldMap (Output.value . Utxo.output) selected+ excess = Value.difference total (Selection.target request)+ change <- if Value.isZero excess then pure [] else (: []) <$> Output.mkOutput (Selection.changeAddress request) excess Datum.NoDatum Nothing+ pure (Selection.Selection selected [] change)++callbacks :: IO ()+callbacks = do+ baseline <- Runtime.liveContexts+ (config, output, _) <- fixture+ calls <- newIORef (0 :: Int)+ let selected = Selection.Selector $ \request -> do+ modifyIORef' calls (+ 1)+ performGC+ Selection.select spendAll request+ injected = config {Builder.selector = Just selected}+ replicateM_ 3 (Builder.build injected (Plan.payTo output) >>= must)+ count <- readIORef calls+ assertBool "selection not called for each build" (count >= 3)+ Runtime.liveContexts >>= (@?= baseline)++fields :: IO ()+fields = do+ (config, output, _) <- fixture+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ let script = Script.Native (Native.allOf [])+ scriptHash <- Script.hash script >>= must+ policy <- must (Policy.fromBytes (Credential.scriptHashBytes scriptHash))+ metadatum <- must (Metadata.mkInteger 42)+ let asset = Asset.Native policy AssetName.empty+ credential = Credential.KeyCredential stake+ reward = Reward.fromCredential Network.testnet credential+ cert = Certificate.StakeRegistration credential+ datum = Data.fromData (Data.Integer 42)+ plan =+ Plan.payTo output+ <> Plan.attachScript script+ <> Plan.mint asset 1+ <> Plan.mint asset 1+ <> Plan.metadata 7 metadatum+ <> Plan.attachDatum datum+ <> Plan.certificate cert+ <> Plan.withdraw reward 1000000+ tx <- Builder.build config plan >>= must+ let actual = semantic tx+ fmap (Value.quantity asset . Fields.mintValue) (Fields.fieldMint actual) @?= Just 2+ fmap Certificates.toList (Fields.fieldCertificates actual) @?= Just [cert]+ fmap Fields.entries (Fields.fieldWithdrawals actual) @?= Just [(reward, 1000000)]+ let outputs = foldMap Output.value (Fields.fieldOutputs actual)+ Value.quantity Asset.Ada outputs @?= 8800000+ Value.quantity asset outputs @?= 2+ assertBool "auxiliary data missing" (isJust (Tx.auxiliaryData tx))+ assertBool "datum witness missing" (datum `elem` Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses tx)))+ where+ isJust Nothing = False; isJust (Just _) = True++scripts :: IO ()+scripts = do+ (config, output, wallet) <- fixture+ script <- Script.Plutus <$> must (Plutus.fromBytes Plutus.V2 (B.pack [1, 2, 3]))+ model <- must (Models.mkCostModel 1 (replicate 175 0))+ hash <- Script.hash script >>= must+ let destination = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.ScriptCredential hash))+ datum = Data.fromData (Data.Integer 42)+ locked <- must (Output.mkOutput destination (Value.lovelace 10000000) (Datum.InlineDatum datum) Nothing)+ let scriptInput = Utxo.utxo (Utxo.input wallet) locked+ collateralId <- must (Id.fromBytes (B.replicate 32 10))+ collateralOutput <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace 5000000) Datum.NoDatum Nothing)+ calls <- newIORef (0 :: Int)+ let evaluate = Evaluation.Evaluator $ \target tx _ -> do+ target @?= Evaluation.TopLevel+ modifyIORef' calls (+ 1)+ pure+ ( Evaluation.mkBudgets+ [ (Evaluation.RedeemerId (Redeemer.purpose r) (Redeemer.index r), ExUnits 100 200)+ | r <- Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses tx))+ ]+ )+ injected = config {Builder.availableUtxos = [], Builder.collateralUtxos = [Utxo.utxo (Input.input collateralId 0) collateralOutput], Builder.evaluator = Just evaluate, Builder.parameters = (Builder.parameters config) {P.parameterCostModels = Just (Models.fromList [model])}}+ tx <- Builder.build injected (Plan.spendWith scriptInput (Just datum) Nothing <> Plan.attachScript script <> Plan.attachScript script <> Plan.attachDatum datum <> Plan.attachDatum datum <> Plan.payTo output) >>= must+ Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses tx)) @?= [datum]+ Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses tx)) @?= [script]+ assertBool "evaluator not called" . (> 0) =<< readIORef calls+ map Redeemer.executionUnits (Witnesses.redeemers (Witnesses.toWitnesses (Tx.witnesses tx))) @?= [ExUnits 100 200]+ let tooSmall = injected {Builder.parameters = (Builder.parameters injected) {P.parameterMaxTxExUnits = Just (ExUnits 99 199)}}+ Builder.build tooSmall (Plan.spendWith scriptInput (Just datum) Nothing <> Plan.attachScript script <> Plan.payTo output)+ >>= (@?= Left (InvalidEvaluationResult "Evaluation exceeds maximum transaction execution units"))+ extreme <- must (Rational.mkNonNegativeRational (2 ^ (64 :: Int) - 1) 1)+ let overpriced = injected {Builder.parameters = (Builder.parameters injected) {P.parameterExecutionCosts = Just (Prices.ExUnitPrices extreme extreme)}}+ before <- readIORef calls+ Builder.build overpriced (Plan.spendWith scriptInput (Just datum) Nothing <> Plan.attachScript script <> Plan.payTo output)+ >>= assertBool "execution fee overflow accepted" . isLeft+ readIORef calls >>= (@?= before)+ baseline <- Runtime.liveContexts+ Builder.build injected {Builder.evaluator = Nothing} (Plan.spendWith scriptInput (Just datum) Nothing <> Plan.attachScript script <> Plan.payTo output)+ >>= assertBool "malformed script unexpectedly executed" . isLeft+ Runtime.liveContexts >>= (@?= baseline)++invalid :: IO ()+invalid = do+ (config, output, input) <- fixture+ one <- must (Metadata.mkInteger 1)+ two <- must (Metadata.mkInteger 2)+ forM_+ [ Plan.validFrom 10 <> Plan.validUntil 10,+ Plan.mint Asset.Ada 1,+ Plan.metadata 1 one <> Plan.metadata 1 two,+ Plan.spend input <> Plan.spendWith input (Just (Data.fromData (Data.Integer 0))) Nothing+ ]+ (Builder.build config >=> (assertBool "invalid plan accepted" . isLeft))+ Builder.build config {Builder.availableUtxos = []} (Plan.payTo output) >>= assertBool "unfunded build accepted" . isLeft++surplus :: IO ()+surplus = do+ (config, output, _) <- fixture+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 9))+ let script = Script.Native (Native.allOf [])+ hash <- Script.hash script >>= must+ policy <- must (Policy.fromBytes (Credential.scriptHashBytes hash))+ let reward = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ asset = Asset.Native policy AssetName.empty+ plan = Plan.payTo output <> Plan.withdraw reward 10000000 <> Plan.attachScript script <> Plan.mint asset 2+ tx <- Builder.build config {Builder.selector = Just spendAll} plan >>= must+ let total = foldMap Output.value (Fields.fieldOutputs (semantic tx))+ Value.quantity Asset.Ada total @?= 19800000+ Value.quantity asset total @?= 2+ cancelled <- Builder.build config (Plan.payTo output <> Plan.mint asset 1 <> Plan.mint asset (-1)) >>= must+ Fields.fieldMint (semantic cancelled) @?= Nothing++bounds :: IO ()+bounds = do+ (config, output, wallet) <- fixture+ huge <- must (Output.mkOutput (Builder.changeAddress config) (Value.lovelace (2 ^ (62 :: Int))) Datum.NoDatum Nothing)+ let first = Utxo.utxo (Utxo.input wallet) huge+ second = Utxo.utxo (Input.input (Input.transactionId (Utxo.input wallet)) 1) huge+ restricted <- must (Slot.mkSlotConfig 0 100 1000)+ late <- must (Slot.mkSlotConfig maxBound 0 1)+ calls <- newIORef (0 :: Int)+ let backend = Selection.Selector (\request -> modifyIORef' calls (+ 1) >> Selection.select spendAll request)+ checked = config {Builder.selector = Just backend}+ cases =+ [ (checked {Builder.availableUtxos = [wallet, wallet]}, Plan.payTo output),+ (checked {Builder.collateralUtxos = [wallet, wallet]}, Plan.payTo output),+ (checked {Builder.availableUtxos = [first, second]}, Plan.payTo output),+ (checked, Plan.payTo huge <> Plan.payTo huge),+ (checked {Builder.minimumFee = 2 ^ (63 :: Int)}, Plan.payTo output),+ (checked {Builder.extraSigners = maxBound}, Plan.payTo output),+ (checked {Builder.slotConfig = restricted}, Plan.validFrom 99 <> Plan.payTo output),+ (checked {Builder.slotConfig = late}, Plan.validUntil 1 <> Plan.payTo output)+ ]+ forM_ cases $ \(context, plan) -> Builder.build context plan >>= assertBool "unsafe request accepted" . isLeft+ readIORef calls >>= (@?= 0)++failures :: IO ()+failures = do+ baseline <- Runtime.liveContexts+ (config, output, _) <- fixture+ let expected = UnsupportedOperation "selector refusal"+ Builder.build config {Builder.selector = Just (Selection.Selector (\_ -> pure (Left expected)))} (Plan.payTo output) >>= (@?= Left expected)+ outcome <- try (Builder.build config {Builder.selector = Just (Selection.Selector (\_ -> throwIO (userError "builder callback failure")))} (Plan.payTo output))+ case outcome of+ Left (failure :: SomeException) -> assertBool "exception identity" ("builder callback failure" `isInfixOf` displayException failure)+ Right _ -> assertFailure "callback exception swallowed"+ Runtime.liveContexts >>= (@?= baseline)++cancellation :: IO ()+cancellation = do+ baseline <- Runtime.liveContexts+ (config, output, _) <- fixture+ started <- newEmptyMVar+ block <- newEmptyMVar+ cleaned <- newEmptyMVar+ finished <- newEmptyMVar+ let selected = Selection.Selector $ \_ -> (putMVar started () >> takeMVar block) `finally` putMVar cleaned ()+ worker <- forkFinally (Builder.build config {Builder.selector = Just selected} (Plan.payTo output)) (putMVar finished)+ takeMVar started+ killThread worker+ joined <- timeout 5000000 (takeMVar finished)+ case joined of Just (Left _) -> pure (); _ -> assertFailure "build cancellation did not unwind"+ takeMVar cleaned+ Runtime.liveContexts >>= (@?= baseline)++{-# ANN laws ("HLint: ignore Monoid law, left identity" :: String) #-}+{-# ANN laws ("HLint: ignore Monoid law, right identity" :: String) #-}+laws :: Property+laws = property $ do+ a <- forAll (Gen.word64 (Range.linear 0 100000))+ b <- forAll (Gen.word64 (Range.linear 0 100000))+ c <- forAll (Gen.word64 (Range.linear 0 100000))+ let x = Plan.validFrom a; y = Plan.validUntil b; z = Plan.validFrom c+ InternalPlan.encodePlan 0 ((x <> y) <> z) === InternalPlan.encodePlan 0 (x <> (y <> z))+ InternalPlan.encodePlan 0 (mempty <> x) === InternalPlan.encodePlan 0 x+ InternalPlan.encodePlan 0 (x <> mempty) === InternalPlan.encodePlan 0 x++uniqueScripts :: IO ()+uniqueScripts = do+ (base, output, _) <- fixture+ let config = base {Builder.parameters = (Builder.parameters base) {P.parameterProtocolVersion = Version.ProtocolVersion 12 0}}+ nativeA = Script.Native (Native.allOf [])+ nativeB = Script.Native (Native.anyOf [])+ nativePlan = Plan.attachScript nativeB <> Plan.attachScript nativeA+ nativeTx <- Builder.build config (nativePlan <> nativePlan <> Plan.payTo output) >>= must+ Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses nativeTx)) @?= [nativeB, nativeA]+ versions <- mapM (\version -> Script.Plutus <$> must (Plutus.fromBytes version (B.pack [1, 2, 3]))) [Plutus.V1 .. Plutus.V4]+ allVersions <- Builder.build config (foldMap Plan.attachScript (versions <> versions) <> Plan.payTo output) >>= must+ Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses allVersions)) @?= versions+ forM_ [Plutus.V1 .. Plutus.V4] $ \version -> do+ canonical <- Script.Plutus <$> must (Plutus.fromBytes version (B.pack [1, 2, 3]))+ first <- Script.Plutus <$> must (Plutus.decodeCbor version (B.pack [0x58, 3, 1, 2, 3]))+ distinct <- Script.Plutus <$> must (Plutus.fromBytes version (B.pack [4, 5, 6]))+ let once = Plan.attachScript first <> Plan.attachScript distinct <> Plan.payTo output+ repeated = Plan.attachScript first <> Plan.attachScript distinct <> Plan.attachScript canonical <> Plan.attachScript first <> Plan.payTo output+ -- Keep the first exact imported framing in the native instruction stream.+ InternalPlan.encodePlan 0 repeated @?= InternalPlan.encodePlan 0 once+ expected <- Builder.build config once >>= must+ actual <- Builder.build config repeated >>= must+ Tx.encodeCbor actual @?= Tx.encodeCbor expected+ length (Witnesses.scripts (Witnesses.toWitnesses (Tx.witnesses actual))) @?= 2++uniqueDatums :: IO ()+uniqueDatums = do+ (config, output, first) <- fixture+ let second = Utxo.utxo (Input.input (Input.transactionId (Utxo.input first)) 1) (Utxo.output first)+ canonical = Data.fromData (Data.Integer 0)+ imported <- must (Data.decodeCbor (B.pack [0x18, 0]))+ Data.toData imported @?= Data.toData canonical+ let requirements = Plan.payTo output+ attachments = Plan.attachDatum imported <> Plan.attachDatum canonical <> Plan.attachDatum imported <> Plan.attachDatum canonical+ explicit <- Builder.build config (attachments <> requirements) >>= must+ Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses explicit)) @?= [imported, canonical]+ forM_ [False, True] $ \attachFirst -> do+ let spends = Plan.spendWith first Nothing (Just imported) <> Plan.spendWith second Nothing (Just imported)+ plan = if attachFirst then attachments <> spends <> requirements else spends <> attachments <> requirements+ tx <- Builder.build config plan >>= must+ Fields.fieldInputs (semantic tx) @?= [Utxo.input first, Utxo.input second]+ Witnesses.datums (Witnesses.toWitnesses (Tx.witnesses tx)) @?= [imported, canonical]+ -- Conflicting declarations for one input still fail before deduplication.+ Builder.build config (Plan.spendWith first Nothing (Just imported) <> Plan.spendWith first Nothing (Just canonical) <> requirements)+ >>= (@?= Left (InvalidTransactionPlan "Conflicting requirements for one spending input"))++poolWitnesses :: IO ()+poolWitnesses = do+ (base, output, _) <- fixture+ operator <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ owner <- must (Credential.keyHashFromBytes (B.replicate 28 2))+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 3))+ margin <- must (Unit.mkUnitInterval 1 20)+ let latest =+ Pool.PoolParameters+ operator+ vrf+ Nothing+ 0+ 0+ margin+ (Reward.fromCredential Network.testnet (Credential.KeyCredential owner))+ (Set.singleton owner)+ ([] :: [Relay.Relay])+ Nothing+ params = (Builder.parameters base) {P.parameterProtocolVersion = Version.ProtocolVersion 12 0, P.parameterMinFeeA = 44, P.parameterMinFeeB = 155381, P.parameterPoolDeposit = 0}+ config = base {Builder.parameters = params, Builder.minimumFee = 0}+ plan = Plan.payTo output <> Plan.certificate (Certificate.PoolRegistration latest)+ conservative <- Builder.build config plan >>= must+ known <- Builder.build (config {Builder.poolState = [latest]}) plan >>= must+ assertBool "known unchanged registration omits one owner witness" (Body.fee (Body.toBody (Tx.body known)) < Body.fee (Body.toBody (Tx.body conservative)))+ let originalBody = Body.toBody (Tx.body conservative)+ draftFields = (Body.bodyFields originalBody) {Fields.fieldOutputs = [output]}+ draftBody <- must (Body.fromBody (originalBody {Body.bodyFields = draftFields, Body.bodyFee = 0}))+ let draft = Tx.fromBody draftBody+ conservativeBalance <- Balancing.balance config [] draft >>= must+ rebalanced <- Balancing.balance (config {Builder.poolState = [latest]}) [] draft >>= must+ assertBool+ "standalone balancing uses the supplied pool state"+ (Body.fee (Body.toBody (Tx.body rebalanced)) < Body.fee (Body.toBody (Tx.body conservativeBalance)))+ duplicate <- Builder.build (config {Builder.poolState = [latest, latest]}) plan+ assertBool "duplicate operators are rejected" (isLeft duplicate)+ let old = config {Builder.parameters = params {P.parameterProtocolVersion = Version.ProtocolVersion 11 0}}+ before <- Builder.build old plan >>= must+ supplied <- Builder.build (old {Builder.poolState = [latest]}) plan >>= must+ Body.fee (Body.toBody (Tx.body supplied)) @?= Body.fee (Body.toBody (Tx.body before))
@@ -0,0 +1,409 @@+{-# LANGUAGE ForeignFunctionInterface #-}+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Native contract corpus: pinned cardano-c transaction_builder/fee.c,+-- balancing/implicit_coin.c, tests/transaction_builder/script_data_hash.cpp+-- (datum-only digest), Apache-2.0. Inputs are assembled through public values;+-- rational and serialized-size expectations are calculated independently.+module TransactionBuilding (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (InvalidExUnits, NativeError))+import qualified Cometa.Error.Code as Code+import qualified Cometa.Internal.Building as Internal+import qualified Cometa.Internal.ParameterSnapshot as Snapshot+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as Ex+import qualified Cometa.Protocol.Parameters as Parameters+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Building as Building+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as Id+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Value+import Control.Monad (forM_, replicateM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import qualified Data.Set as Set+import qualified Data.Text+import Data.Word (Word64, Word8)+import qualified Fixtures.ProtocolParameters as Fixture+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Transaction building utilities"+ [ testCase "serialization sizes agree with native and retain exact encodings" checkSizes,+ testCase "execution totals and exact pricing reject overflow" checkExecution,+ testCase "outer, local intent and complete batch accounting agree" checkBalance,+ testCase "balance includes mint, withdrawals and direct account deposits" checkAccountBalance,+ testCase "pool deposits are charged once across a batch" checkPoolBatch,+ testCase "balance rejects unresolved, duplicate and overflowing inputs" checkBalanceErrors,+ testCase "fee uses actual ledger frame size and checked arithmetic" checkBaseFee,+ testCase "minimum Ada adjusts coin width and rejects multiplication overflow" checkMinimumAda,+ testCase "exact rational reference tiers and execution fees agree" checkFees,+ testCase "reference coverage includes subtransactions and rejects duplicates" checkCoverage,+ testCase "spending scripts and per-body pricing match native balancing" checkSpendingScripts,+ testCase "datum-only native corpus hash and empty absence" checkHash,+ testCase "implicit deposits and refunds are separate checked totals" checkImplicit,+ testCase "malformed native requests unwind and following calls succeed" checkMalformed+ ]++must :: (Show e) => Either e a -> IO a+must value = case value of+ Left failure -> assertFailure (show failure) >> fail "Invalid fixture"+ Right result -> pure result++transaction :: Body.Body -> IO Tx.Transaction+transaction body = Tx.fromBody <$> must (Body.fromBody body)++fixture :: IO (Parameters.Parameters, Utxo.Utxo)+fixture = do+ parameters <- must Fixture.parameters+ key <- must (Credential.keyHashFromBytes (B.replicate 28 7))+ ident <- must (Id.fromBytes (B.replicate 32 8))+ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ script <- must (Plutus.fromBytes Plutus.V3 (B.replicate 26000 1))+ output <- must (Output.mkOutput address (Value.lovelace 2000000) Datum.NoDatum (Just (Script.Plutus script)))+ pure (parameters, Utxo.utxo (Input.input ident 0) output)++checkBaseFee :: IO ()+checkBaseFee = do+ tx <- transaction (Body.body [] [] 0)+ Building.baseFee 17 3 tx >>= (@?= Right (17 + 3 * fromIntegral (B.length (Tx.encodeCbor tx) - 1)))+ Building.baseFee maxBound 1 tx >>= assertOverflow+ Building.baseFee 0 maxBound tx >>= assertOverflow+ Building.baseFee 0 0 tx >>= (@?= Right 0)++checkMinimumAda :: IO ()+checkMinimumAda = do+ (_, resolved) <- fixture+ let output = Utxo.output resolved+ bytes = B.length (Output.encodeCbor output)+ -- Both the starting and minimum coins require five CBOR bytes.+ Building.minimumAda 4310 output >>= (@?= Right (fromIntegral (bytes + 160) * 4310))+ Building.minimumAda 0 output >>= (@?= Right 0)+ Building.minimumAda maxBound output >>= assertOverflow++checkFees :: IO ()+checkFees = do+ (parameters, resolved) <- fixture+ stride <- must (Parameters.mkReferenceScriptCostStride 25600)+ multiplier <- must (Rational.mkNonNegativeRational 6 5)+ let params = parameters {Parameters.parameterRefScriptCostStride = Just stride, Parameters.parameterRefScriptCostMultiplier = Just multiplier}+ body = (Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldReferenceInputs = Just [Utxo.input resolved]}}+ argument = Data.fromData (Data.Integer 42)+ redeemer = Redeemer.Redeemer Redeemer.Spending 0 argument (Ex.ExUnits 3 4)+ witnesses <- Witnesses.fromWitnesses <$> must (Witnesses.mkWitnesses [] [] [] [] [redeemer])+ encoded <- must (Body.fromBody body)+ let tx = Tx.assemble encoded witnesses Nothing+ Building.referenceScriptFee params [resolved] >>= (@?= Right 60853)+ base <- Building.baseFee (Parameters.parameterMinFeeB params) (Parameters.parameterMinFeeA params) tx >>= must+ Building.minimumFee params [resolved] tx >>= (@?= Right (base + 17 + 60853))+ -- Missing tier parameters select the same Conway pricing.+ Building.referenceScriptFee (params {Parameters.parameterRefScriptCostStride = Nothing, Parameters.parameterRefScriptCostMultiplier = Nothing}) [resolved] >>= (@?= Right 60853)+ Building.minimumFee (params {Parameters.parameterExecutionCosts = Nothing}) [resolved] tx >>= assertBool "missing prices" . isLeft+ Building.referenceScriptFee (params {Parameters.parameterRefScriptCostPerByte = Nothing}) [] >>= assertBool "missing reference price" . isLeft++checkCoverage :: IO ()+checkCoverage = do+ (params, resolved) <- fixture+ let fields = (Fields.fields [] []) {Fields.fieldReferenceInputs = Just [Utxo.input resolved]}+ sub <- Sub.fromBody <$> must (SubBody.fromBody (SubBody.fromFields fields))+ tx <- transaction ((Body.body [] [] 0) {Body.bodySubTransactions = Just [sub]})+ Building.minimumFee params [] tx >>= assertBool "unresolved subtransaction reference" . isLeft+ Building.minimumFee params [resolved, resolved] tx >>= assertBool "duplicate references" . isLeft+ Building.referenceScriptFee params [resolved, resolved] >>= assertBool "duplicate reference pricing" . isLeft+ Building.minimumFee params [resolved] tx >>= assertBool "resolved subtransaction succeeds" . not . isLeft+ empty <- transaction (Body.body [] [] 0)+ Building.minimumFee params [resolved] empty >>= assertBool "extraneous reference" . isLeft++checkSpendingScripts :: IO ()+checkSpendingScripts = do+ (params, resolved) <- fixture+ let reference = Utxo.input resolved+ base = Building.baseFee (Parameters.parameterMinFeeB params) (Parameters.parameterMinFeeA params)+ expected <- Building.referenceScriptFee params [resolved] >>= must+ spending <- transaction (Body.body [reference] [] 0)+ linear <- base spending >>= must+ let original = Tx.encodeCbor spending+ Building.minimumFee params [] spending >>= assertBool "spending inputs must resolve" . isLeft+ Building.minimumFee params [resolved] spending >>= (@?= Right (linear + expected))+ Tx.encodeCbor spending @?= original+ both <- transaction ((Body.body [reference] [] 0) {Body.bodyFields = (Fields.fields [reference] []) {Fields.fieldReferenceInputs = Just [reference]}})+ bothLinear <- base both >>= must+ Building.minimumFee params [resolved] both >>= (@?= Right (bothLinear + expected))+ -- The native balancing workflow concatenates each body's priced input set.+ sub <- Sub.fromBody <$> must (SubBody.fromBody (SubBody.body [reference] []))+ batch <- transaction ((Body.body [reference] [] 0) {Body.bodySubTransactions = Just [sub]})+ batchLinear <- base batch >>= must+ -- Fixture byte price 7/3, stride 2^32-1: 52000 script bytes priced once.+ Building.minimumFee params [resolved] batch >>= (@?= Right (batchLinear + 121333))++checkHash :: IO ()+checkHash = do+ Building.scriptDataHash Models.empty (Witnesses.fromWitnesses Witnesses.empty) >>= (@?= Right Nothing)+ let datum = Data.fromData (Data.Integer 1234567890123456789012345678901234567890)+ witnesses <- Witnesses.fromWitnesses <$> must (Witnesses.mkWitnesses [] [] [] [datum] [])+ result <- Building.scriptDataHash Models.empty witnesses >>= must+ expected <- must (Datum.hashFromBytes (B.pack [191, 20, 132, 113, 227, 65, 210, 160, 214, 174, 156, 206, 200, 247, 199, 91, 95, 21, 83, 72, 184, 175, 57, 201, 251, 134, 185, 85, 117, 172, 156, 60]))+ result @?= Just expected+ -- Exact imported datum encoding contributes to the commitment.+ different <- must (Witnesses.decodeCbor (B.pack [0xa1, 0x04, 0x81, 0x18, 0x01]))+ minimal <- must (Witnesses.decodeCbor (B.pack [0xa1, 0x04, 0x81, 0x01]))+ a <- Building.scriptDataHash Models.empty different >>= must+ b <- Building.scriptDataHash Models.empty minimal >>= must+ assertBool "nonminimal datum bytes remain committed" (a /= b)++checkImplicit :: IO ()+checkImplicit = do+ (params, _) <- fixture+ stakeHash <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ let stake = Credential.KeyCredential stakeHash+ certificates = Certificates.fromList [Certificate.StakeRegistration stake, Certificate.StakeDeregistration stake]+ body = (Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldCertificates = Just certificates}}+ tx <- transaction body+ Building.implicitCoin params tx >>= (@?= Right (Building.ImplicitCoin 0 (Parameters.parameterKeyDeposit params) (Parameters.parameterKeyDeposit params)))+ sub <- Sub.fromBody <$> must (SubBody.fromBody (SubBody.fromFields (Body.bodyFields body)))+ Building.subTransactionImplicitCoin params sub >>= (@?= Right (Building.ImplicitCoin 0 (Parameters.parameterKeyDeposit params) (Parameters.parameterKeyDeposit params)))+ enclosing <- transaction ((Body.body [] [] 0) {Body.bodySubTransactions = Just [sub]})+ Building.implicitCoin params enclosing >>= (@?= Right (Building.ImplicitCoin 0 0 0))+ otherHash <- must (Credential.keyHashFromBytes (B.replicate 28 2))+ let account = Reward.fromCredential Network.testnet stake+ other = Reward.fromCredential Network.testnet (Credential.KeyCredential otherHash)+ amounts <- must (Fields.mkEntries [(account, 17), (other, 23)])+ withdrawing <- transaction ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldWithdrawals = Just amounts}})+ Building.implicitCoin params withdrawing >>= (@?= Right (Building.ImplicitCoin 40 0 0))+ excessive <- must (Fields.mkEntries [(account, maxBound), (other, 1)])+ withdrawingOverflow <- transaction ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldWithdrawals = Just excessive}})+ Building.implicitCoin params withdrawingOverflow >>= assertOverflow+ let registrations = Certificates.fromList [Certificate.StakeRegistration stake, Certificate.StakeRegistration stake]+ overflow <- transaction ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldCertificates = Just registrations}})+ Building.implicitCoin (params {Parameters.parameterKeyDeposit = maxBound}) overflow >>= assertOverflow++checkMalformed :: IO ()+checkMalformed = do+ forM_ [0 .. 8] $ \operation -> replicateM_ 20 $ do+ Internal.runUnchecked operation (B.pack [0x82, 0xa0, 0xa0, 0xff]) >>= assertBool "malformed request" . isLeft+ Internal.runUnchecked 99 (B.pack [0x82, 0xa0, 0xa0]) >>= assertBool "unknown operation" . isLeft+ tx <- transaction (Body.body [] [] 0)+ replicateM_ 20 (Building.baseFee 1 1 tx >>= assertBool "fresh native scope after failures" . not . isLeft)+ (parameters, _) <- fixture+ local <- Sub.fromBody <$> must (SubBody.fromBody (SubBody.body [] []))+ forM_ [(6, Tx.encodeCbor tx), (7, Sub.encodeCbor local), (8, Tx.encodeCbor tx)] $ \(operation, encoded) ->+ replicateM_ 20 $+ Internal.runUnchecked operation (B.singleton 0x83 <> encoded <> Snapshot.encodeSnapshot parameters <> B.pack [0x81, 0x80])+ >>= assertBool "partial imbalance request accepted" . isLeft+ Building.batchImbalance parameters [] tx >>= (@?= Right mempty)++assertOverflow :: Either Error a -> IO ()+assertOverflow result = case result of+ Left (NativeError _ code diagnostic) -> do+ code @?= Code.IntegerOverflow+ assertBool "copied native diagnostic is available" (not (Data.Text.null diagnostic))+ Left failure -> assertFailure (show failure)+ Right _ -> assertFailure "Expected native integer overflow"++checkBalance :: IO ()+checkBalance = do+ (parameters, input) <- fixture+ output <- must (Output.mkOutput (Output.address (Utxo.output input)) (Value.lovelace 1800000) Datum.NoDatum Nothing)+ balanced <- transaction (Body.body [Utxo.input input] [output] 200000)+ Building.imbalance parameters [input] balanced >>= (@?= Right mempty)+ Building.isBalanced parameters [input] balanced >>= (@?= Right True)++ localOutput <- must (Output.mkOutput (Output.address output) (Value.lovelace 1000000) Datum.NoDatum Nothing)+ localBody <- must (SubBody.fromBody (SubBody.body [Utxo.input input] [localOutput]))+ let intent = Sub.fromBody localBody+ Building.subTransactionImbalance parameters [input] intent >>= (@?= Right (Value.lovelace 1000000))++ change <- must (Output.mkOutput (Output.address output) (Value.lovelace 800000) Datum.NoDatum Nothing)+ batch <- transaction (Body.body [] [change] 200000) {Body.bodySubTransactions = Just [intent]}+ let before = Tx.encodeCbor batch+ Building.imbalance parameters [input] batch >>= (@?= Right (Value.lovelace (-1000000)))+ Building.batchImbalance parameters [input] batch >>= (@?= Right mempty)+ Building.isBalanced parameters [input] batch >>= (@?= Right True)+ Tx.encodeCbor batch @?= before++checkAccountBalance :: IO ()+checkAccountBalance = do+ (parameters, funding) <- fixture+ policy <- must (Policy.fromBytes (B.replicate 28 1))+ key <- must (Credential.keyHashFromBytes (B.replicate 28 2))+ let token = Asset.Native policy AssetName.empty+ account = Reward.fromCredential Network.testnet (Credential.KeyCredential key)+ address = Output.address (Utxo.output funding)+ source <- must (Output.mkOutput address (Value.lovelace 2000000 <> Value.singleton token 5) Datum.NoDatum Nothing)+ output <- must (Output.mkOutput address (Value.lovelace 2000000 <> Value.singleton token 3) Datum.NoDatum Nothing)+ mint <- must (Fields.mkMint (Value.singleton token (-2)))+ withdrawals <- must (Fields.mkEntries [(account, 17)])+ deposits <- must (Fields.mkEntries [(account, 7)])+ let input = Utxo.utxo (Utxo.input funding) source+ fields =+ (Fields.fields [Utxo.input input] [output])+ { Fields.fieldMint = Just mint,+ Fields.fieldWithdrawals = Just withdrawals,+ Fields.fieldDirectDeposits = Just deposits,+ Fields.fieldDonation = Just 3+ }+ tx <- transaction (Body.body [] [] 7) {Body.bodyFields = fields}+ Building.batchImbalance parameters [input] tx >>= (@?= Right mempty)++checkPoolBatch :: IO ()+checkPoolBatch = do+ (raw, input) <- fixture+ operator <- must (Credential.keyHashFromBytes (B.replicate 28 3))+ stake <- must (Credential.keyHashFromBytes (B.replicate 28 4))+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 5))+ margin <- must (Unit.mkUnitInterval 0 1)+ let pool = Pool.PoolParameters operator vrf Nothing 0 0 margin (Reward.fromCredential Network.testnet (Credential.KeyCredential stake)) Set.empty [] Nothing+ certificates = Just (Certificates.fromList [Certificate.PoolRegistration pool])+ parameters = raw {Parameters.parameterPoolDeposit = 100}+ output <- must (Output.mkOutput (Output.address (Utxo.output input)) (Value.lovelace 1999900) Datum.NoDatum Nothing)+ localBody <- must (SubBody.fromBody (SubBody.fromFields (Fields.fields [] []) {Fields.fieldCertificates = certificates}))+ let intent = Sub.fromBody localBody+ fields = (Fields.fields [Utxo.input input] [output]) {Fields.fieldCertificates = certificates}+ batch <- transaction (Body.body [] [] 0) {Body.bodyFields = fields, Body.bodySubTransactions = Just [intent]}+ Building.imbalance parameters [input] batch >>= (@?= Right mempty)+ Building.subTransactionImbalance parameters [input] intent >>= (@?= Right (Value.lovelace (-100)))+ Building.batchImbalance parameters [input] batch >>= (@?= Right mempty)++checkBalanceErrors :: IO ()+checkBalanceErrors = do+ (parameters, input) <- fixture+ tx <- transaction (Body.body [Utxo.input input] [] 0)+ Building.imbalance parameters [] tx >>= assertBool "missing resolution accepted" . isLeft+ Building.imbalance parameters [input, input] tx >>= assertBool "duplicate resolution accepted" . isLeft+ large <- must (Output.mkOutput (Output.address (Utxo.output input)) (Value.lovelace 9223372036854775807) Datum.NoDatum Nothing)+ otherId <- must (Id.fromBytes (B.replicate 32 9))+ let first = Utxo.utxo (Utxo.input input) large+ second = Utxo.utxo (Input.input otherId 0) large+ overflow <- transaction (Body.body [Utxo.input first, Utxo.input second] [] 0)+ Building.batchImbalance parameters [first, second] overflow >>= assertBool "overflow accepted" . isLeft++-- Independent calculations from the pinned native fee.c, exercised through+-- standalone native owners in test/cbits/runtime_oracle.c. Apache-2.0.+checkSizes :: IO ()+checkSizes = do+ forM_ [(0, 1), (23, 1), (24, 2), (255, 2), (256, 3), (65535, 3), (65536, 5), (4294967295, 5), (4294967296, 9), (maxBound, 9)] $ \(coin, expected) -> do+ Building.coinSize coin @?= expected+ alloca $ \size -> do+ cCoinSize coin size >>= (@?= 0)+ peek size >>= (@?= fromIntegral expected)+ (_, resolved) <- fixture+ let output = Utxo.output resolved+ nativeSize 1 (Output.encodeCbor output) >>= (@?= fromIntegral (Building.outputSize output))+ minimal <- must (Native.decodeCbor (B.pack [0x82, 5, 1]))+ retained <- must (Native.decodeCbor (B.pack [0x82, 5, 0x1b, 0, 0, 0, 0, 0, 0, 0, 1]))+ Building.scriptSize (Script.Native minimal) @?= 3+ Building.scriptSize (Script.Native retained) @?= 11+ plutus <- must (Plutus.decodeCbor Plutus.V4 (B.pack [0x58, 2, 1, 2]))+ Building.scriptSize (Script.Plutus plutus) @?= 2+ forM_ [Script.Native minimal, Script.Native retained, Script.Plutus plutus] $ \script ->+ nativeSize 2 (Script.encodeCbor script) >>= (@?= fromIntegral (Building.scriptSize script))+ tx <- transaction (Body.body [] [output] 0)+ nativeSize 0 (Tx.encodeCbor tx) >>= (@?= fromIntegral (Building.transactionSize tx))+ -- The retained three-element frame has no validity flag to count.+ legacy <- must (Tx.decodeCbor (B.pack [0x83, 0xa3, 0, 0x80, 1, 0x80, 2, 0, 0xa0, 0xf6]))+ nativeSize 0 (Tx.encodeCbor legacy) >>= (@?= fromIntegral (Building.transactionSize legacy))++checkExecution :: IO ()+checkExecution = do+ Building.totalExecutionUnits [] @?= Right (Ex.ExUnits 0 0)+ let argument = Data.fromData (Data.Integer 0)+ redeemer memory steps = Redeemer.Redeemer Redeemer.Spending 0 argument (Ex.ExUnits memory steps)+ Building.totalExecutionUnits [redeemer 1 2, redeemer 3 4] @?= Right (Ex.ExUnits 4 6)+ Building.totalExecutionUnits [redeemer maxBound 0] @?= Right (Ex.ExUnits maxBound 0)+ Building.totalExecutionUnits [redeemer maxBound 0, redeemer 1 0] @?= Left (InvalidExUnits (2 ^ (64 :: Int)) 0)+ Building.totalExecutionUnits [redeemer 0 maxBound, redeemer 0 1] @?= Left (InvalidExUnits 0 (2 ^ (64 :: Int)))+ memoryPrice <- must (Rational.mkNonNegativeRational 7 3)+ stepPrice <- must (Rational.mkNonNegativeRational 11 7)+ let prices = Prices.ExUnitPrices memoryPrice stepPrice+ encoded <- must (Body.fromBody (Body.body [] [] 0))+ forM_ [(0, 0), (1, 0), (0, 1), (1, 1), (3, 7), (100000, 100000)] $ \(memory, steps) -> do+ let budget = Ex.ExUnits memory steps+ witnesses <- Witnesses.fromWitnesses <$> must (Witnesses.mkWitnesses [] [] [] [] [redeemer memory steps])+ let tx = Tx.assemble encoded witnesses Nothing+ expected <- nativeSize 3 (Tx.encodeCbor tx)+ Building.executionFee prices budget @?= Right expected+ localBody <- must (SubBody.fromBody (SubBody.body [] []))+ localWitnesses <- Witnesses.fromWitnesses <$> must (Witnesses.mkWitnesses [] [] [] [] [redeemer 2 6])+ outerWitnesses <- Witnesses.fromWitnesses <$> must (Witnesses.mkWitnesses [] [] [] [] [redeemer 1 1])+ let local = Sub.setWitnesses localWitnesses (Sub.fromBody localBody)+ enclosingBody <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodySubTransactions = Just [local]}))+ let enclosing = Tx.assemble enclosingBody outerWitnesses Nothing+ total <- must (Building.totalExecutionUnits [redeemer 1 1, redeemer 2 6])+ nativeSize 3 (Tx.encodeCbor enclosing) >>= (@?= 18)+ Building.executionFee prices total @?= Right 18+ Building.executionFee prices (Ex.ExUnits 3 7) @?= Right 18+ half <- must (Rational.mkNonNegativeRational 1 2)+ Building.executionFee (Prices.ExUnitPrices half half) (Ex.ExUnits 1 1) @?= Right 1+ tiny <- must (Rational.mkNonNegativeRational 1 (toInteger (maxBound :: Word64)))+ almostOne <- must (Rational.mkNonNegativeRational (toInteger (maxBound :: Word64) - 1) (toInteger (maxBound :: Word64)))+ Building.executionFee (Prices.ExUnitPrices tiny almostOne) (Ex.ExUnits 1 1) @?= Right 1+ largest <- must (Rational.mkNonNegativeRational (toInteger (maxBound :: Word64)) 1)+ zero <- must (Rational.mkNonNegativeRational 0 1)+ let expensive = Prices.ExUnitPrices largest zero+ Building.executionFee expensive (Ex.ExUnits 0 0) @?= Right 0+ Building.executionFee expensive (Ex.ExUnits 1 0) @?= Right maxBound+ assertBool "fee overflow" (isLeft (Building.executionFee expensive (Ex.ExUnits 2 0)))++nativeSize :: Word8 -> B.ByteString -> IO Word64+nativeSize kind bytes = B.useAsCStringLen bytes $ \(input, size) -> alloca $ \output -> do+ cBuildingSize kind (castPtr input) (fromIntegral size) output >>= (@?= 0)+ peek output++foreign import ccall unsafe "cometa_test_building_sizes_oracle"+ cBuildingSize :: Word8 -> Ptr Word8 -> CSize -> Ptr Word64 -> IO CInt++foreign import ccall unsafe "cardano_get_serialized_coin_size"+ cCoinSize :: Word64 -> Ptr CSize -> IO CInt
@@ -0,0 +1,367 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE OverloadedStrings #-}+-- The decoder argument must remain polymorphic for cborg input ownership.+{-# LANGUAGE RankNTypes #-}++-- | Native transaction collection contracts through existing public values.+-- Original tests; reviewed GHC ghc-9.6.7-release Data.OldList.deleteBy (BSD), and+-- cardano-c c5edc7c8f16b3980b6e97ef7fda80fef94adf980 common/utxo_list.c,+-- collections/array.c and transaction_body/transaction_output.c (Apache-2.0).+-- Bounds are checked explicitly; host list clamping is not claimed as native+-- bounds behavior. Native semantic equality is separate from encoded identity.+module TransactionCollectionOperations (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Decoding as D+import qualified Codec.CBOR.Encoding as E+import qualified Codec.CBOR.Read as R+import qualified Codec.CBOR.Write as W+import qualified Cometa.Address as Address+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.Credential as Credential+import Cometa.Error (Error)+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.TransactionId as Id+import qualified Cometa.Value as Value+import Control.Monad (forM_, replicateM, replicateM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as L+import Data.Either (isLeft)+import Data.Int (Int64)+import Data.List (delete, deleteBy)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CInt (..), CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca, allocaBytes)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Hedgehog (Property, classify, evalEither, evalIO, forAll, property, (===))+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- TYPES ----------------------------------------------------------------------++data ListReply = ListReply Bool [Utxo.Utxo] (Maybe [Utxo.Utxo]) deriving (Eq, Show)++data ScriptReply = ScriptReply (Maybe ByteString) ByteString (Maybe ByteString) deriving (Eq, Show)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Transaction collection operations"+ [ testCase "slice and erase reject native bounds rather than clamp" checkBounds,+ testCase "remove deletes first semantic match and retains survivor payloads" checkRemoveIdentity,+ testCase "native import normalizes Plutus envelopes while preserving program bytes" checkImportIdentity,+ testCase "script-reference replacement retains payloads and getters outlive parents" checkScriptReferences,+ testCase "malformed inputs unwind and subsequent scopes recover" checkFailures,+ testProperty "generated native slices preserve order, duplicates and source" propSlice,+ testProperty "generated native erasures return removed and retained segments" propErase,+ testProperty "generated native removal uses structural fields rather than reference alone" propRemove+ ]++must :: (Show e) => Either e a -> IO a+must = either (\failure -> assertFailure (show failure) >> fail "Invalid fixture") pure++scripts :: Either Error [Script.Script]+scripts = do+ retained <- Native.decodeCbor (B.pack [159, 24, 4, 24, 1, 255])+ plutus <- traverse (\version -> Script.Plutus <$> Plutus.fromBytes version (B.pack [1, 2, 3])) [minBound .. maxBound]+ retainedPlutus <- Script.Plutus <$> Plutus.decodeCbor Plutus.V2 (B.pack [88, 3, 1, 2, 3])+ pure ([Script.Native (Native.invalidBefore 1), Script.Native retained] <> plutus <> [retainedPlutus])++fixture :: Either Error [Utxo.Utxo]+fixture = do+ key <- Credential.keyHashFromBytes (B.replicate 28 7)+ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential key))+ make seed amount dat script = do+ identifier <- Id.fromBytes (B.replicate 32 seed)+ output <- Output.mkOutput address (Value.lovelace amount) dat script+ pure (Utxo.utxo (Input.input identifier 0) output)+ retainedDatum <- Data.decodeCbor (B.pack [24, 1])+ scriptValues <- scripts+ plainZero <- make 0 0 Datum.NoDatum Nothing+ plainOne <- make 0 1 Datum.NoDatum Nothing+ canonicalDatum <- make 1 10 (Datum.InlineDatum (Data.fromData (Data.Integer 1))) Nothing+ nonminimalDatum <- make 1 10 (Datum.InlineDatum retainedDatum) Nothing+ withScripts <- traverse (make 2 20 Datum.NoDatum . Just) scriptValues+ pure ([plainZero, plainOne, canonicalDatum, nonminimalDatum] <> withScripts)++-- Native Plutus import stores program bytes and regenerates their outer CBOR+-- bytestring. Public Plutus import retains that envelope, so establish the+-- native-import baseline explicitly before testing collection operations.+importedScript :: Script.Script -> Either Error Script.Script+importedScript value@(Script.Native _) = Right value+importedScript (Script.Plutus value) = Script.Plutus <$> Plutus.fromBytes (Plutus.version value) (Plutus.toBytes value)++importedOutput :: Output.Output -> Either Error Output.Output+importedOutput value = do+ reference <- traverse importedScript (Output.referenceScript value)+ Output.mkOutput (Output.address value) (Output.value value) (Output.datum value) reference++importedUtxo :: Utxo.Utxo -> Either Error Utxo.Utxo+importedUtxo value = Utxo.utxo (Utxo.input value) <$> importedOutput (Utxo.output value)++encodeList :: [Utxo.Utxo] -> ByteString+encodeList values = W.toStrictByteString (E.encodeListLen (fromIntegral (length values)) <> foldMap (E.encodePreEncoded . Utxo.encodeCbor) values)++-- Host bounds validation deliberately precedes take/drop. Native slice rejects+-- empty ranges; native erase permits zero count only at an existing index.+expectedSlice :: Int64 -> Word64 -> [Utxo.Utxo] -> ListReply+expectedSlice start end values+ | start < 0 || toInteger end > toInteger (length values) || toInteger start >= toInteger end = ListReply False values Nothing+ | otherwise = ListReply True values (Just (take (fromIntegral end - fromIntegral start) (drop (fromIntegral start) values)))++expectedErase :: Int64 -> Word64 -> [Utxo.Utxo] -> ListReply+expectedErase start count values+ | position < 0 || position >= total || position + toInteger count > total = ListReply False values Nothing+ | otherwise =+ let (before, rest) = splitAt (fromInteger position) values+ (removed, after) = splitAt (fromIntegral count) rest+ in ListReply True (before <> after) (Just removed)+ where+ total = toInteger (length values)+ position = if start < 0 then total + toInteger start else toInteger start++-- Native equality inspects script/data meaning while public Eq includes their+-- imported encodings. Use public semantic views explicitly for deleteBy.+sameUtxo :: Utxo.Utxo -> Utxo.Utxo -> Bool+sameUtxo left right = Utxo.input left == Utxo.input right && sameOutput (Utxo.output left) (Utxo.output right)+ where+ sameOutput a b = Output.address a == Output.address b && Output.value a == Output.value b && sameDatum (Output.datum a) (Output.datum b) && sameScript (Output.referenceScript a) (Output.referenceScript b)+ sameDatum Datum.NoDatum Datum.NoDatum = True+ sameDatum (Datum.DatumHash a) (Datum.DatumHash b) = a == b+ sameDatum (Datum.InlineDatum a) (Datum.InlineDatum b) = Data.toData a == Data.toData b+ sameDatum _ _ = False+ sameScript Nothing Nothing = True+ sameScript (Just (Script.Native a)) (Just (Script.Native b)) = Native.toJson a == Native.toJson b+ sameScript (Just (Script.Plutus a)) (Just (Script.Plutus b)) = Plutus.version a == Plutus.version b && Plutus.toBytes a == Plutus.toBytes b+ sameScript _ _ = False++checkBounds :: IO ()+checkBounds = do+ allValues <- must fixture+ let values = take 4 allValues+ starts = [minBound, -5, -4, -1, 0, 1, 3, 4, 5, maxBound]+ ends = [0, 1, 3, 4, 5, maxBound]+ forM_ [[], values] $ \source -> forM_ starts $ \start -> forM_ ends $ \end -> do+ listOracle 0 start end source Nothing >>= must >>= (@?= expectedSlice start end source)+ listOracle 1 start end source Nothing >>= must >>= (@?= expectedErase start end source)++checkRemoveIdentity :: IO ()+checkRemoveIdentity = do+ values <- must fixture+ case drop 2 values of+ canonical : retained : _ -> do+ assertBool "encoded datum equality is observable" (canonical /= retained)+ let source = [canonical, retained, canonical]+ expected = deleteBy sameUtxo retained source+ assertBool "plain Eq deletion has a different first match" (delete retained source /= expected)+ actual <- listOracle 2 0 0 source (Just retained) >>= must+ actual @?= ListReply True expected Nothing+ map Utxo.encodeCbor source @?= map Utxo.encodeCbor [canonical, retained, canonical]+ _ -> assertFailure "missing datum fixtures"+ case drop 4 values of+ canonical : retained : _ -> do+ assertBool "encoded native-script equality is observable" (canonical /= retained)+ let source = [canonical, retained, retained]+ listOracle 2 0 0 source (Just retained) >>= must >>= (@?= ListReply True (deleteBy sameUtxo retained source) Nothing)+ _ -> assertFailure "missing script fixtures"+ case values of+ base : _ -> do+ let key = Data.Integer 1+ bytes = Data.Bytes (B.pack [0, 255])+ fields = [Data.Integer 3, Data.Integer 4]+ first = (key, Data.List [Data.Bytes B.empty, Data.Constr 2 fields])+ second = (key, bytes)+ entries = [first, second]+ canonical = Data.fromData (Data.Map entries)+ different =+ [ Data.Map (reverse entries),+ Data.Map [first],+ Data.Map [(key, Data.List [Data.Constr 2 fields, Data.Bytes B.empty]), second],+ Data.Map [(key, Data.List [Data.Bytes B.empty, Data.Constr 3 fields]), second],+ Data.Map [(key, Data.List [Data.Bytes B.empty, Data.Constr 2 (reverse fields)]), second]+ ]+ make payload = do+ let original = Utxo.output base+ output <- Output.mkOutput (Output.address original) (Output.value original) (Datum.InlineDatum payload) Nothing+ pure (Utxo.utxo (Utxo.input base) output)+ B.take 2 (Data.toCbor canonical) @?= B.pack [162, 1]+ retained <- must (Data.decodeCbor (B.pack [162, 24, 1] <> B.drop 2 (Data.toCbor canonical)))+ prefix <- must (traverse (make . Data.fromData) different)+ normal <- must (make canonical)+ target <- must (make retained)+ assertBool "ordered maps, duplicate counts, lists and constructor fields remain distinct" (not (any (sameUtxo target) prefix))+ let source = prefix <> [normal, target, normal]+ listOracle 2 0 0 source (Just target) >>= must >>= (@?= ListReply True (prefix <> [target, normal]) Nothing)+ [] -> assertFailure "missing compound datum fixture"++checkImportIdentity :: IO ()+checkImportIdentity = do+ values <- must fixture+ case reverse values of+ value : _ -> do+ baseline <- must (importedUtxo value)+ let original = Utxo.output value+ expected = Utxo.output baseline+ bytes = Output.encodeCbor original+ expectedScript = Script.encodeCbor <$> Output.referenceScript expected+ assertBool "fixture distinguishes native import from exact public encoding" (value /= baseline)+ scriptOracle 0 bytes Nothing >>= must >>= (@?= ScriptReply expectedScript (Output.encodeCbor expected) expectedScript)+ listOracle 1 0 0 [value] Nothing >>= must >>= (@?= ListReply True [baseline] (Just []))+ case (Output.referenceScript original, Output.referenceScript expected) of+ (Just (Script.Plutus before), Just (Script.Plutus after)) -> Plutus.toBytes after @?= Plutus.toBytes before+ _ -> assertFailure "missing Plutus identity fixture"+ Output.encodeCbor original @?= bytes+ [] -> assertFailure "missing import fixture"++checkScriptReferences :: IO ()+checkScriptReferences = do+ values <- must fixture+ choices <- (Nothing :) . map Just <$> must scripts+ forM_ values $ \value -> forM_ choices $ \replacement -> do+ baseline <- must (importedOutput (Utxo.output value))+ requested <- must (traverse importedScript replacement)+ let original = Utxo.output value+ oldBytes = Script.encodeCbor <$> Output.referenceScript baseline+ bytes = Output.encodeCbor original+ indefinite = B.singleton 191 <> B.drop 1 bytes <> B.singleton 255+ expected <- must (Output.mkOutput (Output.address original) (Output.value original) (Output.datum original) requested)+ -- Native import normalizes map framing and Plutus bytestring envelopes.+ -- Inline datum/native-script CBOR and compiled program bytes remain exact;+ -- the original imported Haskell envelope remains unchanged throughout.+ imported <- must (Output.decodeCbor indefinite)+ actual <- scriptOracle 1 (Output.toCbor imported) replacement >>= must+ actual @?= ScriptReply oldBytes (Output.encodeCbor expected) (Script.encodeCbor <$> requested)+ Output.toCbor imported @?= indefinite+ forM_ [0, 2] $ \operation -> do+ unchanged <- scriptOracle operation bytes Nothing >>= must+ unchanged @?= ScriptReply oldBytes (Output.encodeCbor baseline) oldBytes++checkFailures :: IO ()+checkFailures = do+ values <- must fixture+ forM_ [B.empty, B.singleton 160, B.pack [129, 128], B.pack [129, 130, 128]] $ \invalid ->+ replicateM_ 3 (listBytesOracle 0 0 0 invalid B.empty >>= assertBool "malformed list accepted" . isLeft)+ forM_ [B.empty, B.singleton 128, B.pack [129, 128], B.pack [129, 130, 128]] $ \invalid ->+ replicateM_ 3 (scriptOracle 1 invalid Nothing >>= assertBool "malformed output accepted" . isLeft)+ case drop 4 values of+ value : _ -> do+ let partial = B.singleton 130 <> Utxo.encodeCbor value <> B.singleton 128+ listBytesOracle 0 0 0 partial B.empty >>= assertBool "partial list accepted" . isLeft+ forM_ [B.singleton 128, B.pack [130, 5, 64], B.pack [130, 0, 128, 0]] $ \invalid ->+ invoke (cScript 1) (Output.encodeCbor (Utxo.output value)) invalid scriptReplyDecoder >>= assertBool "malformed replacement accepted" . isLeft+ [] -> assertFailure "missing script fixture"+ baseline <- must (traverse importedUtxo values)+ listOracle 1 0 0 values Nothing >>= must >>= (@?= expectedErase 0 0 baseline)++propSlice :: Property+propSlice = property $ do+ choices <- evalEither fixture+ values <- forAll (Gen.list (Range.linear 0 15) (Gen.element choices))+ start <- forAll (Gen.int64 (Range.linear (-2) 18))+ end <- forAll (Gen.word64 (Range.linear 0 18))+ classify "empty range" (toInteger start == toInteger end)+ classify "out of bounds" (toInteger end > toInteger (length values))+ baseline <- evalEither (traverse importedUtxo values)+ actual <- evalIO (listOracle 0 start end values Nothing) >>= evalEither+ actual === expectedSlice start end baseline++propErase :: Property+propErase = property $ do+ choices <- evalEither fixture+ values <- forAll (Gen.list (Range.linear 0 15) (Gen.element choices))+ start <- forAll (Gen.int64 (Range.linear (-18) 18))+ count <- forAll (Gen.word64 (Range.linear 0 18))+ classify "negative relative index" (start < 0)+ classify "zero deletion" (count == 0)+ baseline <- evalEither (traverse importedUtxo values)+ actual <- evalIO (listOracle 1 start count values Nothing) >>= evalEither+ actual === expectedErase start count baseline++propRemove :: Property+propRemove = property $ do+ choices <- evalEither fixture+ values <- forAll (Gen.list (Range.linear 0 15) (Gen.element choices))+ target <- forAll (Gen.element choices)+ classify "semantic duplicates" (length (filter (sameUtxo target) values) > 1)+ classify "absent item" (not (any (sameUtxo target) values))+ baseline <- evalEither (traverse importedUtxo values)+ actual <- evalIO (listOracle 2 0 0 values (Just target)) >>= evalEither+ actual === ListReply True (deleteBy sameUtxo target baseline) Nothing++listOracle :: Int -> Int64 -> Word64 -> [Utxo.Utxo] -> Maybe Utxo.Utxo -> IO (Either String ListReply)+listOracle operation start count source target = listBytesOracle operation start count (encodeList source) (maybe B.empty Utxo.encodeCbor target)++listBytesOracle :: Int -> Int64 -> Word64 -> ByteString -> ByteString -> IO (Either String ListReply)+listBytesOracle operation start count source target = invoke (cList (fromIntegral operation) start count) source target listReplyDecoder++scriptOracle :: Int -> ByteString -> Maybe Script.Script -> IO (Either String ScriptReply)+scriptOracle operation source replacement = invoke (cScript (fromIntegral operation)) source (maybe B.empty Script.encodeCbor replacement) scriptReplyDecoder++invoke :: (Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt) -> ByteString -> ByteString -> (forall s. D.Decoder s a) -> IO (Either String a)+invoke operation source target decoder = B.useAsCStringLen source $ \(a, aSize) -> B.useAsCStringLen target $ \(b, bSize) ->+ allocaBytes 65536 $ \output -> alloca $ \size -> do+ code <- operation (castPtr a) (fromIntegral aSize) (castPtr b) (fromIntegral bSize) output 65536 size+ if code /= 0+ then pure (Left ("native collection status " <> show code))+ else do+ count <- peek size+ bytes <- B.packCStringLen (castPtr output, fromIntegral count)+ pure $ case R.deserialiseFromBytes decoder (L.fromStrict bytes) of+ Left failure -> Left (show failure)+ Right (rest, value) | L.null rest -> Right value+ Right _ -> Left "Trailing native reply"++listReplyDecoder :: D.Decoder s ListReply+listReplyDecoder = do+ count <- D.decodeListLen+ if count /= 3 then fail "Expected list reply" else ListReply <$> D.decodeBool <*> entries <*> optional entries+ where+ entries = D.decodeListLen >>= \size -> replicateM size (D.decodeBytes >>= either (fail . show) pure . Utxo.decodeCbor)++optional :: D.Decoder s a -> D.Decoder s (Maybe a)+optional decoder = do+ token <- D.peekTokenType+ if token == D.TypeNull then D.decodeNull >> pure Nothing else Just <$> decoder++scriptReplyDecoder :: D.Decoder s ScriptReply+scriptReplyDecoder = do+ count <- D.decodeListLen+ if count /= 3 then fail "Expected script reply" else ScriptReply <$> optional D.decodeBytes <*> D.decodeBytes <*> optional D.decodeBytes++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall safe "cometa_test_transaction_collection_list"+ cList :: CUInt -> Int64 -> Word64 -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt++foreign import ccall safe "cometa_test_transaction_collection_script"+ cScript :: CUInt -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr Word8 -> CSize -> Ptr CSize -> IO CInt
@@ -0,0 +1,225 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- These equations intentionally retain both sides of the advertised laws.+{- HLINT ignore "Functor law" -}+{- HLINT ignore "Use <$>" -}+{- HLINT ignore "Monad law, left identity" -}+{- HLINT ignore "Monad law, right identity" -}+{- HLINT ignore "Use >=>" -}+module TransactionDeferred (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Credential as Credential+import Cometa.Error (Error (InvalidBuildingRequest))+import Cometa.Evaluation (RedeemerId (..))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Protocol.ExUnits as ExUnits+import qualified Cometa.SubTransaction.Plan as SubPlan+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Deferred as Deferred+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Plan as Plan+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.Value as Value+import Control.Monad (forM_)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Word (Word64)+import qualified Hedgehog as H+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Deferred redeemer queries"+ [ testCase "required indices match ordinary draft observers" indices,+ testCase "missing objects and ambiguous outputs fail explicitly" failures,+ testCase "callback adapters match raw callbacks and retain exact data" callbacks,+ testProperty "Functor, Applicative and Monad laws share one draft" laws+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++data Fixture = Fixture+ { fixtureTransaction :: Tx.Transaction,+ fixtureSelected :: [Utxo.Utxo],+ fixtureOutput :: Output.Output,+ fixtureReference :: Input.Input,+ fixturePolicy :: Policy.PolicyId,+ fixtureAccount :: Reward.RewardAddress,+ fixtureVoter :: Voting.Voter,+ fixtureProposal :: Proposal.Proposal+ }++fixture :: IO Fixture+fixture = do+ hash <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ payment <- must (Credential.keyHashFromBytes (B.replicate 28 1))+ drep <- must (Credential.keyHashFromBytes (B.replicate 28 2))+ txid <- must (TxId.fromBytes (B.replicate 32 3))+ policy <- must (Policy.fromBytes (B.replicate 28 4))+ assetName <- must (AssetName.fromBytes B.empty)+ url <- must (Anchor.mkUrl "https://example.com/proposal")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 5))+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential hash)+ address = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential payment))+ reference = Input.input txid 7+ later = Input.input txid 256+ voter = Voting.DRepVoter (Credential.KeyCredential drep)+ anchor = Anchor.Anchor url digest+ proposal = Proposal.Proposal 1 account Action.InfoAction anchor+ votes = Voting.singleton voter (ActionId.ActionId txid 0) (Voting.VotingProcedure Voting.Yes Nothing)+ output <- must (Output.mkOutput address (Value.lovelace 2000000) Datum.NoDatum Nothing)+ withdrawals <- must (Fields.mkEntries [(account, 0)])+ mint <- must (Fields.mkMint (Value.fromList [(Asset.Native policy assetName, 1)]))+ let proposals = Proposal.fromList [proposal]+ let fields =+ (Fields.fields [later, reference] [output])+ { Fields.fieldReferenceInputs = Just [later, reference],+ Fields.fieldMint = Just mint,+ Fields.fieldWithdrawals = Just withdrawals,+ Fields.fieldVotingProcedures = Just votes,+ Fields.fieldProposalProcedures = Just proposals+ }+ dataValue = Data.fromData (Data.Integer 1)+ redeemer = Redeemer.Redeemer Redeemer.Spending 0 dataValue (ExUnits.ExUnits 0 0)+ body <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = fields}))+ witnesses <- must (Witnesses.mkWitnesses [] [] [] [] [redeemer])+ pure (Fixture (Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing) [Utxo.utxo reference output] output reference policy account voter proposal)++indices :: IO ()+indices = do+ f <- fixture+ let tx = fixtureTransaction f+ run query = Deferred.run query tx (fixtureSelected f)+ cases =+ [ (Deferred.inputIndex (fixtureReference f), Indices.findInput (fixtureReference f) tx),+ (Deferred.referenceInputIndex (fixtureReference f), Indices.findReferenceInput (fixtureReference f) tx),+ (Deferred.mintPolicyIndex (fixturePolicy f), Indices.findMintPolicy (fixturePolicy f) tx),+ (Deferred.withdrawalIndex (fixtureAccount f), Indices.findWithdrawal (fixtureAccount f) tx),+ (Deferred.voteIndex (fixtureVoter f), Indices.findVote (fixtureVoter f) tx),+ (Deferred.proposalIndex (fixtureProposal f), Indices.findProposal (fixtureProposal f) tx),+ (Deferred.redeemerIndex (RedeemerId Redeemer.Spending 0), Indices.findRedeemer (RedeemerId Redeemer.Spending 0) tx)+ ]+ forM_ cases $ \(query, ordinary) -> do+ ordinary @?= Just 0+ run query @?= Right 0+ run (Deferred.outputIndex (fixtureOutput f)) @?= Right 0+ run (Deferred.outputIndexWhere ((== Output.address (fixtureOutput f)) . Output.address)) @?= Right 0+ fmap Tx.encodeCbor (run Deferred.draft) @?= Right (Tx.encodeCbor tx)+ run Deferred.selectedInputs @?= Right (fixtureSelected f)+ Deferred.run Deferred.selectedInputs tx (reverse (fixtureSelected f <> fixtureSelected f)) @?= Right (reverse (fixtureSelected f <> fixtureSelected f))++failures :: IO ()+failures = do+ f <- fixture+ body <- must (Body.fromBody (Body.body [] [] 0))+ let empty = Tx.fromBody body+ queries =+ [ Deferred.inputIndex (fixtureReference f),+ Deferred.referenceInputIndex (fixtureReference f),+ Deferred.mintPolicyIndex (fixturePolicy f),+ Deferred.withdrawalIndex (fixtureAccount f),+ Deferred.voteIndex (fixtureVoter f),+ Deferred.proposalIndex (fixtureProposal f),+ Deferred.redeemerIndex (RedeemerId Redeemer.Spending 0),+ Deferred.outputIndex (fixtureOutput f)+ ]+ forM_ queries $ \query -> assertBool "Missing index succeeded" (isLeft (Deferred.run query empty []))+ Deferred.run (Deferred.outputIndex (fixtureOutput f)) empty [] @?= Left (InvalidBuildingRequest "Deferred output is missing")+ duplicateBody <- must (Body.fromBody (Body.body [] [fixtureOutput f, fixtureOutput f] 0))+ Deferred.run (Deferred.outputIndex (fixtureOutput f)) (Tx.fromBody duplicateBody) [] @?= Left (InvalidBuildingRequest "Deferred output is ambiguous")+ Deferred.run (Deferred.outputIndexWhere (const True)) (Tx.fromBody duplicateBody) [] @?= Left (InvalidBuildingRequest "Deferred output is ambiguous")+ let failure = InvalidBuildingRequest "application validation"+ Deferred.run (Deferred.fromEither (Left failure) >> Deferred.inputIndex (fixtureReference f)) empty [] @?= Left failure++callbacks :: IO ()+callbacks = do+ f <- fixture+ let query = (,) <$> Deferred.inputIndex (fixtureReference f) <*> Deferred.outputIndex (fixtureOutput f)+ encode :: (Word64, Word64) -> Data.PlutusData+ encode (input, output) = Data.List [Data.Integer (toInteger input), Data.Integer (toInteger output)]+ callback :: Plan.DeferredRedeemer+ callback = Deferred.redeemer encode query+ subCallback :: SubPlan.DeferredRedeemer+ subCallback = callback+ raw tx _ = do+ input <- maybe (Left (InvalidBuildingRequest "raw input missing")) Right (Indices.findInput (fixtureReference f) tx)+ pure (Data.fromData (encode (input, 0)))+ callback (fixtureTransaction f) (fixtureSelected f) @?= raw (fixtureTransaction f) (fixtureSelected f)+ subCallback (fixtureTransaction f) (fixtureSelected f) @?= callback (fixtureTransaction f) (fixtureSelected f)+ -- Each callback reads its new draft; previously observed positions are not cached.+ let originalBody = Body.toBody (Tx.body (fixtureTransaction f))+ originalFields = Body.bodyFields originalBody+ preceding = Input.input (Input.transactionId (fixtureReference f)) 0+ changedFields = originalFields {Fields.fieldInputs = preceding : Fields.fieldInputs originalFields}+ changedBody <- must (Body.fromBody (originalBody {Body.bodyFields = changedFields}))+ let changed = Tx.fromBody changedBody+ callback changed (fixtureSelected f) @?= Right (Data.fromData (encode (1, 0)))+ callback (fixtureTransaction f) (fixtureSelected f) @?= Right (Data.fromData (encode (0, 0)))+ -- Nonminimal integer encoding remains exact through encodedRedeemer.+ exact <- must (Data.decodeCbor (B.pack [0x18, 0x01]))+ fmap Data.toCbor (Deferred.encodedRedeemer (pure exact) (fixtureTransaction f) (fixtureSelected f)) @?= Right (B.pack [0x18, 0x01])+ let failure = InvalidBuildingRequest "application failure"+ Deferred.redeemer Data.Integer (Deferred.fromEither (Left failure)) (fixtureTransaction f) [] @?= Left failure++laws :: H.Property+laws = H.property $ do+ f <- H.evalIO fixture+ value <- H.forAll (Gen.integral (Range.linear (-100) 100) :: H.Gen Integer)+ fails <- H.forAll Gen.bool+ let run computation = Deferred.run computation (fixtureTransaction f) (fixtureSelected f)+ query = if fails then Deferred.fromEither (Left (InvalidBuildingRequest "law failure")) else (+ value) . toInteger <$> Deferred.inputIndex (fixtureReference f)+ step number = if even number then pure (number + 3) else Deferred.fromEither (Left (InvalidBuildingRequest "odd"))+ next number = (+ number) . toInteger <$> Deferred.outputIndex (fixtureOutput f)+ run (fmap id query) H.=== run query+ run (fmap ((+ 1) . (* 2)) query) H.=== run (fmap (+ 1) (fmap (* 2) query))+ run (pure id <*> query) H.=== run query+ run (pure (+ 1) <*> pure value) H.=== Right (value + 1)+ run (pure (.) <*> pure (+ 1) <*> pure (* 2) <*> query) H.=== run (pure (+ 1) <*> (pure (* 2) <*> query))+ run (pure (+ 1) <*> pure value) H.=== run (pure ($ value) <*> pure (+ 1))+ run (pure value >>= step) H.=== run (step value)+ run (query >>= pure) H.=== run query+ run ((query >>= step) >>= next) H.=== run (query >>= (\number -> step number >>= next))
@@ -0,0 +1,180 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE ForeignFunctionInterface #-}++module TransactionIndices (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as E+import qualified Cometa.Address as Address+import qualified Cometa.Internal.TransactionCbor as Cbor+import qualified Cometa.PolicyId as Policy+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Indices as Indices+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.TransactionId as TxId+import Control.Monad (forM_)+import Data.ByteString (ByteString)+import qualified Data.ByteString as B+import Data.Either (isLeft)+import Data.Word (Word64, Word8)+import Foreign.C.Types (CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (alloca)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Transaction indices"+ [ testCase "sorted input and reference positions agree with native" inputs,+ testCase "output order, address and minimum agree with native" outputs,+ testCase "zero and empty imported mint policies retain positions" mintPolicies,+ testCase "absent collections and unsigned output threshold boundaries" absent+ ]++-- Intentionally noncanonical input/policy order, repeated spending reference,+-- empty and zero-only policies. These public decoded values retain exact bytes.+fixture :: IO Tx.Transaction+fixture = require (Tx.decodeCbor (Cbor.encode encoding))+ where+ encoding = E.encodeListLen 4 <> body <> E.encodeMapLen 0 <> E.encodeBool True <> E.encodeNull+ body =+ E.encodeMapLen 5+ <> E.encodeWord 0+ <> inputSet [(2, 0), (1, 256), (1, 24), (1, 24)]+ <> E.encodeWord 1+ <> E.encodeListLen 3+ <> output 0 2+ <> output 1 10+ <> output 0 10+ <> E.encodeWord 2+ <> E.encodeWord 0+ <> E.encodeWord 9+ <> E.encodeMapLen 3+ <> E.encodeBytes (policyBytes 3)+ <> E.encodeMapLen 1+ <> E.encodeBytes B.empty+ <> E.encodeInt (-2)+ <> E.encodeBytes (policyBytes 1)+ <> E.encodeMapLen 0+ <> E.encodeBytes (policyBytes 2)+ <> E.encodeMapLen 1+ <> E.encodeBytes B.empty+ <> E.encodeWord 0+ <> E.encodeWord 18+ <> inputSet [(2, 1), (1, 256), (1, 24)]+ inputSet values = E.encodeTag 258 <> E.encodeListLen (fromIntegral (length values)) <> foldMap reference values+ reference (seed, index) = E.encodeListLen 2 <> E.encodeBytes (idBytes seed) <> E.encodeWord64 index+ output seed amount = E.encodeListLen 2 <> E.encodeBytes (addressBytes seed) <> E.encodeWord amount++inputs :: IO ()+inputs = do+ transaction <- fixture+ forM_ [(1, 24, Just 0, Just 0), (1, 256, Just 2, Just 1), (2, 0, Just 3, Nothing), (2, 1, Nothing, Just 2), (3, 0, Nothing, Nothing)] $ \(seed, index, spend, reference) -> do+ identifier <- require (TxId.fromBytes (idBytes seed))+ let key = Input.input identifier index+ Indices.findInput key transaction @?= spend+ Indices.findReferenceInput key transaction @?= reference+ native transaction 0 (idBytes seed) index >>= (@?= spend)+ native transaction 1 (idBytes seed) index >>= (@?= reference)++outputs :: IO ()+outputs = do+ transaction <- fixture+ forM_ [(0, 0, Just 0), (0, 2, Just 0), (0, 3, Just 2), (0, 10, Just 2), (0, 11, Nothing), (1, 10, Just 1), (2, 0, Nothing)] $ \(seed, minimumLovelace, expected) -> do+ destination <- require (Address.fromBytes (addressBytes seed))+ Indices.findOutput destination minimumLovelace transaction @?= expected+ native transaction 2 (addressBytes seed) minimumLovelace >>= (@?= expected)++mintPolicies :: IO ()+mintPolicies = do+ let duplicatePolicies =+ Cbor.encode+ ( E.encodeListLen 4+ <> E.encodeMapLen 4+ <> E.encodeWord 0+ <> E.encodeListLen 0+ <> E.encodeWord 1+ <> E.encodeListLen 0+ <> E.encodeWord 2+ <> E.encodeWord 0+ <> E.encodeWord 9+ <> E.encodeMapLen 2+ <> E.encodeBytes (policyBytes 1)+ <> E.encodeMapLen 0+ <> E.encodeBytes (policyBytes 1)+ <> E.encodeMapLen 0+ <> E.encodeMapLen 0+ <> E.encodeBool True+ <> E.encodeNull+ )+ assertBool "duplicate imported policy keys rejected" (isLeft (Tx.decodeCbor duplicatePolicies))+ transaction <- fixture+ forM_ [(1, Just 0), (2, Just 1), (3, Just 2), (4, Nothing)] $ \(seed, expected) -> do+ policy <- require (Policy.fromBytes (policyBytes seed))+ Indices.findMintPolicy policy transaction @?= expected+ native transaction 3 (policyBytes seed) 0 >>= (@?= expected)++absent :: IO ()+absent = do+ body <- require (Body.fromBody (Body.body [] [] 0))+ let transaction = Tx.fromBody body+ identifier <- require (TxId.fromBytes (idBytes 1))+ policy <- require (Policy.fromBytes (policyBytes 1))+ destination <- require (Address.fromBytes (addressBytes 0))+ Indices.findInput (Input.input identifier 0) transaction @?= Nothing+ Indices.findReferenceInput (Input.input identifier 0) transaction @?= Nothing+ Indices.findOutput destination 0 transaction @?= Nothing+ Indices.findMintPolicy policy transaction @?= Nothing+ populated <- fixture+ Indices.findOutput destination 9223372036854775808 populated @?= Nothing+ Indices.findOutput destination maxBound populated @?= Nothing+ native populated 2 (addressBytes 0) 9223372036854775807 >>= (@?= Nothing)++idBytes :: Word8 -> ByteString+idBytes = B.replicate 32++policyBytes :: Word8 -> ByteString+policyBytes = B.replicate 28++addressBytes :: Word8 -> ByteString+addressBytes seed = B.cons 0x60 (B.replicate 28 seed)++require :: (Show error) => Either error value -> IO value+require = either (\failure -> assertFailure (show failure) >> fail "invalid fixture") pure++native :: Tx.Transaction -> CUInt -> ByteString -> Word64 -> IO (Maybe Word64)+native transaction operation key argument =+ B.useAsCStringLen (Tx.encodeCbor transaction) $ \(bytes, size) ->+ B.useAsCStringLen key $ \(keyBytes, keySize) -> alloca $ \result -> do+ status <- cIndex (castPtr bytes) (fromIntegral size) operation (castPtr keyBytes) (fromIntegral keySize) argument result+ if status == 0+ then Just <$> peek result+ else do+ -- CARDANO_ERROR_ELEMENT_NOT_FOUND, lib/include/cardano/error.h.+ status @?= 9+ pure Nothing++-- FOREIGN IMPORTS ------------------------------------------------------------++foreign import ccall unsafe "cometa_test_transaction_index"+ cIndex :: Ptr Word8 -> CSize -> CUInt -> Ptr Word8 -> CSize -> Word64 -> Ptr Word64 -> IO CUInt
@@ -0,0 +1,898 @@+-- Copyright 2026 Biglup Labs+-- SPDX-License-Identifier: Apache-2.0+--+-- Licensed under the Apache License, Version 2.0 (the "License");+-- you may not use this file except in compliance with the License.+-- You may obtain a copy of the License at+--+-- https://www.apache.org/licenses/LICENSE-2.0+--+-- Unless required by applicable law or agreed to in writing, software+-- distributed under the License is distributed on an "AS IS" BASIS,+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+-- See the License for the specific language governing permissions and+-- limitations under the License.+{-# LANGUAGE OverloadedStrings #-}++-- | Complete pinned transaction JSON fixtures and fresh-owner failure paths.+module TransactionInspection (tests) where++-- IMPORTS --------------------------------------------------------------------++import qualified Codec.CBOR.Encoding as Encoding+import qualified Codec.CBOR.Write as Write+import qualified Cometa.Address as Address+import qualified Cometa.Address.Reward as Reward+import qualified Cometa.Address.Shelley as Shelley+import qualified Cometa.AssetId as Asset+import qualified Cometa.AssetName as AssetName+import qualified Cometa.Certificate as Certificate+import qualified Cometa.Certificate.Collection as Certificates+import qualified Cometa.Credential as Credential+import qualified Cometa.Crypto.Blake2b as Hash+import qualified Cometa.Crypto.Ed25519.PublicKey as PublicKey+import qualified Cometa.Crypto.Ed25519.Signature as Signature+import qualified Cometa.Encoding.Collections as Collections+import Cometa.Error (Error (InvalidValueCbor, InvalidValueQuantity))+import qualified Cometa.Governance.Action as Action+import qualified Cometa.Governance.ActionId as ActionId+import qualified Cometa.Governance.Anchor as Anchor+import qualified Cometa.Governance.Committee as Committee+import qualified Cometa.Governance.Constitution as Constitution+import qualified Cometa.Governance.DRep as DRep+import qualified Cometa.Governance.Proposal as Proposal+import qualified Cometa.Governance.Voting as Voting+import qualified Cometa.Inspection as Standalone+import qualified Cometa.Internal.Hex as Hex+import qualified Cometa.Internal.Inspection as Internal+import qualified Cometa.Metadata as Metadata+import qualified Cometa.NetworkId as Network+import qualified Cometa.PlutusData as Data+import qualified Cometa.PolicyId as PolicyId+import qualified Cometa.Pool.BlsKey as Bls+import qualified Cometa.Pool.Metadata as PoolMetadata+import qualified Cometa.Pool.Parameters as Pool+import qualified Cometa.Pool.Relay as Relay+import qualified Cometa.Protocol.CostModels as Models+import qualified Cometa.Protocol.DRepVotingThresholds as DRepThresholds+import qualified Cometa.Protocol.ExUnitPrices as Prices+import qualified Cometa.Protocol.ExUnits as ExUnits+import qualified Cometa.Protocol.Parameters.Update as Update+import qualified Cometa.Protocol.PoolVotingThresholds as PoolThresholds+import qualified Cometa.Protocol.ProposedUpdates as Proposed+import qualified Cometa.Protocol.Rational as Rational+import qualified Cometa.Protocol.Version as Version+import qualified Cometa.Script as Script+import qualified Cometa.Script.Native as Native+import qualified Cometa.Script.Plutus as Plutus+import qualified Cometa.SubTransaction as Sub+import qualified Cometa.SubTransaction.Body as SubBody+import qualified Cometa.Transaction as Tx+import qualified Cometa.Transaction.AuxiliaryData as Auxiliary+import qualified Cometa.Transaction.Body as Body+import qualified Cometa.Transaction.Datum as Datum+import qualified Cometa.Transaction.Fields as Fields+import qualified Cometa.Transaction.Input as Input+import qualified Cometa.Transaction.Inspection as Inspection+import qualified Cometa.Transaction.Output as Output+import qualified Cometa.Transaction.Redeemer as Redeemer+import qualified Cometa.Transaction.Utxo as Utxo+import qualified Cometa.Transaction.Witness as Witness+import qualified Cometa.Transaction.Witnesses as Witnesses+import qualified Cometa.TransactionId as TxId+import qualified Cometa.UnitInterval as Unit+import qualified Cometa.Value as Coin+import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (SomeException, evaluate, throwIO)+import Control.Monad (forM, forM_, replicateM, replicateM_, (>=>))+import Data.Aeson (Value (..), eitherDecodeStrict', encode, object, toJSON, (.=))+import Data.Aeson.Key (Key)+import qualified Data.Aeson.KeyMap as KeyMap+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as Lazy+import Data.Either (isLeft)+import Data.Foldable (toList)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromMaybe)+import qualified Data.Set as Set+import qualified Data.Text as Text+import qualified Fixtures.Inspection as Fixture+import System.Mem (performGC)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- DEFINITIONS ----------------------------------------------------------------++tests :: TestTree+tests =+ testGroup+ "Transaction JSON inspection"+ [ testCase "remaining asset, hash, pool and governance native schemas" remainingInspection,+ testCase "native array and tagged subtype equivalences retain schema and ordering" inspectionArrayEquivalence,+ testCase "protocol collections and Dijkstra standalone schemas match parent fields" standaloneCollections,+ testCase "standalone leaf schemas, optional fields and native lifetime boundaries" standaloneLeaves,+ testCase "standalone leaf inspectors reject complete schema-invalid CBOR" standaloneLeafFailures,+ testCase "standalone values match typed fields of pinned transaction JSON" standaloneCorpus,+ testCase "standalone governance, certificates, pools and protocol fields" standaloneDomains,+ testCase "complete pinned Conway/Dijkstra and native rich JSON matches" corpus,+ testCase "inspection leaves exact bytes, transaction IDs and signatures unchanged" identities,+ testCase "arbitrary integers and binary data retain their JSON meaning" largeValues,+ testCase "malformed, truncated and trailing CBOR fail on every native entrypoint" failures,+ testCase "repeated calls and returned JSON outlive cleanup and collection" repeated,+ testCase "independent concurrent inspections return complete snapshots" concurrent+ ]++must :: (Show error) => Either error value -> IO value+must = either (\failure -> assertFailure (show failure) >> fail "fixture") pure++load :: Fixture.Fixture -> IO (Tx.Transaction, Value)+load fixture = do+ bytes <- maybe (assertFailure "Invalid fixture hexadecimal" >> fail "fixture") pure (Hex.decodeHex (Fixture.fixtureCbor fixture))+ transaction <- must (Tx.decodeCbor bytes)+ expected <- must (eitherDecodeStrict' (Fixture.fixtureJson fixture))+ pure (transaction, expected)++field :: Key -> Value -> IO Value+field key (Object values) = maybe (assertFailure "Missing expected JSON field" >> fail "fixture") pure (KeyMap.lookup key values)+field _ _ = assertFailure "Expected JSON object" >> fail "fixture"++corpus :: IO ()+corpus = forM_ Fixture.fixtures $ \fixture -> do+ (transaction, expected) <- load fixture+ Inspection.transaction transaction >>= (@?= Right expected)+ expectedBody <- field "body" expected+ Inspection.body (Tx.body transaction) >>= (@?= Right expectedBody)+ let subs = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ expectedSubs <- case expectedBody of+ Object values -> case KeyMap.lookup "sub_transactions" values of+ Nothing -> pure []+ Just (Array values') -> pure (toList values')+ _ -> assertFailure "Invalid expected subtransaction array" >> fail "fixture"+ _ -> assertFailure "Invalid expected body" >> fail "fixture"+ length subs @?= length expectedSubs+ forM_ (zip subs expectedSubs) $ \(sub, json) -> do+ Inspection.subTransaction sub >>= (@?= Right json)+ expectedSubBody <- field "body" json+ Inspection.subBody (Sub.body sub) >>= (@?= Right expectedSubBody)+ case json of+ Object values -> do+ assertBool "subtransaction acquired a validity flag" (not (KeyMap.member "is_valid" values))+ case expectedSubBody of+ Object fields -> assertBool "subtransaction acquired a fee" (not (KeyMap.member "fee" fields))+ _ -> assertFailure "Invalid expected subtransaction body"+ _ -> assertFailure "Invalid expected subtransaction"++identities :: IO ()+identities = forM_ Fixture.fixtures $ \fixture -> do+ (transaction, _) <- load fixture+ let original = Tx.encodeCbor transaction+ witnessBytes = Witnesses.toCbor (Tx.witnesses transaction)+ subs = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ subBytes = map Sub.encodeCbor subs+ originalId <- Tx.transactionId transaction+ _ <- Inspection.transaction transaction >>= must+ mapM_ (Inspection.subTransaction >=> must) subs+ Tx.encodeCbor transaction @?= original+ Witnesses.toCbor (Tx.witnesses transaction) @?= witnessBytes+ Tx.transactionId transaction >>= (@?= originalId)+ map Sub.encodeCbor subs @?= subBytes++largeValues :: IO ()+largeValues = do+ let huge = 2 ^ (160 :: Int) + 3+ datum = Data.fromData (Data.List [Data.Integer huge, Data.Integer (negate huge), Data.Bytes (B.pack [0, 255, 128, 0])])+ expectedDatum =+ object+ [ "tag" .= ("list" :: Text.Text),+ "contents"+ .= [ object ["tag" .= ("integer" :: Text.Text), "value" .= Text.pack (show huge)],+ object ["tag" .= ("integer" :: Text.Text), "value" .= Text.pack (show (negate huge))],+ object ["tag" .= ("bytes" :: Text.Text), "value" .= ("00ff8000" :: Text.Text)]+ ]+ ]+ body <- must (Body.fromBody (Body.body [] [] maxBound))+ witnesses <- must (Witnesses.mkWitnesses [] [] [] [datum] [])+ let transaction = Tx.assemble body (Witnesses.fromWitnesses witnesses) Nothing+ expected = object ["body" .= object ["inputs" .= ([] :: [Value]), "outputs" .= ([] :: [Value]), "fee" .= ("18446744073709551615" :: Text.Text)], "is_valid" .= True, "witness_set" .= object ["plutus_data" .= [expectedDatum]]]+ Inspection.transaction transaction >>= (@?= Right expected)+ Standalone.plutusData datum >>= (@?= Right expectedDatum)++failures :: IO ()+failures = do+ let invalid = [B.empty, B.singleton 0xff, B.singleton 0xa1, B.singleton 0xf6]+ replicateM_ 25 $ forM_ [0 .. 25] $ \kind -> forM_ invalid (Internal.runUnchecked kind >=> (assertBool "Malformed CBOR inspection succeeded" . isLeft))+ forM_ Fixture.fixtures $ \fixture -> do+ (transaction, _) <- load fixture+ Internal.runUnchecked 0 (Tx.encodeCbor transaction <> B.singleton 0) >>= assertBool "Trailing transaction bytes accepted" . isLeft+ Internal.runUnchecked 2 (Body.toCbor (Tx.body transaction) <> B.singleton 0) >>= assertBool "Trailing body bytes accepted" . isLeft+ forM_ (fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))) $ \sub -> do+ Internal.runUnchecked 1 (Sub.encodeCbor sub <> B.singleton 0) >>= assertBool "Trailing subtransaction bytes accepted" . isLeft+ Internal.runUnchecked 3 (SubBody.toCbor (Sub.body sub) <> B.singleton 0) >>= assertBool "Trailing sub-body bytes accepted" . isLeft+ Internal.runUnchecked 99 B.empty >>= assertBool "Unknown native inspection operation succeeded" . isLeft+ assertBool "Invalid CBOR constructed a public transaction" (isLeft (Tx.decodeCbor (B.singleton 0xff)))++repeated :: IO ()+repeated = forM_ Fixture.fixtures $ \fixture -> do+ (transaction, expected) <- load fixture+ values <- replicateM 20 (Inspection.transaction transaction >>= must)+ performGC+ map encode values @?= replicate 20 (encode expected)++concurrent :: IO ()+concurrent = do+ fixtures <- traverse load Fixture.fixtures+ completions <- forM fixtures $ \(transaction, expected) -> do+ finished <- newEmptyMVar+ _ <-+ forkFinally+ ( do+ Inspection.transaction transaction >>= (@?= Right expected)+ expectedWitnesses <- field "witness_set" expected+ Standalone.witnesses (Tx.witnesses transaction) >>= (@?= Right expectedWitnesses)+ )+ (putMVar finished)+ pure finished+ forM_ completions $ \finished -> do+ outcome <- takeMVar finished+ either (throwIO :: SomeException -> IO ()) pure outcome++optionalArray :: Key -> Value -> IO [Value]+optionalArray key (Object fields) = case KeyMap.lookup key fields of+ Nothing -> pure []+ Just (Array values) -> pure (toList values)+ _ -> assertFailure "Expected JSON array" >> fail "fixture"+optionalArray _ _ = assertFailure "Expected JSON object" >> fail "fixture"++standaloneCorpus :: IO ()+standaloneCorpus = forM_ Fixture.fixtures $ \fixture -> do+ (transaction, expected) <- load fixture+ expectedBody <- field "body" expected+ expectedWitnesses <- field "witness_set" expected+ inspectFields (Body.bodyFields (Body.toBody (Tx.body transaction))) (Tx.witnesses transaction) expectedBody expectedWitnesses+ forM_ (Tx.auxiliaryData transaction) $ \aux -> do+ json <- field "auxiliary_data" expected+ inspectAuxiliary aux json+ let subs = fromMaybe [] (Body.bodySubTransactions (Body.toBody (Tx.body transaction)))+ expectedSubs <- optionalArray "sub_transactions" expectedBody+ forM_ (zip subs expectedSubs) $ \(sub, json) -> do+ subBody <- field "body" json+ subWitnesses <- field "witness_set" json+ inspectFields (SubBody.fields (SubBody.toBody (Sub.body sub))) (Sub.witnesses sub) subBody subWitnesses+ forM_ (Sub.auxiliaryData sub) $ \aux -> field "auxiliary_data" json >>= inspectAuxiliary aux+ where+ inspectAuxiliary auxiliary json = do+ Standalone.auxiliaryData auxiliary >>= (@?= Right json)+ forM_ (Auxiliary.metadata (Auxiliary.toAuxiliaryData auxiliary)) $ \encoded -> do+ expectedMetadata <- field "metadata" json+ let metadata = Metadata.toMetadata encoded+ Standalone.metadata metadata >>= (@?= Right expectedMetadata)+ entries <- case expectedMetadata of+ Array items -> pure (toList items)+ _ -> assertFailure "Expected metadata entries" >> fail "fixture"+ forM_ (zip (Metadata.toList metadata) entries) $ \((_, metadatum), entry) ->+ field "value" entry >>= \expectedValue -> Standalone.metadatum metadatum >>= (@?= Right expectedValue)+ inspectFields fields witnesses bodyJson witnessJson = do+ Standalone.witnesses witnesses >>= (@?= Right witnessJson)+ inputs <- optionalArray "inputs" bodyJson+ forM_ (zip (Fields.fieldInputs fields) inputs) $ \(reference, json) -> Standalone.input reference >>= (@?= Right json)+ outputs <- optionalArray "outputs" bodyJson+ length outputs @?= length (Fields.fieldOutputs fields)+ forM_ (zip (Fields.fieldOutputs fields) outputs) $ \(output, json) -> do+ Standalone.output output >>= (@?= Right json)+ amount <- field "amount" json+ Standalone.value (Output.value output) >>= (@?= Right amount)+ let expectedDatum = case json of+ Object entries -> KeyMap.lookup "datum" entries+ _ -> Nothing+ Standalone.datum (Output.datum output) >>= (@?= Right expectedDatum)+ reference <- Input.input <$> must (TxId.fromBytes (B.replicate 32 0)) <*> pure 0+ let inputJson = object ["transaction_id" .= Text.replicate 64 "0", "index" .= (0 :: Int)]+ Standalone.utxo (Utxo.utxo reference output) >>= (@?= Right (object ["input" .= inputJson, "output" .= json]))+ certs <- optionalArray "certs" bodyJson+ forM_ (zip (maybe [] Certificates.toList (Fields.fieldCertificates fields)) certs) $ \(cert, json) ->+ Standalone.certificate cert >>= (@?= Right json)+ let typed = Witnesses.toWitnesses witnesses+ keyJson <- optionalArray "vkey_witnesses" witnessJson+ bootstrapJson <- optionalArray "bootstraps" witnessJson+ traverse (Standalone.verificationWitness >=> must) (Witnesses.verificationWitnesses typed) >>= (@?= keyJson)+ traverse (Standalone.bootstrapWitness >=> must) (Witnesses.bootstrapWitnesses typed) >>= (@?= bootstrapJson)+ redeemers <- optionalArray "redeemers" witnessJson+ forM_ (zip (Witnesses.redeemers typed) redeemers) $ \(redeemer, json) -> Standalone.redeemer redeemer >>= (@?= Right json)+ datums <- optionalArray "plutus_data" witnessJson+ forM_ (zip (Witnesses.datums typed) datums) $ \(datum, json) -> Standalone.plutusData datum >>= (@?= Right json)+ nativeJson <- optionalArray "native_scripts" witnessJson+ plutusJson <- optionalArray "plutus_scripts" witnessJson+ let scripts = Witnesses.scripts typed+ natives = [native | Script.Native native <- scripts]+ plutuses = [plutus | Script.Plutus plutus <- scripts]+ length natives @?= length nativeJson+ length plutuses @?= length plutusJson+ forM_ (zip natives nativeJson) $ \(native, json) -> do+ Standalone.nativeScript native >>= (@?= Right json)+ Standalone.script (Script.Native native) >>= (@?= Right (object ["tag" .= ("native_script" :: Text.Text), "value" .= json]))+ forM_ (zip plutuses plutusJson) $ \(plutus, json) -> do+ Standalone.plutusScript plutus >>= (@?= Right json)+ Standalone.script (Script.Plutus plutus) >>= (@?= Right (object ["tag" .= ("plutus_script" :: Text.Text), "value" .= json]))++keyFixture :: IO (Credential.KeyHash purpose)+keyFixture = must (Credential.keyHashFromBytes (B.replicate 28 1))++standaloneDomains :: IO ()+standaloneDomains = do+ stakeKey <- keyFixture+ poolKey <- keyFixture+ drepKey <- keyFixture+ coldKey <- keyFixture+ hotKey <- keyFixture+ genesis <- keyFixture+ delegate <- keyFixture+ scriptHash <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 3))+ margin <- must (Unit.mkUnitInterval 1 5)+ url <- must (Anchor.mkUrl "https://example.com/proposal")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 4))+ txid <- must (TxId.fromBytes (B.replicate 32 5))+ let stake = Credential.KeyCredential stakeKey+ drep = Credential.KeyCredential drepKey+ account = Reward.fromCredential Network.testnet stake+ anchor = Anchor.Anchor url digest+ keyJson = object ["tag" .= ("pubkey_hash" :: Text.Text), "value" .= Text.replicate 28 "01"]+ scriptJson = object ["tag" .= ("script_hash" :: Text.Text), "value" .= Text.replicate 28 "02"]+ anchorJson = object ["url" .= ("https://example.com/proposal" :: Text.Text), "data_hash" .= Text.replicate 32 "04"]+ identifier = ActionId.ActionId txid 65535+ identifierJson = object ["transaction_id" .= Text.replicate 32 "05", "gov_action_index" .= ("65535" :: Text.Text)]+ pool = Pool.PoolParameters poolKey vrf Nothing 10000 1000 margin account (Set.singleton stakeKey) [] Nothing+ changes = Update.empty {Update.updateMinFeeA = Just maxBound}+ changeJson = object ["min_fee_a" .= ("18446744073709551615" :: Text.Text)]+ paymentKey <- keyFixture+ let native = Native.allOf [Native.signature paymentKey]+ pubkeyJson = object ["tag" .= ("pubkey" :: Text.Text), "pubkey" .= Text.replicate 28 "01"]+ nativeJson = object ["tag" .= ("all" :: Text.Text), "scripts" .= [pubkeyJson]]+ Standalone.nativeScript native >>= (@?= Right nativeJson)+ guardKey <- keyFixture+ let nativeCases =+ [ (Native.signature paymentKey, pubkeyJson),+ (Native.anyOf [Native.signature paymentKey], object ["tag" .= ("any" :: Text.Text), "scripts" .= [pubkeyJson]]),+ (Native.atLeast 1 [Native.signature paymentKey], object ["tag" .= ("n_of_k" :: Text.Text), "scripts" .= [pubkeyJson], "n" .= (1 :: Int)]),+ (Native.invalidBefore 0, object ["tag" .= ("timelock_start" :: Text.Text), "slot" .= ("0" :: Text.Text)]),+ (Native.invalidAfter maxBound, object ["tag" .= ("timelock_expiry" :: Text.Text), "slot" .= ("18446744073709551615" :: Text.Text)]),+ (Native.requireGuard (Credential.KeyCredential guardKey), object ["tag" .= ("require_guard" :: Text.Text), "credential" .= keyJson]),+ (Native.requireGuard (Credential.ScriptCredential scriptHash), object ["tag" .= ("require_guard" :: Text.Text), "credential" .= scriptJson])+ ]+ forM_ nativeCases $ \(condition, expected) -> do+ Standalone.nativeScript condition >>= (@?= Right expected)+ Standalone.script (Script.Native condition) >>= (@?= Right (object ["tag" .= ("native_script" :: Text.Text), "value" .= expected]))+ forM_ [(Plutus.V1, "plutus_v1"), (Plutus.V2, "plutus_v2"), (Plutus.V3, "plutus_v3"), (Plutus.V4, "plutus_v4")] $ \(version, language) -> do+ plutus <- must (Plutus.fromBytes version (B.pack [1, 2]))+ Standalone.plutusScript plutus >>= (@?= Right (object ["language" .= (language :: Text.Text), "bytes" .= ("0102" :: Text.Text)]))+ Standalone.credential stake >>= (@?= Right keyJson)+ Standalone.credential (Credential.ScriptCredential scriptHash :: Credential.Credential Credential.Stake) >>= (@?= Right scriptJson)+ Standalone.drep (DRep.DRepCredential drep) >>= (@?= Right keyJson)+ Standalone.drep DRep.AlwaysAbstain >>= (@?= Right (object ["tag" .= ("always_abstain" :: Text.Text)]))+ Standalone.drep DRep.AlwaysNoConfidence >>= (@?= Right (object ["tag" .= ("always_no_confidence" :: Text.Text)]))+ Standalone.anchor anchor >>= (@?= Right anchorJson)+ Standalone.actionId identifier >>= (@?= Right identifierJson)+ Standalone.protocolUpdate changes >>= (@?= Right changeJson)+ Standalone.value (Coin.lovelace (-1)) >>= assertBool "negative output coin accepted" . isLeft+ Standalone.value (Coin.lovelace (2 ^ (64 :: Int))) >>= assertBool "overflowing output coin accepted" . isLeft+ policy <- must (PolicyId.fromBytes (B.replicate 28 6))+ name <- must (AssetName.fromBytes (B.pack [0, 255, 128]))+ let signedAssets = Coin.fromList [(Asset.Native policy name, -1)]+ expectedAssets = object ["coin" .= ("0" :: Text.Text), "assets" .= object ["06060606060606060606060606060606060606060606060606060606" .= object ["00ff80" .= ("-1" :: Text.Text)]]]+ Standalone.value signedAssets >>= (@?= Right expectedAssets)+ withdrawals <- must (Action.withdrawalsFromList [(account, maxBound)])+ let actions =+ [ (Action.ParameterChange Nothing changes (Just scriptHash), "parameter_change_action"),+ (Action.HardForkInitiation (Just identifier) (Version.ProtocolVersion 12 0), "hard_fork_initiation_action"),+ (Action.TreasuryWithdrawals withdrawals Nothing, "treasury_withdrawals_action"),+ (Action.NoConfidence Nothing, "no_confidence"),+ (Action.UpdateCommittee Nothing (Action.removalsFromList []) Committee.emptyMembers margin, "update_committee"),+ (Action.NewConstitution Nothing (Constitution.Constitution anchor Nothing), "new_constitution"),+ (Action.InfoAction, "info_action")+ ]+ forM_ actions $ \(action, tag) -> do+ result <- Standalone.governanceAction action >>= must+ field "tag" result >>= (@?= String tag)+ let proposal = Proposal.Proposal maxBound account action anchor+ expected = object ["deposit" .= ("18446744073709551615" :: Text.Text), "reward_account" .= Reward.toText account, "gov_action" .= result, "anchor" .= anchorJson]+ Standalone.proposal proposal >>= (@?= Right expected)+ Internal.runUnchecked 19 (Action.encodeCbor action <> B.singleton 0) >>= assertBool "Trailing action accepted" . isLeft+ let target = DRep.DRepCredential drep+ certificates =+ [ Certificate.StakeRegistration stake,+ Certificate.StakeDeregistration stake,+ Certificate.StakeDelegation stake poolKey,+ Certificate.PoolRegistration pool,+ Certificate.PoolRetirement poolKey maxBound,+ Certificate.GenesisKeyDelegation genesis delegate vrf,+ Certificate.MoveInstantaneousRewards (Certificate.ToOtherPot Certificate.Reserves 1),+ Certificate.MoveInstantaneousRewards (Certificate.ToStakeCredentials Certificate.Treasury (Map.singleton stake 1)),+ Certificate.Registration stake 1,+ Certificate.Unregistration stake 1,+ Certificate.VoteDelegation stake target,+ Certificate.StakeVoteDelegation stake poolKey target,+ Certificate.StakeRegistrationDelegation stake poolKey 1,+ Certificate.VoteRegistrationDelegation stake target 1,+ Certificate.StakeVoteRegistrationDelegation stake poolKey target 1,+ Certificate.AuthorizeCommitteeHot (Credential.KeyCredential coldKey) (Credential.KeyCredential hotKey),+ Certificate.ResignCommitteeCold (Credential.KeyCredential coldKey) (Just anchor),+ Certificate.RegisterDRep drep 1 (Just anchor),+ Certificate.UnregisterDRep drep 1,+ Certificate.UpdateDRep drep (Just anchor)+ ]+ forM_ certificates $ \cert -> do+ standalone <- Standalone.certificate cert >>= must+ encoded <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldCertificates = Just (Certificates.fromList [cert])}}))+ parent <- Inspection.body encoded >>= must+ optionalArray "certs" parent >>= (@?= [standalone])+ Internal.runUnchecked 7 (Certificate.encodeCbor cert <> B.singleton 0) >>= assertBool "Trailing certificate accepted" . isLeft+ poolCert <- Standalone.certificate (Certificate.PoolRegistration pool) >>= must+ poolJson <- field "pool_params" poolCert+ Standalone.poolParameters pool >>= (@?= Right poolJson)+ let voter = Voting.DRepVoter drep+ votes = Voting.singleton voter identifier (Voting.VotingProcedure Voting.Yes (Just anchor))+ votesBody <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = (Fields.fields [] []) {Fields.fieldVotingProcedures = Just votes}}))+ votesJson <- Inspection.body votesBody >>= must >>= field "voting_procedures"+ Standalone.votingProcedures votes >>= (@?= Right votesJson)+ retained <- replicateM 20 (Standalone.anchor anchor >>= must)+ performGC+ retained @?= replicate 20 anchorJson++ let address = Address.ShelleyAddress (Shelley.enterprise Network.testnet (Credential.KeyCredential paymentKey))+ datum = Data.fromData (Data.Integer (2 ^ (160 :: Int)))+ output <- must (Output.mkOutput address (Coin.lovelace 2000000) (Datum.InlineDatum datum) (Just (Script.Native native)))+ let reference = Input.input txid 0+ resolved = Utxo.utxo reference output+ proposal = Proposal.Proposal 1 account Action.InfoAction anchor+ amountBytes <- must (Coin.encodeCbor signedAssets)+ bytesMetadata <- must (Metadata.mkBytes (B.pack [0, 255, 128]))+ textMetadata <- must (Metadata.mkText "世界")+ lowMetadata <- must (Metadata.mkInteger (negate (2 ^ (64 :: Int))))+ highMetadata <- must (Metadata.mkInteger (2 ^ (64 :: Int) - 1))+ let tagged tag payload = object ["tag" .= (tag :: Text.Text), "value" .= payload]+ bytesJson = tagged "bytes" ("00ff80" :: Text.Text)+ textJson = tagged "string" ("世界" :: Text.Text)+ lowJson = tagged "int" ("-18446744073709551616" :: Text.Text)+ highJson = tagged "int" ("18446744073709551615" :: Text.Text)+ composite = Metadata.map [(bytesMetadata, Metadata.list [lowMetadata, highMetadata, textMetadata]), (bytesMetadata, textMetadata)]+ listJson = object ["tag" .= ("list" :: Text.Text), "contents" .= [lowJson, highJson, textJson]]+ compositeJson = object ["tag" .= ("map" :: Text.Text), "contents" .= [object ["key" .= bytesJson, "value" .= listJson], object ["key" .= bytesJson, "value" .= textJson]]]+ metadata = Metadata.singleton maxBound composite+ metadataJson = [object ["key" .= ("18446744073709551615" :: Text.Text), "value" .= compositeJson]]+ Standalone.metadatum composite >>= (@?= Right compositeJson)+ Standalone.metadata metadata >>= (@?= Right (toJSON metadataJson))+ encodedMetadata <- must (Metadata.decodeCbor (Metadata.encodeCbor metadata))+ plutus <- must (Plutus.fromBytes Plutus.V4 (B.pack [1, 2]))+ let auxiliary = Auxiliary.fromAuxiliaryData (Auxiliary.auxiliaryData (Just encodedMetadata) (Just [native]) [plutus])+ auxiliaryJson = object ["metadata" .= metadataJson, "native_scripts" .= [nativeJson], "plutus_scripts" .= [object ["language" .= ("plutus_v4" :: Text.Text), "bytes" .= ("0102" :: Text.Text)]]]+ Standalone.auxiliaryData auxiliary >>= (@?= Right auxiliaryJson)+ datumHash <- must (Datum.hashFromBytes (B.replicate 32 7))+ Standalone.datum Datum.NoDatum >>= (@?= Right Nothing)+ Standalone.datum (Datum.DatumHash datumHash) >>= (@?= Right (Just (tagged "datum_hash" (Text.replicate 32 "07"))))+ expectedData <- Standalone.plutusData datum >>= must+ Standalone.datum (Datum.InlineDatum datum) >>= (@?= Right (Just (tagged "datum" expectedData)))+ let redeemer = Redeemer.Redeemer Redeemer.Guarding 0 datum (ExUnits.ExUnits 1 2)+ datumEncoding = Write.toStrictByteString (Encoding.encodeListLen 2 <> Encoding.encodeWord 1 <> Encoding.encodeTag 24 <> Encoding.encodeBytes (Data.toCbor datum))+ let encodings =+ [ (4, amountBytes),+ (5, Script.encodeCbor (Script.Native native)),+ (6, Credential.encodeCbor stake),+ (7, Certificate.encodeCbor (Certificate.Registration stake 1)),+ (8, Proposal.encodeCbor proposal),+ (9, Pool.encodeCbor pool),+ (10, Update.encodeCbor changes),+ (11, Data.toCbor datum),+ (12, Output.encodeCbor output),+ (13, Witnesses.toCbor (Witnesses.fromWitnesses Witnesses.empty)),+ (14, Utxo.encodeCbor resolved),+ (15, DRep.encodeCbor DRep.AlwaysAbstain),+ (16, ActionId.encodeCbor identifier),+ (17, Anchor.encodeCbor anchor),+ (18, Voting.encodeCbor votes),+ (19, Action.encodeCbor Action.InfoAction),+ (20, Metadata.encodeMetadatumCbor composite),+ (21, Metadata.encodeCbor metadata),+ (22, Auxiliary.toCbor auxiliary),+ (23, Input.encodeCbor reference),+ (24, datumEncoding),+ (25, Redeemer.encodeCbor redeemer)+ ]+ snapshots <- forM encodings $ \(kind, bytes) -> do+ let original = B.copy bytes+ result <- Internal.inspect "inspection.lifecycle" kind bytes >>= must+ replicateM_ 10 $ do+ Internal.runUnchecked kind (bytes <> B.singleton 0) >>= assertBool "Trailing standalone CBOR accepted" . isLeft+ Internal.runUnchecked kind (B.take (B.length bytes - 1) bytes) >>= assertBool "Truncated standalone CBOR accepted" . isLeft+ after <- Internal.inspect "inspection.lifecycle" kind bytes >>= must+ after @?= result+ bytes @?= original+ pure result+ rendered <- traverse (evaluate . Lazy.toStrict . encode) snapshots+ performGC+ map (Lazy.toStrict . encode) snapshots @?= rendered++-- Expected objects follow the pinned native writers, not global JSON instances.+standaloneLeaves :: IO ()+standaloneLeaves = do+ stake <- keyFixture+ pool <- keyFixture+ committee <- keyFixture+ scriptHash <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ location <- must (Anchor.mkUrl "https://example.com/constitution")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 3))+ dns <- must (Relay.mkDnsName "relay.example.com")+ ipv4 <- must (Relay.ipv4FromText "192.0.2.1")+ ipv6 <- must (Relay.ipv6FromText "2001:0db8:0000:0000:0000:0000:0000:0001")+ metadataUrl <- must (PoolMetadata.mkUrl "")+ metadataHash <- must (PoolMetadata.metadataHashFromBytes (B.replicate 32 4))+ key <- must (PublicKey.fromBytes (B.replicate 32 5))+ signature <- must (Signature.fromBytes (B.replicate 64 6))+ bootstrap <- must (Witness.mkBootstrapWitness key signature (B.replicate 32 7) (B.pack [0, 255]))+ let anchor = Anchor.Anchor location digest+ anchorJson = object ["url" .= ("https://example.com/constitution" :: Text.Text), "data_hash" .= Text.replicate 32 "03"]+ keyJson = object ["tag" .= ("pubkey_hash" :: Text.Text), "value" .= Text.replicate 28 "01"]+ scriptJson = object ["tag" .= ("script_hash" :: Text.Text), "value" .= Text.replicate 28 "02"]+ witness = Witness.verificationWitness key signature+ witnessJson = object ["vkey" .= Text.replicate 32 "05", "signature" .= Text.replicate 64 "06"]+ bootstrapJson = object ["vkey" .= Text.replicate 32 "05", "signature" .= Text.replicate 64 "06", "chain_code" .= Text.replicate 32 "07", "attributes" .= ("00ff" :: Text.Text)]+ check kind bytes action expected = do+ action >>= (@?= Right expected)+ forM_ [B.empty, B.take (B.length bytes - 1) bytes, bytes <> B.singleton 0] (Internal.runUnchecked kind >=> (assertBool "Invalid leaf CBOR accepted" . isLeft))+ snapshots <- replicateM 5 (action >>= must)+ performGC+ snapshots @?= replicate 5 expected+ check 26 (ExUnits.encodeCbor (ExUnits.ExUnits 0 maxBound)) (Standalone.exUnits (ExUnits.ExUnits 0 maxBound)) (object ["mem" .= ("0" :: Text.Text), "steps" .= ("18446744073709551615" :: Text.Text)])+ forM_ [0, maxBound] $ \minor -> do+ let version = Version.ProtocolVersion maxBound minor+ check 27 (Version.encodeCbor version) (Standalone.protocolVersion version) (object ["major" .= (18446744073709551615 :: Integer), "minor" .= toInteger minor])+ forM_ [(0, 1), (1, 3), (2 ^ (64 :: Int) - 1, 2 ^ (64 :: Int) - 1)] $ \(numerator, denominator) -> do+ interval <- must (Unit.mkUnitInterval numerator denominator)+ check 28 (Unit.encodeCbor interval) (Standalone.unitInterval interval) (object ["numerator" .= Text.pack (show (Unit.numerator interval)), "denominator" .= Text.pack (show (Unit.denominator interval))])+ let relayCases =+ [ (Relay.SingleHostAddress Nothing Nothing Nothing, object ["tag" .= ("single_host_addr" :: Text.Text), "port" .= Null, "ipv4" .= Null, "ipv6" .= Null]),+ (Relay.SingleHostAddress (Just 65535) (Just ipv4) Nothing, object ["tag" .= ("single_host_addr" :: Text.Text), "port" .= (65535 :: Int), "ipv4" .= ("192.0.2.1" :: Text.Text), "ipv6" .= Null]),+ (Relay.SingleHostAddress (Just 0) (Just ipv4) (Just ipv6), object ["tag" .= ("single_host_addr" :: Text.Text), "port" .= (0 :: Int), "ipv4" .= ("192.0.2.1" :: Text.Text), "ipv6" .= ("2001:0db8:0000:0000:0000:0000:0000:0001" :: Text.Text)]),+ (Relay.SingleHostName Nothing dns, object ["tag" .= ("single_host_name" :: Text.Text), "port" .= Null, "dns_name" .= ("relay.example.com" :: Text.Text)]),+ (Relay.MultiHostName dns, object ["tag" .= ("multi_host_name" :: Text.Text), "dns_name" .= ("relay.example.com" :: Text.Text)])+ ]+ forM_ relayCases $ \(relay, json) -> check 29 (Relay.encodeCbor relay) (Standalone.relay relay) json+ let metadata = PoolMetadata.Metadata metadataUrl metadataHash+ check 30 (PoolMetadata.encodeCbor metadata) (Standalone.poolMetadata metadata) (object ["url" .= ("" :: Text.Text), "hash" .= Text.replicate 32 "04"])+ forM_ [Nothing, Just scriptHash] $ \guard -> do+ let constitution = Constitution.Constitution anchor guard+ fields = ["anchor" .= anchorJson] <> maybe [] (const ["script_hash" .= Text.replicate 28 "02"]) guard+ check 31 (Constitution.encodeCbor constitution) (Standalone.constitution constitution) (object fields)+ let voterCases =+ [ (Voting.CommitteeVoter (Credential.KeyCredential committee), object ["tag" .= ("cc_credential" :: Text.Text), "credential" .= keyJson]),+ (Voting.CommitteeVoter (Credential.ScriptCredential scriptHash), object ["tag" .= ("cc_credential" :: Text.Text), "credential" .= scriptJson]),+ (Voting.DRepVoter (Credential.KeyCredential stake), object ["tag" .= ("drep_credential" :: Text.Text), "credential" .= keyJson]),+ (Voting.DRepVoter (Credential.ScriptCredential scriptHash), object ["tag" .= ("drep_credential" :: Text.Text), "credential" .= scriptJson]),+ (Voting.StakePoolVoter pool, object ["tag" .= ("spo_keyhash" :: Text.Text), "pubkey_hash" .= Text.replicate 28 "01"])+ ]+ forM_ voterCases $ \(voter, json) -> check 32 (Voting.encodeVoter voter) (Standalone.voter voter) json+ forM_ [(Voting.No, "no"), (Voting.Yes, "yes"), (Voting.Abstain, "abstain")] $ \(vote, label) ->+ forM_ [Nothing, Just anchor] $ \explanation -> do+ let procedure = Voting.VotingProcedure vote explanation+ fields = ["vote" .= (label :: Text.Text)] <> maybe [] (const ["anchor" .= anchorJson]) explanation+ check 33 (Voting.encodeProcedure procedure) (Standalone.votingProcedure procedure) (object fields)+ check 34 (Witness.encodeCbor witness) (Standalone.verificationWitness witness) witnessJson+ check 35 (Witness.encodeBootstrapCbor bootstrap) (Standalone.bootstrapWitness bootstrap) bootstrapJson++ -- Array inspectors preserve order and duplicate entries, including witnesses.+ supplied <- must (Witnesses.mkWitnesses [witness, witness] [bootstrap, bootstrap] [] [] [])+ parent <- Standalone.witnesses (Witnesses.fromWitnesses supplied) >>= must+ field "vkey_witnesses" parent >>= (@?= toJSON [witnessJson, witnessJson])+ field "bootstraps" parent >>= (@?= toJSON [bootstrapJson, bootstrapJson])+ emptyParent <- Standalone.witnesses (Witnesses.fromWitnesses Witnesses.empty) >>= must+ optionalArray "vkey_witnesses" emptyParent >>= (@?= [])+ optionalArray "bootstraps" emptyParent >>= (@?= [])++-- Complete CBOR values exercise schema checks separately from framing errors.+standaloneLeafFailures :: IO ()+standaloneLeafFailures = do+ let array entries = Encoding.encodeListLen (fromIntegral (length entries)) <> mconcat entries+ bytes size = Encoding.encodeBytes (B.replicate size 0)+ invalidCases =+ [ (26, "negative memory", array [Encoding.encodeInt (-1), Encoding.encodeWord 0]),+ (27, "minor exceeds Word32", array [Encoding.encodeWord 0, Encoding.encodeWord64 4294967296]),+ (28, "wrong rational tag", Encoding.encodeTag 29 <> array [Encoding.encodeWord 0, Encoding.encodeWord 1]),+ (29, "unknown relay kind", array [Encoding.encodeWord 3]),+ (30, "metadata hash has integer type", array [Encoding.encodeString "", Encoding.encodeWord 0]),+ (31, "constitution anchor is null", array [Encoding.encodeNull, Encoding.encodeNull]),+ (32, "unknown voter role", array [Encoding.encodeWord 5, bytes 28]),+ (33, "unknown vote choice", array [Encoding.encodeWord 3, Encoding.encodeNull]),+ (34, "short verification key", array [bytes 31, bytes 64]),+ (34, "short signature", array [bytes 32, bytes 63]),+ (35, "bootstrap attributes have integer type", array [bytes 32, bytes 64, bytes 32, Encoding.encodeWord 0]),+ (35, "short bootstrap verification key", array [bytes 31, bytes 64, bytes 32, bytes 0])+ ]+ forM_ invalidCases $ \(kind, label, encoded) -> do+ result <- Internal.runUnchecked kind (Write.toStrictByteString encoded)+ assertBool ("Schema-invalid leaf accepted: " <> label) (isLeft result)++-- Protocol and Dijkstra collection schemas differ from ordinary JSON arrays:+-- language-keyed objects, genesis-keyed objects and ordered key/value entries.+standaloneCollections :: IO ()+standaloneCollections = do+ model <- must (Models.mkCostModel 0 [negate (2 ^ (63 :: Int)), 0, 2 ^ (63 :: Int) - 1])+ future <- must (Models.mkCostModel 255 [7])+ laterModels <- traverse (\language -> must (Models.mkCostModel language [fromIntegral language])) [1, 2, 3]+ let models = Models.fromList (future : model : laterModels)+ modelJson = toJSON (["-9223372036854775808", "0", "9223372036854775807"] :: [Text.Text])+ modelsJson = object ["plutus_v1" .= modelJson, "plutus_v2" .= (["1"] :: [Text.Text]), "plutus_v3" .= (["2"] :: [Text.Text]), "plutus_v4" .= (["3"] :: [Text.Text])]+ modelBytes supplied = Write.toStrictByteString (Encoding.encodeListLen 2 <> Encoding.encodeWord8 (Models.languageId supplied)) <> Models.encodeCostModelCbor supplied+ check kind bytes action expected = do+ let original = B.copy bytes+ action >>= (@?= Right expected)+ forM_ [B.empty, B.take (B.length bytes - 1) bytes, bytes <> B.singleton 0] (Internal.runUnchecked kind >=> (assertBool "Invalid collection CBOR accepted" . isLeft))+ snapshots <- replicateM 5 (action >>= must)+ performGC+ snapshots @?= replicate 5 expected+ bytes @?= original+ fraction numerator denominator = object ["numerator" .= (numerator :: Text.Text), "denominator" .= (denominator :: Text.Text)]+ check 36 (modelBytes model) (Standalone.costModel model) modelJson+ check 36 (modelBytes future) (Standalone.costModel future) (toJSON (["7"] :: [Text.Text]))+ check 37 (Models.encodeCbor models) (Standalone.costModels models) modelsJson+ Standalone.costModels Models.empty >>= (@?= Right (object []))+ map Models.languageId (Models.toList models) @?= [0, 1, 2, 3, 255]+ let originalModelBytes = Models.encodeCbor models+ Standalone.costModels (Models.fromList [future]) >>= (@?= Right (object []))+ Models.encodeCbor models @?= originalModelBytes+ -- Prices may exceed one and fractions remain unreduced in native JSON.+ memoryPrice <- must (Rational.mkNonNegativeRational 6 4)+ stepPrice <- must (Rational.mkNonNegativeRational 2 6)+ let prices = Prices.ExUnitPrices memoryPrice stepPrice+ pricesJson = object ["mem_price" .= fraction "6" "4", "step_price" .= fraction "2" "6"]+ check 38 (Prices.encodeCbor prices) (Standalone.exUnitPrices prices) pricesJson+ thresholds <- traverse (\numerator -> must (Unit.mkUnitInterval numerator 10)) [0 .. 9]+ case thresholds of+ [a, b, c, d, e, f, g, h, i, j] -> do+ let pool = PoolThresholds.PoolVotingThresholds a b c d e+ drep = DRepThresholds.DRepVotingThresholds a b c d e f g h i j+ poolNames = ["motion_no_confidence", "committee_normal", "committee_no_confidence", "hard_fork_initiation", "security_relevant_param"]+ drepNames = ["motion_no_confidence", "committee_normal", "committee_no_confidence", "update_constitution", "hard_fork_initiation", "pp_network_group", "pp_economic_group", "pp_technical_group", "pp_gov_group", "treasury_withdrawal"]+ thresholdJson names = object [name .= fraction (Text.pack (show numerator)) "10" | (name, numerator) <- zip names ([0 ..] :: [Int])]+ poolJson = thresholdJson poolNames+ drepJson = thresholdJson drepNames+ update = Update.empty {Update.updateCostModels = Just models, Update.updateExecutionCosts = Just prices, Update.updatePoolVotingThresholds = Just pool, Update.updateDrepVotingThresholds = Just drep}+ updateJson = object ["cost_models" .= modelsJson, "execution_costs" .= pricesJson, "pool_voting_thresholds" .= poolJson, "drep_voting_thresholds" .= drepJson]+ check 39 (PoolThresholds.encodeCbor pool) (Standalone.poolVotingThresholds pool) poolJson+ check 40 (DRepThresholds.encodeCbor drep) (Standalone.drepVotingThresholds drep) drepJson+ Standalone.protocolUpdate update >>= (@?= Right updateJson)+ genesis <- keyFixture+ proposed <- must (Proposed.fromList [(genesis, update)])+ let proposedJson = object ["01010101010101010101010101010101010101010101010101010101" .= updateJson]+ proposal = Proposed.UpdateProposal maxBound proposed+ proposalJson = object ["epoch" .= (18446744073709551615 :: Integer), "proposed_protocol_parameter_updates" .= proposedJson]+ check 41 (Proposed.encodeCbor proposed) (Standalone.proposedUpdates proposed) proposedJson+ check 42 (Proposed.encodeProposal proposal) (Standalone.updateProposal proposal) proposalJson+ Standalone.proposedUpdates Proposed.empty >>= (@?= Right (object []))+ _ -> assertFailure "Threshold fixture arity"+ stake <- keyFixture+ guard <- keyFixture+ scriptHash <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ keyGuard = Credential.KeyCredential guard+ scriptGuard = Credential.ScriptCredential scriptHash+ datum = Data.fromData (Data.Map [(Data.Integer 1, Data.Integer 2), (Data.Integer 1, Data.Integer 3)])+ keyJson = object ["tag" .= ("pubkey_hash" :: Text.Text), "value" .= Text.replicate 28 "01"]+ scriptJson = object ["tag" .= ("script_hash" :: Text.Text), "value" .= Text.replicate 28 "02"]+ exactJson = object ["tag" .= ("exact" :: Text.Text), "value" .= ("18446744073709551615" :: Text.Text)]+ encodeInterval interval = Write.toStrictByteString $ case interval of+ Fields.ExactBalance amount -> Encoding.encodeWord64 amount+ Fields.BalanceRange lower upper -> Encoding.encodeListLen 2 <> maybe Encoding.encodeNull Encoding.encodeWord64 lower <> maybe Encoding.encodeNull Encoding.encodeWord64 upper+ rangeJson lower upper = object ["tag" .= ("range" :: Text.Text), "inclusive_lower_bound" .= lower, "exclusive_upper_bound" .= upper]+ intervalCases =+ [ (Fields.ExactBalance maxBound, exactJson),+ (Fields.BalanceRange Nothing (Just 0), rangeJson Null (String "0")),+ (Fields.BalanceRange (Just maxBound) Nothing, rangeJson (String "18446744073709551615") Null),+ (Fields.BalanceRange (Just 10) (Just 1), rangeJson (String "10") (String "1"))+ ]+ forM_ intervalCases $ \(interval, json) -> check 43 (encodeInterval interval) (Standalone.balanceInterval interval) json+ Standalone.balanceInterval (Fields.BalanceRange Nothing Nothing) >>= assertBool "Unbounded native interval accepted" . isLeft+ intervals <- must (Fields.mkEntries [(account, Fields.ExactBalance maxBound)])+ deposits <- must (Fields.mkEntries [(account, 0)])+ guards <- must (Fields.mkEntries [(scriptGuard, Just datum), (keyGuard, Nothing)])+ datumJson <- Standalone.plutusData datum >>= must+ let entry key payload = object ["key" .= key, "value" .= payload]+ intervalsJson = toJSON [entry (String (Reward.toText account)) exactJson]+ depositsJson = toJSON [entry (String (Reward.toText account)) (String "0")]+ guardsJson = toJSON [entry keyJson Null, entry scriptJson datumJson]+ fields = (Fields.fields [] []) {Fields.fieldAccountBalanceIntervals = Just intervals, Fields.fieldDirectDeposits = Just deposits, Fields.fieldRequiredTopLevelGuards = Just guards}+ association pairs = Write.toStrictByteString (Encoding.encodeMapLen (fromIntegral (length pairs))) <> foldMap (uncurry (<>)) pairs+ intervalBytes = association [(Write.toStrictByteString (Encoding.encodeBytes (Reward.toBytes account)), encodeInterval (Fields.ExactBalance maxBound))]+ depositsBytes = association [(Write.toStrictByteString (Encoding.encodeBytes (Reward.toBytes account)), Write.toStrictByteString (Encoding.encodeWord64 0))]+ guardsBytes = association [(Credential.encodeCbor keyGuard, Write.toStrictByteString Encoding.encodeNull), (Credential.encodeCbor scriptGuard, Data.toCbor datum)]+ check 44 intervalBytes (Standalone.balanceIntervals intervals) intervalsJson+ check 45 depositsBytes (Standalone.directDeposits deposits) depositsJson+ check 46 guardsBytes (Standalone.requiredGuards guards) guardsJson+ body <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = fields}))+ bodyJson <- Inspection.body body >>= must+ field "account_balance_intervals" bodyJson >>= (@?= intervalsJson)+ field "direct_deposits" bodyJson >>= (@?= depositsJson)+ field "required_top_level_guards" bodyJson >>= (@?= guardsJson)+ subBody <- must (SubBody.fromBody (SubBody.fromFields fields))+ subJson <- Inspection.subBody subBody >>= must+ field "account_balance_intervals" subJson >>= (@?= intervalsJson)+ field "direct_deposits" subJson >>= (@?= depositsJson)+ field "required_top_level_guards" subJson >>= (@?= guardsJson)+ -- Well-framed invalid schemas exercise native validation independently of framing.+ let array entries = Encoding.encodeListLen (fromIntegral (length entries)) <> mconcat entries+ invalid =+ [ (36, array [Encoding.encodeWord 256, array []]),+ (37, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeString "costs"),+ (38, array [Encoding.encodeNull, Encoding.encodeNull]),+ (39, array []),+ (40, array []),+ (41, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeMapLen 0),+ (42, array [Encoding.encodeMapLen 0, Encoding.encodeString "epoch"]),+ (43, array [Encoding.encodeNull, Encoding.encodeNull]),+ (44, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeWord 0),+ (45, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeWord 0),+ (46, Encoding.encodeMapLen 1 <> array [Encoding.encodeWord 0, Encoding.encodeBytes B.empty] <> Encoding.encodeNull)+ ]+ forM_ invalid $ \(kind, bytes) -> Internal.runUnchecked kind (Write.toStrictByteString bytes) >>= assertBool "Invalid standalone collection schema accepted" . isLeft++remainingInspection :: IO ()+remainingInspection = do+ let check kind bytes action expected = do+ let original = B.copy bytes+ action >>= (@?= Right expected)+ forM_ [B.empty, B.take (B.length bytes - 1) bytes, bytes <> B.singleton 0] (Internal.runUnchecked kind >=> (assertBool "Malformed standalone inspection accepted" . isLeft))+ snapshots <- replicateM 5 (action >>= must)+ performGC+ snapshots @?= replicate 5 expected+ bytes @?= original+ array values = Write.toStrictByteString (Encoding.encodeTag 258 <> Encoding.encodeListLen (fromIntegral (length values))) <> mconcat values+ assetObject names = object [name .= (amount :: Text.Text) | (name, amount) <- names]+ emptyName <- must (AssetName.fromBytes B.empty)+ binaryName <- must (AssetName.fromBytes (B.pack [255, 0]))+ maxName <- must (AssetName.fromBytes (B.replicate 32 128))+ forM_ [emptyName, binaryName, maxName] $ \name -> check 47 (AssetName.encodeCbor name) (Standalone.assetName name) (String (AssetName.toHex name))+ digests <- traverse (must . Hash.fromBytes) [B.replicate 64 2, B.singleton 255, B.replicate 28 1, B.replicate 28 1]+ forM_ digests $ \digest -> check 48 (Hash.encodeCbor digest) (Standalone.blake2bHash digest) (String (Hash.toHex digest))+ let expectedHashes = toJSON (["ff", Text.replicate 28 "01", Text.replicate 28 "01", Text.replicate 64 "02"] :: [Text.Text])+ check 52 (Collections.encodeHashesCbor digests) (Standalone.hashes digests) expectedHashes+ Standalone.hashes [] >>= (@?= Right (toJSON ([] :: [Value])))+ bls <- must (Bls.mkBlsKey (B.replicate 96 3) (B.replicate 48 4))+ let blsJson = object ["public_key" .= Text.replicate 96 "03", "possession_proof" .= Text.replicate 48 "04"]+ check 49 (Bls.encodeCbor bls) (Standalone.blsKey bls) blsJson+ cold <- keyFixture+ scriptHash <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ members <- must (Committee.membersFromList [(Credential.ScriptCredential scriptHash, maxBound), (Credential.KeyCredential cold, 0)])+ let keyJson = object ["tag" .= ("pubkey_hash" :: Text.Text), "value" .= Text.replicate 28 "01"]+ scriptJson = object ["tag" .= ("script_hash" :: Text.Text), "value" .= Text.replicate 28 "02"]+ membersJson = toJSON [object ["key" .= keyJson, "value" .= ("0" :: Text.Text)], object ["key" .= scriptJson, "value" .= ("18446744073709551615" :: Text.Text)]]+ check 50 (Committee.encodeMembers members) (Standalone.committeeMembers members) membersJson+ Standalone.committeeMembers Committee.emptyMembers >>= (@?= Right (toJSON ([] :: [Value])))+ stake <- keyFixture+ let account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ scriptAccount = Reward.fromCredential Network.mainnet (Credential.ScriptCredential scriptHash)+ withdrawals = [(scriptAccount, maxBound), (account, 0), (account, 7)]+ entry address amount = object ["key" .= Reward.toText address, "value" .= (amount :: Text.Text)]+ withdrawalsJson = toJSON [entry account "0", entry account "7", entry scriptAccount "18446744073709551615"]+ check 51 (Collections.encodeWithdrawalsCbor withdrawals) (Standalone.withdrawals withdrawals) withdrawalsJson+ Standalone.withdrawals [] >>= (@?= Right (toJSON ([] :: [Value])))+ guard <- keyFixture+ let guards = [Credential.ScriptCredential scriptHash, Credential.KeyCredential guard]+ guardsJson = toJSON [scriptJson, keyJson]+ check 53 (array (map Credential.encodeCbor guards)) (Standalone.guards guards) guardsJson+ Standalone.guards [] >>= (@?= Right (toJSON ([] :: [Value])))+ Standalone.guards (guards <> guards) >>= assertBool "Duplicate guard accepted" . isLeft+ firstBody <- must (SubBody.fromBody (SubBody.body [] []))+ secondBody <- must (SubBody.fromBody (SubBody.fromFields ((Fields.fields [] []) {Fields.fieldDonation = Just 0})))+ let first = Sub.fromBody firstBody+ second = Sub.fromBody secondBody+ firstJson <- Standalone.subTransaction first >>= must+ secondJson <- Standalone.subTransaction second >>= must+ check 54 (array (map Sub.encodeCbor [second, first])) (Standalone.subTransactions [second, first]) (toJSON [secondJson, firstJson])+ Standalone.subTransactions [] >>= (@?= Right (toJSON ([] :: [Value])))+ Standalone.subTransactions [first, first] >>= assertBool "Duplicate intent accepted" . isLeft+ key <- must (PublicKey.fromBytes (B.replicate 32 8))+ signature <- must (Signature.fromBytes (B.replicate 64 9))+ witnesses <- must (Witnesses.mkWitnesses [Witness.verificationWitness key signature] [] [] [] [])+ let differentlyWitnessed = Sub.setWitnesses (Witnesses.fromWitnesses witnesses) first+ Standalone.subTransactions [first, differentlyWitnessed] >>= assertBool "Duplicate body with distinct witness accepted" . isLeft+ policy <- must (PolicyId.fromBytes (B.replicate 28 5))+ otherPolicy <- must (PolicyId.fromBytes (B.replicate 28 6))+ let names = [(maxName, 0), (binaryName, negate (2 ^ (63 :: Int))), (emptyName, 2 ^ (63 :: Int) - 1)]+ namesJson = assetObject [("", "9223372036854775807"), ("ff00", "-9223372036854775808"), ("8080808080808080808080808080808080808080808080808080808080808080", "0")]+ entriesJson = toJSON [object ["asset_name" .= (name :: Text.Text), "amount" .= (amount :: Text.Text)] | (name, amount) <- [("", "9223372036854775807"), ("ff00", "-9223372036854775808"), (Text.replicate 32 "80", "0")]]+ groups = [(otherPolicy, []), (policy, names)]+ groupsJson = object ["05050505050505050505050505050505050505050505050505050505" .= namesJson, "06060606060606060606060606060606060606060606060606060606" .= object []]+ groupEntries = toJSON [object ["script_hash" .= PolicyId.toHex policy, "assets" .= namesJson], object ["script_hash" .= PolicyId.toHex otherPolicy, "assets" .= object []]]+ nameBytes <- must (Collections.encodeAssetNamesCbor names)+ let groupBytes = Write.toStrictByteString (Encoding.encodeMapLen 2 <> Encoding.encodeBytes (PolicyId.toBytes policy)) <> nameBytes <> Write.toStrictByteString (Encoding.encodeBytes (PolicyId.toBytes otherPolicy) <> Encoding.encodeMapLen 0)+ check 55 groupBytes (Standalone.assets groups) groupsJson+ check 56 groupBytes (Standalone.assetEntries groups) groupEntries+ check 57 nameBytes (Standalone.policyAssets names) namesJson+ check 58 nameBytes (Standalone.policyAssetEntries names) entriesJson+ Standalone.assets [] >>= (@?= Right (object []))+ Standalone.assetEntries [] >>= (@?= Right (toJSON ([] :: [Value])))+ Standalone.policyAssets [] >>= (@?= Right (object []))+ Standalone.policyAssetEntries [] >>= (@?= Right (toJSON ([] :: [Value])))+ -- Explicit object restrictions prevent Aeson silently collapsing native keys.+ let repeatedNames = [(emptyName, 0), (emptyName, 1)]+ duplicateName = Left (InvalidValueCbor "Repeated asset names cannot be represented as JSON object keys")+ Standalone.policyAssets repeatedNames >>= (@?= duplicateName)+ Standalone.assets [(policy, repeatedNames)] >>= (@?= duplicateName)+ Standalone.assetEntries [(policy, repeatedNames)] >>= (@?= duplicateName)+ Standalone.assets [(policy, [(emptyName, 1)]), (policy, [])] >>= (@?= Right (object ["05050505050505050505050505050505050505050505050505050505" .= object []]))+ let repeatedJson = toJSON [object ["asset_name" .= ("" :: Text.Text), "amount" .= ("0" :: Text.Text)], object ["asset_name" .= ("" :: Text.Text), "amount" .= ("1" :: Text.Text)]]+ repeatedBytes <- must (Collections.encodeAssetNamesCbor repeatedNames)+ check 58 repeatedBytes (Standalone.policyAssetEntries repeatedNames) repeatedJson+ -- Duplicate policy keys replace the whole previous group in native decoding.+ Standalone.assetEntries [(policy, [(emptyName, 1)]), (policy, [(binaryName, 0)])] >>= (@?= Right (toJSON [object ["script_hash" .= PolicyId.toHex policy, "assets" .= assetObject [("ff00", "0")]]]))+ Standalone.assets [(policy, repeatedNames), (policy, [(binaryName, 0)])] >>= (@?= Right (object ["05050505050505050505050505050505050505050505050505050505" .= assetObject [("ff00", "0")]]))+ forM_ [negate (2 ^ (63 :: Int)) - 1, 2 ^ (63 :: Int)] $ \amount -> do+ let failure = Left (InvalidValueQuantity amount)+ Standalone.policyAssets [(emptyName, amount)] >>= (@?= failure)+ Standalone.policyAssetEntries [(emptyName, amount)] >>= (@?= failure)+ Standalone.assets [(policy, [(emptyName, amount)])] >>= (@?= failure)+ Standalone.assetEntries [(policy, [(emptyName, amount)])] >>= (@?= failure)+ -- Complete, well-framed schema failures are distinct from framing failures.+ let invalid = [(47, Encoding.encodeBytes (B.replicate 33 0)), (48, Encoding.encodeWord 0), (49, Encoding.encodeListLen 2 <> Encoding.encodeBytes (B.replicate 95 0) <> Encoding.encodeBytes (B.replicate 48 0)), (50, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeWord 0), (51, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeWord 0), (52, Encoding.encodeListLen 1 <> Encoding.encodeWord 0), (53, Encoding.encodeListLen 1 <> Encoding.encodeWord 0), (54, Encoding.encodeListLen 1 <> Encoding.encodeWord 0), (55, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeMapLen 0), (56, Encoding.encodeMapLen 1 <> Encoding.encodeWord 0 <> Encoding.encodeMapLen 0), (57, Encoding.encodeMapLen 1 <> Encoding.encodeBytes B.empty <> Encoding.encodeNull), (58, Encoding.encodeMapLen 1 <> Encoding.encodeBytes B.empty <> Encoding.encodeNull)]+ forM_ invalid $ \(kind, encoded) -> Internal.runUnchecked kind (Write.toStrictByteString encoded) >>= assertBool "Invalid standalone schema accepted" . isLeft++inspectionArrayEquivalence :: IO ()+inspectionArrayEquivalence = do+ stake <- keyFixture+ poolKey <- keyFixture+ cold <- keyFixture+ scriptHash <- must (Credential.scriptHashFromBytes (B.replicate 28 2))+ vrf <- must (Pool.vrfKeyHashFromBytes (B.replicate 32 3))+ margin <- must (Unit.mkUnitInterval 1 2)+ dns <- must (Relay.mkDnsName "relay.example.com")+ bls <- must (Bls.mkBlsKey (B.replicate 96 4) (B.replicate 48 5))+ let relays = [Relay.MultiHostName dns, Relay.SingleHostName Nothing dns, Relay.SingleHostAddress Nothing Nothing Nothing, Relay.MultiHostName dns]+ account = Reward.fromCredential Network.testnet (Credential.KeyCredential stake)+ pool = Pool.PoolParameters poolKey vrf (Just bls) 0 0 margin account (Set.singleton stake) relays Nothing+ poolJson <- Standalone.poolParameters pool >>= must+ relayJson <- traverse (Standalone.relay >=> must) relays+ field "relays" poolJson >>= (@?= toJSON relayJson)+ blsJson <- Standalone.blsKey bls >>= must+ field "bls_key" poolJson >>= (@?= blsJson)+ owner <- must (Hash.fromBytes (Credential.keyHashBytes stake))+ ownerJson <- Standalone.blake2bHash owner >>= must+ field "pool_owners" poolJson >>= (@?= toJSON [ownerJson])+ -- The native credential set sorts by kind/hash and retains equal-key entries.+ let removals = Action.removalsFromList [Credential.ScriptCredential scriptHash, Credential.KeyCredential cold, Credential.KeyCredential cold]+ action = Action.UpdateCommittee Nothing removals Committee.emptyMembers margin+ actionJson <- Standalone.governanceAction action >>= must+ removalJson <- traverse (Standalone.credential >=> must) (Action.removalsToList removals)+ field "members_to_remove" actionJson >>= (@?= toJSON removalJson)+ url <- must (Anchor.mkUrl "https://example.com/proposal")+ digest <- must (Anchor.dataHashFromBytes (B.replicate 32 6))+ let anchor = Anchor.Anchor url digest+ firstProposal = Proposal.Proposal 0 account Action.InfoAction anchor+ secondProposal = Proposal.Proposal 1 account Action.InfoAction anchor+ proposals = [secondProposal, firstProposal, secondProposal]+ fields = (Fields.fields [] []) {Fields.fieldProposalProcedures = Just (Proposal.fromList proposals)}+ proposalJson <- traverse (Standalone.proposal >=> must) proposals+ proposalBody <- must (Body.fromBody ((Body.body [] [] 0) {Body.bodyFields = fields}))+ bodyJson <- Standalone.body proposalBody >>= must+ field "proposal_procedures" bodyJson >>= (@?= toJSON proposalJson)++ -- Each language's native list/set writer uses the same payload writer and+ -- preserves insertion order and duplicates. Parent writers use these payloads.+ forM_ [Plutus.V1, Plutus.V2, Plutus.V3, Plutus.V4] $ \version -> do+ first <- must (Plutus.fromBytes version (B.pack [2, 1]))+ second <- must (Plutus.fromBytes version (B.pack [1, 2]))+ let values = [first, second, first]+ auxiliary = Auxiliary.fromAuxiliaryData (Auxiliary.auxiliaryData Nothing Nothing values)+ payloads <- traverse (Standalone.plutusScript >=> must) values+ auxiliaryJson <- Standalone.auxiliaryData auxiliary >>= must+ field "plutus_scripts" auxiliaryJson >>= (@?= toJSON payloads)+ witnesses <- must (Witnesses.mkWitnesses [] [] (map Script.Plutus values) [] [])+ witnessJson <- Standalone.witnesses (Witnesses.fromWitnesses witnesses) >>= must+ field "plutus_scripts" witnessJson >>= (@?= toJSON payloads)+ -- Plutus constructor/list/map subtype functions are tagged, not bare arrays.+ let one = Data.fromData (Data.Integer 1)+ two = Data.fromData (Data.Integer 2)+ integerJson amount = object ["tag" .= ("integer" :: Text.Text), "value" .= (amount :: Text.Text)]+ oneJson = integerJson "1"+ twoJson = integerJson "2"+ entries = [object ["key" .= oneJson, "value" .= twoJson], object ["key" .= oneJson, "value" .= oneJson]]+ Standalone.plutusData (Data.fromData (Data.Constr maxBound [Data.toData one, Data.toData two])) >>= (@?= Right (object ["tag" .= ("constr" :: Text.Text), "alternative" .= ("18446744073709551615" :: Text.Text), "data" .= [oneJson, twoJson]]))+ Standalone.plutusData (Data.fromData (Data.List [Data.toData two, Data.toData one])) >>= (@?= Right (object ["tag" .= ("list" :: Text.Text), "contents" .= [twoJson, oneJson]]))+ Standalone.plutusData (Data.fromData (Data.Map [(Data.toData one, Data.toData two), (Data.toData one, Data.toData one)])) >>= (@?= Right (object ["tag" .= ("map" :: Text.Text), "contents" .= entries]))
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff
file too large to diff