From e108079d5f7890438259297839292d2c3a1e1530 Mon Sep 17 00:00:00 2001 From: John Lotoski Date: Tue, 12 May 2026 19:17:06 -0500 Subject: [PATCH 01/68] bump: dependencies for cardano-node 11.0 Update cabal.project constraints and index-state for cardano-node 11.0.1 (ouroboros-consensus 3.0.1, cardano-ledger-conway >= 1.22.1). Pin validation < 1.2 to avoid breaking API change. Update ogmios source-repository-package to rebased node-11.0 branch. Bump dependency bounds in package.yaml. Co-Authored-By: Claude --- cabal.project | 31 +++++++++++++++++-------------- kupo.cabal | 16 ++++++++-------- package.yaml | 14 +++++++------- 3 files changed, 32 insertions(+), 29 deletions(-) diff --git a/cabal.project b/cabal.project index bab3c3d2..b5ad4714 100644 --- a/cabal.project +++ b/cabal.project @@ -10,8 +10,8 @@ repository cardano-haskell-packages d4a35cd3121aa00d18544bb0ac01c3e1691d618f462c46129271bccf39f7e8ee index-state: - , hackage.haskell.org 2025-09-11T07:59:00Z - , cardano-haskell-packages 2025-09-11T08:36:14Z + , hackage.haskell.org 2026-05-08T22:40:19Z + , cardano-haskell-packages 2026-05-08T13:26:45Z packages: ./ @@ -46,34 +46,37 @@ package direct-sqlite flags: +nomutex constraints: - , any.cardano-node == 10.5.1 + , any.cardano-node == 11.0.1 - , any.cardano-ledger-core == 1.17.0.0 - , any.cardano-ledger-shelley == 1.16.0.0 - , any.cardano-ledger-conway == 1.19.0.0 + , any.cardano-ledger-conway >= 1.22.1.0 - , any.ouroboros-consensus == 0.27.0.0 - , any.ouroboros-consensus-cardano == 0.25.1.0 - , any.ouroboros-network == 0.21.3.0 + , any.ouroboros-consensus ^>= 3.0.1 + , any.ouroboros-network ^>= 1.1 - , any.io-classes == 1.5.0.0 - , any.io-classes-mtl == 0.1.2.0 + , any.io-classes ^>= 1.8 , any.formatting == 7.2.0 + , any.validation < 1.2 , any.text source + -- Use serial block IO instead of io_uring to avoid requiring liburing + , any.blockio +serialblockio + , direct-sqlite == 2.3.29.1 , sqlite-simple == 0.4.19.0.1 allow-newer: *:formatting + , katip:Win32 + , io-sim:time + , io-classes:time -- NOTE update hash using -- nix-prefetch-git https://github.com/CardanoSolutions/ogmios.git --rev --fetch-submodules --quiet | jq '.hash' | tail -c +9 | head -c -2 source-repository-package type: git - location: https://github.com/CardanoSolutions/ogmios - tag: ae876badb138f42dcd6d2389734b0c15502684ed - --sha256: xkOfOdX6Dxi7+VW78Tk3n3MoguIg39pKdxiNVfdeEwE= + location: https://github.com/johnalotoski/ogmios + --sha256: sha256-OjABxe/ICHIkb+5jQI7chCrwnQ2W1oVO02Zxu9yLUKU= + tag: ea80df1204f830050436facdae4287cf674892e5 subdir: server/modules/fast-bech32 diff --git a/kupo.cabal b/kupo.cabal index 3192190a..130f18ff 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -1,4 +1,4 @@ -cabal-version: 1.12 +cabal-version: 3.0 -- This file has been generated from package.yaml by hpack version 0.38.2. -- @@ -214,13 +214,13 @@ library , modern-uri , network-mux , optparse-applicative + , cardano-diffusion , ouroboros-consensus - , ouroboros-consensus-cardano - , ouroboros-consensus-diffusion - , ouroboros-network - , ouroboros-network-api - , ouroboros-network-framework - , ouroboros-network-protocols + , ouroboros-consensus:cardano + , ouroboros-consensus:diffusion + , ouroboros-network:api + , ouroboros-network:framework + , ouroboros-network:protocols , prometheus , relude , resource-pool @@ -395,7 +395,7 @@ test-suite unit , process , quickcheck-state-machine , relude - , si-timers + , io-classes:si-timers , sqlite-simple , stm , temporary diff --git a/package.yaml b/package.yaml index fb57ab51..307c932d 100644 --- a/package.yaml +++ b/package.yaml @@ -93,13 +93,13 @@ library: - modern-uri - network-mux - optparse-applicative + - cardano-diffusion - ouroboros-consensus - - ouroboros-consensus-cardano - - ouroboros-consensus-diffusion - - ouroboros-network - - ouroboros-network-api - - ouroboros-network-framework - - ouroboros-network-protocols + - ouroboros-consensus:cardano + - ouroboros-consensus:diffusion + - ouroboros-network:api + - ouroboros-network:framework + - ouroboros-network:protocols - prometheus - relude - resource-pool @@ -146,7 +146,7 @@ tests: - QuickCheck - quickcheck-state-machine - relude - - si-timers + - io-classes:si-timers - sqlite-simple - stm - temporary From 57a2da989cf773ebc91836fe5c99763a10ecac3b Mon Sep 17 00:00:00 2001 From: John Lotoski Date: Tue, 12 May 2026 19:22:08 -0500 Subject: [PATCH 02/68] update: add Dijkstra era support for cardano-node 11.0 Add BlockDijkstra and DijkstraEra pattern matches across block processing, scripts, transactions, and Hydra/Ogmios modules. Dijkstra transactions are coerced to Conway at the block-processing boundary since the types are representationally identical. Replace unsafeCoerce in Metadata era translation with explicit pattern match and translateTimelock. Update Prelude era list and codec config. Co-Authored-By: Claude --- src/Kupo/Control/MonadOuroboros.hs | 8 ++++--- src/Kupo/Data/Cardano.hs | 24 +++++++++++++++------ src/Kupo/Data/Cardano/AssetName.hs | 4 ---- src/Kupo/Data/Cardano/Metadata.hs | 17 +++++++-------- src/Kupo/Data/Cardano/Point.hs | 2 +- src/Kupo/Data/Cardano/Script.hs | 29 ++++++++++++------------- src/Kupo/Data/Cardano/Transaction.hs | 32 +++++++++++----------------- src/Kupo/Data/Hydra.hs | 24 +++++++++++---------- src/Kupo/Data/Ogmios.hs | 1 + src/Kupo/Prelude.hs | 13 ++++++++--- 10 files changed, 81 insertions(+), 73 deletions(-) diff --git a/src/Kupo/Control/MonadOuroboros.hs b/src/Kupo/Control/MonadOuroboros.hs index 7583f437..61bec00c 100644 --- a/src/Kupo/Control/MonadOuroboros.hs +++ b/src/Kupo/Control/MonadOuroboros.hs @@ -35,6 +35,7 @@ import Kupo.Control.MonadThrow import Network.Mux ( StartOnDemandOrEagerly (..) ) +import qualified Network.Mux import Ouroboros.Consensus.Byron.Ledger.Config ( CodecConfig (..) ) @@ -74,7 +75,7 @@ import Ouroboros.Network.Mux , OuroborosApplication (..) , RunMiniProtocol (..) ) -import Ouroboros.Network.NodeToClient +import Cardano.Network.NodeToClient ( NetworkConnectTracers (..) , NodeToClientVersion (..) , NodeToClientVersionData (..) @@ -119,7 +120,7 @@ instance MonadOuroboros IO where connectTo (mkLocalSnocket iocp) tracers versions socket >>= either throwIO return where tracers = NetworkConnectTracers - { nctMuxTracer = nullTracer + { nctMuxTracers = Network.Mux.nullTracers , nctHandshakeTracer = nullTracer } @@ -167,7 +168,7 @@ codecs epochSlots nodeToClientV = supportedVersions = supportedNodeToClientVersions (Proxy @(BlockT IO)) cfg = - CardanoCodecConfig byron shelley allegra mary alonzo babbage conway + CardanoCodecConfig byron shelley allegra mary alonzo babbage conway dijkstra where byron = ByronCodecConfig epochSlots shelley = ShelleyCodecConfig @@ -176,3 +177,4 @@ codecs epochSlots nodeToClientV = alonzo = ShelleyCodecConfig babbage = ShelleyCodecConfig conway = ShelleyCodecConfig + dijkstra = ShelleyCodecConfig diff --git a/src/Kupo/Data/Cardano.hs b/src/Kupo/Data/Cardano.hs index 59e9ed16..635cff7e 100644 --- a/src/Kupo/Data/Cardano.hs +++ b/src/Kupo/Data/Cardano.hs @@ -97,9 +97,12 @@ import Kupo.Data.Cardano.TransactionId import Kupo.Data.Cardano.TransactionIndex import Kupo.Data.Cardano.Value +import Unsafe.Coerce + ( unsafeCoerce + ) + import qualified Cardano.Chain.UTxO as Ledger.Byron import qualified Cardano.Ledger.Alonzo.Core as Ledger -import qualified Cardano.Ledger.Alonzo.Tx as Ledger import qualified Cardano.Ledger.Alonzo.TxWits as Ledger import qualified Cardano.Ledger.Babbage.Core as Ledger import qualified Cardano.Ledger.Block as Ledger @@ -184,17 +187,24 @@ instance IsBlock Block where in foldrWithIndex ignoreProtocolTxs result (extractTxs blk) BlockShelley (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionShelley) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionShelley) result (txs ^. Ledger.txSeqBlockBodyL) BlockAllegra (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionAllegra) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionAllegra) result (txs ^. Ledger.txSeqBlockBodyL) BlockMary (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionMary) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionMary) result (txs ^. Ledger.txSeqBlockBodyL) BlockAlonzo (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionAlonzo) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionAlonzo) result (txs ^. Ledger.txSeqBlockBodyL) BlockBabbage (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionBabbage) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionBabbage) result (txs ^. Ledger.txSeqBlockBodyL) BlockConway (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionConway) result (Ledger.fromTxSeq txs) + foldrWithIndex (\ix -> fn ix . TransactionConway) result (txs ^. Ledger.txSeqBlockBodyL) + -- NOTE: DijkstraEra transactions are representationally identical to + -- ConwayEra but use nominally distinct data family instances, so coerce + -- is not available. We unsafeCoerce to reuse TransactionConway rather + -- than adding a TransactionDijkstra constructor that would duplicate + -- all Conway handling throughout the codebase. + BlockDijkstra (ShelleyBlock (Ledger.Block _ txs) _) -> + foldrWithIndex (\ix -> fn ix . TransactionConway . unsafeCoerce) result (txs ^. Ledger.txSeqBlockBodyL) spentInputs :: Transaction diff --git a/src/Kupo/Data/Cardano/AssetName.hs b/src/Kupo/Data/Cardano/AssetName.hs index ccb3f5ac..e0c6927c 100644 --- a/src/Kupo/Data/Cardano/AssetName.hs +++ b/src/Kupo/Data/Cardano/AssetName.hs @@ -2,10 +2,6 @@ module Kupo.Data.Cardano.AssetName where import Kupo.Prelude -import Ouroboros.Consensus.Util - ( eitherToMaybe - ) - import qualified Cardano.Ledger.Mary.Value as Ledger import qualified Data.ByteString as BS diff --git a/src/Kupo/Data/Cardano/Metadata.hs b/src/Kupo/Data/Cardano/Metadata.hs index 9abf0456..bcc2561a 100644 --- a/src/Kupo/Data/Cardano/Metadata.hs +++ b/src/Kupo/Data/Cardano/Metadata.hs @@ -22,12 +22,7 @@ import Kupo.Data.Cardano.MetadataHash ( MetadataHash , metadataHashToJson ) -import Ouroboros.Consensus.Util - ( eitherToMaybe - ) - import qualified Cardano.Ledger.Allegra.Scripts as Ledger.Allegra -import qualified Cardano.Ledger.Alonzo.TxAuxData as Ledger.Alonzo import qualified Cardano.Ledger.Core as Ledger import qualified Cardano.Ledger.Shelley.TxAuxData as Ledger import qualified Data.Aeson as Json @@ -39,6 +34,10 @@ import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Text.Read as T +-- NOTE: Kept as ConwayEra rather than DijkstraEra because Dijkstra +-- transactions are coerced to Conway at the block-processing boundary +-- (see Kupo.Data.Cardano). The two eras share identical representations +-- for AlonzoTxAuxData, so the choice is cosmetic. type Metadata = AlonzoTxAuxData ConwayEra @@ -175,13 +174,13 @@ fromMaryMetadata (AllegraTxAuxData labels timelocks) = {-# INLINABLE fromMaryMetadata #-} fromAlonzoMetadata :: AlonzoTxAuxData AlonzoEra -> Metadata -fromAlonzoMetadata = - Ledger.Alonzo.translateAlonzoTxAuxData +fromAlonzoMetadata (AlonzoTxAuxData labels timelocks scripts) = + AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) scripts {-# INLINABLE fromAlonzoMetadata #-} fromBabbageMetadata :: AlonzoTxAuxData BabbageEra -> Metadata -fromBabbageMetadata = - Ledger.upgradeTxAuxData +fromBabbageMetadata (AlonzoTxAuxData labels timelocks scripts) = + AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) scripts {-# INLINABLE fromBabbageMetadata #-} fromConwayMetadata :: AlonzoTxAuxData ConwayEra -> Metadata diff --git a/src/Kupo/Data/Cardano/Point.hs b/src/Kupo/Data/Cardano/Point.hs index 6c1ab358..2a14f9e0 100644 --- a/src/Kupo/Data/Cardano/Point.hs +++ b/src/Kupo/Data/Cardano/Point.hs @@ -45,7 +45,7 @@ import qualified Ouroboros.Network.Block as Ouroboros type Point = Ouroboros.Point Block -instance ToJSON Point where +instance {-# OVERLAPPING #-} ToJSON Point where toJSON = error "ToJSON Point called instead of 'toEncoding'." toEncoding = pointToJson diff --git a/src/Kupo/Data/Cardano/Script.hs b/src/Kupo/Data/Cardano/Script.hs index 6e18f464..95930b47 100644 --- a/src/Kupo/Data/Cardano/Script.hs +++ b/src/Kupo/Data/Cardano/Script.hs @@ -16,10 +16,6 @@ import Kupo.Data.Cardano.NativeScript import Kupo.Data.Cardano.ScriptHash ( ScriptHash ) -import Ouroboros.Consensus.Util - ( eitherToMaybe - ) - import qualified Cardano.Ledger.Allegra.Scripts as Ledger.Allegra import qualified Cardano.Ledger.Allegra.TxAuxData as Ledger.Allegra import qualified Cardano.Ledger.Alonzo as Ledger.Alonzo @@ -42,9 +38,9 @@ type Script = scriptFromAllegraAuxiliaryData :: forall era. ( Ledger.Core.Era era - , Ledger.Core.Script era ~ Ledger.Allegra.Timelock era + , Ledger.Core.NativeScript era ~ Ledger.Allegra.Timelock era ) - => (Ledger.Core.Script era -> Script) + => (Ledger.Allegra.Timelock era -> Script) -> Ledger.Allegra.AllegraTxAuxData era -> Map ScriptHash Script -> Map ScriptHash Script @@ -66,7 +62,7 @@ scriptFromAlonzoAuxiliaryData -> Map ScriptHash Script scriptFromAlonzoAuxiliaryData liftScript (Ledger.Alonzo.AlonzoTxAuxData _ scripts _) m0 = foldr - (\((liftScript . Ledger.Alonzo.TimelockScript) -> s) -> Map.insert (hashScript s) s) + (\((liftScript . Ledger.Alonzo.NativeScript) -> s) -> Map.insert (hashScript s) s) m0 scripts {-# INLINABLE scriptFromAlonzoAuxiliaryData #-} @@ -75,14 +71,14 @@ fromAllegraScript :: Ledger.Allegra.Timelock AllegraEra -> Script fromAllegraScript = - Ledger.Alonzo.TimelockScript . Ledger.Allegra.translateTimelock + Ledger.Alonzo.NativeScript . Ledger.Allegra.translateTimelock {-# INLINABLE fromAllegraScript #-} fromMaryScript :: Ledger.Allegra.Timelock MaryEra -> Script fromMaryScript = - Ledger.Alonzo.TimelockScript . Ledger.Allegra.translateTimelock + Ledger.Alonzo.NativeScript . Ledger.Allegra.translateTimelock {-# INLINABLE fromMaryScript #-} fromAlonzoScript @@ -112,13 +108,14 @@ scriptToJson scriptToJson script = encodeObject [ ("script", encodeBytes (Ledger.Core.originalBytes script)) , ("language", case script of - Ledger.Alonzo.TimelockScript _ -> + Ledger.Alonzo.NativeScript _ -> Json.text "native" Ledger.Alonzo.PlutusScript ps -> case Ledger.Alonzo.plutusScriptLanguage ps of Ledger.PlutusV1 -> Json.text "plutus:v1" Ledger.PlutusV2 -> Json.text "plutus:v2" Ledger.PlutusV3 -> Json.text "plutus:v3" + Ledger.PlutusV4 -> Json.text "plutus:v4" ) ] @@ -128,13 +125,14 @@ scriptToBytes scriptToBytes = let withTag n s = BS.singleton n <> Ledger.Core.originalBytes s in \case - Ledger.Alonzo.TimelockScript script -> + Ledger.Alonzo.NativeScript script -> withTag 0 script Ledger.Alonzo.PlutusScript script -> case Ledger.Alonzo.plutusScriptLanguage script of Ledger.PlutusV1 -> withTag 1 script Ledger.PlutusV2 -> withTag 2 script Ledger.PlutusV3 -> withTag 3 script + Ledger.PlutusV4 -> withTag 4 script unsafeScriptFromBytes :: HasCallStack @@ -150,12 +148,13 @@ scriptFromBytes scriptFromBytes (toLazy -> bytes) = eitherToMaybe $ do (script, tag) <- left (DecoderErrorDeserialiseFailure "Script") $ - Cbor.deserialiseFromBytes Cbor.decodeWord8 bytes + Cbor.deserialiseFromBytes Cbor.decodeWord bytes case tag of - 0 -> Ledger.Alonzo.TimelockScript <$> decodeCborAnn @BabbageEra "Timelock" decCBOR script + 0 -> Ledger.Alonzo.NativeScript <$> decodeCborAnn @BabbageEra "Timelock" decCBOR script 1 -> plutusScript Ledger.PlutusV1 script 2 -> plutusScript Ledger.PlutusV2 script 3 -> plutusScript Ledger.PlutusV3 script + 4 -> plutusScript Ledger.PlutusV4 script t -> Left (DecoderErrorUnknownTag "Script" t) where plutusScript lang s = @@ -165,7 +164,7 @@ scriptFromBytes (toLazy -> bytes) = script = maybeToRight (Ledger.DecoderErrorCustom "Incompatible language and era" $ show (lang, uplc)) - (Ledger.Alonzo.mkBinaryPlutusScript @ConwayEra lang uplc) + (Ledger.Alonzo.mkBinaryPlutusScript lang uplc) in Ledger.Alonzo.PlutusScript <$> script @@ -173,7 +172,7 @@ fromNativeScript :: NativeScript -> Script fromNativeScript = - Ledger.Alonzo.TimelockScript + Ledger.Alonzo.NativeScript {-# INLINABLE fromNativeScript #-} hashScript diff --git a/src/Kupo/Data/Cardano/Transaction.hs b/src/Kupo/Data/Cardano/Transaction.hs index 134a3f4e..19c1ee96 100644 --- a/src/Kupo/Data/Cardano/Transaction.hs +++ b/src/Kupo/Data/Cardano/Transaction.hs @@ -8,9 +8,7 @@ import Kupo.Data.Cardano.TransactionId ) import qualified Cardano.Chain.UTxO as Ledger.Byron -import qualified Cardano.Ledger.Alonzo.Tx as Ledger.Alonzo import qualified Cardano.Ledger.Core as Ledger -import qualified Cardano.Ledger.Shelley.Tx as Ledger.Shelley -- Transaction @@ -20,37 +18,31 @@ data Transaction !Ledger.Byron.Tx !Ledger.Byron.TxId | TransactionShelley - !(Ledger.Shelley.ShelleyTx ShelleyEra) + !(Ledger.Tx Ledger.TopTx ShelleyEra) | TransactionAllegra - !(Ledger.Shelley.ShelleyTx AllegraEra) + !(Ledger.Tx Ledger.TopTx AllegraEra) | TransactionMary - !(Ledger.Shelley.ShelleyTx MaryEra) + !(Ledger.Tx Ledger.TopTx MaryEra) | TransactionAlonzo - !(Ledger.Alonzo.AlonzoTx AlonzoEra) + !(Ledger.Tx Ledger.TopTx AlonzoEra) | TransactionBabbage - !(Ledger.Alonzo.AlonzoTx BabbageEra) + !(Ledger.Tx Ledger.TopTx BabbageEra) | TransactionConway - !(Ledger.Alonzo.AlonzoTx ConwayEra) + !(Ledger.Tx Ledger.TopTx ConwayEra) instance HasTransactionId Transaction where getTransactionId = \case TransactionByron _ i -> transactionIdFromByron i TransactionShelley tx -> - let body = Ledger.Shelley.body tx - in Ledger.txIdTxBody @ShelleyEra body + Ledger.txIdTx @ShelleyEra tx TransactionAllegra tx -> - let body = Ledger.Shelley.body tx - in Ledger.txIdTxBody @AllegraEra body + Ledger.txIdTx @AllegraEra tx TransactionMary tx -> - let body = Ledger.Shelley.body tx - in Ledger.txIdTxBody @MaryEra body + Ledger.txIdTx @MaryEra tx TransactionAlonzo tx -> - let body = Ledger.Alonzo.body tx - in Ledger.txIdTxBody @AlonzoEra body + Ledger.txIdTx @AlonzoEra tx TransactionBabbage tx -> - let body = Ledger.Alonzo.body tx - in Ledger.txIdTxBody @BabbageEra body + Ledger.txIdTx @BabbageEra tx TransactionConway tx -> - let body = Ledger.Alonzo.body tx - in Ledger.txIdTxBody @ConwayEra body + Ledger.txIdTx @ConwayEra tx diff --git a/src/Kupo/Data/Hydra.hs b/src/Kupo/Data/Hydra.hs index 01f0401b..c7aa9a0a 100644 --- a/src/Kupo/Data/Hydra.hs +++ b/src/Kupo/Data/Hydra.hs @@ -10,8 +10,10 @@ import Cardano.Crypto.Hash , hashWith ) import Cardano.Ledger.Alonzo.Scripts - ( AlonzoPlutusPurpose (..) - , AsIx (..) + ( AsIx (..) + ) +import Cardano.Ledger.Conway.Scripts + ( ConwayPlutusPurpose (..) ) import Cardano.Ledger.Alonzo.TxWits ( unRedeemers @@ -26,6 +28,7 @@ import Cardano.Ledger.Api , scriptTxWitsL , witsTxL ) +import qualified Cardano.Ledger.Core as Ledger import Cardano.Ledger.Hashes ( unsafeMakeSafeHash ) @@ -47,9 +50,7 @@ import Kupo.Data.Cardano , TransactionId , Value , binaryDataFromBytes - , fromBabbageData - , fromBabbageOutput - , fromBabbageScript + , fromConwayData , getOutputIndex , getTransactionId , mkOutput @@ -73,7 +74,6 @@ import Kupo.Data.PartialBlock , PartialTransaction (..) ) -import qualified Cardano.Ledger.Api as Ledger import qualified Codec.CBOR.Decoding as Cbor import qualified Codec.CBOR.Read as Cbor import qualified Data.Aeson.Key as Key @@ -181,7 +181,7 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do bytes <- decodeBase16' hexText - tx <- case decodeCborAnn @ConwayEra "PartialTransaction" decCBOR (fromStrict bytes) of + (tx :: Ledger.Tx Ledger.TopTx ConwayEra) <- case decodeCborAnn @ConwayEra "PartialTransaction" decCBOR (fromStrict bytes) of Left e -> fail $ show e Right tx -> pure tx @@ -198,23 +198,23 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do let body' = tx ^. bodyTxL let id = Ledger.txIdTxBody body' let wits' = tx ^. witsTxL - let outputs' = map fromBabbageOutput $ toList (body' ^. outputsTxBodyL) + let outputs' = toList (body' ^. outputsTxBodyL) pure PartialTransaction { id , inputs = toList (body' ^. inputsTxBodyL) , outputs = withReferences 0 id outputs' - , datums = Map.map fromBabbageData $ unTxDats (wits' ^. datsTxWitsL) + , datums = Map.map fromConwayData $ unTxDats (wits' ^. datsTxWitsL) , spendRedeemers = Map.foldrWithKey (\purpose (redeemer, _) -> case purpose of - AlonzoSpending (AsIx ix) -> Map.insert (fromIntegral ix) (fromBabbageData redeemer) + ConwaySpending (AsIx ix) -> Map.insert (fromIntegral ix) (fromConwayData redeemer) _ -> identity ) mempty (unRedeemers $ wits' ^. rdmrsTxWitsL) - , scripts = Map.map fromBabbageScript (wits' ^. scriptTxWitsL) + , scripts = wits' ^. scriptTxWitsL , metadata = Nothing } @@ -305,6 +305,8 @@ decodeScriptInEnvelope = Json.withObject "ScriptInEnvelope" $ \o -> do scriptFromBytes' (BS.pack [2] <> nestedBytes) "PlutusScriptLanguage PlutusScriptV3" -> scriptFromBytes' (BS.pack [3] <> nestedBytes) + "PlutusScriptLanguage PlutusScriptV4" -> + scriptFromBytes' (BS.pack [4] <> nestedBytes) (_ :: Text) -> fail "unrecognized script language" where diff --git a/src/Kupo/Data/Ogmios.hs b/src/Kupo/Data/Ogmios.hs index 0b24ee28..5f172e40 100644 --- a/src/Kupo/Data/Ogmios.hs +++ b/src/Kupo/Data/Ogmios.hs @@ -325,6 +325,7 @@ decodeScript = Json.withObject "Script" $ \o -> do "plutus:v1" -> decodePlutus "01" =<< o .: "cbor" "plutus:v2" -> decodePlutus "02" =<< o .: "cbor" "plutus:v3" -> decodePlutus "03" =<< o .: "cbor" + "plutus:v4" -> decodePlutus "04" =<< o .: "cbor" (_ :: Text) -> fail "unrecognized script language" where decodeNative = diff --git a/src/Kupo/Prelude.hs b/src/Kupo/Prelude.hs index 6bd04ac6..fc4f858f 100644 --- a/src/Kupo/Prelude.hs +++ b/src/Kupo/Prelude.hs @@ -40,6 +40,7 @@ module Kupo.Prelude , at -- * Extras + , eitherToMaybe , foldrWithIndex , next , nubOn @@ -75,6 +76,7 @@ module Kupo.Prelude , AlonzoEra , BabbageEra , ConwayEra + , DijkstraEra , MostRecentEra -- * System @@ -92,7 +94,7 @@ import Cardano.Crypto.Hash , Hash (..) , HashAlgorithm (..) , hashFromBytes - , sizeHash + , hashSize ) import Cardano.Ledger.Allegra ( AllegraEra @@ -169,7 +171,8 @@ import Ouroboros.Consensus.Cardano.Block ( CardanoEras ) import Ouroboros.Consensus.Shelley.Eras - ( StandardCrypto + ( DijkstraEra + , StandardCrypto ) import Ouroboros.Consensus.Shelley.Ledger ( ShelleyBlock @@ -358,6 +361,10 @@ unsafeDecodeCbor lbl decoder = -- Extras -- +-- | Convert an 'Either' to a 'Maybe', discarding the error. +eitherToMaybe :: Either e a -> Maybe a +eitherToMaybe = either (const Nothing) Just + -- | Remove duplicates from a list based on information extracted from the -- elements. nubOn :: Eq b => (a -> b) -> [a] -> [a] @@ -419,7 +426,7 @@ unsafeHashFromBytes bytes digestSize :: forall alg. HashAlgorithm alg => Int digestSize = - fromIntegral (sizeHash (Proxy @alg)) + fromIntegral (hashSize (Proxy @alg)) {-# INLINABLE digestSize #-} hashToJson :: HashAlgorithm alg => Hash alg a -> Json.Encoding From b6108fa3715fc1bf485b3804546cd36d5dd42cc8 Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Wed, 13 May 2026 22:42:03 -0500 Subject: [PATCH 03/68] fix: properly support DijkstraEra instead of unsafeCoerce through ConwayEra Replace the unsafeCoerce-based approach to Dijkstra era handling with proper TransactionDijkstra constructors and explicit era conversion functions. Change the Metadata, Output, Script, and BinaryData type aliases from ConwayEra to DijkstraEra and add the necessary upgrade paths through all era conversion functions using Ledger.Dijkstra.upgradeTimelock. Add cardano-ledger-dijkstra as an explicit dependency. Co-Authored-By: Claude --- kupo.cabal | 13 +++++-- package.yaml | 1 + src/Kupo/Data/Cardano.hs | 54 ++++++++++++++++++++++------ src/Kupo/Data/Cardano/BinaryData.hs | 23 ++++++++++++ src/Kupo/Data/Cardano/Datum.hs | 20 +++++++++++ src/Kupo/Data/Cardano/Metadata.hs | 30 ++++++++-------- src/Kupo/Data/Cardano/Output.hs | 26 ++++++++++---- src/Kupo/Data/Cardano/Redeemers.hs | 6 ++++ src/Kupo/Data/Cardano/Script.hs | 24 ++++++++----- src/Kupo/Data/Cardano/Transaction.hs | 4 +++ src/Kupo/Data/Hydra.hs | 6 ++-- 11 files changed, 163 insertions(+), 44 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index 130f18ff..9beb2672 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -1,6 +1,6 @@ cabal-version: 3.0 --- This file has been generated from package.yaml by hpack version 0.38.2. +-- This file has been generated from package.yaml by hpack version 0.38.3. -- -- see: https://github.com/sol/hpack @@ -131,6 +131,8 @@ library Kupo.Version.TH other-modules: Paths_kupo + autogen-modules: + Paths_kupo hs-source-dirs: src default-extensions: @@ -184,6 +186,7 @@ library , bytestring , cardano-crypto-class , cardano-crypto-wrapper + , cardano-diffusion , cardano-ledger-allegra , cardano-ledger-alonzo , cardano-ledger-api @@ -192,6 +195,7 @@ library , cardano-ledger-byron , cardano-ledger-conway , cardano-ledger-core + , cardano-ledger-dijkstra , cardano-ledger-mary , cardano-ledger-shelley , cardano-slotting @@ -214,7 +218,6 @@ library , modern-uri , network-mux , optparse-applicative - , cardano-diffusion , ouroboros-consensus , ouroboros-consensus:cardano , ouroboros-consensus:diffusion @@ -255,6 +258,8 @@ executable kupo main-is: Main.hs other-modules: Paths_kupo + autogen-modules: + Paths_kupo hs-source-dirs: app default-extensions: @@ -332,6 +337,8 @@ test-suite unit Test.Kupo.OptionsSpec Test.KupoSpec Paths_kupo + autogen-modules: + Paths_kupo hs-source-dirs: test default-extensions: @@ -388,6 +395,7 @@ test-suite unit , http-media , http-types , io-classes + , io-classes:si-timers , io-sim , kupo , lens-aeson @@ -395,7 +403,6 @@ test-suite unit , process , quickcheck-state-machine , relude - , io-classes:si-timers , sqlite-simple , stm , temporary diff --git a/package.yaml b/package.yaml index 307c932d..fae6acf4 100644 --- a/package.yaml +++ b/package.yaml @@ -71,6 +71,7 @@ library: - cardano-ledger-byron - cardano-ledger-conway - cardano-ledger-core + - cardano-ledger-dijkstra - cardano-ledger-mary - cardano-ledger-shelley - cardano-slotting diff --git a/src/Kupo/Data/Cardano.hs b/src/Kupo/Data/Cardano.hs index 635cff7e..64d49adb 100644 --- a/src/Kupo/Data/Cardano.hs +++ b/src/Kupo/Data/Cardano.hs @@ -97,10 +97,6 @@ import Kupo.Data.Cardano.TransactionId import Kupo.Data.Cardano.TransactionIndex import Kupo.Data.Cardano.Value -import Unsafe.Coerce - ( unsafeCoerce - ) - import qualified Cardano.Chain.UTxO as Ledger.Byron import qualified Cardano.Ledger.Alonzo.Core as Ledger import qualified Cardano.Ledger.Alonzo.TxWits as Ledger @@ -198,13 +194,8 @@ instance IsBlock Block where foldrWithIndex (\ix -> fn ix . TransactionBabbage) result (txs ^. Ledger.txSeqBlockBodyL) BlockConway (ShelleyBlock (Ledger.Block _ txs) _) -> foldrWithIndex (\ix -> fn ix . TransactionConway) result (txs ^. Ledger.txSeqBlockBodyL) - -- NOTE: DijkstraEra transactions are representationally identical to - -- ConwayEra but use nominally distinct data family instances, so coerce - -- is not available. We unsafeCoerce to reuse TransactionConway rather - -- than adding a TransactionDijkstra constructor that would duplicate - -- all Conway handling throughout the codebase. BlockDijkstra (ShelleyBlock (Ledger.Block _ txs) _) -> - foldrWithIndex (\ix -> fn ix . TransactionConway . unsafeCoerce) result (txs ^. Ledger.txSeqBlockBodyL) + foldrWithIndex (\ix -> fn ix . TransactionDijkstra) result (txs ^. Ledger.txSeqBlockBodyL) spentInputs :: Transaction @@ -236,6 +227,12 @@ instance IsBlock Block where tx ^. Ledger.bodyTxL . Ledger.inputsTxBodyL Ledger.IsValid False -> tx ^. Ledger.bodyTxL . Ledger.collateralInputsTxBodyL + TransactionDijkstra tx -> + case tx ^. Ledger.isValidTxL of + Ledger.IsValid True -> + tx ^. Ledger.bodyTxL . Ledger.inputsTxBodyL + Ledger.IsValid False -> + tx ^. Ledger.bodyTxL . Ledger.collateralInputsTxBodyL where transformByron (Ledger.Byron.TxInUtxo txId ix) = mkOutputReference @@ -319,12 +316,29 @@ instance IsBlock Block where in case tx ^. Ledger.isValidTxL of Ledger.IsValid True -> - traverseAndTransform identity txId meta 0 outs + traverseAndTransform fromConwayOutput txId meta 0 outs Ledger.IsValid False -> -- From Conway formal specification: -- -- Note that the new collOuts function generates a single output -- with an index |txouts{txb}|. + let start = fromIntegral (length outs) in + case body ^. Ledger.collateralReturnTxBodyL of + SNothing -> + [] + SJust r -> + traverseAndTransform fromConwayOutput txId meta start (r :<| mempty) + TransactionDijkstra tx -> + let + body = tx ^. Ledger.bodyTxL + txId = Ledger.txIdTxBody @DijkstraEra body + outs = body ^. Ledger.outputsTxBodyL + meta = tx ^. Ledger.auxDataTxL & strictMaybe emptyMetadata fromDijkstraMetadata + in + case tx ^. Ledger.isValidTxL of + Ledger.IsValid True -> + traverseAndTransform identity txId meta 0 outs + Ledger.IsValid False -> let start = fromIntegral (length outs) in case body ^. Ledger.collateralReturnTxBodyL of SNothing -> @@ -391,6 +405,8 @@ instance IsBlock Block where fromBabbageData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) TransactionConway tx -> fromConwayData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) + TransactionDijkstra tx -> + fromDijkstraData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) witnessedScripts :: Transaction @@ -423,6 +439,13 @@ instance IsBlock Block where & scriptsFromOutputs (fromBabbageOutput <$> tx ^. Ledger.bodyTxL . Ledger.outputsTxBodyL) TransactionConway tx -> + ( fromConwayScript <$> tx ^. Ledger.witsTxL . Ledger.scriptTxWitsL + ) & strictMaybe identity + (scriptFromAlonzoAuxiliaryData fromConwayScript) + (tx ^. Ledger.auxDataTxL) + & scriptsFromOutputs + (fromConwayOutput <$> tx ^. Ledger.bodyTxL . Ledger.outputsTxBodyL) + TransactionDijkstra tx -> ( tx ^. Ledger.witsTxL . Ledger.scriptTxWitsL ) & strictMaybe identity (scriptFromAlonzoAuxiliaryData identity) @@ -478,6 +501,13 @@ instance IsBlock Block where SJust auxData -> let meta = fromConwayMetadata auxData in Just (hashMetadata meta, meta) + TransactionDijkstra tx -> + case tx ^. Ledger.auxDataTxL of + SNothing -> + Nothing + SJust auxData -> + let meta = fromDijkstraMetadata auxData + in Just (hashMetadata meta, meta) spendRedeemer :: Transaction @@ -499,3 +529,5 @@ instance IsBlock Block where Just (RedeemersBabbage (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) TransactionConway tx -> Just (RedeemersConway (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) + TransactionDijkstra tx -> + Just (RedeemersDisjkstra (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) diff --git a/src/Kupo/Data/Cardano/BinaryData.hs b/src/Kupo/Data/Cardano/BinaryData.hs index fae48be1..096d6c67 100644 --- a/src/Kupo/Data/Cardano/BinaryData.hs +++ b/src/Kupo/Data/Cardano/BinaryData.hs @@ -75,3 +75,26 @@ fromConwayData fromConwayData = Ledger.dataToBinaryData {-# INLINEABLE fromConwayData #-} + +fromDijkstraData + :: Ledger.Data DijkstraEra + -> BinaryData +fromDijkstraData = + unsafeBinaryDataFromBytes . Ledger.originalBytes +{-# INLINEABLE fromDijkstraData #-} + +fromDijkstraBinaryData + :: Ledger.BinaryData DijkstraEra + -> BinaryData +fromDijkstraBinaryData = + unsafeBinaryDataFromBytes . Ledger.originalBytes . Ledger.binaryDataToData +{-# INLINEABLE fromDijkstraBinaryData #-} + +toDijkstraBinaryData + :: BinaryData + -> Ledger.BinaryData DijkstraEra +toDijkstraBinaryData bd = + case Ledger.makeBinaryData (toShort (binaryDataToBytes bd)) of + Right b -> b + Left _ -> error "toDijkstraBinaryData: impossible" +{-# INLINEABLE toDijkstraBinaryData #-} diff --git a/src/Kupo/Data/Cardano/Datum.hs b/src/Kupo/Data/Cardano/Datum.hs index d4de93a3..fc2c9dd8 100644 --- a/src/Kupo/Data/Cardano/Datum.hs +++ b/src/Kupo/Data/Cardano/Datum.hs @@ -4,7 +4,9 @@ import Kupo.Prelude import Kupo.Data.Cardano.BinaryData ( BinaryData + , fromDijkstraBinaryData , hashBinaryData + , toDijkstraBinaryData ) import Kupo.Data.Cardano.DatumHash ( DatumHash @@ -36,6 +38,24 @@ fromConwayDatum = \case Ledger.DatumHash ref -> Reference (Left ref) Ledger.Datum bin -> Inline (Right bin) +fromDijkstraDatum + :: Ledger.Datum DijkstraEra + -> Datum +fromDijkstraDatum = \case + Ledger.NoDatum -> NoDatum + Ledger.DatumHash ref -> Reference (Left ref) + Ledger.Datum bin -> Inline (Right (fromDijkstraBinaryData bin)) + +toDijkstraDatum + :: Datum + -> Ledger.Datum DijkstraEra +toDijkstraDatum = \case + NoDatum -> Ledger.NoDatum + Reference (Left ref) -> Ledger.DatumHash ref + Reference (Right bin) -> Ledger.Datum (toDijkstraBinaryData bin) + Inline (Left ref) -> Ledger.DatumHash ref + Inline (Right bin) -> Ledger.Datum (toDijkstraBinaryData bin) + getBinaryData :: Datum -> Maybe BinaryData diff --git a/src/Kupo/Data/Cardano/Metadata.hs b/src/Kupo/Data/Cardano/Metadata.hs index bcc2561a..bd56e892 100644 --- a/src/Kupo/Data/Cardano/Metadata.hs +++ b/src/Kupo/Data/Cardano/Metadata.hs @@ -24,6 +24,7 @@ import Kupo.Data.Cardano.MetadataHash ) import qualified Cardano.Ledger.Allegra.Scripts as Ledger.Allegra import qualified Cardano.Ledger.Core as Ledger +import qualified Cardano.Ledger.Dijkstra.Scripts as Ledger.Dijkstra import qualified Cardano.Ledger.Shelley.TxAuxData as Ledger import qualified Data.Aeson as Json import qualified Data.Aeson.Encoding as Json @@ -34,12 +35,8 @@ import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Text.Read as T --- NOTE: Kept as ConwayEra rather than DijkstraEra because Dijkstra --- transactions are coerced to Conway at the block-processing boundary --- (see Kupo.Data.Cardano). The two eras share identical representations --- for AlonzoTxAuxData, so the choice is cosmetic. type Metadata = - AlonzoTxAuxData ConwayEra + AlonzoTxAuxData DijkstraEra emptyMetadata :: Metadata emptyMetadata = @@ -67,7 +64,7 @@ metadataToText = metadataFromText :: Text -> Maybe Metadata metadataFromText txt = do bytes <- eitherToMaybe $ decodeBase16 (encodeUtf8 txt) - eitherToMaybe $ decodeCborAnn @ConwayEra "Metadata" decCBOR (toLazy bytes) + eitherToMaybe $ decodeCborAnn @DijkstraEra "Metadata" decCBOR (toLazy bytes) metadataToJson :: Metadata -> Json.Encoding metadataToJson (AlonzoTxAuxData labels _ _) = @@ -165,25 +162,30 @@ fromShelleyMetadata (ShelleyTxAuxData labels) = fromAllegraMetadata :: AllegraTxAuxData AllegraEra -> Metadata fromAllegraMetadata (AllegraTxAuxData labels timelocks) = - AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) mempty + AlonzoTxAuxData labels (Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock <$> timelocks) mempty {-# INLINABLE fromAllegraMetadata #-} fromMaryMetadata :: AllegraTxAuxData MaryEra -> Metadata fromMaryMetadata (AllegraTxAuxData labels timelocks) = - AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) mempty + AlonzoTxAuxData labels (Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock <$> timelocks) mempty {-# INLINABLE fromMaryMetadata #-} fromAlonzoMetadata :: AlonzoTxAuxData AlonzoEra -> Metadata -fromAlonzoMetadata (AlonzoTxAuxData labels timelocks scripts) = - AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) scripts +fromAlonzoMetadata (AlonzoTxAuxData labels timelocks plutus) = + AlonzoTxAuxData labels (Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock <$> timelocks) plutus {-# INLINABLE fromAlonzoMetadata #-} fromBabbageMetadata :: AlonzoTxAuxData BabbageEra -> Metadata -fromBabbageMetadata (AlonzoTxAuxData labels timelocks scripts) = - AlonzoTxAuxData labels (Ledger.Allegra.translateTimelock <$> timelocks) scripts +fromBabbageMetadata (AlonzoTxAuxData labels timelocks plutus) = + AlonzoTxAuxData labels (Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock <$> timelocks) plutus {-# INLINABLE fromBabbageMetadata #-} fromConwayMetadata :: AlonzoTxAuxData ConwayEra -> Metadata -fromConwayMetadata = - identity +fromConwayMetadata (AlonzoTxAuxData labels timelocks plutus) = + AlonzoTxAuxData labels (Ledger.Dijkstra.upgradeTimelock <$> timelocks) plutus {-# INLINABLE fromConwayMetadata #-} + +fromDijkstraMetadata :: AlonzoTxAuxData DijkstraEra -> Metadata +fromDijkstraMetadata = + identity +{-# INLINABLE fromDijkstraMetadata #-} diff --git a/src/Kupo/Data/Cardano/Output.hs b/src/Kupo/Data/Cardano/Output.hs index c51bf076..ff92bea2 100644 --- a/src/Kupo/Data/Cardano/Output.hs +++ b/src/Kupo/Data/Cardano/Output.hs @@ -17,8 +17,8 @@ import Kupo.Data.Cardano.Address ) import Kupo.Data.Cardano.Datum ( Datum - , fromConwayDatum - , toConwayDatum + , fromDijkstraDatum + , toDijkstraDatum ) import Kupo.Data.Cardano.Script ( ComparableScript @@ -53,7 +53,7 @@ import qualified Data.Map as Map -- Output type Output = - Ledger.Babbage.BabbageTxOut ConwayEra + Ledger.Babbage.BabbageTxOut DijkstraEra mkOutput :: Address @@ -65,7 +65,7 @@ mkOutput address value datum script = Ledger.Babbage.BabbageTxOut address value - (toConwayDatum datum) + (toDijkstraDatum datum) (maybeToStrictMaybe script) {-# INLINABLE mkOutput #-} @@ -116,9 +116,23 @@ fromBabbageOutput :: Ledger.Core.TxOut BabbageEra -> Output fromBabbageOutput = - Ledger.Core.upgradeTxOut + Ledger.Core.upgradeTxOut . Ledger.Core.upgradeTxOut {-# INLINABLE fromBabbageOutput #-} +fromConwayOutput + :: Ledger.Core.TxOut ConwayEra + -> Output +fromConwayOutput = + Ledger.Core.upgradeTxOut +{-# INLINABLE fromConwayOutput #-} + +fromDijkstraOutput + :: Ledger.Core.TxOut DijkstraEra + -> Output +fromDijkstraOutput = + identity +{-# INLINABLE fromDijkstraOutput #-} + getAddress :: Output -> Address @@ -137,7 +151,7 @@ getDatum :: Output -> Datum getDatum (Ledger.Babbage.BabbageTxOut _address _value datum _refScript) = - fromConwayDatum datum + fromDijkstraDatum datum {-# INLINABLE getDatum #-} getScript diff --git a/src/Kupo/Data/Cardano/Redeemers.hs b/src/Kupo/Data/Cardano/Redeemers.hs index 55d70806..fc985c76 100644 --- a/src/Kupo/Data/Cardano/Redeemers.hs +++ b/src/Kupo/Data/Cardano/Redeemers.hs @@ -7,6 +7,7 @@ import Kupo.Data.Cardano.BinaryData , fromAlonzoData , fromBabbageData , fromConwayData + , fromDijkstraData ) import Kupo.Data.Cardano.OutputIndex ( InputIndex @@ -15,12 +16,14 @@ import Kupo.Data.Cardano.OutputIndex import qualified Cardano.Ledger.Alonzo.Scripts as Ledger import qualified Cardano.Ledger.Alonzo.TxWits as Ledger import qualified Cardano.Ledger.Conway.Scripts as Ledger +import qualified Cardano.Ledger.Dijkstra.Scripts as Ledger import qualified Data.Map as Map data Redeemers = RedeemersAlonzo (Ledger.Redeemers AlonzoEra) | RedeemersBabbage (Ledger.Redeemers BabbageEra) | RedeemersConway (Ledger.Redeemers ConwayEra) + | RedeemersDisjkstra (Ledger.Redeemers DijkstraEra) lookupSpendRedeemer :: InputIndex @@ -36,3 +39,6 @@ lookupSpendRedeemer ix = \case RedeemersConway (Ledger.Redeemers redeemers) -> let purpose = Ledger.ConwaySpending (Ledger.AsIx (fromIntegral ix)) in fromConwayData . fst <$> Map.lookup purpose redeemers + RedeemersDisjkstra (Ledger.Redeemers redeemers) -> + let purpose = Ledger.DijkstraSpending (Ledger.AsIx (fromIntegral ix)) + in fromDijkstraData . fst <$> Map.lookup purpose redeemers diff --git a/src/Kupo/Data/Cardano/Script.hs b/src/Kupo/Data/Cardano/Script.hs index 95930b47..100932bf 100644 --- a/src/Kupo/Data/Cardano/Script.hs +++ b/src/Kupo/Data/Cardano/Script.hs @@ -23,6 +23,7 @@ import qualified Cardano.Ledger.Alonzo.Scripts as Ledger.Alonzo import qualified Cardano.Ledger.Alonzo.TxAuxData as Ledger.Alonzo import qualified Cardano.Ledger.Binary.Plain as Ledger import qualified Cardano.Ledger.Core as Ledger.Core +import qualified Cardano.Ledger.Dijkstra.Scripts as Ledger.Dijkstra import qualified Cardano.Ledger.Plutus.Language as Ledger import qualified Codec.CBOR.Decoding as Cbor @@ -33,7 +34,7 @@ import qualified Data.ByteString as BS import qualified Data.Map as Map type Script = - Ledger.Alonzo.Script ConwayEra + Ledger.Alonzo.Script DijkstraEra scriptFromAllegraAuxiliaryData :: forall era. @@ -71,14 +72,14 @@ fromAllegraScript :: Ledger.Allegra.Timelock AllegraEra -> Script fromAllegraScript = - Ledger.Alonzo.NativeScript . Ledger.Allegra.translateTimelock + Ledger.Alonzo.NativeScript . Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock {-# INLINABLE fromAllegraScript #-} fromMaryScript :: Ledger.Allegra.Timelock MaryEra -> Script fromMaryScript = - Ledger.Alonzo.NativeScript . Ledger.Allegra.translateTimelock + Ledger.Alonzo.NativeScript . Ledger.Dijkstra.upgradeTimelock . Ledger.Allegra.translateTimelock {-# INLINABLE fromMaryScript #-} fromAlonzoScript @@ -92,16 +93,23 @@ fromBabbageScript :: Ledger.Alonzo.Script BabbageEra -> Script fromBabbageScript = - Ledger.Core.upgradeScript + Ledger.Core.upgradeScript . Ledger.Core.upgradeScript {-# INLINABLE fromBabbageScript #-} fromConwayScript :: Ledger.Alonzo.Script ConwayEra -> Script fromConwayScript = - identity + Ledger.Core.upgradeScript {-# INLINABLE fromConwayScript #-} +fromDijkstraScript + :: Ledger.Alonzo.Script DijkstraEra + -> Script +fromDijkstraScript = + identity +{-# INLINABLE fromDijkstraScript #-} + scriptToJson :: Script -> Json.Encoding @@ -150,7 +158,7 @@ scriptFromBytes (toLazy -> bytes) = (script, tag) <- left (DecoderErrorDeserialiseFailure "Script") $ Cbor.deserialiseFromBytes Cbor.decodeWord bytes case tag of - 0 -> Ledger.Alonzo.NativeScript <$> decodeCborAnn @BabbageEra "Timelock" decCBOR script + 0 -> (Ledger.Alonzo.NativeScript . Ledger.Dijkstra.upgradeTimelock) <$> decodeCborAnn @ConwayEra "Timelock" decCBOR script 1 -> plutusScript Ledger.PlutusV1 script 2 -> plutusScript Ledger.PlutusV2 script 3 -> plutusScript Ledger.PlutusV3 script @@ -172,14 +180,14 @@ fromNativeScript :: NativeScript -> Script fromNativeScript = - Ledger.Alonzo.NativeScript + fromConwayScript . Ledger.Alonzo.NativeScript {-# INLINABLE fromNativeScript #-} hashScript :: Script -> ScriptHash hashScript = - Ledger.Core.hashScript @ConwayEra + Ledger.Core.hashScript @DijkstraEra {-# INLINABLE hashScript #-} newtype ComparableScript = ComparableScript { unComparableScript :: Script } diff --git a/src/Kupo/Data/Cardano/Transaction.hs b/src/Kupo/Data/Cardano/Transaction.hs index 19c1ee96..cf88421e 100644 --- a/src/Kupo/Data/Cardano/Transaction.hs +++ b/src/Kupo/Data/Cardano/Transaction.hs @@ -29,6 +29,8 @@ data Transaction !(Ledger.Tx Ledger.TopTx BabbageEra) | TransactionConway !(Ledger.Tx Ledger.TopTx ConwayEra) + | TransactionDijkstra + !(Ledger.Tx Ledger.TopTx DijkstraEra) instance HasTransactionId Transaction where getTransactionId = \case @@ -46,3 +48,5 @@ instance HasTransactionId Transaction where Ledger.txIdTx @BabbageEra tx TransactionConway tx -> Ledger.txIdTx @ConwayEra tx + TransactionDijkstra tx -> + Ledger.txIdTx @DijkstraEra tx diff --git a/src/Kupo/Data/Hydra.hs b/src/Kupo/Data/Hydra.hs index c7aa9a0a..13dcdc5f 100644 --- a/src/Kupo/Data/Hydra.hs +++ b/src/Kupo/Data/Hydra.hs @@ -51,6 +51,8 @@ import Kupo.Data.Cardano , Value , binaryDataFromBytes , fromConwayData + , fromConwayOutput + , fromConwayScript , getOutputIndex , getTransactionId , mkOutput @@ -198,7 +200,7 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do let body' = tx ^. bodyTxL let id = Ledger.txIdTxBody body' let wits' = tx ^. witsTxL - let outputs' = toList (body' ^. outputsTxBodyL) + let outputs' = toList (fromConwayOutput <$> body' ^. outputsTxBodyL) pure PartialTransaction { id @@ -214,7 +216,7 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do ) mempty (unRedeemers $ wits' ^. rdmrsTxWitsL) - , scripts = wits' ^. scriptTxWitsL + , scripts = fromConwayScript <$> wits' ^. scriptTxWitsL , metadata = Nothing } From 00b332b9226aa36522ed2ca44f1fedcf69ebe96e Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 12:30:35 +1000 Subject: [PATCH 04/68] fix: use proper type-safe conversions for DijkstraEra BinaryData Replace unsafeBinaryDataFromBytes with Ledger.dataToBinaryData and Ledger.upgradeData for era conversions. With BinaryData now aliased to DijkstraEra, fromDijkstraBinaryData and toDijkstraBinaryData simplify to identity. Uses coerce for the phantom era parameter in Conway datum conversions. Co-Authored-By: Claude --- src/Kupo/Data/Cardano/BinaryData.hs | 15 +++++++-------- src/Kupo/Data/Cardano/Datum.hs | 16 ++++++++-------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/Kupo/Data/Cardano/BinaryData.hs b/src/Kupo/Data/Cardano/BinaryData.hs index 096d6c67..f77a2a56 100644 --- a/src/Kupo/Data/Cardano/BinaryData.hs +++ b/src/Kupo/Data/Cardano/BinaryData.hs @@ -12,7 +12,7 @@ import qualified Data.Aeson as Json import qualified Data.Aeson.Encoding as Json type BinaryData = - Ledger.BinaryData ConwayEra + Ledger.BinaryData DijkstraEra type BinaryDataHash = DatumHash @@ -66,6 +66,7 @@ fromBabbageData -> BinaryData fromBabbageData = Ledger.dataToBinaryData + . (Ledger.upgradeData :: Ledger.Data ConwayEra -> Ledger.Data DijkstraEra) . Ledger.upgradeData {-# INLINEABLE fromBabbageData #-} @@ -73,28 +74,26 @@ fromConwayData :: Ledger.Data ConwayEra -> BinaryData fromConwayData = - Ledger.dataToBinaryData + Ledger.dataToBinaryData . Ledger.upgradeData {-# INLINEABLE fromConwayData #-} fromDijkstraData :: Ledger.Data DijkstraEra -> BinaryData fromDijkstraData = - unsafeBinaryDataFromBytes . Ledger.originalBytes + Ledger.dataToBinaryData {-# INLINEABLE fromDijkstraData #-} fromDijkstraBinaryData :: Ledger.BinaryData DijkstraEra -> BinaryData fromDijkstraBinaryData = - unsafeBinaryDataFromBytes . Ledger.originalBytes . Ledger.binaryDataToData + identity {-# INLINEABLE fromDijkstraBinaryData #-} toDijkstraBinaryData :: BinaryData -> Ledger.BinaryData DijkstraEra -toDijkstraBinaryData bd = - case Ledger.makeBinaryData (toShort (binaryDataToBytes bd)) of - Right b -> b - Left _ -> error "toDijkstraBinaryData: impossible" +toDijkstraBinaryData = + identity {-# INLINEABLE toDijkstraBinaryData #-} diff --git a/src/Kupo/Data/Cardano/Datum.hs b/src/Kupo/Data/Cardano/Datum.hs index fc2c9dd8..bd6572ff 100644 --- a/src/Kupo/Data/Cardano/Datum.hs +++ b/src/Kupo/Data/Cardano/Datum.hs @@ -4,9 +4,7 @@ import Kupo.Prelude import Kupo.Data.Cardano.BinaryData ( BinaryData - , fromDijkstraBinaryData , hashBinaryData - , toDijkstraBinaryData ) import Kupo.Data.Cardano.DatumHash ( DatumHash @@ -20,15 +18,17 @@ data Datum | Inline !(Either DatumHash BinaryData) deriving (Generic, Show, Eq, Ord) +-- NOTE: The era parameter of BinaryData is phantom, so coerce between +-- BinaryData ConwayEra and BinaryData DijkstraEra is safe. toConwayDatum :: Datum -> Ledger.Datum ConwayEra toConwayDatum = \case NoDatum -> Ledger.NoDatum Reference (Left ref) -> Ledger.DatumHash ref - Reference (Right bin) -> Ledger.Datum bin + Reference (Right bin) -> Ledger.Datum (coerce bin) Inline (Left ref) -> Ledger.DatumHash ref - Inline (Right bin) -> Ledger.Datum bin + Inline (Right bin) -> Ledger.Datum (coerce bin) fromConwayDatum :: Ledger.Datum ConwayEra @@ -36,7 +36,7 @@ fromConwayDatum fromConwayDatum = \case Ledger.NoDatum -> NoDatum Ledger.DatumHash ref -> Reference (Left ref) - Ledger.Datum bin -> Inline (Right bin) + Ledger.Datum bin -> Inline (Right (Ledger.dataToBinaryData (Ledger.upgradeData (Ledger.binaryDataToData bin)))) fromDijkstraDatum :: Ledger.Datum DijkstraEra @@ -44,7 +44,7 @@ fromDijkstraDatum fromDijkstraDatum = \case Ledger.NoDatum -> NoDatum Ledger.DatumHash ref -> Reference (Left ref) - Ledger.Datum bin -> Inline (Right (fromDijkstraBinaryData bin)) + Ledger.Datum bin -> Inline (Right bin) toDijkstraDatum :: Datum @@ -52,9 +52,9 @@ toDijkstraDatum toDijkstraDatum = \case NoDatum -> Ledger.NoDatum Reference (Left ref) -> Ledger.DatumHash ref - Reference (Right bin) -> Ledger.Datum (toDijkstraBinaryData bin) + Reference (Right bin) -> Ledger.Datum bin Inline (Left ref) -> Ledger.DatumHash ref - Inline (Right bin) -> Ledger.Datum (toDijkstraBinaryData bin) + Inline (Right bin) -> Ledger.Datum bin getBinaryData :: Datum From af68a61bbb52f621ebde26c17285e6cd19edba5b Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 12:44:44 +1000 Subject: [PATCH 05/68] fix: use DijkstraNativeScript for NativeScript type alias Replace Timelock ConwayEra with DijkstraNativeScript DijkstraEra and simplify scriptFromBytes to decode directly at DijkstraEra instead of decoding at ConwayEra and upgrading. Removes the extra upgradeTimelock and fromConwayScript steps from fromNativeScript. Co-Authored-By: Claude --- src/Kupo/Data/Cardano/NativeScript.hs | 3 ++- src/Kupo/Data/Cardano/Script.hs | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Kupo/Data/Cardano/NativeScript.hs b/src/Kupo/Data/Cardano/NativeScript.hs index 76d9dca6..3283f8b1 100644 --- a/src/Kupo/Data/Cardano/NativeScript.hs +++ b/src/Kupo/Data/Cardano/NativeScript.hs @@ -18,6 +18,7 @@ import Cardano.Ledger.Keys ) import qualified Cardano.Ledger.Allegra.Scripts as Ledger.Allegra +import qualified Cardano.Ledger.Dijkstra.Scripts as Ledger.Dijkstra import qualified Cardano.Ledger.Shelley.Scripts as Ledger.Shelley -type NativeScript = Ledger.Allegra.Timelock ConwayEra +type NativeScript = Ledger.Dijkstra.DijkstraNativeScript DijkstraEra diff --git a/src/Kupo/Data/Cardano/Script.hs b/src/Kupo/Data/Cardano/Script.hs index 100932bf..e1580f3e 100644 --- a/src/Kupo/Data/Cardano/Script.hs +++ b/src/Kupo/Data/Cardano/Script.hs @@ -158,7 +158,7 @@ scriptFromBytes (toLazy -> bytes) = (script, tag) <- left (DecoderErrorDeserialiseFailure "Script") $ Cbor.deserialiseFromBytes Cbor.decodeWord bytes case tag of - 0 -> (Ledger.Alonzo.NativeScript . Ledger.Dijkstra.upgradeTimelock) <$> decodeCborAnn @ConwayEra "Timelock" decCBOR script + 0 -> Ledger.Alonzo.NativeScript <$> decodeCborAnn @DijkstraEra "DijkstraNativeScript" decCBOR script 1 -> plutusScript Ledger.PlutusV1 script 2 -> plutusScript Ledger.PlutusV2 script 3 -> plutusScript Ledger.PlutusV3 script @@ -180,7 +180,7 @@ fromNativeScript :: NativeScript -> Script fromNativeScript = - fromConwayScript . Ledger.Alonzo.NativeScript + Ledger.Alonzo.NativeScript {-# INLINABLE fromNativeScript #-} hashScript From 3a15c93a5bb7a126ebf48c34495e14ea01161763 Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 13:13:14 +1000 Subject: [PATCH 06/68] docs: explain OVERLAPPING pragma on ToJSON Point instance Add comment noting that ouroboros-network provides a general ToJSON (Point block) instance that conflicts with this one. Co-Authored-By: Claude --- src/Kupo/Data/Cardano/Point.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Kupo/Data/Cardano/Point.hs b/src/Kupo/Data/Cardano/Point.hs index 2a14f9e0..599233a7 100644 --- a/src/Kupo/Data/Cardano/Point.hs +++ b/src/Kupo/Data/Cardano/Point.hs @@ -45,6 +45,8 @@ import qualified Ouroboros.Network.Block as Ouroboros type Point = Ouroboros.Point Block +-- ouroboros-network provides a general 'ToJSON (Ouroboros.Point block)' instance +-- that conflicts with this one, so we need OVERLAPPING to prefer this definition. instance {-# OVERLAPPING #-} ToJSON Point where toJSON = error "ToJSON Point called instead of 'toEncoding'." toEncoding = pointToJson From 8f32e3b85d2221479252b073c38c90f098656dea Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 13:40:39 +1000 Subject: [PATCH 07/68] fix: replace remaining unsafeBinaryDataFromBytes calls in BinaryData Use Ledger.dataToBinaryData with Ledger.upgradeData for Alonzo and Babbage era data conversions, removing the HasCallStack constraint from fromAlonzoData and the intermediate type annotation from fromBabbageData. Co-Authored-By: Claude --- src/Kupo/Data/Cardano/BinaryData.hs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/Kupo/Data/Cardano/BinaryData.hs b/src/Kupo/Data/Cardano/BinaryData.hs index f77a2a56..d84f1edd 100644 --- a/src/Kupo/Data/Cardano/BinaryData.hs +++ b/src/Kupo/Data/Cardano/BinaryData.hs @@ -54,20 +54,17 @@ unsafeBinaryDataFromBytes = {-# INLINABLE unsafeBinaryDataFromBytes #-} fromAlonzoData - :: HasCallStack - => Ledger.Data AlonzoEra + :: Ledger.Data AlonzoEra -> BinaryData fromAlonzoData = - unsafeBinaryDataFromBytes . Ledger.originalBytes + Ledger.dataToBinaryData . Ledger.upgradeData {-# INLINEABLE fromAlonzoData #-} fromBabbageData :: Ledger.Data BabbageEra -> BinaryData fromBabbageData = - Ledger.dataToBinaryData - . (Ledger.upgradeData :: Ledger.Data ConwayEra -> Ledger.Data DijkstraEra) - . Ledger.upgradeData + Ledger.dataToBinaryData . Ledger.upgradeData {-# INLINEABLE fromBabbageData #-} fromConwayData From 22c0060108573b35ad02f9e7563a07f34ffc3d7c Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 14:24:56 +1000 Subject: [PATCH 08/68] refactor: remove unused toConwayDatum and fromConwayDatum These Conway-era datum conversions are dead code now that the Datum, BinaryData, and Output types are all aliased to DijkstraEra. Co-Authored-By: Claude --- src/Kupo/Data/Cardano/Datum.hs | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/Kupo/Data/Cardano/Datum.hs b/src/Kupo/Data/Cardano/Datum.hs index bd6572ff..db9788db 100644 --- a/src/Kupo/Data/Cardano/Datum.hs +++ b/src/Kupo/Data/Cardano/Datum.hs @@ -18,25 +18,6 @@ data Datum | Inline !(Either DatumHash BinaryData) deriving (Generic, Show, Eq, Ord) --- NOTE: The era parameter of BinaryData is phantom, so coerce between --- BinaryData ConwayEra and BinaryData DijkstraEra is safe. -toConwayDatum - :: Datum - -> Ledger.Datum ConwayEra -toConwayDatum = \case - NoDatum -> Ledger.NoDatum - Reference (Left ref) -> Ledger.DatumHash ref - Reference (Right bin) -> Ledger.Datum (coerce bin) - Inline (Left ref) -> Ledger.DatumHash ref - Inline (Right bin) -> Ledger.Datum (coerce bin) - -fromConwayDatum - :: Ledger.Datum ConwayEra - -> Datum -fromConwayDatum = \case - Ledger.NoDatum -> NoDatum - Ledger.DatumHash ref -> Reference (Left ref) - Ledger.Datum bin -> Inline (Right (Ledger.dataToBinaryData (Ledger.upgradeData (Ledger.binaryDataToData bin)))) fromDijkstraDatum :: Ledger.Datum DijkstraEra From 4cfbb6cbd5de57266b348bc0076735daf97dac0b Mon Sep 17 00:00:00 2001 From: John Lotoski Date: Wed, 13 May 2026 22:33:12 -0500 Subject: [PATCH 09/68] fix: use OS-assigned ports in state-machine test The previous genServerPort (1024 + size + arbitrary) could generate privileged ports below 1024 and duplicate ports across iterations, causing bind failures. Replace with OS-assigned ephemeral ports via bind-to-zero on localhost. Also use newEnvironmentWith throwIO so test failures surface the real exception instead of opaque ExitFailure 1. Co-Authored-By: Claude --- kupo.cabal | 1 + package.yaml | 1 + test/Test/Kupo/AppSpec.hs | 29 ++++++++++++++++------------- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index 9beb2672..37c6415a 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -399,6 +399,7 @@ test-suite unit , io-sim , kupo , lens-aeson + , network , openapi3 , process , quickcheck-state-machine diff --git a/package.yaml b/package.yaml index fae6acf4..229eed2c 100644 --- a/package.yaml +++ b/package.yaml @@ -140,6 +140,7 @@ tests: - http-types - io-classes - io-sim + - network - kupo - lens-aeson - openapi3 diff --git a/test/Test/Kupo/AppSpec.hs b/test/Test/Kupo/AppSpec.hs index 4e0bd353..7d645bd3 100644 --- a/test/Test/Kupo/AppSpec.hs +++ b/test/Test/Kupo/AppSpec.hs @@ -37,7 +37,7 @@ import GHC.Generics ) import Kupo ( kupoWith - , newEnvironment + , newEnvironmentWith , runWith ) import Kupo.App @@ -146,6 +146,7 @@ import Network.HTTP.Client ( defaultManagerSettings , newManager ) +import qualified Network.Socket import Network.WebSockets ( ConnectionException (..) ) @@ -176,7 +177,6 @@ import Test.Kupo.Data.Generators ) import Test.QuickCheck ( Gen - , arbitrary , choose , counterexample , elements @@ -184,7 +184,6 @@ import Test.QuickCheck , frequency , label , oneof - , sized ) import Test.QuickCheck.Monadic ( assert @@ -193,7 +192,8 @@ import Test.QuickCheck.Monadic , run ) import Test.QuickCheck.Property - ( withMaxSuccess + ( ioProperty + , withMaxSuccess ) import Test.StateMachine ( CommandNames @@ -243,10 +243,10 @@ spec = do <$> runIO (lookupEnv varStateMachineIterations) prop "State-Machine" $ withMaxSuccess maxSuccess $ - forAll genInputManagement $ \inputManagement -> do - forAll genServerPort $ \serverPort -> do - let httpClient = newHttpClientWith manager (serverHost, serverPort) (\_ -> pure ()) - let stateMachine = StateMachine + forAll genInputManagement $ \inputManagement -> ioProperty $ do + serverPort <- getFreePort + let httpClient = newHttpClientWith manager (serverHost, serverPort) (\_ -> pure ()) + stateMachine = StateMachine initModel transition (precondition longestRollback) @@ -257,7 +257,7 @@ spec = do (semantics garbageCollectionInterval httpClient chan) mock (cleanup chan) - forAllCommands stateMachine Nothing $ \cmds -> monadicIO $ do + pure $ forAllCommands stateMachine Nothing $ \cmds -> monadicIO $ do let config = Configuration { chainProducer = CardanoNode -- NOTE: unused, but must be different than ReadOnlyReplica { nodeSocket = "/dev/null" @@ -275,7 +275,7 @@ spec = do , garbageCollectionInterval , deferIndexes } - env <- run (newEnvironment config) + env <- run (newEnvironmentWith throwIO config) producer <- run (newMockProducer httpClient <$> atomically (dupTChan chan)) fetchBlock <- run (newMockFetchBlock <$> atomically (dupTChan chan)) let fetchTip = throwIO UnusedFetchTipClient @@ -309,9 +309,12 @@ spec = do garbageCollectionInterval = 0.4 deferIndexes = InstallIndexesIfNotExist tracers = configureTracers (defaultTracers Nothing) nullTracer - genServerPort = sized $ \n -> do - i <- arbitrary - pure (1024 + n + i) + getFreePort = do + sock <- Network.Socket.socket Network.Socket.AF_INET Network.Socket.Stream 0 + Network.Socket.bind sock (Network.Socket.SockAddrInet 0 (Network.Socket.tupleToHostAddress (127,0,0,1))) + port <- Network.Socket.socketPort sock + Network.Socket.close sock + pure (fromIntegral port) -------------------------------------------------------------------------------- ---- Events / Respone From d7c50de7a944e3ac092b934b7008940c23ad8584 Mon Sep 17 00:00:00 2001 From: Erik de Castro Lopo Date: Thu, 14 May 2026 14:42:21 +1000 Subject: [PATCH 10/68] Comment about Hydra and its transaction encoding Co-Authored-By: Claude --- src/Kupo/Data/Hydra.hs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Kupo/Data/Hydra.hs b/src/Kupo/Data/Hydra.hs index 13dcdc5f..1bd18e21 100644 --- a/src/Kupo/Data/Hydra.hs +++ b/src/Kupo/Data/Hydra.hs @@ -183,6 +183,9 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do bytes <- decodeBase16' hexText + -- NOTE: Hydra currently serialises transactions as Conway-era CBOR. When Hydra upgrades its + -- internal transaction encoding to Dijkstra, this line and the fromConway* calls below will + -- need to change. (tx :: Ledger.Tx Ledger.TopTx ConwayEra) <- case decodeCborAnn @ConwayEra "PartialTransaction" decCBOR (fromStrict bytes) of Left e -> fail $ show e Right tx -> pure tx From fc3797649cf9f962de7e7c0590a3e1930c66430a Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 26 May 2026 10:28:15 +0200 Subject: [PATCH 11/68] restore previous Ogmios revision in cabal.project This is only used to pull in the fast-bech32 module, which is not impacted by the hard fork at all. --- cabal.project | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cabal.project b/cabal.project index b5ad4714..fb53b03f 100644 --- a/cabal.project +++ b/cabal.project @@ -74,9 +74,9 @@ allow-newer: -- nix-prefetch-git https://github.com/CardanoSolutions/ogmios.git --rev --fetch-submodules --quiet | jq '.hash' | tail -c +9 | head -c -2 source-repository-package type: git - location: https://github.com/johnalotoski/ogmios - --sha256: sha256-OjABxe/ICHIkb+5jQI7chCrwnQ2W1oVO02Zxu9yLUKU= - tag: ea80df1204f830050436facdae4287cf674892e5 + location: https://github.com/CardanoSolutions/ogmios + tag: ae876badb138f42dcd6d2389734b0c15502684ed + --sha256: xkOfOdX6Dxi7+VW78Tk3n3MoguIg39pKdxiNVfdeEwE= subdir: server/modules/fast-bech32 From fd21bcd0b73605b2f099a258269289c477413073 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 09:10:02 +0200 Subject: [PATCH 12/68] replace buildjet instances with github runners; Buildjet has shut down, and github does provide arm runners nowadays. --- .github/workflows/build.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index dc356d98..8526be13 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -21,7 +21,7 @@ jobs: - os: macos arch: x86_64 - runs-on: ${{ matrix.arch == 'x86_64' && 'buildjet-4vcpu-ubuntu-2204' || (matrix.os == 'linux' && 'buildjet-16vcpu-ubuntu-2204-arm' || 'macos-latest') }} + runs-on: ${{ matrix.arch == 'x86_64' && 'ubuntu-24.04' || (matrix.os == 'linux' && 'ubuntu-24.04-arm' || 'macos-15') }} steps: - name: 📥 Checkout repository From e68001a98699e45b61ec0649b1378c1959b9246f Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 09:16:19 +0200 Subject: [PATCH 13/68] bump workflow actions, mostly getting rid of node.js v20 --- .github/workflows/build.yaml | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 8526be13..5eafb04c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -25,7 +25,7 @@ jobs: steps: - name: 📥 Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v7 with: submodules: true @@ -55,7 +55,7 @@ jobs: make configure - name: 💾 Cache - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: | ~/.cabal-static/packages @@ -77,7 +77,7 @@ jobs: - name: 📎 Upload Artifact if: ${{ github.event_name == 'push' }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: kupo-${{ steps.tag.outputs.value }}-${{ matrix.arch }}-${{ matrix.os }} path: | @@ -97,16 +97,16 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v7 with: submodules: true - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - name: Docker meta id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v6 with: images: ${{ env.DOCKER_IMAGE }} tags: | @@ -126,7 +126,7 @@ jobs: GIT_SHA: ${{ github.sha }} - name: hadolint - uses: hadolint/hadolint-action@v3.0.0 + uses: hadolint/hadolint-action@v3.3.0 with: dockerfile: "./Dockerfile" failure-threshold: warning @@ -134,7 +134,7 @@ jobs: - name: Login to DockerHub if: ${{ github.event_name == 'push' }} - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }} @@ -147,7 +147,7 @@ jobs: - name: Build and push (latest) if: ${{ github.event_name == 'push' }} id: build - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v7 with: context: . platforms: ${{ matrix.os }}/${{ matrix.arch == 'x86_64' && 'amd64' || 'arm64' }} @@ -165,7 +165,7 @@ jobs: - name: Upload digest if: ${{ github.event_name == 'push' }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: digests-${{ matrix.arch == 'x86_64' && 'amd64' || 'arm64' }} path: /tmp/digests/* @@ -177,23 +177,23 @@ jobs: runs-on: ubuntu-latest steps: - name: Download digests (amd) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: digests-amd64 path: /tmp/digests - name: Download digests (arm) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: digests-arm64 path: /tmp/digests - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - name: Docker meta id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v6 with: images: ${{ env.DOCKER_IMAGE }} tags: | @@ -202,7 +202,7 @@ jobs: - name: Login to DockerHub if: ${{ github.event_name == 'push' && steps.meta.outputs.tags != '' }} - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }} From 6685d68e97cc05b00fc1f25fff22cc4fc27aa8eb Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 18 Jun 2026 14:17:56 +0000 Subject: [PATCH 14/68] Start separate test suite for flaky tests; extract 'read-only' --- kupo.cabal | 63 ++++++++++++++++- package.yaml | 15 ++++ test-accept/Spec.hs | 5 ++ test-accept/Test/KupoSpec.hs | 132 +++++++++++++++++++++++++++++++++++ 4 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 test-accept/Spec.hs create mode 100644 test-accept/Test/KupoSpec.hs diff --git a/kupo.cabal b/kupo.cabal index 37c6415a..d43ef64a 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -1,6 +1,6 @@ cabal-version: 3.0 --- This file has been generated from package.yaml by hpack version 0.38.3. +-- This file has been generated from package.yaml by hpack version 0.39.5. -- -- see: https://github.com/sol/hpack @@ -309,6 +309,67 @@ executable kupo if flag(postgres) cpp-options: -Dpostgres +test-suite accept + type: exitcode-stdio-1.0 + main-is: Spec.hs + other-modules: + Test.KupoSpec + Paths_kupo + autogen-modules: + Paths_kupo + hs-source-dirs: + test-accept + default-extensions: + BangPatterns + BinaryLiterals + ConstraintKinds + DataKinds + DefaultSignatures + DeriveDataTypeable + DeriveFoldable + DeriveFunctor + DeriveGeneric + DeriveTraversable + DerivingStrategies + EmptyDataDecls + ExistentialQuantification + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + InstanceSigs + KindSignatures + LambdaCase + MultiParamTypeClasses + MultiWayIf + NamedFieldPuns + NoImplicitPrelude + NumericUnderscores + OverloadedStrings + PartialTypeSignatures + PatternGuards + RankNTypes + ScopedTypeVariables + StandaloneDeriving + TupleSections + TypeApplications + TypeFamilies + TypeSynonymInstances + ViewPatterns + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N + build-tool-depends: + hspec-discover:hspec-discover + build-depends: + base + , directory + , filepath + , hspec + , http-client + , http-types + , process + , temporary + default-language: Haskell2010 + test-suite unit type: exitcode-stdio-1.0 main-is: Spec.hs diff --git a/package.yaml b/package.yaml index 229eed2c..af27b501 100644 --- a/package.yaml +++ b/package.yaml @@ -161,6 +161,21 @@ tests: - yaml build-tools: - hspec-discover + accept: + main: Spec.hs + source-dirs: test-accept + ghc-options: *ghc-options-test + dependencies: + - base + - directory + - filepath + - hspec + - http-client + - http-types + - process + - temporary + build-tools: + - hspec-discover executables: kupo: diff --git a/test-accept/Spec.hs b/test-accept/Spec.hs new file mode 100644 index 00000000..b5bf490e --- /dev/null +++ b/test-accept/Spec.hs @@ -0,0 +1,5 @@ +-- This Source Code Form is subject to the terms of the Mozilla Public +-- License, v. 2.0. If a copy of the MPL was not distributed with this +-- file, You can obtain one at http://mozilla.org/MPL/2.0/. + +{-# OPTIONS_GHC -F -pgmF hspec-discover #-} diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs new file mode 100644 index 00000000..c6504b4e --- /dev/null +++ b/test-accept/Test/KupoSpec.hs @@ -0,0 +1,132 @@ +{- This Source Code Form is subject to the terms of the Mozilla Public +-- License, v. 2.0. If a copy of the MPL was not distributed with this +-- file, You can obtain one at http://mozilla.org/MPL/2.0/. +-} + +{- Tests for some corner cases that were flaky when run with `cabal test unit`. + - These tests actually run the executable made with `cabal build` + - So they are external integration/end-to-end acceptance tests. + - To run: `PATH=$(dirname $(cabal list-bin exe:kupo)):$PATH cabal test accept` + -} + +module Test.KupoSpec + ( spec + ) where + +import Prelude + +import Control.Concurrent + ( threadDelay + ) +import Control.Exception + ( assert + , bracket + , try + ) +import Network.HTTP.Client + ( HttpException + , defaultManagerSettings + , httpNoBody + , newManager + , parseRequest + , responseStatus + ) +import Network.HTTP.Types.Status + ( status202 + ) +import System.Directory + ( Permissions (..) + , getPermissions + , removePathForcibly + , setPermissions + ) +import System.Environment + ( getEnv + ) +import System.IO.Temp + ( createTempDirectory + ) +import System.Process + ( proc + , withCreateProcess + ) +import Test.Hspec + ( Spec + , around + , describe + , it + , shouldReturn + ) + +spec :: Spec +spec = around withDir $ do + describe "Kupo server start/restart corner cases" $ do + it "Can start in readonly mode on readonly DB" $ \dir -> do + createDatabaseFiles dir + makeUnwritable dir + startReadOnly dir `shouldReturn` True + +withDir :: (FilePath -> IO ()) -> IO () +withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly + +createDatabaseFiles :: FilePath -> IO () +createDatabaseFiles dir = do + socket <- getEnv "CARDANO_NODE_SOCKET" + config <- getEnv "CARDANO_NODE_CONFIG" + let kupo = proc "kupo" + ["--node-socket", socket + ,"--node-config", config + ,"--workdir", dir + ,"--since", "tip" + ,"--match", "*/*" + ] + withCreateProcess kupo $ \ _ _ _ _ -> do + ready <- eventuallyReady + pure (assert ready ()) + +startReadOnly :: FilePath -> IO Bool +startReadOnly dir = do + let kupo = proc "kupo" + ["--read-only" + ,"--workdir", dir + ] + withCreateProcess kupo $ \ _ _ _ _ -> do + eventuallyReady + +makeUnwritable :: FilePath -> IO () +makeUnwritable = setWritable False + +setWritable :: Bool -> FilePath -> IO () +setWritable x path = do + p <- getPermissions path + setPermissions path (p {writable = x}) + +eventuallyReady :: IO Bool +eventuallyReady = go (0::Int) + where + go attempt + | attempt > 20 = pure False + | otherwise = check attempt + check attempt = do + ready <- tryHttp isReady + case ready of + Right True -> pure True + _ -> wait attempt + wait attempt = do + threadDelay 1_000_000 -- 1s between retries + go (attempt + 1) + +isReady :: IO Bool +isReady = do + manager <- newManager defaultManagerSettings + request <- parseRequest (url <> "/health") + response <- httpNoBody request manager + pure (responseStatus response == status202) + +tryHttp :: IO a -> IO (Either HttpException a) +tryHttp m = try m + +url :: String +url = "http://127.0.0.1:1442" + + From 029deca1efcbcb0bb45be60bf5a52f2fad3041a8 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 29 Jun 2026 08:18:02 +0000 Subject: [PATCH 15/68] Polish test-accept instructions and remove old read-only endToEnd test --- kupo.cabal | 1 - package.yaml | 1 - test-accept/Test/KupoSpec.hs | 2 +- test/Test/KupoSpec.hs | 40 ------------------------------------ 4 files changed, 1 insertion(+), 43 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index d43ef64a..c27e0a24 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -362,7 +362,6 @@ test-suite accept build-depends: base , directory - , filepath , hspec , http-client , http-types diff --git a/package.yaml b/package.yaml index af27b501..6f0d5561 100644 --- a/package.yaml +++ b/package.yaml @@ -168,7 +168,6 @@ tests: dependencies: - base - directory - - filepath - hspec - http-client - http-types diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index c6504b4e..eaddf05e 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -6,7 +6,7 @@ {- Tests for some corner cases that were flaky when run with `cabal test unit`. - These tests actually run the executable made with `cabal build` - So they are external integration/end-to-end acceptance tests. - - To run: `PATH=$(dirname $(cabal list-bin exe:kupo)):$PATH cabal test accept` + - To run: `cabal build exe:kupo && cabal exec cabal test accept` -} module Test.KupoSpec diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index fa8ff16e..37536fac 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -109,15 +109,6 @@ import Network.HTTP.Client , newManager , responseTimeoutNone ) -import System.Directory - ( Permissions (..) - , getPermissions - , listDirectory - , setPermissions - ) -import System.FilePath - ( () - ) import System.IO.Temp ( withSystemTempDirectory , withTempFile @@ -619,37 +610,6 @@ spec = skippableContext "End-to-end" $ do points' <- listCheckpoints forM_ points' $ \point -> getPointSlotNo point `shouldSatisfy` (<= maxSlot) - endToEnd "Read-only works with read-only permissions" $ - \(configure, runSpec, HttpClient{..}) -> do - withSystemTempDirectory "kupo-end-to-end" $ \tmp -> do - - -- Start first time to create database files - (cfg, env) <- configure $ \defaultCfg -> defaultCfg - { databaseLocation = Dir tmp - , since = Just (SincePoint lastByronPoint) - , patterns = fromList [MatchAny OnlyShelley] - , deferIndexes = SkipNonEssentialIndexes - } - runSpec env 5 $ do - waitSlot (> 0) - listPatterns `shouldReturn` [MatchAny OnlyShelley] - - -- Change permissions and re-start in replica mode - filenames <- listDirectory tmp - let paths = map (tmp ) filenames - mapM_ makeUnwritable paths - makeUnwritable tmp - (_, env') <- configure $ \_ -> cfg - { chainProducer = ReadOnlyReplica } - runSpec env' 5 $ do - waitSlot (> 0) - listPatterns `shouldReturn` [MatchAny OnlyShelley] - - where - makeUnwritable f = do - p <- getPermissions f - setPermissions f (p {writable = False}) - -- | Create an 'EndToEndContext' around each child specification item within that 'Spec' tree. The -- spec items are 'skippable' and only executed if the appropriate environment variables are present. -- From 4d7cd1a87314caa422364b6c6640c1a268f9ccc5 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Tue, 30 Jun 2026 12:57:21 +0000 Subject: [PATCH 16/68] Extract 'can connect' test to new test-accept --- kupo.cabal | 1 + package.yaml | 1 + test-accept/Test/KupoSpec.hs | 134 ++++++++++++++++++++++++++--------- test/Test/KupoSpec.hs | 10 --- 4 files changed, 104 insertions(+), 42 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index c27e0a24..e2e8903e 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -361,6 +361,7 @@ test-suite accept hspec-discover:hspec-discover build-depends: base + , bytestring , directory , hspec , http-client diff --git a/package.yaml b/package.yaml index 6f0d5561..cedf765a 100644 --- a/package.yaml +++ b/package.yaml @@ -167,6 +167,7 @@ tests: ghc-options: *ghc-options-test dependencies: - base + - bytestring - directory - hspec - http-client diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index eaddf05e..23cd33a9 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -23,16 +23,23 @@ import Control.Exception , bracket , try ) +import Data.Char + (ord + ) import Network.HTTP.Client ( HttpException + , Request , defaultManagerSettings - , httpNoBody + , httpLbs , newManager , parseRequest + , responseBody , responseStatus ) import Network.HTTP.Types.Status - ( status202 + ( Status + , status202 + , status200 ) import System.Directory ( Permissions (..) @@ -47,7 +54,8 @@ import System.IO.Temp ( createTempDirectory ) import System.Process - ( proc + ( CreateProcess + , proc , withCreateProcess ) import Test.Hspec @@ -58,31 +66,64 @@ import Test.Hspec , shouldReturn ) +import qualified Data.ByteString.Lazy as B + +type ResponseCheck = Status -> B.ByteString -> Bool + spec :: Spec -spec = around withDir $ do - describe "Kupo server start/restart corner cases" $ do - it "Can start in readonly mode on readonly DB" $ \dir -> do - createDatabaseFiles dir - makeUnwritable dir - startReadOnly dir `shouldReturn` True +spec = do + + describe "Kupo server start/restart corner cases (in-memory DB)" $ do + + it "Can connect" $ do + startInMemorySinceOriginMatchShelley `shouldReturn` True + + around withDir $ do + + describe "Kupo server start/restart corner cases (file DB)" $ do + + it "Can start in readonly mode on readonly DB" $ \dir -> do + createDatabaseFiles dir + makeUnwritable dir + startReadOnly dir `shouldReturn` True + +startInMemorySinceOriginMatchShelley :: IO Bool +startInMemorySinceOriginMatchShelley = do + process <- kupo + ["--since" , "origin" + ,"--match" , "*/*" + ,"--in-memory" + ] + withCreateProcess process $ \ _ _ _ _ -> do + eventually isConnected withDir :: (FilePath -> IO ()) -> IO () withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly createDatabaseFiles :: FilePath -> IO () createDatabaseFiles dir = do + process <- kupo + ["--since" , "tip" + ,"--match" , "*/*" + ,"--workdir", dir + ] + withCreateProcess process $ \ _ _ _ _ -> do + ready <- eventually isReady + pure (assert ready ()) + +kupo :: [String] -> IO CreateProcess +kupo options = do socket <- getEnv "CARDANO_NODE_SOCKET" config <- getEnv "CARDANO_NODE_CONFIG" - let kupo = proc "kupo" - ["--node-socket", socket - ,"--node-config", config - ,"--workdir", dir - ,"--since", "tip" - ,"--match", "*/*" - ] - withCreateProcess kupo $ \ _ _ _ _ -> do - ready <- eventuallyReady - pure (assert ready ()) + pure $ proc "kupo" + (["--node-socket", socket + ,"--node-config", config + ] + ++ options + ) + +makeUnwritable :: FilePath -> IO () +makeUnwritable = setWritable False startReadOnly :: FilePath -> IO Bool startReadOnly dir = do @@ -91,24 +132,21 @@ startReadOnly dir = do ,"--workdir", dir ] withCreateProcess kupo $ \ _ _ _ _ -> do - eventuallyReady - -makeUnwritable :: FilePath -> IO () -makeUnwritable = setWritable False + eventually isReady setWritable :: Bool -> FilePath -> IO () setWritable x path = do p <- getPermissions path setPermissions path (p {writable = x}) -eventuallyReady :: IO Bool -eventuallyReady = go (0::Int) +eventually :: IO Bool -> IO Bool +eventually p = go (0::Int) where go attempt | attempt > 20 = pure False | otherwise = check attempt check attempt = do - ready <- tryHttp isReady + ready <- tryHttp p case ready of Right True -> pure True _ -> wait attempt @@ -116,12 +154,43 @@ eventuallyReady = go (0::Int) threadDelay 1_000_000 -- 1s between retries go (attempt + 1) +isConnected :: IO Bool +isConnected = checkResponse "/checkpoints" containsNonEmptyList + isReady :: IO Bool -isReady = do - manager <- newManager defaultManagerSettings - request <- parseRequest (url <> "/health") - response <- httpNoBody request manager - pure (responseStatus response == status202) +isReady = checkResponse "/health" isHealthy + +checkResponse :: String -> ResponseCheck -> IO Bool +checkResponse path check = do + manager <- newManager defaultManagerSettings + request' <- request path + response <- httpLbs request' manager + let + status = responseStatus response + body = responseBody response + pure (check status body) + +containsNonEmptyList :: Status -> B.ByteString -> Bool +containsNonEmptyList status body = + status == status200 + && B.length body > 2 + && startsWithBracket body + && endsWithBracket body + +startsWithBracket :: B.ByteString -> Bool +startsWithBracket xs = + case B.uncons xs of + Nothing -> False + Just (w, _) -> w == fromIntegral (ord '[') + +endsWithBracket :: B.ByteString -> Bool +endsWithBracket xs = + case B.unsnoc xs of + Nothing -> False + Just (_, w) -> w == fromIntegral (ord ']') + +isHealthy :: ResponseCheck +isHealthy status _ = status == status202 tryHttp :: IO a -> IO (Either HttpException a) tryHttp m = try m @@ -129,4 +198,5 @@ tryHttp m = try m url :: String url = "http://127.0.0.1:1442" - +request :: String -> IO Request +request = parseRequest . (url <>) diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 37536fac..3c2fc621 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -227,16 +227,6 @@ endToEnd = specify spec :: Spec spec = skippableContext "End-to-end" $ do - endToEnd "can connect" $ \(configure, runSpec, HttpClient{..}) -> do - (_cfg, env) <- configure $ \defaultCfg -> defaultCfg - { databaseLocation = InMemory Nothing - , since = Just (SincePoint GenesisPoint) - , patterns = fromList [MatchAny OnlyShelley] - } - runSpec env 5 $ do - waitSlot (> 0) - matches <- getAllMatches NoStatusFlag AsReference - matches `shouldSatisfy` not . null endToEnd "in-memory" $ \(configure, runSpec, HttpClient{..}) -> do (cfg, env) <- configure $ \defaultCfg -> defaultCfg From 3e1a2c0d7c33748c784bb57f004c41c97b3f9f7c Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Wed, 1 Jul 2026 07:27:40 +0000 Subject: [PATCH 17/68] Refactor to introduce 'restart' test --- test-accept/Test/KupoSpec.hs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 23cd33a9..9bd1ef18 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -83,10 +83,13 @@ spec = do describe "Kupo server start/restart corner cases (file DB)" $ do it "Can start in readonly mode on readonly DB" $ \dir -> do - createDatabaseFiles dir + runServerUntil dir "tip" isReady makeUnwritable dir startReadOnly dir `shouldReturn` True + it "Can restart with same arguments" $ \dir -> do + runServerUntil dir somePoint hasReachedSomePoint + startInMemorySinceOriginMatchShelley :: IO Bool startInMemorySinceOriginMatchShelley = do process <- kupo @@ -100,16 +103,16 @@ startInMemorySinceOriginMatchShelley = do withDir :: (FilePath -> IO ()) -> IO () withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly -createDatabaseFiles :: FilePath -> IO () -createDatabaseFiles dir = do +runServerUntil :: FilePath -> String -> IO Bool -> IO () +runServerUntil dir point check = do process <- kupo - ["--since" , "tip" + ["--since" , point ,"--match" , "*/*" ,"--workdir", dir ] withCreateProcess process $ \ _ _ _ _ -> do - ready <- eventually isReady - pure (assert ready ()) + checked <- eventually check + pure (assert checked ()) kupo :: [String] -> IO CreateProcess kupo options = do @@ -127,11 +130,11 @@ makeUnwritable = setWritable False startReadOnly :: FilePath -> IO Bool startReadOnly dir = do - let kupo = proc "kupo" + let process = proc "kupo" ["--read-only" ,"--workdir", dir ] - withCreateProcess kupo $ \ _ _ _ _ -> do + withCreateProcess process $ \ _ _ _ _ -> do eventually isReady setWritable :: Bool -> FilePath -> IO () @@ -160,6 +163,9 @@ isConnected = checkResponse "/checkpoints" containsNonEmptyList isReady :: IO Bool isReady = checkResponse "/health" isHealthy +hasReachedSomePoint :: IO Bool +hasReachedSomePoint = checkResponse "/checkpoints" containsNonEmptyList + checkResponse :: String -> ResponseCheck -> IO Bool checkResponse path check = do manager <- newManager defaultManagerSettings @@ -200,3 +206,7 @@ url = "http://127.0.0.1:1442" request :: String -> IO Request request = parseRequest . (url <>) + +somePoint :: String +somePoint = + "11017324.195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" From 9a699737a74e5b18edab789b8a623793fdf813e9 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Wed, 1 Jul 2026 10:07:36 +0000 Subject: [PATCH 18/68] Refactor to use Aeson --- kupo.cabal | 3 ++- package.yaml | 1 + test-accept/Test/KupoSpec.hs | 39 ++++++++++++++++-------------------- 3 files changed, 20 insertions(+), 23 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index e2e8903e..8f5e064e 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -360,7 +360,8 @@ test-suite accept build-tool-depends: hspec-discover:hspec-discover build-depends: - base + aeson + , base , bytestring , directory , hspec diff --git a/package.yaml b/package.yaml index cedf765a..06e5ddb9 100644 --- a/package.yaml +++ b/package.yaml @@ -166,6 +166,7 @@ tests: source-dirs: test-accept ghc-options: *ghc-options-test dependencies: + - aeson - base - bytestring - directory diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 9bd1ef18..d7a7b833 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -23,8 +23,8 @@ import Control.Exception , bracket , try ) -import Data.Char - (ord +import Data.Aeson + ( (.:) ) import Network.HTTP.Client ( HttpException @@ -66,10 +66,13 @@ import Test.Hspec , shouldReturn ) +import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as B type ResponseCheck = Status -> B.ByteString -> Bool +newtype Slot = Slot Integer deriving (Eq, Ord, Show) + spec :: Spec spec = do @@ -158,13 +161,13 @@ eventually p = go (0::Int) go (attempt + 1) isConnected :: IO Bool -isConnected = checkResponse "/checkpoints" containsNonEmptyList +isConnected = checkResponse "/checkpoints" containsCheckpoints isReady :: IO Bool isReady = checkResponse "/health" isHealthy hasReachedSomePoint :: IO Bool -hasReachedSomePoint = checkResponse "/checkpoints" containsNonEmptyList +hasReachedSomePoint = checkResponse "/checkpoints" containsCheckpoints checkResponse :: String -> ResponseCheck -> IO Bool checkResponse path check = do @@ -176,24 +179,13 @@ checkResponse path check = do body = responseBody response pure (check status body) -containsNonEmptyList :: Status -> B.ByteString -> Bool -containsNonEmptyList status body = - status == status200 - && B.length body > 2 - && startsWithBracket body - && endsWithBracket body - -startsWithBracket :: B.ByteString -> Bool -startsWithBracket xs = - case B.uncons xs of - Nothing -> False - Just (w, _) -> w == fromIntegral (ord '[') - -endsWithBracket :: B.ByteString -> Bool -endsWithBracket xs = - case B.unsnoc xs of - Nothing -> False - Just (_, w) -> w == fromIntegral (ord ']') +containsCheckpoints :: Status -> B.ByteString -> Bool +containsCheckpoints status body = + status == status200 && hasSlots (A.decode body :: Maybe [Slot]) + where + hasSlots Nothing = False + hasSlots (Just []) = False + hasSlots (Just _ ) = True isHealthy :: ResponseCheck isHealthy status _ = status == status202 @@ -210,3 +202,6 @@ request = parseRequest . (url <>) somePoint :: String somePoint = "11017324.195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" + +instance A.FromJSON Slot where + parseJSON = A.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" From 268596901322894360aeb728b065e410e53b9d9c Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 2 Jul 2026 08:48:55 +0000 Subject: [PATCH 19/68] Extract 'can restart' test to new test-accept --- test-accept/Test/KupoSpec.hs | 92 +++++++++++++++++++++--------------- test/Test/KupoSpec.hs | 9 ---- 2 files changed, 55 insertions(+), 46 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index d7a7b833..3e71d1d0 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -79,44 +79,63 @@ spec = do describe "Kupo server start/restart corner cases (in-memory DB)" $ do it "Can connect" $ do - startInMemorySinceOriginMatchShelley `shouldReturn` True + -- Start a kupo and check that it eventually has checkpoints + withKupo + ["--since" , "origin" + ,"--match" , "*/*" + ,"--in-memory" + ] + $ eventually isConnected `shouldReturn` True around withDir $ do describe "Kupo server start/restart corner cases (file DB)" $ do it "Can start in readonly mode on readonly DB" $ \dir -> do - runServerUntil dir "tip" isReady + -- Start a kupo on fresh database until it's ready + withKupo + ["--since" , "tip" + ,"--match" , "*/*" + ,"--workdir", dir + ] + $ do + ready <- eventually isReady + pure (assert ready ()) + -- Change permissions on database's directory makeUnwritable dir - startReadOnly dir `shouldReturn` True + -- Start a read-only kupo on dir and check that it's also ready + let process = proc "kupo" + ["--read-only" + ,"--workdir", dir + ] + withCreateProcess process $ \ _ _ _ _ -> do + eventually isReady `shouldReturn` True it "Can restart with same arguments" $ \dir -> do - runServerUntil dir somePoint hasReachedSomePoint - -startInMemorySinceOriginMatchShelley :: IO Bool -startInMemorySinceOriginMatchShelley = do - process <- kupo - ["--since" , "origin" - ,"--match" , "*/*" - ,"--in-memory" - ] - withCreateProcess process $ \ _ _ _ _ -> do - eventually isConnected + let options = + ["--since" , somePoint + ,"--match" , "*/*" + ,"--workdir", dir + ] + -- Start kupo on fresh dir until reaches somePoint + withKupo options $ do + reached <- eventually hasReachedSomePoint + pure (assert reached ()) + -- Restart kupo on same dir and check that it is immediately + -- already at or past same point + withKupo options $ do + ready <- eventually isReady + pure (assert ready ()) + hasReachedSomePoint `shouldReturn` True + +withKupo :: [String] -> IO a -> IO a +withKupo options action = do + process <- kupo options + withCreateProcess process $ \_ _ _ _ -> action withDir :: (FilePath -> IO ()) -> IO () withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly -runServerUntil :: FilePath -> String -> IO Bool -> IO () -runServerUntil dir point check = do - process <- kupo - ["--since" , point - ,"--match" , "*/*" - ,"--workdir", dir - ] - withCreateProcess process $ \ _ _ _ _ -> do - checked <- eventually check - pure (assert checked ()) - kupo :: [String] -> IO CreateProcess kupo options = do socket <- getEnv "CARDANO_NODE_SOCKET" @@ -131,15 +150,6 @@ kupo options = do makeUnwritable :: FilePath -> IO () makeUnwritable = setWritable False -startReadOnly :: FilePath -> IO Bool -startReadOnly dir = do - let process = proc "kupo" - ["--read-only" - ,"--workdir", dir - ] - withCreateProcess process $ \ _ _ _ _ -> do - eventually isReady - setWritable :: Bool -> FilePath -> IO () setWritable x path = do p <- getPermissions path @@ -167,7 +177,7 @@ isReady :: IO Bool isReady = checkResponse "/health" isHealthy hasReachedSomePoint :: IO Bool -hasReachedSomePoint = checkResponse "/checkpoints" containsCheckpoints +hasReachedSomePoint = checkResponse "/checkpoints" $ hasReached $ Slot 11017324 checkResponse :: String -> ResponseCheck -> IO Bool checkResponse path check = do @@ -179,7 +189,7 @@ checkResponse path check = do body = responseBody response pure (check status body) -containsCheckpoints :: Status -> B.ByteString -> Bool +containsCheckpoints :: ResponseCheck containsCheckpoints status body = status == status200 && hasSlots (A.decode body :: Maybe [Slot]) where @@ -187,8 +197,16 @@ containsCheckpoints status body = hasSlots (Just []) = False hasSlots (Just _ ) = True +hasReached :: Slot -> ResponseCheck +hasReached slot status body = + status == status200 && hasReached' slot (A.decode body :: Maybe [Slot]) + where + hasReached' _ Nothing = False + hasReached' _ (Just []) = False + hasReached' x (Just (y:_)) = y >= x + isHealthy :: ResponseCheck -isHealthy status _ = status == status202 +isHealthy status _ = status == status202 || status == status200 tryHttp :: IO a -> IO (Either HttpException a) tryHttp m = try m diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 3c2fc621..7f7ccad9 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -259,15 +259,6 @@ spec = skippableContext "End-to-end" $ do } runSpec env 5 $ waitSlot (> (getPointSlotNo somePoint)) - do -- Can restart the server - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint somePoint) - , patterns = fromList [MatchAny OnlyShelley] - } - runSpec env 5 $ do - cps <- fmap getPointSlotNo <$> listCheckpoints - maximum cps `shouldSatisfy` (> (getPointSlotNo somePoint)) - do -- Can't restart with different, too recent, --since target on same db (_, env) <- configure $ \defaultCfg -> defaultCfg { since = Just (SincePoint someOtherPoint) From 5c8da439389d380a1c5fcf38768f4cdc920d6620 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 2 Jul 2026 12:45:11 +0000 Subject: [PATCH 20/68] Extract 'cannot restart with later since' test to new test-accept --- test-accept/Test/KupoSpec.hs | 64 +++++++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 3e71d1d0..d928f018 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -9,9 +9,9 @@ - To run: `cabal build exe:kupo && cabal exec cabal test accept` -} -module Test.KupoSpec - ( spec - ) where +module Test.KupoSpec where +-- ( spec +-- ) where import Prelude @@ -53,8 +53,13 @@ import System.Environment import System.IO.Temp ( createTempDirectory ) +import System.Exit + ( ExitCode (..) + ) import System.Process ( CreateProcess + , ProcessHandle + , getProcessExitCode , proc , withCreateProcess ) @@ -94,13 +99,13 @@ spec = do it "Can start in readonly mode on readonly DB" $ \dir -> do -- Start a kupo on fresh database until it's ready withKupo - ["--since" , "tip" + ["--since" , somePoint ,"--match" , "*/*" ,"--workdir", dir ] $ do - ready <- eventually isReady - pure (assert ready ()) + reached <- eventually hasReachedSomeOtherPoint + pure (assert reached ()) -- Change permissions on database's directory makeUnwritable dir -- Start a read-only kupo on dir and check that it's also ready @@ -124,14 +129,31 @@ spec = do -- Restart kupo on same dir and check that it is immediately -- already at or past same point withKupo options $ do - ready <- eventually isReady - pure (assert ready ()) + connected <- eventually isConnected + pure (assert connected ()) hasReachedSomePoint `shouldReturn` True -withKupo :: [String] -> IO a -> IO a -withKupo options action = do + it "Cannot restart with later '--since'" $ \dir -> do + let options = + ["--match" , "*/*" + ,"--workdir", dir + ] + -- Start kupo on fresh dir until reaches somePoint + withKupo (options ++ ["--since", somePoint]) $ do + reached <- eventually hasReachedSomePoint + pure (assert reached ()) + -- Restart kupo on same dir but later "--since" and check + -- that its exits with error code + withKupoH (options ++ ["--since", someOtherPoint]) $ \h -> do + eventually (exitsWithError h) `shouldReturn` True + +withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a +withKupoH options action = do process <- kupo options - withCreateProcess process $ \_ _ _ _ -> action + withCreateProcess process $ \_ _ _ h -> action h + +withKupo :: [String] -> IO a -> IO a +withKupo options action = withKupoH options (\_ -> action) withDir :: (FilePath -> IO ()) -> IO () withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly @@ -177,7 +199,21 @@ isReady :: IO Bool isReady = checkResponse "/health" isHealthy hasReachedSomePoint :: IO Bool -hasReachedSomePoint = checkResponse "/checkpoints" $ hasReached $ Slot 11017324 +hasReachedSomePoint = hasReachedPoint $ Slot 11017324 + +hasReachedSomeOtherPoint :: IO Bool +hasReachedSomeOtherPoint = hasReachedPoint $ Slot 36492716 + +hasReachedPoint :: Slot -> IO Bool +hasReachedPoint p = checkResponse "/checkpoints" $ hasReached $ p + +exitsWithError :: ProcessHandle -> IO Bool +exitsWithError h = do + e <- getProcessExitCode h + pure $ case e of + Nothing -> False + Just ExitSuccess -> False + Just (ExitFailure _) -> True checkResponse :: String -> ResponseCheck -> IO Bool checkResponse path check = do @@ -221,5 +257,9 @@ somePoint :: String somePoint = "11017324.195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" +someOtherPoint :: String +someOtherPoint = + "36492716.d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" + instance A.FromJSON Slot where parseJSON = A.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" From 27b93b4947d67013e09de578bfbfea8a51dd57c2 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 2 Jul 2026 13:18:55 +0000 Subject: [PATCH 21/68] Extract 'cannot restart with different pattern' test to new test-accept --- test-accept/Test/KupoSpec.hs | 26 +++++++++++++++++++++++++- test/Test/KupoSpec.hs | 23 ----------------------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index d928f018..7a0a473c 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -6,7 +6,17 @@ {- Tests for some corner cases that were flaky when run with `cabal test unit`. - These tests actually run the executable made with `cabal build` - So they are external integration/end-to-end acceptance tests. - - To run: `cabal build exe:kupo && cabal exec cabal test accept` + - To run on development server (in current repo): + - `cabal build exe:kupo && cabal exec cabal test accept` + - To run on installed server (in PATH, e.g. with brew install): + - `cabal test accept` + - To run on server in an alternative repo (e.g. different branch): + - ``` + - pushd ../kupo-pr-204 + - tmpPath=$(dirname $(cabal list-bin exe:kupo)) + - popd + - PATH=$tmpPath:$PATH cabal test accept + - ``` -} module Test.KupoSpec where @@ -147,6 +157,20 @@ spec = do withKupoH (options ++ ["--since", someOtherPoint]) $ \h -> do eventually (exitsWithError h) `shouldReturn` True + it "Cannot restart with different patterns" $ \dir -> do + let options = + ["--since", somePoint + ,"--workdir", dir + ] + -- Start kupo on fresh dir until reaches somePoint + withKupo (options ++ ["--match" , "*/*"]) $ do + reached <- eventually hasReachedSomePoint + pure (assert reached ()) + -- Restart kupo on same dir but with different pattern and check + -- that its exits with error code + withKupoH (options ++ ["--match", "*"]) $ \h -> do + eventually (exitsWithError h) `shouldReturn` True + withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a withKupoH options action = do process <- kupo options diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 7f7ccad9..893d89d4 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -147,7 +147,6 @@ import Test.Kupo.Fixture , someDatumInWitnessHash , someMetadata , someNonExistingPoint - , someOtherPoint , someOtherStakeKey , somePhase2FailedTransactionIdWithReturn , somePoint @@ -251,28 +250,6 @@ spec = skippableContext "End-to-end" $ do waitSlot (> (cp + 1_000)) healthCheck (serverHost cfg) (serverPort cfg) - endToEnd "start → restart(s)" $ \(configure, runSpec, HttpClient{..}) -> do - do -- Can start the server on a fresh new db - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint somePoint) - , patterns = fromList [MatchAny OnlyShelley] - } - runSpec env 5 $ waitSlot (> (getPointSlotNo somePoint)) - - do -- Can't restart with different, too recent, --since target on same db - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint someOtherPoint) - , patterns = fromList [MatchAny OnlyShelley] - } - shouldThrowTimeout @ConflictingOptionsException 1 (runSpec env) - - do -- Can't restart with different, non-empty, patterns - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint somePoint) - , patterns = fromList [MatchAny IncludingBootstrap] - } - shouldThrowTimeout @ConflictingOptionsException 1 (runSpec env) - endToEnd "Can't start the server on a fresh new db without explicit point" $ \(configure, runSpec, _) -> do (_, env) <- configure $ \defaultCfg -> defaultCfg { since = Nothing From a20f37e2b6cb7e34a875b31e48c8f884ad67f8c7 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Tue, 7 Jul 2026 13:18:01 +0000 Subject: [PATCH 22/68] Extract 'Auto-magically restart (--defer-db-indexes)' test to new test-accept --- test-accept/Test/KupoSpec.hs | 73 +++++++++++++++++++++++++++++++++--- test-accept/point-recent.dat | 1 + test/Test/KupoSpec.hs | 14 ------- 3 files changed, 69 insertions(+), 19 deletions(-) create mode 100644 test-accept/point-recent.dat diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 7a0a473c..0f1581ab 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -19,9 +19,9 @@ - ``` -} -module Test.KupoSpec where --- ( spec --- ) where +module Test.KupoSpec + ( spec + ) where import Prelude @@ -43,9 +43,13 @@ import Network.HTTP.Client , httpLbs , newManager , parseRequest + , requestHeaders , responseBody , responseStatus ) +import Network.HTTP.Types.Header + (hAccept + ) import Network.HTTP.Types.Status ( Status , status202 @@ -86,7 +90,12 @@ import qualified Data.ByteString.Lazy as B type ResponseCheck = Status -> B.ByteString -> Bool -newtype Slot = Slot Integer deriving (Eq, Ord, Show) +newtype Slot = Slot Integer deriving (Eq, Ord, Read, Show) + +data Point = Point Slot String + deriving (Eq, Ord, Read, Show) + +newtype Indexes = Indexes String deriving (Eq, Ord, Show) spec :: Spec spec = do @@ -102,6 +111,18 @@ spec = do ] $ eventually isConnected `shouldReturn` True + it "Auto-magically restart when --defer-db-indexes is enabled)" $ do + -- Read from file a valid point recent but before tip + point <- recentPoint + -- Start kupo since that point and with --defer-db-indexes + withKupo + ["--since", fmtPoint point + ,"--match", "*" + ,"--in-memory" + ,"--defer-db-indexes" + ] + $ eventually (hasIndexes point) `shouldReturn` True + around withDir $ do describe "Kupo server start/restart corner cases (file DB)" $ do @@ -222,6 +243,12 @@ isConnected = checkResponse "/checkpoints" containsCheckpoints isReady :: IO Bool isReady = checkResponse "/health" isHealthy +hasIndexes :: Point -> IO Bool +hasIndexes pt = do + indexes <- checkResponse "/health" hasIndexesInstalled + chckpts <- checkResponse "/checkpoints" (laterThan pt) + pure (indexes && chckpts) + hasReachedSomePoint :: IO Bool hasReachedSomePoint = hasReachedPoint $ Slot 11017324 @@ -243,7 +270,10 @@ checkResponse :: String -> ResponseCheck -> IO Bool checkResponse path check = do manager <- newManager defaultManagerSettings request' <- request path - response <- httpLbs request' manager + let request'' = request' + {requestHeaders = [(hAccept, "application/json; charset=utf-8")] + } + response <- httpLbs request'' manager let status = responseStatus response body = responseBody response @@ -268,6 +298,21 @@ hasReached slot status body = isHealthy :: ResponseCheck isHealthy status _ = status == status202 || status == status200 +hasIndexesInstalled :: ResponseCheck +hasIndexesInstalled status body = + (status == status200 || status == status202) + && (indexesFlag body) == Just (Indexes "installed") + +laterThan :: Point -> ResponseCheck +laterThan (Point slot _) status body = + status == status200 && laterThanSlot (A.decode body :: Maybe [Slot]) + where + laterThanSlot Nothing = False + laterThanSlot (Just slots) = all (>= slot) slots + +indexesFlag :: B.ByteString -> Maybe Indexes +indexesFlag = A.decode + tryHttp :: IO a -> IO (Either HttpException a) tryHttp m = try m @@ -285,5 +330,23 @@ someOtherPoint :: String someOtherPoint = "36492716.d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" +recentPoint :: IO Point +recentPoint = fmap read (readFile "test-accept/point-recent.dat") + +fmtPoint :: Point -> String +fmtPoint (Point (Slot slot) hash) = show slot ++ "." ++ hash + instance A.FromJSON Slot where parseJSON = A.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" + +instance A.FromJSON Indexes where + parseJSON = A.withObject "Health" $ \o -> do + c <- o .: "configuration" + i <- c .: "indexes" + pure (Indexes i) + +instance A.FromJSON Point where + parseJSON = A.withObject "Point" $ \o -> do + s <- o .: "slot_no" + h <- o .: "header_hash" + pure (Point s h) diff --git a/test-accept/point-recent.dat b/test-accept/point-recent.dat new file mode 100644 index 00000000..5068525a --- /dev/null +++ b/test-accept/point-recent.dat @@ -0,0 +1 @@ +Point (Slot 127736556) "6c025ce6cb810135f8c37559db48d7d15faf9222873ace16f847da822c328d31" diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 893d89d4..95d1aec0 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -536,20 +536,6 @@ spec = skippableContext "End-to-end" $ do res <- putPatternSince (MatchDelegation someOtherStakeKey) (Right tip) res `shouldBe` True - endToEnd "Auto-magically restart when reaching the tip (--defer-db-indexes enabled)" $ \(configure, runSpec, HttpClient{..}) -> do - tip <- currentNetworkTip - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just SinceTip - , patterns = fromList [MatchAny IncludingBootstrap] - , deferIndexes = SkipNonEssentialIndexes - } - runSpec env 120 $ do - waitSlot (>= getPointSlotNo tip) - points <- listCheckpoints - forM_ points $ \point -> getPointSlotNo point `shouldSatisfy` (>= getPointSlotNo tip) - Health{configuration} <- getHealth - configuration `shouldBe` (Just InstallIndexesIfNotExist) - endToEnd "Does not synchronize beyond a given point when asked (--until)" $ \(configure, runSpec, HttpClient{..}) -> do let maxSlot = 11037873 -- Somewhat after `somePoint`, but close enough. Note that this slot must still exist (i.e. be active) -- if we don't want `waitSlot` down below to be waiting forever! From 184ef4cfb6be9044a15fcae678cef8be4584794f Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 9 Jul 2026 10:43:48 +0000 Subject: [PATCH 23/68] Extract 'Dynamically add pattern' test to new test-accept --- kupo.cabal | 2 +- package.yaml | 2 +- test-accept/Test/KupoSpec.hs | 158 +++++++++++++++++++++++++++-------- test/Test/KupoSpec.hs | 50 ----------- 4 files changed, 125 insertions(+), 87 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index 8f5e064e..8f761e74 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -369,6 +369,7 @@ test-suite accept , http-types , process , temporary + , typed-process default-language: Haskell2010 test-suite unit @@ -463,7 +464,6 @@ test-suite unit , lens-aeson , network , openapi3 - , process , quickcheck-state-machine , relude , sqlite-simple diff --git a/package.yaml b/package.yaml index 06e5ddb9..991f3368 100644 --- a/package.yaml +++ b/package.yaml @@ -144,7 +144,6 @@ tests: - kupo - lens-aeson - openapi3 - - process - QuickCheck - quickcheck-state-machine - relude @@ -175,6 +174,7 @@ tests: - http-types - process - temporary + - typed-process build-tools: - hspec-discover diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 0f1581ab..85e11a57 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -21,6 +21,7 @@ module Test.KupoSpec ( spec + , currentNetworkTip ) where import Prelude @@ -35,14 +36,18 @@ import Control.Exception ) import Data.Aeson ( (.:) + , (.=) ) import Network.HTTP.Client ( HttpException , Request + , RequestBody (..) , defaultManagerSettings , httpLbs + , method , newManager , parseRequest + , requestBody , requestHeaders , responseBody , responseStatus @@ -51,7 +56,7 @@ import Network.HTTP.Types.Header (hAccept ) import Network.HTTP.Types.Status - ( Status + ( Status (..) , status202 , status200 ) @@ -87,6 +92,7 @@ import Test.Hspec import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as B +import qualified System.Process.Typed as TP type ResponseCheck = Status -> B.ByteString -> Bool @@ -95,8 +101,18 @@ newtype Slot = Slot Integer deriving (Eq, Ord, Read, Show) data Point = Point Slot String deriving (Eq, Ord, Read, Show) +-- Wrapper type needed to have a separate FromJSON instance +-- since the cardano-cli formats slot/hash differently from Kupo +newtype CliPoint = CliPoint Point + deriving (Eq, Ord, Read, Show) + +-- Wrapper type useful to have a specific ToJSON instance +newtype PutPatternBody = PutPatternBody Point + newtype Indexes = Indexes String deriving (Eq, Ord, Show) +type StakeKey = String + spec :: Spec spec = do @@ -111,18 +127,34 @@ spec = do ] $ eventually isConnected `shouldReturn` True - it "Auto-magically restart when --defer-db-indexes is enabled)" $ do + it "Auto-magically restarts when --defer-db-indexes is enabled)" $ do -- Read from file a valid point recent but before tip point <- recentPoint -- Start kupo since that point and with --defer-db-indexes withKupo - ["--since", fmtPoint point - ,"--match", "*" + ["--since" , fromPoint point + ,"--match" , "*" ,"--in-memory" ,"--defer-db-indexes" ] $ eventually (hasIndexes point) `shouldReturn` True + it "Dynamically adds pattern and rolls back to given past point" $ do + -- Start a kupo since "pointB" and matching on stakeB + withKupo + ["--since" , fromPoint pointB + ,"--match" , "*/" <> stakeB + ,"--in-memory" + ] + $ do + -- Wait for indexing to have started + reached <- eventually (hasReachedPoint pointB) + pure (assert reached ()) + later <- allCheckpointsLaterThan pointB + pure (assert later ()) + -- Add other pattern forcing rollback to earlier pointA + putNewPattern stakeA pointA `shouldReturn` True + around withDir $ do describe "Kupo server start/restart corner cases (file DB)" $ do @@ -130,12 +162,12 @@ spec = do it "Can start in readonly mode on readonly DB" $ \dir -> do -- Start a kupo on fresh database until it's ready withKupo - ["--since" , somePoint + ["--since" , fromPoint pointA ,"--match" , "*/*" ,"--workdir", dir ] $ do - reached <- eventually hasReachedSomeOtherPoint + reached <- eventually (hasReachedPoint pointB) pure (assert reached ()) -- Change permissions on database's directory makeUnwritable dir @@ -149,43 +181,43 @@ spec = do it "Can restart with same arguments" $ \dir -> do let options = - ["--since" , somePoint + ["--since" , fromPoint pointA ,"--match" , "*/*" ,"--workdir", dir ] - -- Start kupo on fresh dir until reaches somePoint + -- Start kupo on fresh dir until reaches pointA withKupo options $ do - reached <- eventually hasReachedSomePoint + reached <- eventually (hasReachedPoint pointA) pure (assert reached ()) -- Restart kupo on same dir and check that it is immediately -- already at or past same point withKupo options $ do connected <- eventually isConnected pure (assert connected ()) - hasReachedSomePoint `shouldReturn` True + (hasReachedPoint pointA) `shouldReturn` True it "Cannot restart with later '--since'" $ \dir -> do let options = ["--match" , "*/*" ,"--workdir", dir ] - -- Start kupo on fresh dir until reaches somePoint - withKupo (options ++ ["--since", somePoint]) $ do - reached <- eventually hasReachedSomePoint + -- Start kupo on fresh dir until reaches pointA + withKupo (options ++ ["--since", fromPoint pointA]) $ do + reached <- eventually (hasReachedPoint pointA) pure (assert reached ()) -- Restart kupo on same dir but later "--since" and check -- that its exits with error code - withKupoH (options ++ ["--since", someOtherPoint]) $ \h -> do + withKupoH (options ++ ["--since", fromPoint pointB]) $ \h -> do eventually (exitsWithError h) `shouldReturn` True it "Cannot restart with different patterns" $ \dir -> do let options = - ["--since", somePoint + ["--since", fromPoint pointA ,"--workdir", dir ] - -- Start kupo on fresh dir until reaches somePoint + -- Start kupo on fresh dir until reaches pointA withKupo (options ++ ["--match" , "*/*"]) $ do - reached <- eventually hasReachedSomePoint + reached <- eventually (hasReachedPoint pointA) pure (assert reached ()) -- Restart kupo on same dir but with different pattern and check -- that its exits with error code @@ -249,14 +281,11 @@ hasIndexes pt = do chckpts <- checkResponse "/checkpoints" (laterThan pt) pure (indexes && chckpts) -hasReachedSomePoint :: IO Bool -hasReachedSomePoint = hasReachedPoint $ Slot 11017324 - -hasReachedSomeOtherPoint :: IO Bool -hasReachedSomeOtherPoint = hasReachedPoint $ Slot 36492716 +hasReachedPoint :: Point -> IO Bool +hasReachedPoint = checkResponse "/checkpoints" . hasReached -hasReachedPoint :: Slot -> IO Bool -hasReachedPoint p = checkResponse "/checkpoints" $ hasReached $ p +allCheckpointsLaterThan :: Point -> IO Bool +allCheckpointsLaterThan = checkResponse "/checkpoints" . laterThan exitsWithError :: ProcessHandle -> IO Bool exitsWithError h = do @@ -279,6 +308,19 @@ checkResponse path check = do body = responseBody response pure (check status body) +putNewPattern :: StakeKey -> Point -> IO Bool +putNewPattern key point = do + manager <- newManager defaultManagerSettings + request' <- request ("/patterns/*/" <> key) + let request'' = request' + { method = "PUT" + , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) + } + response <- httpLbs request'' manager + case responseStatus response of + (Status 200 _) -> pure True + _ -> pure False + containsCheckpoints :: ResponseCheck containsCheckpoints status body = status == status200 && hasSlots (A.decode body :: Maybe [Slot]) @@ -287,8 +329,8 @@ containsCheckpoints status body = hasSlots (Just []) = False hasSlots (Just _ ) = True -hasReached :: Slot -> ResponseCheck -hasReached slot status body = +hasReached :: Point -> ResponseCheck +hasReached (Point slot _) status body = status == status200 && hasReached' slot (A.decode body :: Maybe [Slot]) where hasReached' _ Nothing = False @@ -322,19 +364,39 @@ url = "http://127.0.0.1:1442" request :: String -> IO Request request = parseRequest . (url <>) -somePoint :: String -somePoint = - "11017324.195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" - -someOtherPoint :: String -someOtherPoint = - "36492716.d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" +-- A point that exists on-chain. Earlier than pointB. +-- (Called somePoint in other 'unit' test suite) +pointA :: Point +pointA = + Point + (Slot 11017324) + "195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" + +-- A point that exists on-chain. Later than pointA. +-- (Called someOtherPoint in other 'unit' test suite) +pointB :: Point +pointB = + Point + (Slot 36492716) + "d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" + +-- Some stake key in Shelley, present in addresses from early blocks of Shelley. +-- (Called someStakeKey in other 'unit' test suite) +stakeA :: StakeKey +stakeA = + "968d1021ebd7178e1fb0e79676982825cabc779b653e1234d58ce3c6" + +-- Similar to stakeA but distinct from it. +-- (Called someOtherStakeKey in other 'unit' test suite) +stakeB :: StakeKey +stakeB = + "f130204b518f70c19995449e3737eded3d9ffc31cb50ec0e45010ba3" recentPoint :: IO Point recentPoint = fmap read (readFile "test-accept/point-recent.dat") -fmtPoint :: Point -> String -fmtPoint (Point (Slot slot) hash) = show slot ++ "." ++ hash +fromPoint :: Point -> String +fromPoint (Point (Slot slot) hash) = show slot ++ "." ++ hash instance A.FromJSON Slot where parseJSON = A.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" @@ -350,3 +412,29 @@ instance A.FromJSON Point where s <- o .: "slot_no" h <- o .: "header_hash" pure (Point s h) + +instance A.FromJSON CliPoint where + parseJSON = A.withObject "CliPoint" $ \o -> do + s <- o .: "slot" + h <- o .: "hash" + pure (CliPoint (Point (Slot s) h)) + +instance A.ToJSON PutPatternBody where + toJSON (PutPatternBody (Point (Slot slot) hash)) = A.object + [ "rollback_to" .= A.object + [ "slot_no" .= slot + , "header_hash" .= hash + ] + , "limit" .= ("unsafe_allow_beyond_safe_zone" :: String) + ] + +currentNetworkTip :: IO (Maybe CliPoint) +currentNetworkTip = do + let args = + [ "query", "tip" + , "--testnet-magic", "1" + ] + (_, out) <- TP.readProcessStdout (TP.proc "cardano-cli" args) + pure (A.decode out) + + diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 95d1aec0..31a185ef 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -18,11 +18,6 @@ import Control.Monad.Trans.Writer ( execWriterT , tell ) -import Data.Aeson.Lens - ( _Integer - , _String - , key - ) import Data.List ( maximum , (\\) @@ -69,13 +64,11 @@ import Kupo.Control.MonadTime ) import Kupo.Data.Cardano ( Datum (..) - , Point , ScriptReference (..) , getPointSlotNo , hasPolicyId , mkOutputReference , pattern GenesisPoint - , pointFromText , unsafeValueFromList ) import Kupo.Data.ChainSync @@ -113,11 +106,6 @@ import System.IO.Temp ( withSystemTempDirectory , withTempFile ) -import System.Process - ( CreateProcess (..) - , proc - , readCreateProcess - ) import Test.Hspec ( Arg , Spec @@ -188,11 +176,7 @@ import System.IO ( hClose , hGetLine ) -import System.Environment - ( getEnvironment - ) -import qualified Data.Aeson as Json import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as Builder import qualified Prelude @@ -525,17 +509,6 @@ spec = skippableContext "End-to-end" $ do connectionStatus `shouldBe` Connected configuration `shouldBe` Nothing - endToEnd "Dynamically add pattern and restart to a past point when at the tip" $ \(configure, runSpec, HttpClient{..}) -> do - tip <- currentNetworkTip - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint tip) - , patterns = fromList [MatchAny IncludingBootstrap] - } - runSpec env 120 $ do - waitSlot (>= getPointSlotNo tip) - res <- putPatternSince (MatchDelegation someOtherStakeKey) (Right tip) - res `shouldBe` True - endToEnd "Does not synchronize beyond a given point when asked (--until)" $ \(configure, runSpec, HttpClient{..}) -> do let maxSlot = 11037873 -- Somewhat after `somePoint`, but close enough. Note that this slot must still exist (i.e. be active) -- if we don't want `waitSlot` down below to be waiting forever! @@ -733,29 +706,6 @@ withReplica cfg test = do withTracers h version (defaultTracers (Just Info)) $ \tr -> do race_ (kupo tr `runWith` replicaEnv) (test replicaHttpClient) -currentNetworkTip :: IO Point -currentNetworkTip = do - lookupEnv varCardanoNodeSocket >>= \case - Nothing -> - fail $ varCardanoNodeSocket <> " not set but necessary for this test." - Just socket -> do - baseEnv <- getEnvironment - let env = Just (("CARDANO_NODE_SOCKET_PATH", socket):baseEnv) - let args = - [ "query", "tip" - , "--testnet-magic", "1" - , "--cardano-mode" - ] - out <- readCreateProcess ((proc "cardano-cli" args) { env }) "" - case Json.eitherDecode @Json.Value (encodeUtf8 out) of - Left err -> - fail err - Right json -> do - maybe (fail "couldn't decode tip from cardano-cli") pure $ do - slotNo <- json ^? key "slot" . _Integer - headerHash <- json ^? key "hash" ._String - pointFromText (show slotNo <> "." <> headerHash) - shouldThrowTimeout :: forall e. (Exception e) => DiffTime -> (DiffTime -> IO () -> IO ()) -> IO () shouldThrowTimeout t action = do let stub = action (t + 1) (threadDelay (t + 1)) From 7b822bfe7bc83561d7fef325c2ecccc00e040558 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Thu, 9 Jul 2026 13:33:17 +0000 Subject: [PATCH 24/68] Improvements: - Make `Dynamically add pattern` like the original, i.e. at tip - Make `Can restart with same arguments` totally reliable (was flaky) --- test-accept/Test/KupoSpec.hs | 87 ++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 29 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 85e11a57..dc8c71fc 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -21,7 +21,6 @@ module Test.KupoSpec ( spec - , currentNetworkTip ) where import Prelude @@ -51,6 +50,8 @@ import Network.HTTP.Client , requestHeaders , responseBody , responseStatus + , responseTimeout + , responseTimeoutNone ) import Network.HTTP.Types.Header (hAccept @@ -111,7 +112,7 @@ newtype PutPatternBody = PutPatternBody Point newtype Indexes = Indexes String deriving (Eq, Ord, Show) -type StakeKey = String +type Pattern = String spec :: Spec spec = do @@ -139,21 +140,25 @@ spec = do ] $ eventually (hasIndexes point) `shouldReturn` True - it "Dynamically adds pattern and rolls back to given past point" $ do - -- Start a kupo since "pointB" and matching on stakeB - withKupo - ["--since" , fromPoint pointB - ,"--match" , "*/" <> stakeB - ,"--in-memory" - ] - $ do - -- Wait for indexing to have started - reached <- eventually (hasReachedPoint pointB) - pure (assert reached ()) - later <- allCheckpointsLaterThan pointB - pure (assert later ()) - -- Add other pattern forcing rollback to earlier pointA - putNewPattern stakeA pointA `shouldReturn` True + it "Dynamically adds pattern and rolls back (when at tip)" $ do + tip <- currentNetworkTip + case tip of + Nothing -> fail "Need to be able to use cardano-cli to get tip" + Just (CliPoint point) -> + -- Start a kupo since "tip" and matching on stakeA + withKupo + ["--since" , fromPoint point + ,"--match" , stakeA + ,"--in-memory" + ] + $ do + -- Wait for indexing to have finished + reached <- eventually (hasReachedPoint point) + pure (assert reached ()) + getPatterns `shouldReturn` Just [stakeA] + -- Add stakeB pattern forcing rollback to same point + putNewPattern stakeB point `shouldReturn` True + getPatterns `shouldReturn` Just [stakeA, stakeB] around withDir $ do @@ -192,9 +197,8 @@ spec = do -- Restart kupo on same dir and check that it is immediately -- already at or past same point withKupo options $ do - connected <- eventually isConnected - pure (assert connected ()) - (hasReachedPoint pointA) `shouldReturn` True + eventually (hasCheckpointsAllLaterThan pointA) + `shouldReturn` True it "Cannot restart with later '--since'" $ \dir -> do let options = @@ -284,8 +288,8 @@ hasIndexes pt = do hasReachedPoint :: Point -> IO Bool hasReachedPoint = checkResponse "/checkpoints" . hasReached -allCheckpointsLaterThan :: Point -> IO Bool -allCheckpointsLaterThan = checkResponse "/checkpoints" . laterThan +hasCheckpointsAllLaterThan :: Point -> IO Bool +hasCheckpointsAllLaterThan = checkResponse "/checkpoints" . nonEmptyAndLaterThan exitsWithError :: ProcessHandle -> IO Bool exitsWithError h = do @@ -308,13 +312,30 @@ checkResponse path check = do body = responseBody response pure (check status body) -putNewPattern :: StakeKey -> Point -> IO Bool -putNewPattern key point = do +getPatterns :: IO (Maybe [Pattern]) +getPatterns = do + manager <- newManager defaultManagerSettings + request' <- request ("/patterns") + let request'' = request' + {requestHeaders = [(hAccept, "application/json; charset=utf-8")] + } + response <- httpLbs request'' manager + case responseStatus response of + (Status 200 _) -> do + let body = responseBody response + pure (A.decode body :: Maybe [Pattern]) + _ -> + pure Nothing + + +putNewPattern :: Pattern -> Point -> IO Bool +putNewPattern pattern point = do manager <- newManager defaultManagerSettings - request' <- request ("/patterns/*/" <> key) + request' <- request ("/patterns/" <> pattern) let request'' = request' { method = "PUT" , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) + , responseTimeout = responseTimeoutNone } response <- httpLbs request'' manager case responseStatus response of @@ -352,6 +373,14 @@ laterThan (Point slot _) status body = laterThanSlot Nothing = False laterThanSlot (Just slots) = all (>= slot) slots +nonEmptyAndLaterThan :: Point -> ResponseCheck +nonEmptyAndLaterThan (Point slot _) status body = + status == status200 && laterThanSlot (A.decode body :: Maybe [Slot]) + where + laterThanSlot Nothing = False + laterThanSlot (Just [] ) = False + laterThanSlot (Just slots) = all (>= slot) slots + indexesFlag :: B.ByteString -> Maybe Indexes indexesFlag = A.decode @@ -382,15 +411,15 @@ pointB = -- Some stake key in Shelley, present in addresses from early blocks of Shelley. -- (Called someStakeKey in other 'unit' test suite) -stakeA :: StakeKey +stakeA :: Pattern stakeA = - "968d1021ebd7178e1fb0e79676982825cabc779b653e1234d58ce3c6" + "*/968d1021ebd7178e1fb0e79676982825cabc779b653e1234d58ce3c6" -- Similar to stakeA but distinct from it. -- (Called someOtherStakeKey in other 'unit' test suite) -stakeB :: StakeKey +stakeB :: Pattern stakeB = - "f130204b518f70c19995449e3737eded3d9ffc31cb50ec0e45010ba3" + "*/f130204b518f70c19995449e3737eded3d9ffc31cb50ec0e45010ba3" recentPoint :: IO Point recentPoint = fmap read (readFile "test-accept/point-recent.dat") From 94fdbd3ddf9e8c6a7ccd305c4f69705b0e726150 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 13 Jul 2026 11:45:51 +0000 Subject: [PATCH 25/68] Refactor variable name --- test-accept/Test/KupoSpec.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index dc8c71fc..4277b0fb 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -141,23 +141,23 @@ spec = do $ eventually (hasIndexes point) `shouldReturn` True it "Dynamically adds pattern and rolls back (when at tip)" $ do - tip <- currentNetworkTip - case tip of + maybeTip <- currentNetworkTip + case maybeTip of Nothing -> fail "Need to be able to use cardano-cli to get tip" - Just (CliPoint point) -> + Just (CliPoint tip) -> -- Start a kupo since "tip" and matching on stakeA withKupo - ["--since" , fromPoint point + ["--since" , fromPoint tip ,"--match" , stakeA ,"--in-memory" ] $ do -- Wait for indexing to have finished - reached <- eventually (hasReachedPoint point) + reached <- eventually (hasReachedPoint tip) pure (assert reached ()) getPatterns `shouldReturn` Just [stakeA] -- Add stakeB pattern forcing rollback to same point - putNewPattern stakeB point `shouldReturn` True + putNewPattern stakeB tip `shouldReturn` True getPatterns `shouldReturn` Just [stakeA, stakeB] around withDir $ do From 30c25b6892259ddbdf6c006e2095c455b4c7d6de Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 13 Jul 2026 14:06:07 +0000 Subject: [PATCH 26/68] Extract 'Dynamically add pattern (while syncing)' test to new test-accept --- test-accept/Test/KupoSpec.hs | 158 ++++++++++++++++++++++++++--------- test/Test/KupoSpec.hs | 43 ---------- 2 files changed, 120 insertions(+), 81 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 4277b0fb..51420dcb 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -114,6 +114,9 @@ newtype Indexes = Indexes String deriving (Eq, Ord, Show) type Pattern = String +data Match = Match Integer String Int Int + deriving (Eq, Ord, Read, Show) + spec :: Spec spec = do @@ -160,6 +163,43 @@ spec = do putNewPattern stakeB tip `shouldReturn` True getPatterns `shouldReturn` Just [stakeA, stakeB] + it "Dynamically adds pattern and rolls back (when syncing)" $ do + let options = + ["--since" , fromPoint lastByron + ,"--in-memory" + ] + -- Start a kupo since last Byron block and matching on stakeA + withKupo (options ++ ["--match", stakeA]) $ do + -- Wait for indexing at least 100_000 slots + reached <- eventually (hasReachedPoint lastByron136K) + pure (assert reached ()) + getPatterns `shouldReturn` Just [stakeA] + getMatchesInWindow lastByron lastByron136K + `shouldReturn` Just + -- slot, hash, transaction idx, output idx + [Match 86440 "49ef96" 0 1] + -- Start over, same again except matching on stakeB + withKupo (options ++ ["--match", stakeB]) $ do + -- Wait for indexing at least 100_000 slots + reached <- eventually (hasReachedPoint lastByron136K) + pure (assert reached ()) + getPatterns `shouldReturn` Just [stakeB] + getMatchesInWindow lastByron lastByron136K + `shouldReturn` Just + -- output index is different from stakeA's match + [Match 86440 "49ef96" 0 2] + -- Add stakeA pattern forcing rollback to last Byron block + putNewPattern stakeA lastByron `shouldReturn` True + getPatterns `shouldReturn` Just [stakeA, stakeB] + reachedAgain <- eventually (hasReachedPoint lastByron136K) + pure (assert reachedAgain ()) + getMatchesInWindow lastByron lastByron136K + `shouldReturn` Just + -- now we have both matches together, proving rollback + [ Match 86440 "49ef96" 0 2 + , Match 86440 "49ef96" 0 1 + ] + around withDir $ do describe "Kupo server start/restart corner cases (file DB)" $ do @@ -333,8 +373,8 @@ putNewPattern pattern point = do manager <- newManager defaultManagerSettings request' <- request ("/patterns/" <> pattern) let request'' = request' - { method = "PUT" - , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) + { method = "PUT" + , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) , responseTimeout = responseTimeoutNone } response <- httpLbs request'' manager @@ -342,6 +382,36 @@ putNewPattern pattern point = do (Status 200 _) -> pure True _ -> pure False +getMatchesInWindow :: Point -> Point -> IO (Maybe [Match]) +getMatchesInWindow from to = do + manager <- newManager defaultManagerSettings + request' <- request ("/matches") + let request'' = request' + {requestHeaders = [(hAccept, "application/json; charset=utf-8")] + , responseTimeout = responseTimeoutNone + } + response <- httpLbs request'' manager + case responseStatus response of + (Status 200 _) -> do + let body = responseBody response + let maybeMatches = A.decode body :: Maybe [Match] + pure (filter (matchInWindow from to) <$> maybeMatches) + _ -> + pure Nothing + +matchInWindow :: Point -> Point -> Match -> Bool +matchInWindow (Point (Slot s1) _) (Point (Slot s2) _) (Match s _ _ _) = + s1 < s && s < s2 + +currentNetworkTip :: IO (Maybe CliPoint) +currentNetworkTip = do + let args = + [ "query", "tip" + , "--testnet-magic", "1" + ] + (_, out) <- TP.readProcessStdout (TP.proc "cardano-cli" args) + pure (A.decode out) + containsCheckpoints :: ResponseCheck containsCheckpoints status body = status == status200 && hasSlots (A.decode body :: Maybe [Slot]) @@ -393,34 +463,6 @@ url = "http://127.0.0.1:1442" request :: String -> IO Request request = parseRequest . (url <>) --- A point that exists on-chain. Earlier than pointB. --- (Called somePoint in other 'unit' test suite) -pointA :: Point -pointA = - Point - (Slot 11017324) - "195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" - --- A point that exists on-chain. Later than pointA. --- (Called someOtherPoint in other 'unit' test suite) -pointB :: Point -pointB = - Point - (Slot 36492716) - "d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" - --- Some stake key in Shelley, present in addresses from early blocks of Shelley. --- (Called someStakeKey in other 'unit' test suite) -stakeA :: Pattern -stakeA = - "*/968d1021ebd7178e1fb0e79676982825cabc779b653e1234d58ce3c6" - --- Similar to stakeA but distinct from it. --- (Called someOtherStakeKey in other 'unit' test suite) -stakeB :: Pattern -stakeB = - "*/f130204b518f70c19995449e3737eded3d9ffc31cb50ec0e45010ba3" - recentPoint :: IO Point recentPoint = fmap read (readFile "test-accept/point-recent.dat") @@ -457,13 +499,53 @@ instance A.ToJSON PutPatternBody where , "limit" .= ("unsafe_allow_beyond_safe_zone" :: String) ] -currentNetworkTip :: IO (Maybe CliPoint) -currentNetworkTip = do - let args = - [ "query", "tip" - , "--testnet-magic", "1" - ] - (_, out) <- TP.readProcessStdout (TP.proc "cardano-cli" args) - pure (A.decode out) +instance A.FromJSON Match where + parseJSON = A.withObject "Match" $ \o -> do + tidx <- o .: "transaction_index" + oidx <- o .: "output_index" + c <- o .: "created_at" + slot <- c .: "slot_no" + hash <- c .: "header_hash" + pure (Match slot (take 6 hash) tidx oidx) + +-- A point that exists on-chain. Earlier than pointB. +-- (Called somePoint in other 'unit' test suite) +pointA :: Point +pointA = + Point + (Slot 11017324) + "195908564a66d713bd2b71a9b1f290be6853cb31085fe7371276a35a2f8f7e62" + +-- A point that exists on-chain. Later than pointA. +-- (Called someOtherPoint in other 'unit' test suite) +pointB :: Point +pointB = + Point + (Slot 36492716) + "d51095ef5405d83e7a1c82b98d12b357ba6b95f070f684bb38ab47ef90b21688" +-- A point that exists on-chain. Last Byron block. +lastByron :: Point +lastByron = + Point + (Slot 84242) + "45899e8002b27df291e09188bfe3aeb5397ac03546a7d0ead93aa2500860f1af" + +-- A point that exists on-chain. Over 100_000 slots after lastByron +lastByron136K :: Point +lastByron136K = + Point + (Slot 220860) + "10915760772b5cf13b5138eda8a4ea36f871ece619547bc4eec63831008ebf69" +-- Some stake key in Shelley, present in addresses from early blocks of Shelley. +-- (Called someStakeKey in other 'unit' test suite) +stakeA :: Pattern +stakeA = + "*/968d1021ebd7178e1fb0e79676982825cabc779b653e1234d58ce3c6" + +-- Similar to stakeA but distinct from it. +-- (Called someOtherStakeKey in other 'unit' test suite) +stakeB :: Pattern +stakeB = + "*/f130204b518f70c19995449e3737eded3d9ffc31cb50ec0e45010ba3" diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 31a185ef..7441d15b 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -369,49 +369,6 @@ spec = skippableContext "End-to-end" $ do whenInline <- getAllMatches NoStatusFlag InlineAll <&> extractInline whenInline `shouldSatisfy` elem someScriptInOutput - - endToEnd "Dynamically add pattern and restart to a past point when syncing" $ \(configure, runSpec, HttpClient{..}) -> do - (_, env) <- configure $ \defaultCfg -> defaultCfg - { since = Just (SincePoint lastByronPoint) - , patterns = fromList [MatchDelegation someStakeKey] - } - -- NOTE: maxSlot must be high enough after the rollback point to have a chance to observe the - -- rollback. If too low, Kupo might have already re-synchronised and we can't assert that a - -- rollback did happen. - let maxSlot = getPointSlotNo lastByronPoint + 100_000 - let onlyInWindow r - | getPointSlotNo (createdAt r) <= maxSlot = - Just r { spentAt = Nothing } - | otherwise = - Nothing - ref <- newIORef ([], []) - runSpec env 10 $ do - waitSlot (>= maxSlot) - xs <- mapMaybe onlyInWindow <$> getAllMatches NoStatusFlag AsReference - xs `shouldNotBe` [] - res <- putPatternSince (MatchDelegation someOtherStakeKey) (Right lastByronPoint) - res `shouldBe` True - waitSlot (< maxSlot) -- Observe rollback - waitSlot (>= maxSlot) - ys <- mapMaybe onlyInWindow <$> getAllMatches NoStatusFlag AsReference - (xs \\ ys) `shouldBe` [] - (sort <$> listPatterns) `shouldReturn` - [ MatchDelegation someStakeKey - , MatchDelegation someOtherStakeKey - ] - void $ atomicSwapIORef ref (xs, ys) - (xs, ys) <- readIORef ref - withSystemTempDirectory "kupo-end-to-end" $ \tmp' -> do - (_, env') <- configure $ \defaultCfg -> defaultCfg - { databaseLocation = Dir tmp' - , since = Just (SincePoint lastByronPoint) - , patterns = fromList [MatchDelegation someOtherStakeKey] - } - runSpec env' 10 $ do - waitSlot (>= maxSlot) - zs <- mapMaybe onlyInWindow <$> getAllMatches NoStatusFlag AsReference - ys \\ zs `shouldBe` xs - endToEnd "Failing to insert patterns (failed to resolve point) doesn't disturb normal operations" $ \(configure, runSpec, HttpClient{..}) -> do (_, env) <- configure $ \defaultCfg -> defaultCfg { since = Just (SincePoint lastByronPoint) From 322c82507bc3449b85f8b4c0b365478d5c035aed Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 13 Jul 2026 14:39:48 +0000 Subject: [PATCH 27/68] Refactor: remove redundant imports --- test/Test/KupoSpec.hs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/test/Test/KupoSpec.hs b/test/Test/KupoSpec.hs index 7441d15b..2188d133 100644 --- a/test/Test/KupoSpec.hs +++ b/test/Test/KupoSpec.hs @@ -20,10 +20,6 @@ import Control.Monad.Trans.Writer ) import Data.List ( maximum - , (\\) - ) -import GHC.IORef - ( atomicSwapIORef ) import Kupo ( Env @@ -114,7 +110,6 @@ import Test.Hspec , context , runIO , shouldBe - , shouldNotBe , shouldReturn , shouldSatisfy , specify @@ -150,7 +145,6 @@ import Test.Kupo.Fixture , someScriptInWitness , someScriptInWitnessHash , someSlotWithMetadata - , someStakeKey , someThirdTransactionId , someTransactionId , someTransactionIdWithMetadata From b2035e957f37a58417639df35318345f6086996b Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 13 Jul 2026 14:46:17 +0000 Subject: [PATCH 28/68] Refactor: improve test-accept reliability on pr-204 branch --- test-accept/Test/KupoSpec.hs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 51420dcb..38c1661e 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -190,9 +190,9 @@ spec = do [Match 86440 "49ef96" 0 2] -- Add stakeA pattern forcing rollback to last Byron block putNewPattern stakeA lastByron `shouldReturn` True - getPatterns `shouldReturn` Just [stakeA, stakeB] reachedAgain <- eventually (hasReachedPoint lastByron136K) pure (assert reachedAgain ()) + getPatterns `shouldReturn` Just [stakeA, stakeB] getMatchesInWindow lastByron lastByron136K `shouldReturn` Just -- now we have both matches together, proving rollback From a0545d616b7dcec778210a75824c0575d2ae09e0 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Mon, 13 Jul 2026 15:34:56 +0000 Subject: [PATCH 29/68] Refactor: improve reliability on pr-204 by not reusing port between test-accept tests --- test-accept/Test/KupoSpec.hs | 147 ++++++++++++++++++++--------------- 1 file changed, 84 insertions(+), 63 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 38c1661e..1f1f6057 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -125,23 +125,25 @@ spec = do it "Can connect" $ do -- Start a kupo and check that it eventually has checkpoints withKupo - ["--since" , "origin" + ["--port" , "1443" + ,"--since" , "origin" ,"--match" , "*/*" ,"--in-memory" ] - $ eventually isConnected `shouldReturn` True + $ eventually (isConnected 1443) `shouldReturn` True it "Auto-magically restarts when --defer-db-indexes is enabled)" $ do -- Read from file a valid point recent but before tip point <- recentPoint -- Start kupo since that point and with --defer-db-indexes withKupo - ["--since" , fromPoint point + ["--port" , "1444" + ,"--since" , fromPoint point ,"--match" , "*" ,"--in-memory" ,"--defer-db-indexes" ] - $ eventually (hasIndexes point) `shouldReturn` True + $ eventually (hasIndexes 1444 point) `shouldReturn` True it "Dynamically adds pattern and rolls back (when at tip)" $ do maybeTip <- currentNetworkTip @@ -150,18 +152,19 @@ spec = do Just (CliPoint tip) -> -- Start a kupo since "tip" and matching on stakeA withKupo - ["--since" , fromPoint tip + ["--port" , "1445" + ,"--since" , fromPoint tip ,"--match" , stakeA ,"--in-memory" ] $ do -- Wait for indexing to have finished - reached <- eventually (hasReachedPoint tip) + reached <- eventually (hasReachedPoint 1445 tip) pure (assert reached ()) - getPatterns `shouldReturn` Just [stakeA] + getPatterns 1445 `shouldReturn` Just [stakeA] -- Add stakeB pattern forcing rollback to same point - putNewPattern stakeB tip `shouldReturn` True - getPatterns `shouldReturn` Just [stakeA, stakeB] + putNewPattern 1445 stakeB tip `shouldReturn` True + getPatterns 1445 `shouldReturn` Just [stakeA, stakeB] it "Dynamically adds pattern and rolls back (when syncing)" $ do let options = @@ -169,31 +172,31 @@ spec = do ,"--in-memory" ] -- Start a kupo since last Byron block and matching on stakeA - withKupo (options ++ ["--match", stakeA]) $ do + withKupo (options ++ ["--match", stakeA, "--port", "1446"]) $ do -- Wait for indexing at least 100_000 slots - reached <- eventually (hasReachedPoint lastByron136K) + reached <- eventually (hasReachedPoint 1446 lastByron136K) pure (assert reached ()) - getPatterns `shouldReturn` Just [stakeA] - getMatchesInWindow lastByron lastByron136K + getPatterns 1446 `shouldReturn` Just [stakeA] + getMatchesInWindow 1446 lastByron lastByron136K `shouldReturn` Just -- slot, hash, transaction idx, output idx [Match 86440 "49ef96" 0 1] -- Start over, same again except matching on stakeB - withKupo (options ++ ["--match", stakeB]) $ do + withKupo (options ++ ["--match", stakeB, "--port", "1447"]) $ do -- Wait for indexing at least 100_000 slots - reached <- eventually (hasReachedPoint lastByron136K) + reached <- eventually (hasReachedPoint 1447 lastByron136K) pure (assert reached ()) - getPatterns `shouldReturn` Just [stakeB] - getMatchesInWindow lastByron lastByron136K + getPatterns 1447 `shouldReturn` Just [stakeB] + getMatchesInWindow 1447 lastByron lastByron136K `shouldReturn` Just -- output index is different from stakeA's match [Match 86440 "49ef96" 0 2] -- Add stakeA pattern forcing rollback to last Byron block - putNewPattern stakeA lastByron `shouldReturn` True - reachedAgain <- eventually (hasReachedPoint lastByron136K) + putNewPattern 1447 stakeA lastByron `shouldReturn` True + reachedAgain <- eventually (hasReachedPoint 1447 lastByron136K) pure (assert reachedAgain ()) - getPatterns `shouldReturn` Just [stakeA, stakeB] - getMatchesInWindow lastByron lastByron136K + getPatterns 1447 `shouldReturn` Just [stakeA, stakeB] + getMatchesInWindow 1447 lastByron lastByron136K `shouldReturn` Just -- now we have both matches together, proving rollback [ Match 86440 "49ef96" 0 2 @@ -207,22 +210,24 @@ spec = do it "Can start in readonly mode on readonly DB" $ \dir -> do -- Start a kupo on fresh database until it's ready withKupo - ["--since" , fromPoint pointA + ["--port" , "1448" + ,"--since" , fromPoint pointA ,"--match" , "*/*" ,"--workdir", dir ] $ do - reached <- eventually (hasReachedPoint pointB) + reached <- eventually (hasReachedPoint 1448 pointB) pure (assert reached ()) -- Change permissions on database's directory makeUnwritable dir -- Start a read-only kupo on dir and check that it's also ready let process = proc "kupo" - ["--read-only" + ["--port" , "1449" + ,"--read-only" ,"--workdir", dir ] withCreateProcess process $ \ _ _ _ _ -> do - eventually isReady `shouldReturn` True + eventually (isReady 1449) `shouldReturn` True it "Can restart with same arguments" $ \dir -> do let options = @@ -231,13 +236,13 @@ spec = do ,"--workdir", dir ] -- Start kupo on fresh dir until reaches pointA - withKupo options $ do - reached <- eventually (hasReachedPoint pointA) + withKupo (options ++ ["--port","1450"]) $ do + reached <- eventually (hasReachedPoint 1450 pointA) pure (assert reached ()) -- Restart kupo on same dir and check that it is immediately -- already at or past same point - withKupo options $ do - eventually (hasCheckpointsAllLaterThan pointA) + withKupo (options ++ ["--port","1451"]) $ do + eventually (hasCheckpointsAllLaterThan 1450 pointA) `shouldReturn` True it "Cannot restart with later '--since'" $ \dir -> do @@ -246,12 +251,20 @@ spec = do ,"--workdir", dir ] -- Start kupo on fresh dir until reaches pointA - withKupo (options ++ ["--since", fromPoint pointA]) $ do - reached <- eventually (hasReachedPoint pointA) + let optionsA = options ++ + [ "--port" , "1451" + , "--since", fromPoint pointA + ] + withKupo optionsA $ do + reached <- eventually (hasReachedPoint 1451 pointA) pure (assert reached ()) -- Restart kupo on same dir but later "--since" and check -- that its exits with error code - withKupoH (options ++ ["--since", fromPoint pointB]) $ \h -> do + let optionsB = options ++ + [ "--port" , "1452" + , "--since", fromPoint pointB + ] + withKupoH optionsB $ \h -> do eventually (exitsWithError h) `shouldReturn` True it "Cannot restart with different patterns" $ \dir -> do @@ -260,12 +273,20 @@ spec = do ,"--workdir", dir ] -- Start kupo on fresh dir until reaches pointA - withKupo (options ++ ["--match" , "*/*"]) $ do - reached <- eventually (hasReachedPoint pointA) + let optionsA = options ++ + [ "--port" , "1453" + , "--match", "*/*" + ] + withKupo optionsA $ do + reached <- eventually (hasReachedPoint 1453 pointA) pure (assert reached ()) -- Restart kupo on same dir but with different pattern and check -- that its exits with error code - withKupoH (options ++ ["--match", "*"]) $ \h -> do + let optionsB = options ++ + [ "--port" , "1454" + , "--match", "*" + ] + withKupoH optionsB $ \h -> do eventually (exitsWithError h) `shouldReturn` True withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a @@ -313,23 +334,23 @@ eventually p = go (0::Int) threadDelay 1_000_000 -- 1s between retries go (attempt + 1) -isConnected :: IO Bool -isConnected = checkResponse "/checkpoints" containsCheckpoints +isConnected :: Int -> IO Bool +isConnected port = checkResponse port "/checkpoints" containsCheckpoints -isReady :: IO Bool -isReady = checkResponse "/health" isHealthy +isReady :: Int -> IO Bool +isReady port = checkResponse port "/health" isHealthy -hasIndexes :: Point -> IO Bool -hasIndexes pt = do - indexes <- checkResponse "/health" hasIndexesInstalled - chckpts <- checkResponse "/checkpoints" (laterThan pt) +hasIndexes :: Int -> Point -> IO Bool +hasIndexes port point = do + indexes <- checkResponse port "/health" hasIndexesInstalled + chckpts <- checkResponse port "/checkpoints" (laterThan point) pure (indexes && chckpts) -hasReachedPoint :: Point -> IO Bool -hasReachedPoint = checkResponse "/checkpoints" . hasReached +hasReachedPoint :: Int -> Point -> IO Bool +hasReachedPoint port = checkResponse port "/checkpoints" . hasReached -hasCheckpointsAllLaterThan :: Point -> IO Bool -hasCheckpointsAllLaterThan = checkResponse "/checkpoints" . nonEmptyAndLaterThan +hasCheckpointsAllLaterThan :: Int -> Point -> IO Bool +hasCheckpointsAllLaterThan port = checkResponse port "/checkpoints" . nonEmptyAndLaterThan exitsWithError :: ProcessHandle -> IO Bool exitsWithError h = do @@ -339,10 +360,10 @@ exitsWithError h = do Just ExitSuccess -> False Just (ExitFailure _) -> True -checkResponse :: String -> ResponseCheck -> IO Bool -checkResponse path check = do +checkResponse :: Int -> String -> ResponseCheck -> IO Bool +checkResponse port path check = do manager <- newManager defaultManagerSettings - request' <- request path + request' <- request port path let request'' = request' {requestHeaders = [(hAccept, "application/json; charset=utf-8")] } @@ -352,10 +373,10 @@ checkResponse path check = do body = responseBody response pure (check status body) -getPatterns :: IO (Maybe [Pattern]) -getPatterns = do +getPatterns :: Int -> IO (Maybe [Pattern]) +getPatterns port = do manager <- newManager defaultManagerSettings - request' <- request ("/patterns") + request' <- request port "/patterns" let request'' = request' {requestHeaders = [(hAccept, "application/json; charset=utf-8")] } @@ -368,10 +389,10 @@ getPatterns = do pure Nothing -putNewPattern :: Pattern -> Point -> IO Bool -putNewPattern pattern point = do +putNewPattern :: Int -> Pattern -> Point -> IO Bool +putNewPattern port pattern point = do manager <- newManager defaultManagerSettings - request' <- request ("/patterns/" <> pattern) + request' <- request port ("/patterns/" <> pattern) let request'' = request' { method = "PUT" , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) @@ -382,10 +403,10 @@ putNewPattern pattern point = do (Status 200 _) -> pure True _ -> pure False -getMatchesInWindow :: Point -> Point -> IO (Maybe [Match]) -getMatchesInWindow from to = do +getMatchesInWindow :: Int -> Point -> Point -> IO (Maybe [Match]) +getMatchesInWindow port from to = do manager <- newManager defaultManagerSettings - request' <- request ("/matches") + request' <- request port "/matches" let request'' = request' {requestHeaders = [(hAccept, "application/json; charset=utf-8")] , responseTimeout = responseTimeoutNone @@ -457,11 +478,11 @@ indexesFlag = A.decode tryHttp :: IO a -> IO (Either HttpException a) tryHttp m = try m -url :: String -url = "http://127.0.0.1:1442" +url :: Int -> String +url port = "http://127.0.0.1:" <> show port -request :: String -> IO Request -request = parseRequest . (url <>) +request :: Int -> String -> IO Request +request port = parseRequest . (url port <>) recentPoint :: IO Point recentPoint = fmap read (readFile "test-accept/point-recent.dat") From c1648555082c13e8d2b0077082467fa2cd9aab94 Mon Sep 17 00:00:00 2001 From: notunrandom <122674938+notunrandom@users.noreply.github.com> Date: Tue, 14 Jul 2026 07:46:16 +0000 Subject: [PATCH 30/68] Fix: correct an error in the ports of test-accept tests --- test-accept/Test/KupoSpec.hs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 1f1f6057..4b271b12 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -242,7 +242,7 @@ spec = do -- Restart kupo on same dir and check that it is immediately -- already at or past same point withKupo (options ++ ["--port","1451"]) $ do - eventually (hasCheckpointsAllLaterThan 1450 pointA) + eventually (hasCheckpointsAllLaterThan 1451 pointA) `shouldReturn` True it "Cannot restart with later '--since'" $ \dir -> do @@ -252,16 +252,16 @@ spec = do ] -- Start kupo on fresh dir until reaches pointA let optionsA = options ++ - [ "--port" , "1451" + [ "--port" , "1452" , "--since", fromPoint pointA ] withKupo optionsA $ do - reached <- eventually (hasReachedPoint 1451 pointA) + reached <- eventually (hasReachedPoint 1452 pointA) pure (assert reached ()) -- Restart kupo on same dir but later "--since" and check -- that its exits with error code let optionsB = options ++ - [ "--port" , "1452" + [ "--port" , "1453" , "--since", fromPoint pointB ] withKupoH optionsB $ \h -> do @@ -274,16 +274,16 @@ spec = do ] -- Start kupo on fresh dir until reaches pointA let optionsA = options ++ - [ "--port" , "1453" + [ "--port" , "1454" , "--match", "*/*" ] withKupo optionsA $ do - reached <- eventually (hasReachedPoint 1453 pointA) + reached <- eventually (hasReachedPoint 1454 pointA) pure (assert reached ()) -- Restart kupo on same dir but with different pattern and check -- that its exits with error code let optionsB = options ++ - [ "--port" , "1454" + [ "--port" , "1455" , "--match", "*" ] withKupoH optionsB $ \h -> do From 65611ea1c1fa74dfc39bd958953be4e6a6df68ad Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 10:51:23 +0200 Subject: [PATCH 31/68] ensure 'kupo' is required as a build-tool Without that, 'proc' is effectively calling into a pre-installed binary available on PATH, not necessarily the one being worked on. By requiring it as part of the build-tools, cabal places the project executable in the PATH for the test. This not only ensures that 'kupo' is available for the test even when not installed, but it also ensures it uses the right version of the binary. --- kupo.cabal | 2 ++ package.yaml | 1 + 2 files changed, 3 insertions(+) diff --git a/kupo.cabal b/kupo.cabal index 8f761e74..8400de27 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -357,6 +357,8 @@ test-suite accept TypeSynonymInstances ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N + build-tools: + kupo build-tool-depends: hspec-discover:hspec-discover build-depends: diff --git a/package.yaml b/package.yaml index 991f3368..4d152fd4 100644 --- a/package.yaml +++ b/package.yaml @@ -177,6 +177,7 @@ tests: - typed-process build-tools: - hspec-discover + - kupo executables: kupo: From bf5558bf54c45f1fd3ae46520d7a9b08a788f991 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 10:52:16 +0200 Subject: [PATCH 32/68] reformat test-accept files. --- test-accept/Test/KupoSpec.hs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 4b271b12..4d247b82 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -54,12 +54,12 @@ import Network.HTTP.Client , responseTimeoutNone ) import Network.HTTP.Types.Header - (hAccept + ( hAccept ) import Network.HTTP.Types.Status ( Status (..) - , status202 , status200 + , status202 ) import System.Directory ( Permissions (..) @@ -70,12 +70,12 @@ import System.Directory import System.Environment ( getEnv ) -import System.IO.Temp - ( createTempDirectory - ) import System.Exit ( ExitCode (..) ) +import System.IO.Temp + ( createTempDirectory + ) import System.Process ( CreateProcess , ProcessHandle @@ -91,7 +91,7 @@ import Test.Hspec , shouldReturn ) -import qualified Data.Aeson as A +import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as B import qualified System.Process.Typed as TP From 2a9bd08e0f6974b1f1e89ebc75fa5cf86eb0bd88 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 11:42:19 +0200 Subject: [PATCH 33/68] collect logs while running and annotate tests with logs (shown on failure). --- kupo.cabal | 3 ++ package.yaml | 3 ++ test-accept/Test/KupoSpec.hs | 79 ++++++++++++++++++++++++++++-------- 3 files changed, 67 insertions(+), 18 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index 8400de27..e1c345ed 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -363,14 +363,17 @@ test-suite accept hspec-discover:hspec-discover build-depends: aeson + , async , base , bytestring , directory , hspec + , hspec-expectations , http-client , http-types , process , temporary + , text , typed-process default-language: Haskell2010 diff --git a/package.yaml b/package.yaml index 4d152fd4..a9e0ed4c 100644 --- a/package.yaml +++ b/package.yaml @@ -166,14 +166,17 @@ tests: ghc-options: *ghc-options-test dependencies: - aeson + - async - base - bytestring - directory - hspec + - hspec-expectations - http-client - http-types - process - temporary + - text - typed-process build-tools: - hspec-discover diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 4d247b82..5937a790 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -28,15 +28,25 @@ import Prelude import Control.Concurrent ( threadDelay ) +import Control.Concurrent.Async + ( withAsync + ) import Control.Exception - ( assert + ( SomeException + , assert , bracket , try ) +import Control.Exception.Base + ( throwIO + ) import Data.Aeson ( (.:) , (.=) ) +import Data.Maybe + ( fromJust + ) import Network.HTTP.Client ( HttpException , Request @@ -77,10 +87,13 @@ import System.IO.Temp ( createTempDirectory ) import System.Process - ( CreateProcess + ( CreateProcess (..) , ProcessHandle + , StdStream (CreatePipe) , getProcessExitCode , proc + , terminateProcess + , waitForProcess , withCreateProcess ) import Test.Hspec @@ -91,9 +104,13 @@ import Test.Hspec , shouldReturn ) +import qualified Control.Concurrent.Async as Async import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as B +import qualified Data.Text as T +import qualified Data.Text.IO as T import qualified System.Process.Typed as TP +import qualified Test.Hspec.Expectations.Contrib as HSpec type ResponseCheck = Status -> B.ByteString -> Bool @@ -221,13 +238,11 @@ spec = do -- Change permissions on database's directory makeUnwritable dir -- Start a read-only kupo on dir and check that it's also ready - let process = proc "kupo" - ["--port" , "1449" - ,"--read-only" - ,"--workdir", dir - ] - withCreateProcess process $ \ _ _ _ _ -> do - eventually (isReady 1449) `shouldReturn` True + withKupoNoDefault + ["--port" , "1449" + ,"--read-only" + ,"--workdir", dir + ] $ eventually (isReady 1449) `shouldReturn` True it "Can restart with same arguments" $ \dir -> do let options = @@ -292,24 +307,52 @@ spec = do withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a withKupoH options action = do process <- kupo options - withCreateProcess process $ \_ _ _ h -> action h + withCreateProcess process $ \_stdin stdout _stderr h -> do + withAsync (T.hGetContents (fromJust stdout)) $ \logsAsync -> do + outcome <- try @SomeException (action h) + stopProcess h + logs <- Async.wait logsAsync + T.length logs `seq` case outcome of + Right a -> + pure a + Left err -> + HSpec.annotate + ("Kupo logs:\n" <> T.unpack logs) + (throwIO err) + where + stopProcess :: ProcessHandle -> IO () + stopProcess h = do + exitCode <- getProcessExitCode h + case exitCode of + Just _ -> + pure () + Nothing -> do + terminateProcess h + _ <- waitForProcess h + pure () withKupo :: [String] -> IO a -> IO a -withKupo options action = withKupoH options (\_ -> action) - -withDir :: (FilePath -> IO ()) -> IO () -withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly - -kupo :: [String] -> IO CreateProcess -kupo options = do +withKupo options action = do socket <- getEnv "CARDANO_NODE_SOCKET" config <- getEnv "CARDANO_NODE_CONFIG" - pure $ proc "kupo" + withKupoH (["--node-socket", socket ,"--node-config", config ] ++ options ) + (\_ -> action) + +withKupoNoDefault :: [String] -> IO a -> IO a +withKupoNoDefault options action = + withKupoH options (\_ -> action) + +withDir :: (FilePath -> IO ()) -> IO () +withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly + +kupo :: [String] -> IO CreateProcess +kupo options = do + pure $ (proc "kupo" options) { std_out = CreatePipe } makeUnwritable :: FilePath -> IO () makeUnwritable = setWritable False From c2f857b8f7cb811f2bff9068a666b6dc408b8ec6 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 11:42:33 +0200 Subject: [PATCH 34/68] fix missing socket path for the cardano-cli command. --- test-accept/Test/KupoSpec.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 5937a790..bb4e1b49 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -469,9 +469,11 @@ matchInWindow (Point (Slot s1) _) (Point (Slot s2) _) (Match s _ _ _) = currentNetworkTip :: IO (Maybe CliPoint) currentNetworkTip = do + socket <- getEnv "CARDANO_NODE_SOCKET" let args = [ "query", "tip" , "--testnet-magic", "1" + , "--socket-path", socket ] (_, out) <- TP.readProcessStdout (TP.proc "cardano-cli" args) pure (A.decode out) From f06f951f63741ec7850bbf625b4a65e0a019fd44 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 12:01:04 +0200 Subject: [PATCH 35/68] simplify DSL for writing specification by asserting in 'eventually'. --- test-accept/Test/KupoSpec.hs | 49 ++++++++++++------------------------ 1 file changed, 16 insertions(+), 33 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index bb4e1b49..d53b613f 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -147,7 +147,7 @@ spec = do ,"--match" , "*/*" ,"--in-memory" ] - $ eventually (isConnected 1443) `shouldReturn` True + $ eventually (isConnected 1443) it "Auto-magically restarts when --defer-db-indexes is enabled)" $ do -- Read from file a valid point recent but before tip @@ -160,7 +160,7 @@ spec = do ,"--in-memory" ,"--defer-db-indexes" ] - $ eventually (hasIndexes 1444 point) `shouldReturn` True + $ eventually (hasIndexes 1444 point) it "Dynamically adds pattern and rolls back (when at tip)" $ do maybeTip <- currentNetworkTip @@ -176,8 +176,7 @@ spec = do ] $ do -- Wait for indexing to have finished - reached <- eventually (hasReachedPoint 1445 tip) - pure (assert reached ()) + eventually (hasReachedPoint 1445 tip) getPatterns 1445 `shouldReturn` Just [stakeA] -- Add stakeB pattern forcing rollback to same point putNewPattern 1445 stakeB tip `shouldReturn` True @@ -191,8 +190,7 @@ spec = do -- Start a kupo since last Byron block and matching on stakeA withKupo (options ++ ["--match", stakeA, "--port", "1446"]) $ do -- Wait for indexing at least 100_000 slots - reached <- eventually (hasReachedPoint 1446 lastByron136K) - pure (assert reached ()) + eventually (hasReachedPoint 1446 lastByron136K) getPatterns 1446 `shouldReturn` Just [stakeA] getMatchesInWindow 1446 lastByron lastByron136K `shouldReturn` Just @@ -201,8 +199,7 @@ spec = do -- Start over, same again except matching on stakeB withKupo (options ++ ["--match", stakeB, "--port", "1447"]) $ do -- Wait for indexing at least 100_000 slots - reached <- eventually (hasReachedPoint 1447 lastByron136K) - pure (assert reached ()) + eventually (hasReachedPoint 1447 lastByron136K) getPatterns 1447 `shouldReturn` Just [stakeB] getMatchesInWindow 1447 lastByron lastByron136K `shouldReturn` Just @@ -210,8 +207,7 @@ spec = do [Match 86440 "49ef96" 0 2] -- Add stakeA pattern forcing rollback to last Byron block putNewPattern 1447 stakeA lastByron `shouldReturn` True - reachedAgain <- eventually (hasReachedPoint 1447 lastByron136K) - pure (assert reachedAgain ()) + eventually (hasReachedPoint 1447 lastByron136K) getPatterns 1447 `shouldReturn` Just [stakeA, stakeB] getMatchesInWindow 1447 lastByron lastByron136K `shouldReturn` Just @@ -231,10 +227,7 @@ spec = do ,"--since" , fromPoint pointA ,"--match" , "*/*" ,"--workdir", dir - ] - $ do - reached <- eventually (hasReachedPoint 1448 pointB) - pure (assert reached ()) + ] $ eventually (hasReachedPoint 1448 pointB) -- Change permissions on database's directory makeUnwritable dir -- Start a read-only kupo on dir and check that it's also ready @@ -242,7 +235,7 @@ spec = do ["--port" , "1449" ,"--read-only" ,"--workdir", dir - ] $ eventually (isReady 1449) `shouldReturn` True + ] $ eventually (isReady 1449) it "Can restart with same arguments" $ \dir -> do let options = @@ -251,14 +244,10 @@ spec = do ,"--workdir", dir ] -- Start kupo on fresh dir until reaches pointA - withKupo (options ++ ["--port","1450"]) $ do - reached <- eventually (hasReachedPoint 1450 pointA) - pure (assert reached ()) + withKupo (options ++ ["--port","1450"]) $ eventually (hasReachedPoint 1450 pointA) -- Restart kupo on same dir and check that it is immediately -- already at or past same point - withKupo (options ++ ["--port","1451"]) $ do - eventually (hasCheckpointsAllLaterThan 1451 pointA) - `shouldReturn` True + withKupo (options ++ ["--port","1451"]) $ eventually (hasCheckpointsAllLaterThan 1451 pointA) it "Cannot restart with later '--since'" $ \dir -> do let options = @@ -270,17 +259,14 @@ spec = do [ "--port" , "1452" , "--since", fromPoint pointA ] - withKupo optionsA $ do - reached <- eventually (hasReachedPoint 1452 pointA) - pure (assert reached ()) + withKupo optionsA $ eventually (hasReachedPoint 1452 pointA) -- Restart kupo on same dir but later "--since" and check -- that its exits with error code let optionsB = options ++ [ "--port" , "1453" , "--since", fromPoint pointB ] - withKupoH optionsB $ \h -> do - eventually (exitsWithError h) `shouldReturn` True + withKupoH optionsB $ \h -> eventually (exitsWithError h) it "Cannot restart with different patterns" $ \dir -> do let options = @@ -292,17 +278,14 @@ spec = do [ "--port" , "1454" , "--match", "*/*" ] - withKupo optionsA $ do - reached <- eventually (hasReachedPoint 1454 pointA) - pure (assert reached ()) + withKupo optionsA $ eventually (hasReachedPoint 1454 pointA) -- Restart kupo on same dir but with different pattern and check -- that its exits with error code let optionsB = options ++ [ "--port" , "1455" , "--match", "*" ] - withKupoH optionsB $ \h -> do - eventually (exitsWithError h) `shouldReturn` True + withKupoH optionsB $ \h -> eventually (exitsWithError h) withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a withKupoH options action = do @@ -362,8 +345,8 @@ setWritable x path = do p <- getPermissions path setPermissions path (p {writable = x}) -eventually :: IO Bool -> IO Bool -eventually p = go (0::Int) +eventually :: IO Bool -> IO () +eventually p = go (0::Int) >>= flip assert (pure ()) where go attempt | attempt > 20 = pure False From b4b12324523b66d8bbf23004a71537d0c6faccd8 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 12:02:39 +0200 Subject: [PATCH 36/68] fix dynamic pattern addition spec There's a delay between the response from the API and the moment the rollback effectively happens. So that mean, right after 'putNewPattern' succeeds, the current point can still be quite far in the future because we haven't rolled back yet. So waiting for the pattern to be visible solves the problem. --- test-accept/Test/KupoSpec.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index d53b613f..1d4efae9 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -46,6 +46,7 @@ import Data.Aeson ) import Data.Maybe ( fromJust + , fromMaybe ) import Network.HTTP.Client ( HttpException @@ -207,8 +208,8 @@ spec = do [Match 86440 "49ef96" 0 2] -- Add stakeA pattern forcing rollback to last Byron block putNewPattern 1447 stakeA lastByron `shouldReturn` True + eventually $ ((== [stakeA, stakeB]) . fromMaybe []) <$> getPatterns 1447 eventually (hasReachedPoint 1447 lastByron136K) - getPatterns 1447 `shouldReturn` Just [stakeA, stakeB] getMatchesInWindow 1447 lastByron lastByron136K `shouldReturn` Just -- now we have both matches together, proving rollback From 91a7ee13fbe16d2761c3ccbeb32b150776351877 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 12:08:49 +0200 Subject: [PATCH 37/68] fix default options now missing on KupoH --- test-accept/Test/KupoSpec.hs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 1d4efae9..2671d44d 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -288,8 +288,8 @@ spec = do ] withKupoH optionsB $ \h -> eventually (exitsWithError h) -withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a -withKupoH options action = do +withKupoProcess :: [String] -> (ProcessHandle -> IO a) -> IO a +withKupoProcess options action = do process <- kupo options withCreateProcess process $ \_stdin stdout _stderr h -> do withAsync (T.hGetContents (fromJust stdout)) $ \logsAsync -> do @@ -315,21 +315,19 @@ withKupoH options action = do _ <- waitForProcess h pure () -withKupo :: [String] -> IO a -> IO a -withKupo options action = do +withKupoH :: [String] -> (ProcessHandle -> IO a) -> IO a +withKupoH options action = do socket <- getEnv "CARDANO_NODE_SOCKET" config <- getEnv "CARDANO_NODE_CONFIG" - withKupoH - (["--node-socket", socket - ,"--node-config", config - ] - ++ options - ) - (\_ -> action) + withKupoProcess (["--node-socket", socket ,"--node-config", config] ++ options) action + +withKupo :: [String] -> IO a -> IO a +withKupo options action = do + withKupoH options (const action) withKupoNoDefault :: [String] -> IO a -> IO a withKupoNoDefault options action = - withKupoH options (\_ -> action) + withKupoProcess options (const action) withDir :: (FilePath -> IO ()) -> IO () withDir = bracket (createTempDirectory "." "test-tmp") removePathForcibly From 04820f766c21d6a356aeb479fae296d964082661 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 15 Jul 2026 12:09:00 +0200 Subject: [PATCH 38/68] address linter warnings. --- test-accept/Test/KupoSpec.hs | 54 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/test-accept/Test/KupoSpec.hs b/test-accept/Test/KupoSpec.hs index 2671d44d..4f9e4fdd 100644 --- a/test-accept/Test/KupoSpec.hs +++ b/test-accept/Test/KupoSpec.hs @@ -106,14 +106,14 @@ import Test.Hspec ) import qualified Control.Concurrent.Async as Async -import qualified Data.Aeson as A -import qualified Data.ByteString.Lazy as B +import qualified Data.Aeson as Aeson +import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.IO as T import qualified System.Process.Typed as TP import qualified Test.Hspec.Expectations.Contrib as HSpec -type ResponseCheck = Status -> B.ByteString -> Bool +type ResponseCheck = Status -> BL.ByteString -> Bool newtype Slot = Slot Integer deriving (Eq, Ord, Read, Show) @@ -409,7 +409,7 @@ getPatterns port = do case responseStatus response of (Status 200 _) -> do let body = responseBody response - pure (A.decode body :: Maybe [Pattern]) + pure (Aeson.decode body :: Maybe [Pattern]) _ -> pure Nothing @@ -420,7 +420,7 @@ putNewPattern port pattern point = do request' <- request port ("/patterns/" <> pattern) let request'' = request' { method = "PUT" - , requestBody = RequestBodyLBS (A.encode (PutPatternBody point)) + , requestBody = RequestBodyLBS (Aeson.encode (PutPatternBody point)) , responseTimeout = responseTimeoutNone } response <- httpLbs request'' manager @@ -440,7 +440,7 @@ getMatchesInWindow port from to = do case responseStatus response of (Status 200 _) -> do let body = responseBody response - let maybeMatches = A.decode body :: Maybe [Match] + let maybeMatches = Aeson.decode body :: Maybe [Match] pure (filter (matchInWindow from to) <$> maybeMatches) _ -> pure Nothing @@ -458,11 +458,11 @@ currentNetworkTip = do , "--socket-path", socket ] (_, out) <- TP.readProcessStdout (TP.proc "cardano-cli" args) - pure (A.decode out) + pure (Aeson.decode out) containsCheckpoints :: ResponseCheck containsCheckpoints status body = - status == status200 && hasSlots (A.decode body :: Maybe [Slot]) + status == status200 && hasSlots (Aeson.decode body :: Maybe [Slot]) where hasSlots Nothing = False hasSlots (Just []) = False @@ -470,7 +470,7 @@ containsCheckpoints status body = hasReached :: Point -> ResponseCheck hasReached (Point slot _) status body = - status == status200 && hasReached' slot (A.decode body :: Maybe [Slot]) + status == status200 && hasReached' slot (Aeson.decode body :: Maybe [Slot]) where hasReached' _ Nothing = False hasReached' _ (Just []) = False @@ -486,24 +486,24 @@ hasIndexesInstalled status body = laterThan :: Point -> ResponseCheck laterThan (Point slot _) status body = - status == status200 && laterThanSlot (A.decode body :: Maybe [Slot]) + status == status200 && laterThanSlot (Aeson.decode body :: Maybe [Slot]) where laterThanSlot Nothing = False laterThanSlot (Just slots) = all (>= slot) slots nonEmptyAndLaterThan :: Point -> ResponseCheck nonEmptyAndLaterThan (Point slot _) status body = - status == status200 && laterThanSlot (A.decode body :: Maybe [Slot]) + status == status200 && laterThanSlot (Aeson.decode body :: Maybe [Slot]) where laterThanSlot Nothing = False laterThanSlot (Just [] ) = False laterThanSlot (Just slots) = all (>= slot) slots -indexesFlag :: B.ByteString -> Maybe Indexes -indexesFlag = A.decode +indexesFlag :: BL.ByteString -> Maybe Indexes +indexesFlag = Aeson.decode tryHttp :: IO a -> IO (Either HttpException a) -tryHttp m = try m +tryHttp = try url :: Int -> String url port = "http://127.0.0.1:" <> show port @@ -517,38 +517,38 @@ recentPoint = fmap read (readFile "test-accept/point-recent.dat") fromPoint :: Point -> String fromPoint (Point (Slot slot) hash) = show slot ++ "." ++ hash -instance A.FromJSON Slot where - parseJSON = A.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" +instance Aeson.FromJSON Slot where + parseJSON = Aeson.withObject "Slot" $ \o -> Slot <$> o .: "slot_no" -instance A.FromJSON Indexes where - parseJSON = A.withObject "Health" $ \o -> do +instance Aeson.FromJSON Indexes where + parseJSON = Aeson.withObject "Health" $ \o -> do c <- o .: "configuration" i <- c .: "indexes" pure (Indexes i) -instance A.FromJSON Point where - parseJSON = A.withObject "Point" $ \o -> do +instance Aeson.FromJSON Point where + parseJSON = Aeson.withObject "Point" $ \o -> do s <- o .: "slot_no" h <- o .: "header_hash" pure (Point s h) -instance A.FromJSON CliPoint where - parseJSON = A.withObject "CliPoint" $ \o -> do +instance Aeson.FromJSON CliPoint where + parseJSON = Aeson.withObject "CliPoint" $ \o -> do s <- o .: "slot" h <- o .: "hash" pure (CliPoint (Point (Slot s) h)) -instance A.ToJSON PutPatternBody where - toJSON (PutPatternBody (Point (Slot slot) hash)) = A.object - [ "rollback_to" .= A.object +instance Aeson.ToJSON PutPatternBody where + toJSON (PutPatternBody (Point (Slot slot) hash)) = Aeson.object + [ "rollback_to" .= Aeson.object [ "slot_no" .= slot , "header_hash" .= hash ] , "limit" .= ("unsafe_allow_beyond_safe_zone" :: String) ] -instance A.FromJSON Match where - parseJSON = A.withObject "Match" $ \o -> do +instance Aeson.FromJSON Match where + parseJSON = Aeson.withObject "Match" $ \o -> do tidx <- o .: "transaction_index" oidx <- o .: "output_index" c <- o .: "created_at" From c4e14e20908cea38b381ca676cf0309e06f0df04 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 10:48:20 +0200 Subject: [PATCH 39/68] use 'build-tool-depends' instead of 'build-tools' in .cabal file --- kupo.cabal | 6 ------ package.yaml | 4 ++-- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index e1c345ed..b7de510c 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -357,10 +357,6 @@ test-suite accept TypeSynonymInstances ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N - build-tools: - kupo - build-tool-depends: - hspec-discover:hspec-discover build-depends: aeson , async @@ -447,8 +443,6 @@ test-suite unit TypeSynonymInstances ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N - build-tool-depends: - hspec-discover:hspec-discover build-depends: QuickCheck , aeson diff --git a/package.yaml b/package.yaml index a9e0ed4c..4aa56739 100644 --- a/package.yaml +++ b/package.yaml @@ -158,7 +158,7 @@ tests: - wai-extra - websockets - yaml - build-tools: + build-tools-depends: - hspec-discover accept: main: Spec.hs @@ -178,7 +178,7 @@ tests: - temporary - text - typed-process - build-tools: + build-tools-depends: - hspec-discover - kupo From 304db43b9e26f4a6464c853347b2fba9c4ca624f Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 10:57:37 +0200 Subject: [PATCH 40/68] fill-in CHANGELOG for v2.12.0 --- CHANGELOG.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dfe632e3..48330b17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,21 @@ -### [2.12.0] - UNRELEASED +### [2.12.0] - 2026-07-18 #### Added -N/A +- Allow controlling return type of asset quantities through a media query. Allowing string instead of integer when using `Accept: application/json:asset-quantity=string`. + +- New slot-range index usage for wildcard (*) match queries (see [#194](https://github.com/CardanoSolutions/kupo/issues/194)). #### Changed -- Bumped internal dependencies to cardano-node==10.5.1 +- Bumped internal dependencies to cardano-node==11.0.1. - Fixed network synchronisation calculations (see [#191](https://github.com/CardanoSolutions/kupo/issues/191)). +- Rework some integration tests to avoid issues with closed file handles. + +- Fixed read-only mode requiring write permissions on the database directory. + #### Removed N/A From f201d9c3a0191677dfeb3ce78d331b2ad7322962 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 11:18:09 +0200 Subject: [PATCH 41/68] fix typo 'build-tool-depends' --- kupo.cabal | 5 +++++ package.yaml | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index b7de510c..6919dd2f 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -357,6 +357,9 @@ test-suite accept TypeSynonymInstances ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N + build-tool-depends: + hspec-discover:hspec-discover + , kupo:kupo build-depends: aeson , async @@ -443,6 +446,8 @@ test-suite unit TypeSynonymInstances ViewPatterns ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints -Wunused-packages -threaded -rtsopts -with-rtsopts=-N + build-tool-depends: + hspec-discover:hspec-discover build-depends: QuickCheck , aeson diff --git a/package.yaml b/package.yaml index 4aa56739..3cb0abdb 100644 --- a/package.yaml +++ b/package.yaml @@ -158,7 +158,7 @@ tests: - wai-extra - websockets - yaml - build-tools-depends: + build-tool-depends: - hspec-discover accept: main: Spec.hs @@ -178,7 +178,7 @@ tests: - temporary - text - typed-process - build-tools-depends: + build-tool-depends: - hspec-discover - kupo From c12f942114d2b190a1c5312e346f38d7de595e7c Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 11:44:49 +0200 Subject: [PATCH 42/68] fix asset quantity encoding wrongly defaulting to string in some cases. Closes #207. --- src/Kupo/App/Http.hs | 25 +--------- src/Kupo/Data/Http/QuantityEncoding.hs | 50 ++++++++++++++----- .../Kupo/Data/Http/QuantityEncodingSpec.hs | 30 +++++++---- 3 files changed, 60 insertions(+), 45 deletions(-) diff --git a/src/Kupo/App/Http.hs b/src/Kupo/App/Http.hs index 1b376d20..93a7b099 100644 --- a/src/Kupo/App/Http.hs +++ b/src/Kupo/App/Http.hs @@ -118,9 +118,6 @@ import Kupo.Data.Http.GetCheckpointMode import Kupo.Data.Http.OrderMatchesBy ( orderMatchesBy ) -import Kupo.Data.Http.QuantityEncoding - ( QuantityEncoding (..) - ) import Kupo.Data.Http.ReferenceFlag ( referenceFlagFromQueryParams ) @@ -150,13 +147,6 @@ import Kupo.Data.Pattern , resultToJson , wildcard ) -import Network.HTTP.Media - ( mapAccept - ) -import Network.HTTP.Media.MediaType - ( (//) - , (/:) - ) import Network.HTTP.Types ( Header , hAccept @@ -610,20 +600,7 @@ handleGetMatches resHeaders reqHeaders patternQuery queryParams Database{..} = h sortDirection <- mkSortDirection <$> orderMatchesBy queryParams `orAbort` Errors.invalidSortDirection - let qualities = - [ ("application" // "json" /: QuantityEncoding.mediaTypeParam - , EncodeAsString - ) - , ("application" // "json" /: QuantityEncoding.mediaTypeParam /: ("charset", "utf-8") - , EncodeAsString - ) - , ("application" // "json" /: ("charset", "utf-8") /: QuantityEncoding.mediaTypeParam - , EncodeAsString - ) - ] - - let quantityEncoding = (findAcceptHeader reqHeaders >>= mapAccept qualities) - & fromMaybe EncodeAsInteger + let quantityEncoding = QuantityEncoding.matchAcceptHeader (findAcceptHeader reqHeaders) let resHeaders' = (QuantityEncoding.adjustMediaType quantityEncoding resHeaders) diff --git a/src/Kupo/Data/Http/QuantityEncoding.hs b/src/Kupo/Data/Http/QuantityEncoding.hs index fb783f8f..332b3733 100644 --- a/src/Kupo/Data/Http/QuantityEncoding.hs +++ b/src/Kupo/Data/Http/QuantityEncoding.hs @@ -6,6 +6,7 @@ module Kupo.Data.Http.QuantityEncoding ( QuantityEncoding(..) , adjustMediaType , mediaTypeParam + , matchAcceptHeader ) where import Kupo.Prelude @@ -16,6 +17,7 @@ import qualified Prelude as P import Network.HTTP.Media ( MediaType + , mapAccept , mapContentMedia , renderHeader , (//) @@ -28,24 +30,48 @@ import Network.HTTP.Types ) data QuantityEncoding = EncodeAsInteger | EncodeAsString - deriving Show + deriving (Show, Eq) adjustMediaType :: QuantityEncoding -> ResponseHeaders -> ResponseHeaders -adjustMediaType EncodeAsInteger = P.id -adjustMediaType EncodeAsString = map insertParam +adjustMediaType = \case + EncodeAsInteger -> P.id + EncodeAsString -> map insertParam mediaTypeParam :: (ByteString, ByteString) mediaTypeParam = ("asset-quantity", "string") insertParam :: Header -> Header -insertParam (n,v) - | n == hContentType = (n, maybe v P.id (mapContentMedia mmap v)) +insertParam (n, v) + | n == hContentType = (n, fromMaybe v (mapContentMedia mmap v)) | otherwise = (n, v) + where + mmap :: [(MediaType,ByteString)] + mmap = + [ ( "application" // "json" /: ("charset", "utf-8") + , renderHeader $ "application" // "json" /: ("charset", "utf-8") /: mediaTypeParam + ) + , ( "application"//"json" + , renderHeader $ "application" // "json" /: mediaTypeParam + ) + ] -mmap :: [(MediaType,ByteString)] -mmap = - [("application"//"json"/:("charset","utf-8"), - renderHeader $ "application"//"json"/:("charset","utf-8")/:mediaTypeParam) - ,("application"//"json", - renderHeader $ "application"//"json"/:mediaTypeParam) - ] +matchAcceptHeader :: Maybe ByteString -> QuantityEncoding +matchAcceptHeader header = fromMaybe EncodeAsInteger $ header >>= mapAccept qualities + where + qualities = + [ ("application" // "json" + , EncodeAsInteger + ) + , ("application" // "json" /: ("charset", "utf-8") + , EncodeAsInteger + ) + , ("application" // "json" /: mediaTypeParam + , EncodeAsString + ) + , ("application" // "json" /: mediaTypeParam /: ("charset", "utf-8") + , EncodeAsString + ) + , ("application" // "json" /: ("charset", "utf-8") /: mediaTypeParam + , EncodeAsString + ) + ] diff --git a/test/Test/Kupo/Data/Http/QuantityEncodingSpec.hs b/test/Test/Kupo/Data/Http/QuantityEncodingSpec.hs index 583261d2..901d2e29 100644 --- a/test/Test/Kupo/Data/Http/QuantityEncodingSpec.hs +++ b/test/Test/Kupo/Data/Http/QuantityEncodingSpec.hs @@ -11,6 +11,7 @@ import Kupo.Prelude import Kupo.Data.Http.QuantityEncoding ( QuantityEncoding (..) , adjustMediaType + , matchAcceptHeader , mediaTypeParam ) import Network.HTTP.Media.MediaType @@ -21,8 +22,7 @@ import Network.HTTP.Media.RenderHeader ( renderHeader ) import Network.HTTP.Types - ( ResponseHeaders - , hContentType + ( hContentType ) import Test.Hspec ( Spec @@ -32,17 +32,29 @@ import Test.Hspec ) spec :: Spec -spec = +spec = do describe "Adjusting media type" $ do - + let headers = [(hContentType, renderHeader ("application" // "json"))] specify "Media type is unchanged for EncodeAsInteger" $ do adjustMediaType EncodeAsInteger headers `shouldBe` headers + let headers' = [(hContentType , renderHeader ("application" // "json" /: mediaTypeParam))] specify "Adds 'asset-quantity' param for EncodeAsString" $ do adjustMediaType EncodeAsString headers `shouldBe` headers' -headers :: ResponseHeaders -headers = [(hContentType , renderHeader ("application"//"json"))] - -headers' :: ResponseHeaders -headers' = [(hContentType , renderHeader ("application"//"json"/:mediaTypeParam))] + describe "matchAcceptHeader" $ do + specify "default to Integer" $ do + matchAcceptHeader Nothing `shouldBe` EncodeAsInteger + + forM_ + [ ( "application/json", EncodeAsInteger ) + , ( "application/json;charset=utf-8", EncodeAsInteger ) + , ( "application/json;charset=UTF-8", EncodeAsInteger ) + , ( "application/json;asset-quantity=string", EncodeAsString ) + , ( "application/json;charset=utf-8;asset-quantity=string", EncodeAsString ) + , ( "application/json;charset=UTF-8;asset-quantity=string", EncodeAsString ) + , ( "application/json;asset-quantity=string;charset=utf-8", EncodeAsString ) + , ( "application/json;asset-quantity=string;charset=UTF-8", EncodeAsString ) + ] $ \(accept, expected) -> + specify (decodeUtf8 accept <> " -> " <> show expected) $ + matchAcceptHeader (Just accept) `shouldBe` expected From 2107456a8f61236e81f9015dc34a85be5bcc48ce Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 12:18:58 +0200 Subject: [PATCH 43/68] Allow custom database indexes via environment variables Closes #206. --- CHANGELOG.md | 6 +++ docs/api/nightly.yaml | 19 +++++++++ src/Kupo/App/Database/SQLite.hs | 69 ++++++++++++++++++++------------- 3 files changed, 67 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 48330b17..c7b3b158 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ - New slot-range index usage for wildcard (*) match queries (see [#194](https://github.com/CardanoSolutions/kupo/issues/194)). +- Custom indexes can now be added via environment variable, prefixed with `KUPO_INDEX_`. They behave as standard indexes with regards to `--defer-db-indexes` and are only installed if not already present. Indexes are named after the environment variable (after the dropping the prefix). So for example, to add an index for unspent inputs by payment credential, you can now provide: + + ```console + KUPO_INDEX_inputsByPaymentCredentialUnspent="inputs(payment_credential COLLATE NOCASE) WHERE spent_at IS NULL" kupo ... + ``` + #### Changed - Bumped internal dependencies to cardano-node==11.0.1. diff --git a/docs/api/nightly.yaml b/docs/api/nightly.yaml index f9259a96..adca8d18 100644 --- a/docs/api/nightly.yaml +++ b/docs/api/nightly.yaml @@ -273,6 +273,25 @@ info: $ man kupo ``` + # Custom database indexes + + Kupo supports custom database indexes, provided by environment variable. + Hence, any environment variable prefixed with `KUPO_INDEX_` will be parsed + and interpreted as a custom database index, managed with the pre-defined + indexes. + + For example, you can add a custom index `inputsByPaymentCredentialUnspent` + for matching unspent inputs by payment cred by setting the following + environment variable: + + ```env + KUPO_INDEX_inputsByPaymentCredentialUnspent="inputs(payment_credential COLLATE NOCASE) WHERE spent_at IS NULL" + ``` + + Use this carefully, as too many indexes may greatly impact the database sync performances and also other queries. + + Existing indexes and the overall database internal schema is [available here](https://github.com/CardanoSolutions/kupo/tree/master/db#overview). + # Patterns ## Overview diff --git a/src/Kupo/App/Database/SQLite.hs b/src/Kupo/App/Database/SQLite.hs index dfe80d10..90b0984d 100644 --- a/src/Kupo/App/Database/SQLite.hs +++ b/src/Kupo/App/Database/SQLite.hs @@ -181,6 +181,9 @@ import Kupo.Control.MonadLog ( TraceProgress (..) , nullTracer ) +import System.Environment + ( getEnvironment + ) import Text.URI ( URI ) @@ -1161,33 +1164,45 @@ installIndexes -> Connection -> DeferIndexesInstallation -> IO () -installIndexes tr conn = \case - SkipNonEssentialIndexes -> do - dropIndexIfExists (contramap DatabaseConnection tr) conn "inputsByAddress" False - dropIndexIfExists (contramap DatabaseConnection tr) conn "inputsByDatumHash" False - dropIndexIfExists (contramap DatabaseConnection tr) conn "inputsByPaymentCredential" False - dropIndexIfExists (contramap DatabaseConnection tr) conn "inputsByCreatedAt" False - dropIndexIfExists (contramap DatabaseConnection tr) conn "inputsBySpentAt" False - dropIndexIfExists (contramap DatabaseConnection tr) conn "policiesByPolicyId" False - InstallIndexesIfNotExist -> do - installIndex tr conn - "inputsByAddress" - "inputs(address COLLATE NOCASE)" - installIndex tr conn - "inputsByDatumHash" - "inputs(datum_hash)" - installIndex tr conn - "inputsByPaymentCredential" - "inputs(payment_credential COLLATE NOCASE)" - installIndex tr conn - "inputsByCreatedAt" - "inputs(created_at)" - installIndex tr conn - "inputsBySpentAt" - "inputs(spent_at)" - installIndex tr conn - "policiesByPolicyId" - "policies(policy_id)" +installIndexes tr conn indexBehavior = do + customIndexes <- parseCustomIndexes <$> getEnvironment + + case indexBehavior of + SkipNonEssentialIndexes -> do + dropIndex "inputsByAddress" + dropIndex "inputsByDatumHash" + dropIndex "inputsByPaymentCredential" + dropIndex "inputsByCreatedAt" + dropIndex "inputsBySpentAt" + dropIndex "policiesByPolicyId" + forM_ customIndexes (\(name, _definition) -> dropIndex name) + where + dropIndex name = dropIndexIfExists (contramap DatabaseConnection tr) conn name False + InstallIndexesIfNotExist -> do + installIndex tr conn + "inputsByAddress" + "inputs(address COLLATE NOCASE)" + installIndex tr conn + "inputsByDatumHash" + "inputs(datum_hash)" + installIndex tr conn + "inputsByPaymentCredential" + "inputs(payment_credential COLLATE NOCASE)" + installIndex tr conn + "inputsByCreatedAt" + "inputs(created_at)" + installIndex tr conn + "inputsBySpentAt" + "inputs(spent_at)" + installIndex tr conn + "policiesByPolicyId" + "policies(policy_id)" + forM_ customIndexes (uncurry (installIndex tr conn)) + where + parseCustomIndexes = mapMaybe $ \(key, value) -> + case T.stripPrefix "KUPO_INDEX_" (toText key) of + Nothing -> Nothing + Just name -> Just (name, toText value) -- Create the given index with some extra logging around it. installIndex :: Tracer IO TraceDatabase -> Connection -> Text -> Text -> IO () From 2c45f3b4f9af75af966f5f402a6655cd3502cc28 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 12:20:38 +0200 Subject: [PATCH 44/68] update compatibility matrix. --- README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9b5fd567..c082a62f 100644 --- a/README.md +++ b/README.md @@ -38,15 +38,16 @@ Finally, [discussions 💡][discussions] contains ongoing discussions regarding # Compatibility -Kupo | Cardano-node | Ogmios | Hydra ---- | --- | --- | --- -`v2.11.*` | `10.1.*`, `10.0.*` | `v6.*.*` | `0.20.0`, `0.21.0` -`v2.10.*` | `10.1.*`, `10.0.*`, `9.0.0` | `v6.*.*` | `0.16.0` -`v2.9.*` | `10.1.*`, `10.0.*`, `9.0.0` | `v6.*.*` | `0.16.0` -`v2.8.*` | `8.7.*` | `v6.*.*` | `0.13.0` -`v2.7.*` | `8.1.*`, `8.6.*` | `v6.*.*` | `0.13.0` -`v2.6.*` | `8.1.*` | `v6.*.*` | N/A -`v2.5.*` | `1.35.*`, `8.1.*` | `v5.*.*` | N/A +Kupo | Cardano-node | Ogmios | Hydra +--- | --- | --- | --- +`v2.12.*` | `11.0.*` | `v7.*.*`, `v6.*.*` | `0.20.0`, `0.21.0` +`v2.11.*` | `10.1.*`, `10.0.*` | `v6.*.*` | `0.20.0`, `0.21.0` +`v2.10.*` | `10.1.*`, `10.0.*`, `9.0.0` | `v6.*.*` | `0.16.0` +`v2.9.*` | `10.1.*`, `10.0.*`, `9.0.0` | `v6.*.*` | `0.16.0` +`v2.8.*` | `8.7.*` | `v6.*.*` | `0.13.0` +`v2.7.*` | `8.1.*`, `8.6.*` | `v6.*.*` | `0.13.0` +`v2.6.*` | `8.1.*` | `v6.*.*` | N/A +`v2.5.*` | `1.35.*`, `8.1.*` | `v5.*.*` | N/A # System Requirements From 10ab69d109d7e6492fc0d8e08ad6a036fe195602 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 12:21:16 +0200 Subject: [PATCH 45/68] bump version to 2.12.0 --- kupo.cabal | 2 +- package.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/kupo.cabal b/kupo.cabal index 6919dd2f..aa2ea9d9 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -5,7 +5,7 @@ cabal-version: 3.0 -- see: https://github.com/sol/hpack name: kupo -version: 0 +version: 2.12.0 synopsis: A daemon for building lookup indexes from entities of the Cardano blockchain description: Please see the README on GitHub at category: Web diff --git a/package.yaml b/package.yaml index 3cb0abdb..4b9ce5d9 100644 --- a/package.yaml +++ b/package.yaml @@ -1,7 +1,7 @@ _config: !include ".hpack.config.yaml" name: kupo -version: 0 +version: 2.12.0 stability: stable github: "cardanosolutions/kupo" license: MPL-2.0 From 491918a50b45ed2b3de682ee79e03c6dc09779a3 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Sat, 18 Jul 2026 12:22:30 +0200 Subject: [PATCH 46/68] rotate and bump API docs to v2.12.0 --- docs/api/{v2.10.0.yaml => v2.12.0.yaml} | 199 +++++++++++++++++++++--- docs/index.html | 2 +- kupo.cabal | 2 +- 3 files changed, 183 insertions(+), 20 deletions(-) rename docs/api/{v2.10.0.yaml => v2.12.0.yaml} (92%) diff --git a/docs/api/v2.10.0.yaml b/docs/api/v2.12.0.yaml similarity index 92% rename from docs/api/v2.10.0.yaml rename to docs/api/v2.12.0.yaml index 90ad286a..c17fe644 100644 --- a/docs/api/v2.10.0.yaml +++ b/docs/api/v2.12.0.yaml @@ -5,7 +5,7 @@ servers: info: title: Kupo - version: v2.10.0 + version: v2.12.0 license: name: MPL-2.0 url: https://raw.githubusercontent.com/cardanosolutions/kupo/master/LICENSE @@ -81,8 +81,8 @@ info: Make sure to have [nix](https://nixos.org/download.html#nix-install-linux) installed with a cache: ``` - trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= loony-tools:pr9m4BkM/5/eSTZlkQyRt57Jz7OMBxNSUiMC4FkcNfk= - substituters = https://cache.zw3rk.com/ https://cache.nixos.org/ + trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= + substituters = https://cache.iog.io/ https://cache.nixos.org/ ``` On MacOS, you'll need to install `libffi` and `bzip2` if they aren't already installed. @@ -273,6 +273,25 @@ info: $ man kupo ``` + # Custom database indexes + + Kupo supports custom database indexes, provided by environment variable. + Hence, any environment variable prefixed with `KUPO_INDEX_` will be parsed + and interpreted as a custom database index, managed with the pre-defined + indexes. + + For example, you can add a custom index `inputsByPaymentCredentialUnspent` + for matching unspent inputs by payment cred by setting the following + environment variable: + + ```env + KUPO_INDEX_inputsByPaymentCredentialUnspent="inputs(payment_credential COLLATE NOCASE) WHERE spent_at IS NULL" + ``` + + Use this carefully, as too many indexes may greatly impact the database sync performances and also other queries. + + Existing indexes and the overall database internal schema is [available here](https://github.com/CardanoSolutions/kupo/tree/master/db#overview). + # Patterns ## Overview @@ -569,7 +588,7 @@ info: | Last Allegra block | N/A | N/A | | Last Mary block | N/A | N/A | | Last Alonzo block | 259180 | 0ad91d3bbe350b1cfa05b13dba5263c47c5eca4f97b3a3105eba96416785a487 | - | Last Conway block | 55814394 | bdd4baa2c81d0500a695f836332193ea06c2ce364e585057142220fc0782144c | + | Last Babbage block | 55814394 | bdd4baa2c81d0500a695f836332193ea06c2ce364e585057142220fc0782144c | | Last Conway block | N/A | N/A | See configuration files for Preview. @@ -1260,6 +1279,31 @@ components: 1220099e5e430475c219518179efc7e6c8289db028904834025d5b086: 231 289db028904834025d5b085d5b08661220099e5e430475c2195181796.08661220099e: 1 + ValueAsString: + type: object + description: A (multi-asset) value of a transaction's output. + additionalProperties: false + required: + - coins + properties: + coins: + type: string + description: A quantity of Lovelace, encoded as string when 'asset-quantity=string' is specified as media-type parameter. + example: "42" + assets: + type: object + description: A _key:value_ map of asset identifier → quantity. + propertyNames: + type: string + pattern: ^[a-f0-9]{56}(.[a-f0-9]{2,64})?$ + additionalProperties: + x-additionalPropertiesName: "{policy-id}.{asset-name}" + type: string + description: A quantity of some asset, encoded as string when 'asset-quantity=string' is specified as media-type parameter. + example: + 1220099e5e430475c219518179efc7e6c8289db028904834025d5b086: "231" + 289db028904834025d5b085d5b08661220099e5e430475c2195181796.08661220099e: "1" + Wildcard: type: string title: Wildcard @@ -1317,6 +1361,58 @@ components: - $ref: "#/components/schemas/SpentAt" - type: "null" + MatchQuantityAsString: + type: object + additionalProperties: false + required: + - transaction_index + - transaction_id + - output_index + - address + - value + - datum_hash + - script_hash + - created_at + - spent_at + properties: + transaction_index: + $ref: "#/components/schemas/TransactionIndex" + transaction_id: + $ref: "#/components/schemas/TransactionId" + output_index: + $ref: "#/components/schemas/OutputIndex" + address: + $ref: "#/components/schemas/Address" + value: + $ref: "#/components/schemas/ValueAsString" + datum_hash: + $ref: "#/components/schemas/DatumHash" + datum: + description: The resolved datum, if available. The field is only and always present (yet may be `null`) if `?resolve_hashes` was set. + oneOf: + - <<: *BinaryData + description: A serialized Plutus' Data. + - type: "null" + description: None or unknown datum. + datum_type: + $ref: "#/components/schemas/DatumType" + script_hash: + $ref: "#/components/schemas/ScriptHash" + script: + description: The resolved script, if available. The field is only and always present (yet may be `null`) if `?resolve_hashes` was set. + oneOf: + - $ref: "#/components/schemas/Script" + - type: "null" + description: None or unknown script. + created_at: + <<: *Point + description: Block reference at which this transaction was included in the ledger. + spent_at: + description: Block reference at which this transaction input was spent, if any. + oneOf: + - $ref: "#/components/schemas/SpentAt" + - type: "null" + Health: type: object description: An overview of the server & connection status. Note that, when `most_recent_checkpoint` and `most_recent_node_tip` are equal, the index is fully synchronized. @@ -1325,6 +1421,8 @@ components: - connection_status - most_recent_checkpoint - most_recent_node_tip + - seconds_since_last_block + - network_synchronization - configuration - version properties: @@ -1346,6 +1444,20 @@ components: description: Absolute slot number of the current tip of the node. - type: "null" description: Absolute slot number of the current tip of the node. + seconds_since_last_block: + oneOf: + - type: integer + description: Number of seconds elapsed since the last block was ingested by Kupo. + - type: "null" + description: Number of seconds elapsed since the last block was ingested by Kupo. + network_synchronization: + oneOf: + - type: number + minimum: 0 + maximum: 1 + description: A progress percentage of the synchronization towards the node tip. + - type: "null" + description: A progress percentage of the synchronization towards the node tip. configuration: type: object description: A summary of hand-picked configuration parameters. @@ -1371,20 +1483,6 @@ components: - `connected` and `disconnected` (from `connection_status`) are encoded as `1.0` and `0.0` respectively. - `installed` and `deferred` (from `configuration.indexes`) are encoded as `1.0` and `0.0` respectively. - `version` is not present in the Prometheus metrics. - examples: - response: - value: | - # TYPE kupo_connection_status gauge - kupo_connection_status 1.0 - - # TYPE kupo_most_recent_checkpoint counter - kupo_most_recent_checkpoint 294998 - - # TYPE kupo_most_recent_node_tip counter - kupo_most_recent_node_tip 71753381 - - # TYPE kupo_configuration_indexes gauge - kupo_configuration_indexes 1.0 parameters: asset-name: @@ -1778,6 +1876,13 @@ paths: Optionally, use `?resolve_hashes` to automatically resolve and include `datum` and `script` associated with hash references, if available. Datums and scripts can otherwise be fetched using the [_Get Datum by Hash_](#tag/Datums/paths/~1datums~1{datum-hash}/get) and [_Get Script by Hash_](#tag/Scripts/paths/~1scripts~1{script-hash}/get) endpoints respectively. Note that it is generally a bad idea to fetch **ALL matches** for indexes built off permissive patterns (e.g. `*`), for the server will yield a large response. + + > TIP
+ > + > You can customize coins and assets quantities encoding to always be strings instead of integers through the + > `Accept` header media-type as such: + > + > `Accept: application/json;asset-quantity=string` parameters: - $ref: "#/components/parameters/resolve-hashes" - $ref: "#/components/parameters/spent" @@ -1801,6 +1906,11 @@ paths: type: array items: $ref: "#/components/schemas/Match" + "application/json;charset=utf-8;asset-quantity=string": + schema: + type: array + items: + $ref: "#/components/schemas/MatchQuantityAsString" 304: $ref: "#/components/responses/304" @@ -1812,6 +1922,13 @@ paths: description: | Retrieve matches from the database matching the given pattern, in descending `slot_no` order. Results are streamed to the client for more efficiency. See [Patterns](#section/Patterns) for more information about constructing patterns. + + > TIP
+ > + > You can customize coins and assets quantities encoding to always be strings instead of integers through the + > `Accept` header media-type as such: + > + > `Accept: application/json;asset-quantity=string` parameters: - $ref: "#/components/parameters/pattern" - $ref: "#/components/parameters/resolve-hashes" @@ -1836,6 +1953,11 @@ paths: type: array items: $ref: "#/components/schemas/Match" + "application/json;charset=utf-8;asset-quantity=string": + schema: + type: array + items: + $ref: "#/components/schemas/MatchQuantityAsString" 304: $ref: "#/components/responses/304" 400: @@ -2197,6 +2319,24 @@ paths: "text/plain;charset=utf-8": schema: $ref: "#/components/schemas/HealthPrometheus" + example: &HealthPrometheusExample | + # TYPE kupo_configuration_indexes gauge + kupo_configuration_indexes 1.0 + + # TYPE kupo_connection_status gauge + kupo_connection_status 1.0 + + # TYPE kupo_most_recent_checkpoint counter + kupo_most_recent_checkpoint 61264845 + + # TYPE kupo_most_recent_node_tip counter + kupo_most_recent_node_tip 82838775 + + # TYPE kupo_network_synchronization gauge + kupo_network_synchronization 0.73956 + + # TYPE kupo_seconds_since_last_block gauge + kupo_seconds_since_last_block 2.0 202: description: Syncing @@ -2207,6 +2347,7 @@ paths: $ref: "#/components/schemas/Health" "text/plain;charset=utf-8": + example: *HealthPrometheusExample schema: $ref: "#/components/schemas/HealthPrometheus" @@ -2219,5 +2360,27 @@ paths: $ref: "#/components/schemas/Health" "text/plain;charset=utf-8": + example: *HealthPrometheusExample schema: $ref: "#/components/schemas/HealthPrometheus" + + /metrics: + get: + operationId: getMetrics + tags: ["Health"] + summary: Get Metrics + description: | + Like [`/health`](#operation/getHealth), but always return `200 OK` as a status. + responses: + 200: + description: Metrics + headers: *default-headers + content: + "text/plain;charset=utf-8": + example: *HealthPrometheusExample + schema: + $ref: "#/components/schemas/HealthPrometheus" + + "application/json;charset=utf-8": + schema: + $ref: "#/components/schemas/Health" diff --git a/docs/index.html b/docs/index.html index a5ee3f27..0dc4881e 100644 --- a/docs/index.html +++ b/docs/index.html @@ -126,8 +126,8 @@
- v2.10.0 v2.11.0 + v2.12.0 nightly