From ed7ceff6c23c6e2409399d4456d9fe4fa29b8cd2 Mon Sep 17 00:00:00 2001 From: Mateusz Galazyn Date: Fri, 27 Nov 2026 10:03:02 +0100 Subject: [PATCH 1/5] Index Dijkstra sub-transactions through Ogmios Ogmios now serialises Dijkstra transactions in full, including their sub-transactions, so Kupo no longer needs to stop at the first Dijkstra block that holds transactions. It reads each sub-transaction as a transaction of its own and files it under the top-level transaction, as the node-to-client path already does. Kupo still stops at a Dijkstra transaction without 'inputs', which is what an Ogmios from before full Dijkstra support sends. The flag that records this is renamed from 'isDijkstraBlock' to 'hasTransactionStubs', because a Dijkstra block is no longer a reason to refuse by itself. --- CHANGELOG.md | 2 +- src/Kupo/Data/Cardano.hs | 6 ++--- src/Kupo/Data/Hydra.hs | 6 ++++- src/Kupo/Data/Ogmios.hs | 39 ++++++++++++++++++++++-------- src/Kupo/Data/PartialBlock.hs | 23 ++++++++++++------ test/Test/Kupo/App/HttpSpec.hs | 4 ++- test/Test/Kupo/AppSpec.hs | 14 +++++++++-- test/Test/Kupo/Data/OgmiosSpec.hs | 2 +- test/Test/Kupo/Data/PatternSpec.hs | 4 ++- 9 files changed, 73 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a3ffb77a..34965ad1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - Kupo now indexes Dijkstra blocks when it is connected directly to cardano-node. With Ogmios, Kupo stops with an error at the first Dijkstra block, because Ogmios does not serialise Dijkstra transactions yet. -- Kupo now indexes Dijkstra sub-transactions when it is connected directly to cardano-node, instead of stopping at the first transaction that carries them. Kupo records the outputs that each sub-transaction creates and the inputs that it spends under the sub-transaction's own id, with the index of its top-level transaction in the block. A `*@` pattern matches the outputs of that transaction only, so the id of a top-level transaction does not match the outputs of its sub-transactions. When a top-level transaction fails phase-2 validation, its sub-transactions create and spend nothing. +- Kupo now indexes Dijkstra sub-transactions, instead of stopping at the first transaction that carries them. Kupo records the outputs that each sub-transaction creates and the inputs that it spends under the sub-transaction's own id, with the index of its top-level transaction in the block. A `*@` pattern matches the outputs of that transaction only, so the id of a top-level transaction does not match the outputs of its sub-transactions. When a top-level transaction fails phase-2 validation, its sub-transactions create and spend nothing. - Each match returned by `/matches` now carries `sub_transaction_index` and `top_level_transaction_id`. For an output created by a Dijkstra sub-transaction, they give the position of the sub-transaction among those of its top-level transaction, starting at 0, and the id of that top-level transaction; `transaction_id` stays the id of the sub-transaction itself. Both are `null` for an output of a top-level transaction. The `spent_at` object of a match gains `top_level_transaction_id`: the id of the top-level transaction when a sub-transaction spent the output, `null` otherwise. Existing fields keep their meaning, and `transaction_index` is still the position of the top-level transaction in the block. diff --git a/src/Kupo/Data/Cardano.hs b/src/Kupo/Data/Cardano.hs index 12c38ce2..737bb825 100644 --- a/src/Kupo/Data/Cardano.hs +++ b/src/Kupo/Data/Cardano.hs @@ -173,15 +173,15 @@ class HasTransactionId (BlockBody block) => IsBlock (block :: Type) where -- | Raised on a Dijkstra block whose sub-transactions Kupo cannot index. data UnsupportedSubTransactions = UnverifiableSubTransactions !Point - -- ^ A Dijkstra block whose transactions Kupo cannot inspect. + -- ^ A Dijkstra block whose transactions Ogmios sent without their bodies. deriving (Show) instance Exception UnsupportedSubTransactions where displayException = \case UnverifiableSubTransactions point -> - "Ogmios does not serialise Dijkstra transactions yet, so Kupo cannot index the block at slot " + "This Ogmios does not serialise Dijkstra transactions in full, so Kupo cannot index the block at slot " <> toString (slotNoToText (getPointSlotNo point)) - <> ". Connect Kupo directly to cardano-node to index Dijkstra blocks." + <> ". Upgrade Ogmios, or connect Kupo directly to cardano-node." instance IsBlock Void where type BlockBody Void = Void diff --git a/src/Kupo/Data/Hydra.hs b/src/Kupo/Data/Hydra.hs index 10ad84c1..8b2daf88 100644 --- a/src/Kupo/Data/Hydra.hs +++ b/src/Kupo/Data/Hydra.hs @@ -121,7 +121,7 @@ mkHydraBlock number txs = do , PartialBlock { blockPoint = BlockPoint slotNo headerHash , blockBody = toList txs - , isDijkstraBlock = False + , hasTransactionStubs = False } ) @@ -179,6 +179,8 @@ decodeGenesisTxForUTxO id indexOutputs = do , datums = mempty , scripts = mempty , metadata = Nothing + , appliedSubTransactions = [] + , unappliedSubTransactions = [] } decodePartialTransaction :: Json.Value -> Json.Parser PartialTransaction @@ -225,6 +227,8 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do (unRedeemers $ wits' ^. rdmrsTxWitsL) , scripts = Map.map fromConwayScript (wits' ^. scriptTxWitsL) , metadata = Nothing + , appliedSubTransactions = [] + , unappliedSubTransactions = [] } decodeInput diff --git a/src/Kupo/Data/Ogmios.hs b/src/Kupo/Data/Ogmios.hs index b72b6470..3169c582 100644 --- a/src/Kupo/Data/Ogmios.hs +++ b/src/Kupo/Data/Ogmios.hs @@ -199,19 +199,26 @@ decodeBlock = Json.withObject "Block" $ \o -> do slot <- o .:? "slot" >>= \case Just slot -> pure slot Nothing -> o .: "height" - isDijkstraBlock <- (== Just ("dijkstra" :: Text)) <$> o .:? "era" - -- Ogmios serialises Dijkstra transactions as stubs, which do not decode. - txs <- if isDijkstraBlock then pure [] else o .:? "transactions" .!= [] - blockBody <- traverse decodePartialTransaction txs - pure PartialBlock { blockPoint = BlockPoint (SlotNo slot) id, blockBody, isDijkstraBlock } + era <- o .:? "era" + txs <- o .:? "transactions" .!= [] + -- Older Ogmios versions send each Dijkstra transaction with only its id and 'spends'. + let hasTransactionStubs = era == Just ("dijkstra" :: Text) && any (not . KeyMap.member "inputs") txs + blockBody <- if hasTransactionStubs then pure [] else traverse (decodePartialTransaction . Json.Object) txs + pure PartialBlock { blockPoint = BlockPoint (SlotNo slot) id, blockBody, hasTransactionStubs } decodePartialTransaction :: Json.Value -> Json.Parser PartialTransaction decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do - id <- o .: "id" >>= decodeTransactionId - inputSource <- o .: "spends" + decodeTransaction inputSource o + +decodeTransaction + :: Json.Key + -> Json.Object + -> Json.Parser PartialTransaction +decodeTransaction inputSource o = do + id <- o .: "id" >>= decodeTransactionId inputs <- o .:? inputSource .!= [] >>= traverse decodeInput @@ -228,14 +235,16 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do scripts <- o .:? "scripts" .!= Json.Object mempty >>= decodeScripts - outputs <- case Key.toText inputSource of + subTransactions <- o .:? "subTransactions" .!= [] >>= traverse decodeSubTransaction + + (outputs, appliedSubTransactions, unappliedSubTransactions) <- case Key.toText inputSource of "collaterals" -> do outs <- o .:? "outputs" .!= ([] :: [Json.Value]) colReturn <- o .:? "collateralReturn" >>= traverse decodeOutput - pure $ withReferences (fromIntegral $ length outs) id (maybeToList colReturn) + pure (withReferences (fromIntegral $ length outs) id (maybeToList colReturn), [], subTransactions) "inputs" -> do outs <- o .:? "outputs" .!= [] >>= traverse decodeOutput - pure $ withReferences 0 id outs + pure (withReferences 0 id outs, subTransactions, []) (_ :: Text) -> do fail "unrecognized input source" @@ -247,8 +256,18 @@ decodePartialTransaction = Json.withObject "PartialTransaction" $ \o -> do , spendRedeemers , scripts , metadata + , appliedSubTransactions + , unappliedSubTransactions } +-- | A sub-transaction has no 'spends': the validity of its top-level transaction decides +-- whether the ledger applies it. +decodeSubTransaction + :: Json.Value + -> Json.Parser PartialTransaction +decodeSubTransaction = + Json.withObject "SubTransaction" (decodeTransaction "inputs") + decodeAddress :: Text -> Json.Parser Address diff --git a/src/Kupo/Data/PartialBlock.hs b/src/Kupo/Data/PartialBlock.hs index 86e61d16..a63c19c8 100644 --- a/src/Kupo/Data/PartialBlock.hs +++ b/src/Kupo/Data/PartialBlock.hs @@ -36,11 +36,10 @@ import qualified Data.Set as Set data PartialBlock = PartialBlock { blockPoint :: !Point , blockBody :: ![PartialTransaction] - -- ^ The decoded transactions, empty for a Dijkstra block. - , isDijkstraBlock :: !Bool - -- ^ Whether this is a Dijkstra block whose transactions were not decoded. - -- Ogmios sends Dijkstra transactions without their bodies, and Hydra - -- decodes Conway transactions only. + -- ^ The decoded transactions, empty when 'hasTransactionStubs'. + , hasTransactionStubs :: !Bool + -- ^ Whether Ogmios sent the Dijkstra transactions of this block without + -- their bodies, as Ogmios versions before full Dijkstra support do. } deriving (Eq, Show) -- | A partial transaction, analogous to 'PartialBlock', trimmed down to the @@ -53,6 +52,10 @@ data PartialTransaction = PartialTransaction , spendRedeemers :: !(Map InputIndex BinaryData) , scripts :: !(Map ScriptHash Script) , metadata :: !(Maybe (MetadataHash, Metadata)) + , appliedSubTransactions :: ![PartialTransaction] + -- ^ The Dijkstra sub-transactions of a phase-2 valid transaction, in the order the ledger applies them. + , unappliedSubTransactions :: ![PartialTransaction] + -- ^ The Dijkstra sub-transactions of a phase-2 invalid transaction, which the ledger discards. } deriving (Eq, Show) instance HasTransactionId PartialTransaction where @@ -70,10 +73,16 @@ instance IsBlock PartialBlock where foldBlock fn result = foldrWithIndex fn result . blockBody - checkSubTransactions PartialBlock{blockPoint, isDijkstraBlock} = - when isDijkstraBlock $ + checkSubTransactions PartialBlock{blockPoint, hasTransactionStubs} = + when hasTransactionStubs $ Left (UnverifiableSubTransactions blockPoint) + subTransactions = + appliedSubTransactions + + discardedSubTransactions = + unappliedSubTransactions + mapMaybeOutputs fn tx = let meta = maybe emptyMetadata snd (metadata tx) in mapMaybe (\outs -> uncurry fn outs meta) (outputs tx) diff --git a/test/Test/Kupo/App/HttpSpec.hs b/test/Test/Kupo/App/HttpSpec.hs index c2567b3d..8844b5ce 100644 --- a/test/Test/Kupo/App/HttpSpec.hs +++ b/test/Test/Kupo/App/HttpSpec.hs @@ -547,8 +547,10 @@ newStubbedApplication defaultPatterns = do , datums = mempty , spendRedeemers = mempty , metadata + , appliedSubTransactions = [] + , unappliedSubTransactions = [] } - pure $ PartialBlock { blockPoint, blockBody, isDijkstraBlock = False } + pure $ PartialBlock { blockPoint, blockBody, hasTransactionStubs = False } ) patternsVar healthStub diff --git a/test/Test/Kupo/AppSpec.hs b/test/Test/Kupo/AppSpec.hs index d609e668..eff6183f 100644 --- a/test/Test/Kupo/AppSpec.hs +++ b/test/Test/Kupo/AppSpec.hs @@ -742,7 +742,7 @@ genContinuingBlock utxo txs previousTip = do blockPoint <- BlockPoint (next (getPointSlotNo previousTip)) <$> genHeaderHash (txs', utxo') <- runStateT (genTransactionSublist txs) utxo blockBody <- (txs' <>) <$> evalStateT genPartialTransactions utxo' - pure PartialBlock { blockPoint, blockBody, isDijkstraBlock = False } + pure PartialBlock { blockPoint, blockBody, hasTransactionStubs = False } -- | Generate a list of transactions using and modifying a given utxo. The -- generation stops when there's no more utxos or, arbitrarily (1 chance out of @@ -778,7 +778,17 @@ genPartialTransaction = do replicateM nScripts (lift genScript) & fmap (foldMap (\v -> Map.singleton (hashScript v) v)) metadata <- lift $ oneof [pure Nothing, Just <$> genMetadata] - pure PartialTransaction { id, inputs, outputs, datums, spendRedeemers, scripts, metadata } + pure PartialTransaction + { id + , inputs + , outputs + , datums + , spendRedeemers + , scripts + , metadata + , appliedSubTransactions = [] + , unappliedSubTransactions = [] + } where maxNumberOfInputs = 3 maxNumberOfOutputs = 3 diff --git a/test/Test/Kupo/Data/OgmiosSpec.hs b/test/Test/Kupo/Data/OgmiosSpec.hs index a9edd32c..6d9af10a 100644 --- a/test/Test/Kupo/Data/OgmiosSpec.hs +++ b/test/Test/Kupo/Data/OgmiosSpec.hs @@ -78,7 +78,7 @@ spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do propVector ((dir ) <$> vectors) decodeNextBlockResponse context "checkSubTransactions" $ do - it "rejects a Dijkstra block, whose transactions Ogmios does not serialise" $ do + it "rejects a Dijkstra block whose transactions Ogmios sends without their bodies" $ do let stub = Json.object [ "id" .= txId , "spends" .= ("inputs" :: Text) diff --git a/test/Test/Kupo/Data/PatternSpec.hs b/test/Test/Kupo/Data/PatternSpec.hs index bf0d57e6..00a51300 100644 --- a/test/Test/Kupo/Data/PatternSpec.hs +++ b/test/Test/Kupo/Data/PatternSpec.hs @@ -150,8 +150,10 @@ spec = parallel $ do , spendRedeemers = Map.fromList [(ix, redeemer ix) | (ix, _) <- ascending] , scripts = mempty , metadata = Nothing + , appliedSubTransactions = [] + , unappliedSubTransactions = [] } - let blk = PartialBlock { blockPoint = pt, blockBody = [tx], isDijkstraBlock = False } + let blk = PartialBlock { blockPoint = pt, blockBody = [tx], hasTransactionStubs = False } let codecs = Codecs { toResult = identity , toBinaryData = \_ _ -> () From 12215502fd1001e163e0fe4da6d01a631e31e385 Mon Sep 17 00:00:00 2001 From: Mateusz Galazyn Date: Fri, 27 Nov 2026 10:03:10 +0100 Subject: [PATCH 2/5] Decode the guard redeemer purpose from Ogmios Dijkstra transactions can carry redeemers for guards, and Ogmios names their purpose 'guard'. Without a case for it, Kupo failed on "unknown script purpose: guard" for any such transaction. --- src/Kupo/Data/Ogmios.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Kupo/Data/Ogmios.hs b/src/Kupo/Data/Ogmios.hs index 3169c582..9df20e48 100644 --- a/src/Kupo/Data/Ogmios.hs +++ b/src/Kupo/Data/Ogmios.hs @@ -122,6 +122,7 @@ data ScriptPurpose | Withdraw | Vote | Propose + | Guard deriving (Eq) -- Encoders @@ -432,6 +433,7 @@ decodeScriptPurpose = \case "withdraw" -> pure Withdraw "vote" -> pure Vote "propose" -> pure Propose + "guard" -> pure Guard purpose -> fail $ "unknown script purpose: " ++ toString purpose decodeDatumHash From c2b9a43455b9a3b96ddf7f64fbe3a608b016cdd6 Mon Sep 17 00:00:00 2001 From: Mateusz Galazyn Date: Fri, 27 Nov 2026 10:03:36 +0100 Subject: [PATCH 3/5] Read native scripts from their CBOR when Ogmios includes it Ogmios adds the CBOR of a native script only when it runs with --include-script-cbor. Decode it when it is there, so that Kupo stores the on-chain bytes instead of a re-encoding of the JSON, and fall back to the JSON otherwise. Plutus scripts already come from their CBOR. The CBOR also covers every clause the JSON cannot describe fully, such as the guard clauses of Dijkstra native scripts. --- CHANGELOG.md | 2 + src/Kupo/Data/Ogmios.hs | 13 +++--- test/Test/Kupo/Data/OgmiosSpec.hs | 72 +++++++++++++++++++++++++++---- 3 files changed, 73 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 34965ad1..92a59ed6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ - Kupo now returns datums and redeemers from Babbage and Conway transaction witnesses with their on-chain bytes, as it already does for inline datums and other eras. Earlier versions returned a re-encoding of the same value, which cannot be used as-is to spend an output locked by that datum's hash. Databases built by earlier versions keep the re-encoded bytes. +- Through an Ogmios that runs with `--include-script-cbor`, Kupo now stores native scripts with their on-chain bytes instead of a re-encoding of their JSON. + - Kupo now limits the statistics scan of SQLite's `PRAGMA optimize`, which it runs at start-up, after `kupo copy` and on every garbage collection pass. On large databases the unbounded scan could take hours and stall chain sync. See https://github.com/CardanoSolutions/kupo/issues/209. #### Removed diff --git a/src/Kupo/Data/Ogmios.hs b/src/Kupo/Data/Ogmios.hs index 9df20e48..c9c0b09c 100644 --- a/src/Kupo/Data/Ogmios.hs +++ b/src/Kupo/Data/Ogmios.hs @@ -344,17 +344,18 @@ decodeScript -> Json.Parser Script decodeScript = Json.withObject "Script" $ \o -> do o .: "language" >>= \case - "native" -> decodeNative =<< o .: "json" - "plutus:v1" -> decodePlutus "01" =<< o .: "cbor" - "plutus:v2" -> decodePlutus "02" =<< o .: "cbor" - "plutus:v3" -> decodePlutus "03" =<< o .: "cbor" - "plutus:v4" -> decodePlutus "04" =<< o .: "cbor" + -- Ogmios includes the CBOR of native scripts only when run with --include-script-cbor. + "native" -> (decodeTagged "00" =<< o .: "cbor") <|> (decodeNative =<< o .: "json") + "plutus:v1" -> decodeTagged "01" =<< o .: "cbor" + "plutus:v2" -> decodeTagged "02" =<< o .: "cbor" + "plutus:v3" -> decodeTagged "03" =<< o .: "cbor" + "plutus:v4" -> decodeTagged "04" =<< o .: "cbor" (_ :: Text) -> fail "unrecognized script language" where decodeNative = fmap fromNativeScript . decodeNativeScript - decodePlutus tag bytes = do + decodeTagged tag bytes = do case scriptFromBytes <$> decodeBase16 (encodeUtf8 @Text (tag <> bytes)) of Right (Just s) -> pure s diff --git a/test/Test/Kupo/Data/OgmiosSpec.hs b/test/Test/Kupo/Data/OgmiosSpec.hs index 6d9af10a..e9a08027 100644 --- a/test/Test/Kupo/Data/OgmiosSpec.hs +++ b/test/Test/Kupo/Data/OgmiosSpec.hs @@ -8,6 +8,9 @@ module Test.Kupo.Data.OgmiosSpec import Kupo.Prelude +import Data.Aeson + ( (.=) + ) import Data.List ( (!!) ) @@ -17,6 +20,8 @@ import Kupo.App.ChainSync.Ogmios import Kupo.Data.Cardano ( IsBlock (..) , UnsupportedSubTransactions (..) + , hashScript + , scriptHashToText ) import Kupo.Data.Ogmios ( NextBlockResponse (..) @@ -39,6 +44,7 @@ import Test.Hspec , it , parallel , runIO + , shouldBe , shouldSatisfy ) import Test.Hspec.QuickCheck @@ -55,11 +61,12 @@ import Test.QuickCheck.Monadic , run ) +import qualified Data.Aeson as Json +import qualified Data.Aeson.Key as Key +import qualified Data.Aeson.Types as Json +import qualified Data.Map as Map import qualified Data.Text as Text -import Data.Aeson as Json -import Data.Aeson.Types as Json - spec :: Spec spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do context "decodeFindIntersectResponse" $ do @@ -98,6 +105,20 @@ spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do withBlock (nextBlock "conway" [tx]) $ \blk -> checkSubTransactions blk `shouldSatisfy` isRight + context "native scripts with a guard clause" $ do + it "decodes them from their CBOR" $ do + let tx = transactionWithScript scriptGuardHash $ Json.object + [ "language" .= ("native" :: Text) + , "json" .= guardClause [] + , "cbor" .= scriptGuardCbor + ] + withBlock (nextBlock "dijkstra" [tx]) $ \blk -> + witnessedScriptHashes blk `shouldBe` [(scriptGuardHash, scriptGuardHash)] + +-- +-- Helpers +-- + withBlock :: Json.Value -> (PartialBlock -> Expectation) -> Expectation withBlock value check = case Json.parse decodeNextBlockResponse value of @@ -127,11 +148,11 @@ nextBlock era txs = Json.object , "slot" .= (42 :: Int) ] -txId :: Text -txId = Text.replicate 64 "a" - -blockId :: Text -blockId = Text.replicate 64 "b" +-- | The witnessed scripts of a block, with their key and their own hash. +witnessedScriptHashes :: PartialBlock -> [(Text, Text)] +witnessedScriptHashes = + fmap (\(scriptHash, script) -> (scriptHashToText scriptHash, scriptHashToText (hashScript script))) + . foldBlock (\_ -> (<>) . Map.toList . witnessedScripts @PartialBlock) [] propVector :: [FilePath] @@ -151,3 +172,38 @@ propVector vectors decoder = do assert False Json.Success{} -> do assert True + +-- +-- Fixtures +-- + +txId :: Text +txId = Text.replicate 64 "a" + +blockId :: Text +blockId = Text.replicate 64 "b" + +transactionWithScript :: Text -> Json.Value -> Json.Value +transactionWithScript scriptHash script = Json.object + [ "id" .= txId + , "spends" .= ("inputs" :: Text) + , "inputs" .= ([] :: [Json.Value]) + , "scripts" .= Json.object [ Key.fromText scriptHash .= script ] + ] + +-- | A guard clause on the hash 11...11, with extra fields such as its 'origin'. +guardClause :: [Json.Pair] -> Json.Value +guardClause extra = Json.object $ + [ "clause" .= ("guard" :: Text) + , "from" .= Text.replicate 28 "11" + ] + <> extra + +-- | The guard clause on the script hash 11...11. +scriptGuardCbor :: Text +scriptGuardCbor = + "82068201581c" <> Text.replicate 28 "11" + +scriptGuardHash :: Text +scriptGuardHash = + "b9114d0c8fcf4610e179afba560689b160b29a062643772105feb6e7" From 3f268c7ae0e5e372f81688ecee0052f208768069 Mon Sep 17 00:00:00 2001 From: Mateusz Galazyn Date: Fri, 27 Nov 2026 10:03:36 +0100 Subject: [PATCH 4/5] Decode native script guard clauses from Ogmios A guard clause names a hash that is either a key or a script, and the ledger hashes the two differently. Ogmios includes the 'origin' of the hash in the JSON of the clause, so read it from there when the script has no CBOR. When there is neither, fail with a message that says how to fix it, instead of guessing the wrong script hash. --- CHANGELOG.md | 2 +- src/Kupo/Data/Cardano/NativeScript.hs | 1 + src/Kupo/Data/Ogmios.hs | 10 +++++++++ test/Test/Kupo/Data/OgmiosSpec.hs | 29 +++++++++++++++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92a59ed6..cb62f8c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ #### Added -- Kupo now indexes Dijkstra blocks when it is connected directly to cardano-node. With Ogmios, Kupo stops with an error at the first Dijkstra block, because Ogmios does not serialise Dijkstra transactions yet. +- Kupo now indexes Dijkstra blocks, both when it is connected directly to cardano-node and through Ogmios. Through Ogmios, it needs an Ogmios that serialises Dijkstra transactions in full (https://github.com/IntersectMBO/ogmios/pull/22 and https://github.com/IntersectMBO/ogmios/pull/24); with an older Ogmios, Kupo stops with an error at the first Dijkstra block that holds transactions. Through Ogmios, Kupo also stops at a native script with a guard clause when Ogmios does not say whether the guard is a key or a script: Kupo reads that from the clause's `origin` field, or from the script's CBOR when Ogmios runs with `--include-script-cbor`. - Kupo now indexes Dijkstra sub-transactions, instead of stopping at the first transaction that carries them. Kupo records the outputs that each sub-transaction creates and the inputs that it spends under the sub-transaction's own id, with the index of its top-level transaction in the block. A `*@` pattern matches the outputs of that transaction only, so the id of a top-level transaction does not match the outputs of its sub-transactions. When a top-level transaction fails phase-2 validation, its sub-transactions create and spend nothing. diff --git a/src/Kupo/Data/Cardano/NativeScript.hs b/src/Kupo/Data/Cardano/NativeScript.hs index 3283f8b1..d2c63b02 100644 --- a/src/Kupo/Data/Cardano/NativeScript.hs +++ b/src/Kupo/Data/Cardano/NativeScript.hs @@ -8,6 +8,7 @@ module Kupo.Data.Cardano.NativeScript , pattern Ledger.Shelley.RequireMOf , pattern Ledger.Allegra.RequireTimeExpire , pattern Ledger.Allegra.RequireTimeStart + , pattern Ledger.Dijkstra.RequireGuard , KeyHash(..) ) where diff --git a/src/Kupo/Data/Ogmios.hs b/src/Kupo/Data/Ogmios.hs index c9c0b09c..525203d3 100644 --- a/src/Kupo/Data/Ogmios.hs +++ b/src/Kupo/Data/Ogmios.hs @@ -70,6 +70,7 @@ import Kupo.Data.Cardano , pattern GenesisTip , pattern RequireAllOf , pattern RequireAnyOf + , pattern RequireGuard , pattern RequireMOf , pattern RequireSignature , pattern RequireTimeExpire @@ -97,6 +98,8 @@ import Ouroboros.Consensus.HardFork.Combinator ( OneEraHash (..) ) +import qualified Cardano.Ledger.Credential as Ledger +import qualified Cardano.Ledger.Hashes as Ledger import qualified Cardano.Ledger.Shelley.TxAuxData as Ledger import qualified Data.Aeson.Encoding as Json import qualified Data.Aeson.Key as Key @@ -386,6 +389,13 @@ decodeNativeScript o = do RequireTimeExpire . SlotNo <$> (o .: "slot") "after" -> do RequireTimeStart . SlotNo <$> (o .: "slot") + -- Older Ogmios versions give a bare hash, with no 'origin' to tell a key from a script. + "guard" -> do + let credential = o .: "origin" >>= \case + "verificationKey" -> Ledger.KeyHashObj . KeyHash <$> (o .: "from" >>= decodeHash) + "script" -> Ledger.ScriptHashObj . Ledger.ScriptHash <$> (o .: "from" >>= decodeHash) + (_ :: Text) -> fail "unrecognized guard origin" + RequireGuard <$> (credential <|> fail "cannot decode a native script guard clause without its CBOR or a known origin: upgrade Ogmios, or run it with --include-script-cbor") (_ :: Text) -> fail "unrecognized native script clause" diff --git a/test/Test/Kupo/Data/OgmiosSpec.hs b/test/Test/Kupo/Data/OgmiosSpec.hs index e9a08027..bbb9a545 100644 --- a/test/Test/Kupo/Data/OgmiosSpec.hs +++ b/test/Test/Kupo/Data/OgmiosSpec.hs @@ -115,6 +115,30 @@ spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do withBlock (nextBlock "dijkstra" [tx]) $ \blk -> witnessedScriptHashes blk `shouldBe` [(scriptGuardHash, scriptGuardHash)] + it "decodes a key guard from its JSON origin" $ do + let tx = transactionWithScript keyGuardHash $ Json.object + [ "language" .= ("native" :: Text) + , "json" .= guardClause ["origin" .= ("verificationKey" :: Text)] + ] + withBlock (nextBlock "dijkstra" [tx]) $ \blk -> + witnessedScriptHashes blk `shouldBe` [(keyGuardHash, keyGuardHash)] + + it "decodes a script guard from its JSON origin" $ do + let tx = transactionWithScript scriptGuardHash $ Json.object + [ "language" .= ("native" :: Text) + , "json" .= guardClause ["origin" .= ("script" :: Text)] + ] + withBlock (nextBlock "dijkstra" [tx]) $ \blk -> + witnessedScriptHashes blk `shouldBe` [(scriptGuardHash, scriptGuardHash)] + + it "refuses them without their CBOR or origin" $ do + let tx = transactionWithScript scriptGuardHash $ Json.object + [ "language" .= ("native" :: Text) + , "json" .= guardClause [] + ] + void (Json.parseEither decodeNextBlockResponse (nextBlock "dijkstra" [tx])) + `shouldSatisfy` isLeft + -- -- Helpers -- @@ -207,3 +231,8 @@ scriptGuardCbor = scriptGuardHash :: Text scriptGuardHash = "b9114d0c8fcf4610e179afba560689b160b29a062643772105feb6e7" + +-- | The hash of the guard clause on the key hash 11...11. +keyGuardHash :: Text +keyGuardHash = + "7c11fec0e82c325085e055b9d3e829f12d1bcb41c3e2dd6dec8e8f54" From 638917ac8b5f7ca7518765477dd2f5f6442e3039 Mon Sep 17 00:00:00 2001 From: Mateusz Galazyn Date: Fri, 27 Nov 2026 10:03:36 +0100 Subject: [PATCH 5/5] Take the Ogmios test vectors from IntersectMBO/ogmios The sub-transaction support of the Ogmios path lives in IntersectMBO/ogmios, not in the cardanosolutions fork. Point the submodule there, at the head of the pull request that adds the guard clause origin, so that the tests read its Dijkstra golden files. New tests decode the golden Dijkstra transaction from its JSON and from its CBOR and compare what Kupo reads from the two, which covers the sub-transactions, their positions, and the discarded sub-transactions of a phase-2 invalid transaction. --- .gitmodules | 4 +- test/Test/Kupo/Data/OgmiosSpec.hs | 187 +++++++++++++++++++++++++++++- test/vectors/ogmios | 2 +- 3 files changed, 190 insertions(+), 3 deletions(-) diff --git a/.gitmodules b/.gitmodules index afd26822..f203f2e8 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,11 @@ [submodule "config"] path = config url = https://github.com/input-output-hk/cardano-configurations.git +# TODO: pinned to the head of https://github.com/IntersectMBO/ogmios/pull/45 (guard clause origin); +# move it to the merge commit on master once the PR merges. [submodule "test/ogmios"] path = test/vectors/ogmios - url = https://github.com/cardanosolutions/ogmios.git + url = https://github.com/IntersectMBO/ogmios.git [submodule "test/vectors/hydra"] path = test/vectors/hydra url = https://github.com/input-output-hk/hydra.git diff --git a/test/Test/Kupo/Data/OgmiosSpec.hs b/test/Test/Kupo/Data/OgmiosSpec.hs index bbb9a545..154943ff 100644 --- a/test/Test/Kupo/Data/OgmiosSpec.hs +++ b/test/Test/Kupo/Data/OgmiosSpec.hs @@ -2,15 +2,24 @@ -- 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/. +{-# LANGUAGE AllowAmbiguousTypes #-} + module Test.Kupo.Data.OgmiosSpec ( spec ) where import Kupo.Prelude +import Control.Lens + ( (.~) + ) import Data.Aeson ( (.=) ) +import Data.Aeson.Lens + ( key + , _String + ) import Data.List ( (!!) ) @@ -18,10 +27,28 @@ import Kupo.App.ChainSync.Ogmios ( intersectionNotFound ) import Kupo.Data.Cardano - ( IsBlock (..) + ( BinaryData + , Block + , ComparableOutput + , ComparableScript + , DatumHash + , HasTransactionId (..) + , Input + , InputIndex + , IsBlock (..) + , MetadataHash + , OutputReference + , ScriptHash + , SlotNo (..) + , Transaction (..) + , TransactionId , UnsupportedSubTransactions (..) , hashScript + , mkOutputReference , scriptHashToText + , toComparableOutput + , toComparableScript + , transactionIdFromText ) import Kupo.Data.Ogmios ( NextBlockResponse (..) @@ -29,6 +56,14 @@ import Kupo.Data.Ogmios , decodeFindIntersectionResponse , decodeNextBlockResponse ) +import Kupo.Data.Pattern + ( Codecs (..) + , Match (..) + , MatchBootstrap (..) + , Pattern (..) + , Result (..) + , matchBlock + ) import System.Directory ( listDirectory ) @@ -61,6 +96,7 @@ import Test.QuickCheck.Monadic , run ) +import qualified Cardano.Ledger.Dijkstra.Core as Ledger import qualified Data.Aeson as Json import qualified Data.Aeson.Key as Key import qualified Data.Aeson.Types as Json @@ -95,6 +131,11 @@ spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do Left UnverifiableSubTransactions{} -> True _ -> False + it "accepts a Dijkstra block whose transactions Ogmios serialises in full" $ do + tx <- goldenTransactionJson + withBlock (nextBlock "dijkstra" [tx]) $ \blk -> + checkSubTransactions blk `shouldSatisfy` isRight + it "accepts a Conway block" $ do let tx = Json.object [ "id" .= txId @@ -105,6 +146,59 @@ spec = parallel $ context "can decode relevant Ogmios' test vectors" $ do withBlock (nextBlock "conway" [tx]) $ \blk -> checkSubTransactions blk `shouldSatisfy` isRight + context "sub-transactions" $ do + it "reads a Dijkstra transaction and its sub-transactions as the node-to-client path does" $ do + transactionJson <- goldenTransactionJson + tx <- goldenTransaction + withBlock (nextBlock "dijkstra" [transactionJson]) $ \blk -> do + let views = foldBlock (\_ -> (:) . viewTransaction @PartialBlock) [] blk + views `shouldBe` [viewTransaction @Block (TransactionDijkstra tx)] + (fmap viewId . viewApplied <$> views) `shouldBe` [goldenSubTransactionIds] + (fmap (fmap fst . viewProduced) . viewApplied <$> views) `shouldBe` + [ [ [ mkOutputReference sub0 0 ] + , [ mkOutputReference sub1 0, mkOutputReference sub1 1 ] + ] + ] + + it "matches the outputs and spends of sub-transactions under their top-level transaction" $ do + transactionJson <- goldenTransactionJson + withBlock (nextBlock "dijkstra" [transactionJson]) $ \blk -> do + let Match{consumed, produced} = matchBlock codecs matchAll blk + [ (outputReference, subTransactionOf) | Result{outputReference, subTransactionOf} <- produced ] + `shouldBe` + [ ((mkOutputReference sub0 0, 0), Just (goldenTransactionId, 0)) + , ((mkOutputReference sub1 0, 0), Just (goldenTransactionId, 1)) + , ((mkOutputReference sub1 1, 0), Just (goldenTransactionId, 1)) + , ((mkOutputReference goldenTransactionId 0, 0), Nothing) + , ((mkOutputReference goldenTransactionId 1, 0), Nothing) + , ((mkOutputReference goldenTransactionId 2, 0), Nothing) + ] + Map.keys consumed `shouldBe` sort + [ (goldenTransactionId, Nothing, SlotNo 42) + , (sub0, Just goldenTransactionId, SlotNo 42) + , (sub1, Just goldenTransactionId, SlotNo 42) + ] + + it "discards the sub-transactions of a phase-2 invalid transaction, but keeps their witnesses" $ do + transactionJson <- goldenTransactionJson + tx <- goldenTransaction + let invalidJson = transactionJson & key "spends" . _String .~ "collaterals" + let invalid = tx & Ledger.isPhase2ValidTxL .~ Ledger.Phase2Invalid + withBlock (nextBlock "dijkstra" [invalidJson]) $ \blk -> do + let views = foldBlock (\_ -> (:) . viewTransaction @PartialBlock) [] blk + views `shouldBe` [viewTransaction @Block (TransactionDijkstra invalid)] + (viewApplied <$> views) `shouldBe` [[]] + (fmap viewId . viewDiscarded <$> views) `shouldBe` [goldenSubTransactionIds] + let Match{consumed, produced} = matchBlock codecs matchAll blk + -- The collateral return, indexed after the three outputs. + [ (outputReference, subTransactionOf) | Result{outputReference, subTransactionOf} <- produced ] + `shouldBe` [((mkOutputReference goldenTransactionId 3, 0), Nothing)] + consumed `shouldBe` fromList + [ ( (goldenTransactionId, Nothing, SlotNo 42) + , [(MatchOutputReference goldenCollateral, 0, Nothing)] + ) + ] + context "native scripts with a guard clause" $ do it "decodes them from their CBOR" $ do let tx = transactionWithScript scriptGuardHash $ Json.object @@ -172,12 +266,61 @@ nextBlock era txs = Json.object , "slot" .= (42 :: Int) ] +-- | What Kupo reads from a transaction through 'IsBlock', and from its sub-transactions. +data TransactionView = TransactionView + { viewId :: !TransactionId + , viewSpent :: ![(InputIndex, Input, Maybe BinaryData)] + , viewProduced :: ![(OutputReference, ComparableOutput)] + , viewDatums :: !(Map DatumHash BinaryData) + , viewScripts :: !(Map ScriptHash ComparableScript) + , viewMetadataHash :: !(Maybe MetadataHash) + , viewApplied :: ![TransactionView] + , viewDiscarded :: ![TransactionView] + } deriving (Eq, Show) + +viewTransaction + :: forall block. IsBlock block + => BlockBody block + -> TransactionView +viewTransaction tx = TransactionView + { viewId = + getTransactionId tx + , viewSpent = + [ (ix, input, spendRedeemer @block tx ix) + | (ix, input) <- zip [0 ..] (toList (spentInputs @block tx)) + ] + , viewProduced = + mapMaybeOutputs @block (\ref output _ -> Just (ref, toComparableOutput output)) tx + , viewDatums = + witnessedDatums @block tx + , viewScripts = + toComparableScript <$> witnessedScripts @block tx + , viewMetadataHash = + fst <$> userDefinedMetadata @block tx + , viewApplied = + viewTransaction @block <$> subTransactions @block tx + , viewDiscarded = + viewTransaction @block <$> discardedSubTransactions @block tx + } + -- | The witnessed scripts of a block, with their key and their own hash. witnessedScriptHashes :: PartialBlock -> [(Text, Text)] witnessedScriptHashes = fmap (\(scriptHash, script) -> (scriptHashToText scriptHash, scriptHashToText (hashScript script))) . foldBlock (\_ -> (<>) . Map.toList . witnessedScripts @PartialBlock) [] +matchAll :: Set Pattern +matchAll = + fromList [MatchAny IncludingBootstrap] + +codecs :: Codecs Result () () () +codecs = Codecs + { toResult = identity + , toBinaryData = \_ _ -> () + , toScript = \_ _ -> () + , toPolicy = \_ _ -> () + } + propVector :: [FilePath] -> (Json.Value -> Json.Parser a) @@ -207,6 +350,48 @@ txId = Text.replicate 64 "a" blockId :: Text blockId = Text.replicate 64 "b" +-- | A Dijkstra transaction with two sub-transactions, from Ogmios' golden tests. +goldenTransactionJson :: IO Json.Value +goldenTransactionJson = + either (error . toText) identity + <$> Json.eitherDecodeFileStrict (goldenDir "Transaction_Dijkstra_1.json") + +-- | The same transaction, from its CBOR. +goldenTransaction :: IO (Ledger.Tx Ledger.TopTx DijkstraEra) +goldenTransaction = do + hex <- decodeUtf8 <$> readFileBS (goldenDir "Transaction_Dijkstra_1.cbor.hex") + pure $ unsafeDecodeCborAnn @DijkstraEra "Tx" decCBOR (toLazy . unsafeDecodeBase16 $ Text.strip hex) + +goldenDir :: FilePath +goldenDir = + "./test/vectors/ogmios/server/test/golden" + +goldenTransactionId :: TransactionId +goldenTransactionId = + transactionIdFromHex "dd06f8c4006fc58269f8ad83e125308967960bd25ee1a55b8a1b5e94d98952da" + +goldenSubTransactionIds :: [TransactionId] +goldenSubTransactionIds = + [sub0, sub1] + +sub0 :: TransactionId +sub0 = + transactionIdFromHex "ccaef55f659113c69776852b314e0dd45577f49de1bd5ff16b5deac2b09f4672" + +sub1 :: TransactionId +sub1 = + transactionIdFromHex "03d34728298e26cf5c20a7a4159901abb391116b7c9dc86eb6665afec0a59f83" + +goldenCollateral :: OutputReference +goldenCollateral = + mkOutputReference + (transactionIdFromHex "9b766aeeac195e946a70dd0785c80e585fdcee364aae5fed55ee2f7f5f337a20") + 0 + +transactionIdFromHex :: Text -> TransactionId +transactionIdFromHex hex = + fromMaybe (error $ "invalid transaction id: " <> hex) (transactionIdFromText hex) + transactionWithScript :: Text -> Json.Value -> Json.Value transactionWithScript scriptHash script = Json.object [ "id" .= txId diff --git a/test/vectors/ogmios b/test/vectors/ogmios index ae876bad..fdc347ab 160000 --- a/test/vectors/ogmios +++ b/test/vectors/ogmios @@ -1 +1 @@ -Subproject commit ae876badb138f42dcd6d2389734b0c15502684ed +Subproject commit fdc347abb03f60cf7d2315efb3e85cf98ede7029