diff --git a/CHANGELOG.md b/CHANGELOG.md index b0662c32..5ee48232 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,13 @@ - 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. -- A Dijkstra transaction that carries sub-transactions is not indexed yet. Kupo stops with an error that names the transaction. +- 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. + +- 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. + +- `/matches` accepts a new `top_level_transaction_id` query filter. It returns the outputs created by the Dijkstra sub-transactions of that top-level transaction, and not the outputs of the top-level transaction itself, which `*@` and `transaction_id` still return. Like `transaction_id`, it cannot be combined with `policy_id`, `asset_name` or `output_index`, nor given twice, and `transaction_id` and `top_level_transaction_id` exclude each other; Kupo then answers with a 400 error. The `transaction_id` filter and the `*@` and `@` patterns accept the id of a sub-transaction. + +- `/metadata/{slot}` includes the metadata of Dijkstra sub-transactions. Each entry gains `transaction_id`, the id of the transaction that carries the metadata, and `top_level_transaction_id`, the id of the top-level transaction for a sub-transaction and `null` otherwise. The metadata of the sub-transactions of a transaction comes first, in the order the ledger applies them, followed by the metadata of the transaction itself. The `transaction_id` filter accepts the id of a sub-transaction. The sub-transactions of a transaction that fails phase-2 validation have no entry. - Kupo now records database migrations in a `migrations` table, and no longer runs heavy or breaking migrations silently at startup: - When the database needs a blocking migration, Kupo refuses to start and exits with code 3. Run `kupo db migrate`, then start Kupo again. @@ -27,6 +33,8 @@ - Fixed the input index and the redeemer reported in `spent_at` (`input_index` and `redeemer`) for transactions that spend two or more inputs. Since 2.10.0, Kupo numbered the inputs from the last one, so the index and the redeemer did not match the ledger. They now follow the ledger's input order. For the spends recorded before the upgrade, Kupo registers a data repair, and warns at every start until it is applied. If the index matches `*`, was synchronised from origin and was never pruned with `--prune-utxo`, run `kupo db migrate --confirm-complete-index` to apply it; otherwise, resynchronise. +- At startup, Kupo adds three empty columns to the `inputs` table of an existing database, to prepare the indexing of Dijkstra sub-transactions. The change is automatic and instant, and needs no action. + #### Removed N/A diff --git a/db/README.md b/db/README.md index 9616bd54..6448aad7 100644 --- a/db/README.md +++ b/db/README.md @@ -1,11 +1,62 @@ ## Overview -

- - - Database schema. - -

+The diagram below is maintained by hand and must be updated with each migration. + +```mermaid +erDiagram + inputs { + BLOB ext_output_reference PK + TEXT address + BLOB value + BLOB datum_info "nullable" + BLOB script_hash "nullable" + INTEGER created_at + INTEGER spent_at "nullable" + BLOB spent_by "nullable" + BLOB spent_with "nullable" + INTEGER sub_transaction_index "nullable" + BLOB top_level_transaction_id "nullable" + BLOB spent_by_top_level_transaction_id "nullable" + BLOB output_reference UK "virtual" + BLOB output_index "virtual" + BLOB transaction_index "virtual" + BLOB datum_hash "virtual, nullable" + TEXT payment_credential "virtual, nullable" + } + policies { + BLOB output_reference PK, FK + BLOB policy_id PK + } + checkpoints { + BLOB header_hash + INTEGER slot_no PK + } + binary_data { + BLOB binary_data_hash PK + BLOB binary_data + } + scripts { + BLOB script_hash PK + BLOB script + } + patterns { + TEXT pattern PK + } + migrations { + TEXT id PK + TEXT state + INTEGER cutoff_slot "nullable" + BLOB cursor "nullable" + TEXT kupo_version "nullable" + INTEGER registered_at + INTEGER applied_at "nullable" + } + inputs ||--o{ policies : "output_reference, ON DELETE CASCADE" + checkpoints ||..o{ inputs : "created_at, lookup, no FK" + checkpoints |o..o{ inputs : "spent_at, lookup, no FK" + binary_data |o..o{ inputs : "datum_hash, lookup, no FK" + scripts |o..o{ inputs : "script_hash, lookup, no FK" +```
See complete definition @@ -21,12 +72,15 @@ CREATE TABLE `inputs` ( `spent_at` INTEGER, `spent_by` BLOB, `spent_with` BLOB, + `sub_transaction_index` INTEGER, + `top_level_transaction_id` BLOB, + `spent_by_top_level_transaction_id` BLOB, `output_reference` BLOB NOT NULL GENERATED ALWAYS AS (substr(`ext_output_reference`, 1, 34)) VIRTUAL, `output_index` BLOB NOT NULL GENERATED ALWAYS AS (substr(`ext_output_reference`, -4, 2)) VIRTUAL, `transaction_index` BLOB NOT NULL GENERATED ALWAYS AS (substr(`ext_output_reference`, -2)) VIRTUAL, `datum_hash` BLOB GENERATED ALWAYS AS (substr(`datum_info`, 2)) VIRTUAL, - `payment_credential` TEXT COLLATE NOCASE NOT NULL GENERATED ALWAYS AS (substr(`address`, -56)) VIRTUAL, + `payment_credential` TEXT COLLATE NOCASE GENERATED ALWAYS AS (substr(`address`, -56)) VIRTUAL, PRIMARY KEY (`ext_output_reference`) ); @@ -34,6 +88,7 @@ CREATE TABLE `inputs` ( CREATE UNIQUE INDEX `inputsByOutputReference` ON `inputs` (`output_reference`); CREATE INDEX `inputsByAddress` ON `inputs` (`address` COLLATE NOCASE); +CREATE INDEX `inputsByDatumHash` ON `inputs` (`datum_hash`); CREATE INDEX `inputsByPaymentCredential` ON `inputs` (`payment_credential` COLLATE NOCASE); CREATE INDEX `inputsByCreatedAt` ON `inputs` (`created_at`); CREATE INDEX `inputsBySpentAt` ON `inputs` (`spent_at`); @@ -48,6 +103,8 @@ CREATE TABLE `policies` ( ON DELETE CASCADE ); +CREATE INDEX `policiesByPolicyId` ON `policies` (`policy_id`); + CREATE TABLE `checkpoints` ( `header_hash` BLOB NOT NULL, `slot_no` INTEGER PRIMARY KEY NOT NULL @@ -116,6 +173,11 @@ Kupo refuses a database whose registry holds an id that it does not know, becaus - On a database upgraded from `version=9` or older, which holds no such spends, record the repair as skipped instead. - The repair needs an index that matches `*`, was synchronised from origin and was never pruned with `--prune-utxo`: an interrupted prune can leave only the last inputs of a transaction, which look like a complete set. Resynchronise any other index. +### Migration to `version=13` + +- Add `sub_transaction_index` and `top_level_transaction_id` columns to `inputs`. For an output created by a Dijkstra sub-transaction, they hold the position of the sub-transaction among those of its top-level transaction, starting at 0, and the id of the top-level transaction; `ext_output_reference` then holds the id of the sub-transaction itself. Both are `NULL` for an output of a top-level transaction. +- Add a `spent_by_top_level_transaction_id` column to `inputs`. When a Dijkstra sub-transaction spends the output, it holds the id of the top-level transaction, and `spent_by` holds the id of the sub-transaction. It is `NULL` otherwise. +

v2.10.0


diff --git a/db/schema-dark.png b/db/schema-dark.png deleted file mode 100644 index 3ee96a81..00000000 Binary files a/db/schema-dark.png and /dev/null differ diff --git a/db/schema-light.png b/db/schema-light.png deleted file mode 100644 index c3e76667..00000000 Binary files a/db/schema-light.png and /dev/null differ diff --git a/db/v2.12.0/003.sql b/db/v2.12.0/003.sql new file mode 100644 index 00000000..03e1ce37 --- /dev/null +++ b/db/v2.12.0/003.sql @@ -0,0 +1,3 @@ +ALTER TABLE inputs ADD COLUMN sub_transaction_index INTEGER; +ALTER TABLE inputs ADD COLUMN top_level_transaction_id BLOB; +ALTER TABLE inputs ADD COLUMN spent_by_top_level_transaction_id BLOB; diff --git a/docs/api/nightly.yaml b/docs/api/nightly.yaml index f9259a96..d89546d9 100644 --- a/docs/api/nightly.yaml +++ b/docs/api/nightly.yaml @@ -894,10 +894,21 @@ components: type: object additionalProperties: false required: + - transaction_id + - top_level_transaction_id - hash - schema - raw properties: + transaction_id: + $ref: "#/components/schemas/TransactionId" + + top_level_transaction_id: + description: The id of the top-level transaction carrying the sub-transaction that holds this metadata. `null` when the metadata belongs to a top-level transaction. + oneOf: + - $ref: "#/components/schemas/TransactionId" + - type: "null" + hash: type: string description: A blake2b-256 hash digest of the raw serialized data @@ -1201,6 +1212,7 @@ components: - slot_no - header_hash - transaction_id + - top_level_transaction_id - input_index - redeemer properties: @@ -1212,6 +1224,11 @@ components: oneOf: - $ref: "#/components/schemas/TransactionId" - type: "null" + top_level_transaction_id: + description: The id of the top-level transaction carrying the sub-transaction that spent this output. `null` unless the spending transaction is a sub-transaction, in which case `transaction_id` is the id of the sub-transaction itself. + oneOf: + - $ref: "#/components/schemas/TransactionId" + - type: "null" input_index: oneOf: - $ref: "#/components/schemas/InputIndex" @@ -1221,6 +1238,12 @@ components: - $ref: "#/components/schemas/BinaryData" - type: "null" + SubTransactionIndex: + type: integer + description: The position of a sub-transaction among the sub-transactions of its top-level transaction, starting at 0. + minimum: 0 + example: 1 + TransactionId: type: string description: A blake2b-256 hash digest of a transaction body. @@ -1297,6 +1320,8 @@ components: - transaction_index - transaction_id - output_index + - sub_transaction_index + - top_level_transaction_id - address - value - datum_hash @@ -1310,6 +1335,16 @@ components: $ref: "#/components/schemas/TransactionId" output_index: $ref: "#/components/schemas/OutputIndex" + sub_transaction_index: + description: The position of the sub-transaction that created this output among the sub-transactions of its top-level transaction, starting at 0. `null` for an output of a top-level transaction. + oneOf: + - $ref: "#/components/schemas/SubTransactionIndex" + - type: "null" + top_level_transaction_id: + description: The id of the top-level transaction carrying the sub-transaction that created this output. `null` for an output of a top-level transaction. For an output of a sub-transaction, `transaction_id` is the id of the sub-transaction itself. + oneOf: + - $ref: "#/components/schemas/TransactionId" + - type: "null" address: $ref: "#/components/schemas/Address" value: @@ -1349,6 +1384,8 @@ components: - transaction_index - transaction_id - output_index + - sub_transaction_index + - top_level_transaction_id - address - value - datum_hash @@ -1362,6 +1399,16 @@ components: $ref: "#/components/schemas/TransactionId" output_index: $ref: "#/components/schemas/OutputIndex" + sub_transaction_index: + description: The position of the sub-transaction that created this output among the sub-transactions of its top-level transaction, starting at 0. `null` for an output of a top-level transaction. + oneOf: + - $ref: "#/components/schemas/SubTransactionIndex" + - type: "null" + top_level_transaction_id: + description: The id of the top-level transaction carrying the sub-transaction that created this output. `null` for an output of a top-level transaction. For an output of a sub-transaction, `transaction_id` is the id of the sub-transaction itself. + oneOf: + - $ref: "#/components/schemas/TransactionId" + - type: "null" address: $ref: "#/components/schemas/Address" value: @@ -1792,6 +1839,17 @@ components: description: | A query flag (i.e. `?strict`) to only look for checkpoints that strictly match the provided slot. The behavior otherwise is to look for the largest nearest slot smaller or equal to the one provided. + top-level-transaction-id: + name: top_level_transaction_id + in: query + required: false + schema: + $ref: "#/components/schemas/TransactionId" + description: | + Filters results by top-level transaction id to retrieve the outputs created by the sub-transactions of that transaction. Outputs created by the top-level transaction itself are not returned; match them with a `*@` pattern or the `transaction_id` filter. + Cannot be combined with `policy_id`, `asset_name`, `transaction_id` or `output_index`, nor given more than once; the server then answers with a 400 error. + Like the other query filters, it is applied after the pattern has selected its matches. + transaction-id: &transaction-id name: transaction_id in: query @@ -1800,6 +1858,7 @@ components: $ref: "#/components/schemas/TransactionId" description: | Filters results by transaction id to retrieve items originating from that transaction only. + The id of a Dijkstra sub-transaction is accepted too; it selects the outputs created by that sub-transaction. Useful when combined with a pattern as path-parameter. > WARNING
@@ -1877,6 +1936,7 @@ paths: - $ref: "#/components/parameters/asset-name" - $ref: "#/components/parameters/transaction-id" - $ref: "#/components/parameters/output-index" + - $ref: "#/components/parameters/top-level-transaction-id" responses: 200: description: OK @@ -1924,6 +1984,7 @@ paths: - $ref: "#/components/parameters/asset-name" - $ref: "#/components/parameters/transaction-id" - $ref: "#/components/parameters/output-index" + - $ref: "#/components/parameters/top-level-transaction-id" responses: 200: description: OK @@ -2251,11 +2312,11 @@ paths: description: | Retrieve all metadata data seen in a block at the given slot, possibly filtered by transaction id. - Metadata are ordered according to their respective transaction's order in the block. + Metadata are ordered according to their respective transaction's order in the block. The metadata of the sub-transactions of a Dijkstra transaction come first, in the order the ledger applies them, followed by the metadata of the transaction itself. Each entry names the transaction that carries the metadata. The sub-transactions of a transaction that fails phase-2 validation are not applied and have no entry. parameters: - <<: *transaction-id description: | - Filters results by transaction id to retrieve items originating from that transaction only. + Filters results by transaction id to retrieve items originating from that transaction only. The id of a sub-transaction selects the metadata of that sub-transaction alone. responses: 200: description: OK diff --git a/kupo.cabal b/kupo.cabal index 53c91518..66fa2d4e 100644 --- a/kupo.cabal +++ b/kupo.cabal @@ -29,6 +29,7 @@ extra-source-files: db/v2.1.0/003.sql db/v2.10.0/001.sql db/v2.12.0/001.sql + db/v2.12.0/003.sql db/v2.2.0/001.sql data-files: docs/api/nightly.yaml @@ -72,6 +73,7 @@ library Kupo.App.Database.Migration.V2_10_0_001 Kupo.App.Database.Migration.V2_12_0_001 Kupo.App.Database.Migration.V2_12_0_002 + Kupo.App.Database.Migration.V2_12_0_003 Kupo.App.Database.Migration.V2_1_0_001 Kupo.App.Database.Migration.V2_1_0_002 Kupo.App.Database.Migration.V2_1_0_003 @@ -205,7 +207,6 @@ library , bytestring , cardano-crypto-class , cardano-crypto-wrapper - , cardano-data , cardano-diffusion , cardano-ledger-allegra , cardano-ledger-alonzo @@ -356,6 +357,7 @@ test-suite unit Test.Kupo.Data.OgmiosSpec Test.Kupo.Data.Pattern.Fixture Test.Kupo.Data.PatternSpec + Test.Kupo.Data.SubTransactionSpec Test.Kupo.Data.UtxoConstraint Test.Kupo.Fixture Test.Kupo.OptionsSpec @@ -411,6 +413,10 @@ test-suite unit , base , bytestring , cardano-crypto-class + , cardano-ledger-alonzo + , cardano-ledger-core + , cardano-ledger-dijkstra + , cardano-protocol , containers , contra-tracer , directory @@ -423,8 +429,10 @@ test-suite unit , io-classes:si-timers , io-sim , kupo + , lens , lens-aeson , openapi3 + , ouroboros-consensus:cardano , process , quickcheck-state-machine , relude diff --git a/package.yaml b/package.yaml index 30ca6d17..ce46f243 100644 --- a/package.yaml +++ b/package.yaml @@ -63,7 +63,6 @@ library: - bytestring - cardano-crypto-class - cardano-crypto-wrapper - - cardano-data - cardano-ledger-allegra - cardano-ledger-alonzo - cardano-ledger-api @@ -134,6 +133,10 @@ tests: - base - bytestring - cardano-crypto-class + - cardano-ledger-alonzo + - cardano-ledger-core + - cardano-ledger-dijkstra + - cardano-protocol - containers - contra-tracer - directory @@ -145,8 +148,10 @@ tests: - io-classes - io-sim - kupo + - lens - lens-aeson - openapi3 + - ouroboros-consensus:cardano - process - QuickCheck - quickcheck-state-machine diff --git a/src/Kupo/App.hs b/src/Kupo/App.hs index 3cbe5303..9304033b 100644 --- a/src/Kupo/App.hs +++ b/src/Kupo/App.hs @@ -561,7 +561,7 @@ rollForwardAll tr inputManagement notifyTip Database{..} patterns blks = do onSpentInputs :: Tip -> SlotNo - -> Map (TransactionId, SlotNo) [(Pattern, InputIndex, Maybe BinaryData)] + -> Map (TransactionId, Maybe TransactionId, SlotNo) [(Pattern, InputIndex, Maybe BinaryData)] -> DBTransaction m Int onSpentInputs = case inputManagement of MarkSpentInputs -> diff --git a/src/Kupo/App/Database/Migration.hs b/src/Kupo/App/Database/Migration.hs index 3b01e2eb..a81b02d2 100644 --- a/src/Kupo/App/Database/Migration.hs +++ b/src/Kupo/App/Database/Migration.hs @@ -101,6 +101,7 @@ import qualified Kupo.App.Database.Migration.V2_0_0_beta_001 as V2_0_0_beta_001 import qualified Kupo.App.Database.Migration.V2_10_0_001 as V2_10_0_001 import qualified Kupo.App.Database.Migration.V2_12_0_001 as V2_12_0_001 import qualified Kupo.App.Database.Migration.V2_12_0_002 as V2_12_0_002 +import qualified Kupo.App.Database.Migration.V2_12_0_003 as V2_12_0_003 import qualified Kupo.App.Database.Migration.V2_1_0_001 as V2_1_0_001 import qualified Kupo.App.Database.Migration.V2_1_0_002 as V2_1_0_002 import qualified Kupo.App.Database.Migration.V2_1_0_003 as V2_1_0_003 @@ -126,6 +127,7 @@ migrations = , V2_10_0_001.migration , V2_12_0_001.migration , V2_12_0_002.migration + , V2_12_0_003.migration ] -- | Throw 'UnknownMigrationsException' if a newer Kupo migrated the database. It only reads, so it diff --git a/src/Kupo/App/Database/Migration/V2_12_0_003.hs b/src/Kupo/App/Database/Migration/V2_12_0_003.hs new file mode 100644 index 00000000..69c247c7 --- /dev/null +++ b/src/Kupo/App/Database/Migration/V2_12_0_003.hs @@ -0,0 +1,24 @@ +-- 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/. + +{-# LANGUAGE TemplateHaskell #-} + +module Kupo.App.Database.Migration.V2_12_0_003 + ( migration + ) where + +import Data.FileEmbed + ( embedFile + ) +import Kupo.App.Database.Migration.Definition + ( Migration (..) + , MigrationAction (..) + ) + +migration :: Migration +migration = Migration + { migrationId = "v2.12.0/003" + , migrationSummary = "Add sub-transaction columns to inputs" + , migrationAction = Automatic $(embedFile "db/v2.12.0/003.sql") + } diff --git a/src/Kupo/App/Database/SQLite.hs b/src/Kupo/App/Database/SQLite.hs index fa7896ce..f62f7fb4 100644 --- a/src/Kupo/App/Database/SQLite.hs +++ b/src/Kupo/App/Database/SQLite.hs @@ -114,6 +114,7 @@ import Kupo.Data.Cardano ( SlotNo (..) , mkOutputReference , slotNoToText + , transactionIdToBytes ) import Kupo.Data.Configuration ( DeferIndexesInstallation (..) @@ -625,6 +626,9 @@ mkDatabase tr mode longestRollback bracketConnection = Database , maybe SQLNull (SQLInteger . fromIntegral) spentAtSlotNo , SQLNull , SQLNull + , maybe SQLNull (SQLInteger . fromIntegral) subTransactionIndex + , maybe SQLNull SQLBlob topLevelTransactionId + , maybe SQLNull SQLBlob spentByTopLevelTransactionId ] case datum of Nothing -> @@ -649,13 +653,14 @@ mkDatabase tr mode longestRollback bracketConnection = Database withTotalChanges conn $ mapM_ (execute_ conn . deleteInputsQry) refs - , markInputs = \(parentRef, fromIntegral . unSlotNo -> slotNo) refs -> ReaderT $ \conn -> do + , markInputs = \(parentRef, topLevelRef, fromIntegral . unSlotNo -> slotNo) refs -> ReaderT $ \conn -> do withTotalChanges conn $ forM_ refs $ \(ref, ix, redeemer) -> do execute conn (markInputsQry ref) [ SQLInteger slotNo , SQLBlob (outputReferenceToRow $ mkOutputReference parentRef ix) , maybe SQLNull (SQLBlob . redeemerToRow) redeemer + , maybe SQLNull (SQLBlob . transactionIdToBytes) topLevelRef ] , pruneInputs = ReaderT $ \conn -> do @@ -676,6 +681,9 @@ mkDatabase tr mode longestRollback bracketConnection = Database , matchMaybeBytes -> spentAtHeaderHash , matchMaybeBytes -> spentBy , matchMaybeBytes -> spentWith + , matchMaybeWord64 -> subTransactionIndex + , matchMaybeBytes -> topLevelTransactionId + , matchMaybeBytes -> spentByTopLevelTransactionId , matchMaybeBytes -> datumBinaryData , matchMaybeBytes -> scriptBinaryData ] -> @@ -864,7 +872,7 @@ deleteInputsQry pattern_ = markInputsQry :: Pattern -> Query markInputsQry pattern_ = Query $ unwords - [ "UPDATE inputs SET spent_at = ?, spent_by = ?, spent_with = ?" + [ "UPDATE inputs SET spent_at = ?, spent_by = ?, spent_with = ?, spent_by_top_level_transaction_id = ?" , additionalJoin , "WHERE" , whereClause @@ -936,7 +944,9 @@ foldInputsQry pattern_ slotRange statusFlag referenceFlag sortDirection = \inputs.datum_info, inputs.script_hash, \ \inputs.created_at, createdAt.header_hash, \ \inputs.spent_at, spentAt.header_hash, \ - \inputs.spent_by, inputs.spent_with" + \inputs.spent_by, inputs.spent_with, \ + \inputs.sub_transaction_index, inputs.top_level_transaction_id, \ + \inputs.spent_by_top_level_transaction_id" <> case referenceFlag of AsReference -> ", NULL as datum, NULL as script" InlineAll -> ", datums.binary_data as datum, scripts.script as script" @@ -955,6 +965,8 @@ foldInputsQry pattern_ slotRange statusFlag referenceFlag sortDirection = <> " ORDER BY \ \inputs.created_at " <> ordering <> ", \ \inputs.transaction_index " <> ordering <> ", \ + \(inputs.sub_transaction_index IS NULL) " <> ordering <> ", \ + \inputs.sub_transaction_index " <> ordering <> ", \ \inputs.output_index " <> ordering where inputs = "SELECT * FROM inputs " diff --git a/src/Kupo/App/Database/Types.hs b/src/Kupo/App/Database/Types.hs index 83cb28aa..ea1709e0 100644 --- a/src/Kupo/App/Database/Types.hs +++ b/src/Kupo/App/Database/Types.hs @@ -88,7 +88,7 @@ data Database (m :: Type -> Type) = Database -> DBTransaction m Int , markInputs - :: (TransactionId, SlotNo) + :: (TransactionId, Maybe TransactionId, SlotNo) -> [(Pattern, InputIndex, Maybe BinaryData)] -> DBTransaction m Int diff --git a/src/Kupo/App/Http.hs b/src/Kupo/App/Http.hs index 4ba5075b..feb1e480 100644 --- a/src/Kupo/App/Http.hs +++ b/src/Kupo/App/Http.hs @@ -188,7 +188,6 @@ import qualified Data.Aeson.Encoding as Json import qualified Data.Aeson.Types as Json import qualified Data.ByteString as BS import qualified Data.List as L -import qualified Data.Map as Map import qualified Data.Set as Set import qualified GHC.Clock import qualified Kupo.Data.Http.Default as Default @@ -701,6 +700,8 @@ handleGetMatches resHeaders reqHeaders patternQuery queryParams Database{..} = h \result -> fst (outputReference result) == outRef FilterByTransactionId transactionId -> \result -> (getTransactionId . fst . outputReference) result == transactionId + FilterByTopLevelTransactionId transactionId -> + \result -> (fst <$> subTransactionOf result) == Just transactionId in \yield result -> when (predicateA result && predicateB result) (yield result) @@ -816,16 +817,23 @@ handleGetMetadata baseHeaders slotArg queryParams Database{..} fetchBlock = \yield done -> do either throwIO pure (checkSubTransactions blk) traverse_ yield $ foldBlock - (\ix tx -> - if isNothing filterBy || Just (getTransactionId tx) == filterBy then - Map.alter (const $ userDefinedMetadata @block tx) ix - else - identity - ) - mempty + (\_ix tx -> (<>) (filter isSelected $ metadataOf tx)) + [] blk done atomically (takeTMVar response) + where + isSelected (transactionId, _topLevelTransactionId, _hash, _metadata) = + isNothing filterBy || Just transactionId == filterBy + + -- A transaction's sub-transactions come first, in the order the ledger applies them. + metadataOf tx = + catMaybes $ + fmap (entry (Just tx)) (subTransactions @block tx) <> [entry Nothing tx] + + entry topLevel tx = do + (hash, metadata) <- userDefinedMetadata @block tx + pure (getTransactionId tx, getTransactionId <$> topLevel, hash, metadata) -- -- /patterns diff --git a/src/Kupo/Data/Cardano.hs b/src/Kupo/Data/Cardano.hs index 0b750983..12c38ce2 100644 --- a/src/Kupo/Data/Cardano.hs +++ b/src/Kupo/Data/Cardano.hs @@ -104,7 +104,6 @@ import qualified Cardano.Ledger.Alonzo.TxWits as Ledger import qualified Cardano.Ledger.Babbage.Core as Ledger import qualified Cardano.Ledger.Block as Ledger import qualified Cardano.Ledger.Dijkstra.Core as Ledger -import qualified Data.OMap.Strict as OMap import qualified Data.Set as Set -- IsBlock @@ -127,6 +126,22 @@ class HasTransactionId (BlockBody block) => IsBlock (block :: Type) where :: block -> Either UnsupportedSubTransactions () + -- | The sub-transactions of a top-level transaction, in the order the ledger applies them. + -- None by default. + subTransactions + :: BlockBody block + -> [BlockBody block] + subTransactions = + const [] + + -- | The sub-transactions of a phase-2 invalid top-level transaction, which the ledger discards. + -- None by default. + discardedSubTransactions + :: BlockBody block + -> [BlockBody block] + discardedSubTransactions = + const [] + spentInputs :: BlockBody block -> Set Input @@ -155,19 +170,14 @@ class HasTransactionId (BlockBody block) => IsBlock (block :: Type) where -- Block --- | Raised on a block carrying Dijkstra sub-transactions, which are not indexed yet. +-- | Raised on a Dijkstra block whose sub-transactions Kupo cannot index. data UnsupportedSubTransactions - = UnsupportedSubTransactions !TransactionId - -- ^ A Dijkstra transaction carries sub-transactions. - | UnverifiableSubTransactions !Point + = UnverifiableSubTransactions !Point -- ^ A Dijkstra block whose transactions Kupo cannot inspect. deriving (Show) instance Exception UnsupportedSubTransactions where displayException = \case - UnsupportedSubTransactions txId -> - "Dijkstra transaction " <> toString (transactionIdToText txId) - <> " carries sub-transactions, which Kupo does not index yet." UnverifiableSubTransactions point -> "Ogmios does not serialise Dijkstra transactions yet, so Kupo cannot index the block at slot " <> toString (slotNoToText (getPointSlotNo point)) @@ -178,6 +188,8 @@ instance IsBlock Void where getPoint = absurd foldBlock _ _ = absurd checkSubTransactions = absurd + subTransactions = absurd + discardedSubTransactions = absurd spentInputs = absurd mapMaybeOutputs _ = absurd witnessedDatums = absurd @@ -224,20 +236,64 @@ instance IsBlock Block where BlockDijkstra (ShelleyBlock (Ledger.Block _ txs) _) -> foldrWithIndex (\ix -> fn ix . TransactionDijkstra) result (txs ^. Ledger.txSeqBlockBodyL) - checkSubTransactions = \case - BlockDijkstra (ShelleyBlock (Ledger.Block _ txs) _) -> - traverse_ rejectSubTransactions (txs ^. Ledger.txSeqBlockBodyL) - _ -> - Right () - where - -- Sub-transactions are not indexed yet: fail loudly instead of - -- silently dropping their inputs and outputs. - rejectSubTransactions - :: Ledger.Tx Ledger.TopTx DijkstraEra - -> Either UnsupportedSubTransactions () - rejectSubTransactions tx = - unless (OMap.null (tx ^. Ledger.bodyTxL . Ledger.subTransactionsTxBodyL)) $ - Left (UnsupportedSubTransactions (Ledger.txIdTx @DijkstraEra tx)) + checkSubTransactions = + const (Right ()) + + subTransactions + :: Transaction + -> [Transaction] + subTransactions = \case + TransactionByron{} -> + [] + TransactionShelley{} -> + [] + TransactionAllegra{} -> + [] + TransactionMary{} -> + [] + TransactionAlonzo{} -> + [] + TransactionBabbage{} -> + [] + TransactionConway{} -> + [] + TransactionDijkstra tx -> + -- A phase-2 invalid transaction applies none of its sub-transactions. + case tx ^. Ledger.isPhase2ValidTxL of + Ledger.Phase2Valid -> + SubTransactionDijkstra <$> toList (tx ^. Ledger.bodyTxL . Ledger.subTransactionsTxBodyL) + Ledger.Phase2Invalid -> + [] + -- Sub-transactions cannot themselves contain sub-transactions. + SubTransactionDijkstra{} -> + [] + + discardedSubTransactions + :: Transaction + -> [Transaction] + discardedSubTransactions = \case + TransactionByron{} -> + [] + TransactionShelley{} -> + [] + TransactionAllegra{} -> + [] + TransactionMary{} -> + [] + TransactionAlonzo{} -> + [] + TransactionBabbage{} -> + [] + TransactionConway{} -> + [] + TransactionDijkstra tx -> + case tx ^. Ledger.isPhase2ValidTxL of + Ledger.Phase2Valid -> + [] + Ledger.Phase2Invalid -> + SubTransactionDijkstra <$> toList (tx ^. Ledger.bodyTxL . Ledger.subTransactionsTxBodyL) + SubTransactionDijkstra{} -> + [] spentInputs :: Transaction @@ -275,6 +331,8 @@ instance IsBlock Block where tx ^. Ledger.bodyTxL . Ledger.inputsTxBodyL Ledger.Phase2Invalid -> tx ^. Ledger.bodyTxL . Ledger.collateralInputsTxBodyL + SubTransactionDijkstra tx -> + tx ^. Ledger.bodyTxL . Ledger.inputsTxBodyL where transformByron (Ledger.Byron.TxInUtxo txId ix) = mkOutputReference @@ -387,6 +445,14 @@ instance IsBlock Block where [] SJust r -> traverseAndTransform identity txId meta start (r :<| mempty) + SubTransactionDijkstra tx -> + let + body = tx ^. Ledger.bodyTxL + txId = Ledger.txIdTxBody @DijkstraEra body + outs = body ^. Ledger.outputsTxBodyL + meta = tx ^. Ledger.auxDataTxL & strictMaybe emptyMetadata identity + in + traverseAndTransform identity txId meta 0 outs where traverseAndTransformByron :: forall output. () @@ -449,6 +515,8 @@ instance IsBlock Block where fromConwayData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) TransactionDijkstra tx -> fromDijkstraData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) + SubTransactionDijkstra tx -> + fromDijkstraData <$> Ledger.unTxDats (tx ^. Ledger.witsTxL . Ledger.datsTxWitsL) witnessedScripts :: Transaction @@ -494,6 +562,13 @@ instance IsBlock Block where (tx ^. Ledger.auxDataTxL) & scriptsFromOutputs (tx ^. Ledger.bodyTxL . Ledger.outputsTxBodyL) + SubTransactionDijkstra tx -> + ( tx ^. Ledger.witsTxL . Ledger.scriptTxWitsL + ) & strictMaybe identity + (scriptFromAlonzoAuxiliaryData identity) + (tx ^. Ledger.auxDataTxL) + & scriptsFromOutputs + (tx ^. Ledger.bodyTxL . Ledger.outputsTxBodyL) userDefinedMetadata :: Transaction @@ -549,6 +624,12 @@ instance IsBlock Block where Nothing SJust auxData -> Just (hashMetadata auxData, auxData) + SubTransactionDijkstra tx -> + case tx ^. Ledger.auxDataTxL of + SNothing -> + Nothing + SJust auxData -> + Just (hashMetadata auxData, auxData) spendRedeemer :: Transaction @@ -572,3 +653,5 @@ instance IsBlock Block where Just (RedeemersConway (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) TransactionDijkstra tx -> Just (RedeemersDijkstra (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) + SubTransactionDijkstra tx -> + Just (RedeemersDijkstra (tx ^. Ledger.witsTxL . Ledger.rdmrsTxWitsL)) diff --git a/src/Kupo/Data/Cardano/Metadata.hs b/src/Kupo/Data/Cardano/Metadata.hs index 95be51b0..e54a5208 100644 --- a/src/Kupo/Data/Cardano/Metadata.hs +++ b/src/Kupo/Data/Cardano/Metadata.hs @@ -26,6 +26,10 @@ import Kupo.Data.Cardano.MetadataHash ( MetadataHash , metadataHashToJson ) +import Kupo.Data.Cardano.TransactionId + ( TransactionId + , transactionIdToJson + ) import Ouroboros.Consensus.Util ( eitherToMaybe ) @@ -157,10 +161,14 @@ metadataFromJson = fmap mkMetadata . Json.withObject "Metadata" ) pure (Ledger.Map xs) -metadataToJson' :: (MetadataHash, Metadata) -> Json.Encoding -metadataToJson' (hash, meta) = +-- | The metadata of a transaction, with the id of that transaction and, for a +-- sub-transaction, the id of its top-level transaction. +metadataToJson' :: (TransactionId, Maybe TransactionId, MetadataHash, Metadata) -> Json.Encoding +metadataToJson' (transactionId, topLevelTransactionId, hash, meta) = encodeObject - [ ("hash", metadataHashToJson hash) + [ ("transaction_id", transactionIdToJson transactionId) + , ("top_level_transaction_id", maybe Json.null_ transactionIdToJson topLevelTransactionId) + , ("hash", metadataHashToJson hash) , ("raw", Json.text (metadataToText meta)) , ("schema", metadataToJson meta) ] diff --git a/src/Kupo/Data/Cardano/Transaction.hs b/src/Kupo/Data/Cardano/Transaction.hs index 87fc7594..d849ee17 100644 --- a/src/Kupo/Data/Cardano/Transaction.hs +++ b/src/Kupo/Data/Cardano/Transaction.hs @@ -36,6 +36,8 @@ data Transaction !(Ledger.Tx Ledger.TopTx ConwayEra) | TransactionDijkstra !(Ledger.Tx Ledger.TopTx DijkstraEra) + | SubTransactionDijkstra + !(Ledger.Tx Ledger.SubTx DijkstraEra) instance HasTransactionId Transaction where getTransactionId = \case @@ -55,3 +57,5 @@ instance HasTransactionId Transaction where Ledger.txIdTx @ConwayEra tx TransactionDijkstra tx -> Ledger.txIdTx @DijkstraEra tx + SubTransactionDijkstra tx -> + Ledger.txIdTx @DijkstraEra tx diff --git a/src/Kupo/Data/Cardano/TransactionIndex.hs b/src/Kupo/Data/Cardano/TransactionIndex.hs index 83b2dcf8..408fefdc 100644 --- a/src/Kupo/Data/Cardano/TransactionIndex.hs +++ b/src/Kupo/Data/Cardano/TransactionIndex.hs @@ -6,5 +6,8 @@ import qualified Data.Aeson as Json type TransactionIndex = Word16 +-- | Position of a sub-transaction among the sub-transactions of its top-level transaction. +type SubTransactionIndex = Word64 + transactionIndexToJson :: TransactionIndex -> Json.Encoding transactionIndexToJson = toEncoding diff --git a/src/Kupo/Data/Database.hs b/src/Kupo/Data/Database.hs index 53d3608d..71284052 100644 --- a/src/Kupo/Data/Database.hs +++ b/src/Kupo/Data/Database.hs @@ -154,6 +154,9 @@ data Input = Input , spentAtHeaderHash :: !(Maybe ByteString) , spentBy :: !(Maybe ByteString) , spentWith :: !(Maybe ByteString) + , subTransactionIndex :: !(Maybe Word64) + , topLevelTransactionId :: !(Maybe ByteString) + , spentByTopLevelTransactionId :: !(Maybe ByteString) } deriving (Show) resultFromRow @@ -178,6 +181,10 @@ resultFromRow row = App.Result outputReferenceFromRow <$> spentBy row , App.spentWith = redeemerFromRow <$> spentWith row + , App.subTransactionOf = + (,) <$> (unsafeTransactionIdFromBytes <$> topLevelTransactionId row) <*> subTransactionIndex row + , App.spentByTopLevelTransactionId = + unsafeTransactionIdFromBytes <$> spentByTopLevelTransactionId row } resultToRow @@ -215,6 +222,14 @@ resultToRow x = spentWith = redeemerToRow <$> App.spentWith x + (topLevelTransactionId, subTransactionIndex) = + ( transactionIdToBytes . fst <$> App.subTransactionOf x + , snd <$> App.subTransactionOf x + ) + + spentByTopLevelTransactionId = + transactionIdToBytes <$> App.spentByTopLevelTransactionId x + -- -- Policy -- diff --git a/src/Kupo/Data/Http/Error.hs b/src/Kupo/Data/Http/Error.hs index 6741cb58..83ad47c5 100644 --- a/src/Kupo/Data/Http/Error.hs +++ b/src/Kupo/Data/Http/Error.hs @@ -114,6 +114,8 @@ invalidMatchFilter = { hint = "Invalid or incomplete filter query parameters! 'policy_id' and \ \'asset_name' query values must be encoded in base16. Be aware \ \that you MUST specify a 'policy_id' if you specify an 'asset_name'. \ + \'top_level_transaction_id' cannot be combined with 'policy_id', \ + \'transaction_id' or 'output_index'. \ \In case of doubts, check the documentation at: !" , details = Nothing } diff --git a/src/Kupo/Data/Http/FilterMatchesBy.hs b/src/Kupo/Data/Http/FilterMatchesBy.hs index b06d79ad..367800c0 100644 --- a/src/Kupo/Data/Http/FilterMatchesBy.hs +++ b/src/Kupo/Data/Http/FilterMatchesBy.hs @@ -27,6 +27,7 @@ data FilterMatchesBy = FilterByAssetId !AssetId | FilterByPolicyId !PolicyId | FilterByTransactionId !TransactionId + | FilterByTopLevelTransactionId !TransactionId | FilterByOutputReference !OutputReference | NoFilter deriving (Eq, Show, Generic) @@ -40,6 +41,10 @@ data FilterMatchesBy -- The latter can be specified alone, whereas the former can only be specified -- if 'policy_id' is also present. -- +-- 'top_level_transaction_id' selects the outputs of the sub-transactions of a +-- transaction. It cannot be combined with 'policy_id', 'transaction_id' or +-- 'output_index'. +-- -- For examples: -- -- ✓ ?policy_id=123 @@ -49,6 +54,7 @@ data FilterMatchesBy -- ✓ ?transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f -- ✓ ?foo=bar&transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f -- ✓ ?transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f&output_index=14 +-- ✓ ?top_level_transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f -- -- x ?asset_name=456 -- x ?policy_id=123&policy_id=456 @@ -57,27 +63,28 @@ data FilterMatchesBy -- x ?transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f&output_index=14&output_index=42 -- x ?output_index=14 -- x ?policy_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1bea&transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f +-- x ?transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f&top_level_transaction_id=8beca7a84b0ed6d6c22d5f0edb8964a48b9566db20ef2a42c5ae609553a3fd89 +-- x ?top_level_transaction_id=d0ae0c50209357e1356333b10d3a59ff4732e493f06c0ed9e82d1beacdd0343f&output_index=14 -- filterMatchesBy :: Http.Query -> Maybe FilterMatchesBy -filterMatchesBy = search Nothing Nothing +filterMatchesBy = search Nothing Nothing Nothing where - search byPolicyId byTransactionId = \case + search byPolicyId byTransactionId byTopLevelTransactionId = \case [] -> - case (byPolicyId, byTransactionId) of - (Just{}, Just{}) -> Nothing - (Just f, Nothing) -> Just f - (Nothing, Just f) -> Just f - (Nothing, Nothing) -> Just NoFilter + case catMaybes [byPolicyId, byTransactionId, byTopLevelTransactionId] of + [] -> Just NoFilter + [f] -> Just f + _ -> Nothing ("policy_id", Just bytes):rest -> do str <- either (const Nothing) pure (decodeUtf8' bytes) guard (isNothing byPolicyId) policyId <- policyIdFromText str - search (Just (FilterByPolicyId policyId)) byTransactionId rest + search (Just (FilterByPolicyId policyId)) byTransactionId byTopLevelTransactionId rest ("asset_name", Just bytes):rest -> do str <- either (const Nothing) pure (decodeUtf8' bytes) - policyId <- case search byPolicyId byTransactionId rest of + policyId <- case search byPolicyId byTransactionId byTopLevelTransactionId rest of Just (FilterByPolicyId policyId) -> Just policyId _noPolicyId -> @@ -86,7 +93,7 @@ filterMatchesBy = search Nothing Nothing pure $ FilterByAssetId (policyId, assetName) ("output_index", Just bytes):rest -> do str <- either (const Nothing) pure (decodeUtf8' bytes) - txId <- case search byPolicyId byTransactionId rest of + txId <- case search byPolicyId byTransactionId byTopLevelTransactionId rest of Just (FilterByTransactionId tId) -> Just tId _noTransactionId -> @@ -97,6 +104,11 @@ filterMatchesBy = search Nothing Nothing str <- either (const Nothing) pure (decodeUtf8' bytes) guard (isNothing byTransactionId) outputRef <- transactionIdFromText str - search byPolicyId (Just (FilterByTransactionId outputRef)) rest + search byPolicyId (Just (FilterByTransactionId outputRef)) byTopLevelTransactionId rest + ("top_level_transaction_id", Just bytes):rest -> do + str <- either (const Nothing) pure (decodeUtf8' bytes) + guard (isNothing byTopLevelTransactionId) + transactionId <- transactionIdFromText str + search byPolicyId byTransactionId (Just (FilterByTopLevelTransactionId transactionId)) rest _:rest -> - search byPolicyId byTransactionId rest + search byPolicyId byTransactionId byTopLevelTransactionId rest diff --git a/src/Kupo/Data/Pattern.hs b/src/Kupo/Data/Pattern.hs index c8b102a2..3db9560e 100644 --- a/src/Kupo/Data/Pattern.hs +++ b/src/Kupo/Data/Pattern.hs @@ -53,6 +53,7 @@ import Kupo.Data.Cardano , ScriptHash , ScriptReference (..) , SlotNo + , SubTransactionIndex , TransactionId , TransactionIndex , Value @@ -442,6 +443,10 @@ data Result = Result , spentAt :: !(Maybe Point) , spentBy :: !(Maybe OutputReference) , spentWith :: !(Maybe BinaryData) + , subTransactionOf :: !(Maybe (TransactionId, SubTransactionIndex)) + -- ^ For an output of a sub-transaction: the id of its top-level transaction, and its position in it. + , spentByTopLevelTransactionId :: !(Maybe TransactionId) + -- ^ For an input spent by a sub-transaction: the id of its top-level transaction. } deriving (Show, Eq) resultToJson @@ -456,6 +461,10 @@ resultToJson referenceFlag quantityEncoding Result{..} = Json.pairs $ mconcat (transactionIdToJson (getTransactionId $ fst outputReference)) , Json.pair "output_index" (outputIndexToJson (getOutputIndex $ fst outputReference)) + , Json.pair "sub_transaction_index" + (maybe Json.null_ (toEncoding . snd) subTransactionOf) + , Json.pair "top_level_transaction_id" + (maybe Json.null_ (transactionIdToJson . fst) subTransactionOf) , Json.pair "address" (addressToJson address) , Json.pair "value" @@ -493,6 +502,8 @@ resultToJson referenceFlag quantityEncoding Result{..} = Json.pairs $ mconcat (headerHashToJson (unsafeGetPointHeaderHash point)) , Json.pair "transaction_id" (maybe Json.null_ (transactionIdToJson . getTransactionId) spentBy) + , Json.pair "top_level_transaction_id" + (maybe Json.null_ transactionIdToJson spentByTopLevelTransactionId) , Json.pair "input_index" (maybe Json.null_ (outputIndexToJson . getOutputIndex) spentBy) , Json.pair "redeemer" @@ -532,7 +543,8 @@ data Codecs result bin script policy = Codecs -- | A higher-level record to represent the aggregation of matched results. data Match result bin script policy = Match - { consumed :: !(Map (TransactionId, SlotNo) [(Pattern, InputIndex, Maybe BinaryData)]) + { consumed :: !(Map (TransactionId, Maybe TransactionId, SlotNo) [(Pattern, InputIndex, Maybe BinaryData)]) + -- ^ Spent inputs, by spending transaction, its top-level transaction if it is a sub-transaction, and slot. , produced :: ![result] , datums :: ![bin] , scripts :: ![script] @@ -568,36 +580,46 @@ matchBlock -> block -> Match result bin script policy matchBlock Codecs{..} patterns blk = - let pt = getPoint blk in foldBlock (fn pt) mempty blk + let pt = getPoint blk in foldBlock (fnBatch pt) mempty blk where + -- Sub-transactions share the transaction index of their top-level transaction. + -- A discarded (phase-2 invalid) transaction or sub-transaction still puts its datums + -- and scripts on chain, so only those are collected, for lookup by hash. + fnBatch + :: Point + -> TransactionIndex + -> BlockBody block + -> Match result bin script policy + -> Match result bin script policy + fnBatch pt ix tx result = + foldr + (\(subIx, subTx) -> fn pt ix (Just (getTransactionId tx, subIx)) subTx) + (fn pt ix Nothing tx (foldr collectWitnesses result (discardedSubTransactions @block tx))) + (zip [0 ..] (subTransactions @block tx)) + fn :: Point -> TransactionIndex + -> Maybe (TransactionId, SubTransactionIndex) -> BlockBody block -> Match result bin script policy -> Match result bin script policy - fn pt ix tx Match{consumed, produced, datums, scripts, policies} = Match + fn pt ix sub tx Match{consumed, produced, datums, scripts, policies} = collectWitnesses tx Match { consumed = Map.alter (\st -> Just $ foldrWithIndex (\i ref refs -> (MatchOutputReference ref, i, spendRedeemer @block tx i):refs) (fromMaybe mempty st) (spentInputs @block tx) ) - (getTransactionId tx, getPointSlotNo pt) + (getTransactionId tx, fst <$> sub, getPointSlotNo pt) consumed , produced = newProduced - , datums = Map.foldrWithKey - (\k v accum -> toBinaryData k v : accum) - datums - (witnessedDatums @block tx) + , datums - , scripts = Map.foldrWithKey - (\k v accum -> toScript k v : accum) - scripts - (witnessedScripts @block tx) + , scripts , policies = newPolicies @@ -608,20 +630,37 @@ matchBlock Codecs{..} patterns blk = (\pattern_ -> flip (foldr (\(r, p) (rs, ps) -> (r:rs, Set.union p ps))) - (mapMaybeOutputs @block (match pt ix pattern_) tx) + (mapMaybeOutputs @block (match pt ix sub pattern_) tx) ) (produced, policies) patterns + collectWitnesses + :: BlockBody block + -> Match result bin script policy + -> Match result bin script policy + collectWitnesses tx result@Match{datums, scripts} = result + { datums = Map.foldrWithKey + (\k v accum -> toBinaryData k v : accum) + datums + (witnessedDatums @block tx) + + , scripts = Map.foldrWithKey + (\k v accum -> toScript k v : accum) + scripts + (witnessedScripts @block tx) + } + match :: Point -> TransactionIndex + -> Maybe (TransactionId, SubTransactionIndex) -> Pattern -> OutputReference -> Output -> Metadata -> Maybe (result, Set policy) - match pt ix m outRef output metadata = do + match pt ix sub m outRef output metadata = do matching outRef output metadata m $> ( toResult Result { outputReference = (outRef, ix) @@ -633,6 +672,8 @@ matchBlock Codecs{..} patterns blk = , spentAt = Nothing , spentBy = Nothing , spentWith = Nothing + , subTransactionOf = sub + , spentByTopLevelTransactionId = Nothing } , foldrValue (\policy _ -> Set.insert (toPolicy outRef policy)) diff --git a/test/Test/Kupo/App/Database/Migration/V2_12_0_002Spec.hs b/test/Test/Kupo/App/Database/Migration/V2_12_0_002Spec.hs index 74d498d9..46adca74 100644 --- a/test/Test/Kupo/App/Database/Migration/V2_12_0_002Spec.hs +++ b/test/Test/Kupo/App/Database/Migration/V2_12_0_002Spec.hs @@ -196,7 +196,7 @@ spec = parallel $ context "v2.12.0/002" $ do let before = storedRows FromLastInput firstSpend <> [unmatched] <> storedRows FromLastInput secondSpend withSpends 42_000 ["*"] before $ \conn -> do crashing <- crashingInSecondBatch - migrateDatabase nullTracer conn True (take 11 migrations <> [crashing]) + migrateDatabase nullTracer conn True (take 11 migrations <> [crashing] <> drop 12 migrations) `shouldThrow` (== SimulatedCrash) repairRow conn `shouldReturn` [("pending", Just $ cursorBytes (100 + windowSlots - 1) 1 1)] spentRows conn `shouldReturn` diff --git a/test/Test/Kupo/App/Database/MigrationSpec.hs b/test/Test/Kupo/App/Database/MigrationSpec.hs index 961be802..7f67d986 100644 --- a/test/Test/Kupo/App/Database/MigrationSpec.hs +++ b/test/Test/Kupo/App/Database/MigrationSpec.hs @@ -133,7 +133,7 @@ spec = parallel $ do and (zipWith (<) keys (drop 1 keys)) `shouldBe` True specify "the known migrations are automatic, apart from the spent input repair" $ - migrationKind <$> migrations `shouldBe` (AutomaticKind <$ take 11 knownIds) <> [RepairKind] + migrationKind <$> migrations `shouldBe` (AutomaticKind <$ take 11 knownIds) <> [RepairKind, AutomaticKind] specify "a repair names an earlier migration as the one that introduced its data" $ [ repairId @@ -249,18 +249,27 @@ spec = parallel $ do userVersion conn `shouldReturn` [10] addCheckpoint conn runMigrations nullTracer conn migrations - userVersion conn `shouldReturn` [12] + userVersion conn `shouldReturn` [13] -- Backfilled rows have no kupo_version and no applied_at. registryRows conn `shouldReturn` [ (migrationId, "applied", isRegistry, isRegistry) | Migration{migrationId} <- take 11 migrations , let isRegistry = migrationId == "v2.12.0/001" ] - <> [("v2.12.0/002", "pending", True, False)] + <> [("v2.12.0/002", "pending", True, False), ("v2.12.0/003", "applied", True, True)] + + specify "an upgrade from user_version 12 adds empty sub-transaction columns to inputs" $ withDatabase $ \conn -> do + runMigrations nullTracer conn (take 12 migrations) + addCheckpoint conn + execute_ conn "INSERT INTO inputs (ext_output_reference, address, value, created_at) VALUES (zeroblob(36), 'addr', x'00', 42)" + runMigrations nullTracer conn migrations + userVersion conn `shouldReturn` [13] + query_ conn "SELECT sub_transaction_index, top_level_transaction_id, spent_by_top_level_transaction_id FROM inputs" + `shouldReturn` [(Nothing, Nothing, Nothing) :: (Maybe Int, Maybe ByteString, Maybe ByteString)] specify "a fresh database records repairs as skipped" $ withDatabase $ \conn -> do runMigrations nullTracer conn (migrations <> [synthetic RepairKind "test/repair"]) - userVersion conn `shouldReturn` [13] + userVersion conn `shouldReturn` [14] registryRow conn "v2.12.0/002" `shouldReturn` [("skipped", Nothing)] registryRow conn "test/repair" `shouldReturn` [("skipped", Nothing)] @@ -270,7 +279,7 @@ spec = parallel $ do addCheckpoint conn runMigrations nullTracer conn $ migrations <> [synthetic RepairKind "test/repair", syntheticTable Automatic "after"] - userVersion conn `shouldReturn` [14] + userVersion conn `shouldReturn` [15] registryRow conn "test/repair" `shouldReturn` [("pending", Just 42)] registryRow conn "test/after" `shouldReturn` [("applied", Nothing)] syntheticTables conn `shouldReturn` ["synthetic_after"] @@ -286,7 +295,7 @@ spec = parallel $ do ] runMigrations nullTracer conn extended `shouldThrow` isMigrationRequiredFor ["test/blocking", "test/after"] - userVersion conn `shouldReturn` [13] + userVersion conn `shouldReturn` [14] syntheticTables conn `shouldReturn` ["synthetic_before"] registryRow conn "test/before" `shouldReturn` [("applied", Nothing)] registryRow conn "test/blocking" `shouldReturn` [] @@ -510,7 +519,7 @@ spec = parallel $ do reportUnknown `shouldBe` [] -- The database was fresh when Kupo registered the spent input repair. statusState <$> reportMigrations - `shouldBe` (Just Applied <$ take 11 migrations) <> [Just Skipped, Just Pending, Nothing] + `shouldBe` (Just Applied <$ take 11 migrations) <> [Just Skipped, Just Applied, Just Pending, Nothing] drop (length migrations) reportMigrations `shouldBe` [ MigrationStatus { statusId = "test/repair" @@ -675,6 +684,7 @@ knownIds = , "v2.10.0/001" , "v2.12.0/001" , "v2.12.0/002" + , "v2.12.0/003" ] -- Sorts ids such as @v1.0.0-beta/001@ by version, a pre-release before its release, then by diff --git a/test/Test/Kupo/App/Http/Client.hs b/test/Test/Kupo/App/Http/Client.hs index 6797ec91..817dc3fe 100644 --- a/test/Test/Kupo/App/Http/Client.hs +++ b/test/Test/Kupo/App/Http/Client.hs @@ -599,3 +599,12 @@ decodeResult = Json.withObject "Result" $ \o -> Result redeemer <- traverse decodeRedeemer spentAt pure (join redeemer) ) + <*> (do + subTransactionIndex <- o .:? "sub_transaction_index" + parent <- traverse decodeTransactionId =<< o .:? "top_level_transaction_id" + pure (liftA2 (flip (,)) subTransactionIndex parent) + ) + <*> (do + spentAt <- o .:? "spent_at" + join <$> traverse (\spent -> traverse decodeTransactionId =<< spent .:? "top_level_transaction_id") spentAt + ) diff --git a/test/Test/Kupo/App/HttpSpec.hs b/test/Test/Kupo/App/HttpSpec.hs index 6ddaeb48..c2567b3d 100644 --- a/test/Test/Kupo/App/HttpSpec.hs +++ b/test/Test/Kupo/App/HttpSpec.hs @@ -6,6 +6,7 @@ module Test.Kupo.App.HttpSpec ( spec + , healthStub ) where import Data.Aeson @@ -314,6 +315,13 @@ spec = do res & Wai.assertStatus (Http.statusCode Http.status200) res & assertJson True schema + session specification get "/matches?top_level_transaction_id=309706b92ad8340cd6a5d31bf9d2e682fdab9fc8865ee3de14e09dedf9b1b635" $ \assertJson endpoint -> do + let schema = findSchema specification endpoint Http.status200 + res <- Wai.request $ Wai.defaultRequest + & flip Wai.setPath "/matches?top_level_transaction_id=309706b92ad8340cd6a5d31bf9d2e682fdab9fc8865ee3de14e09dedf9b1b635" + res & Wai.assertStatus (Http.statusCode Http.status200) + res & assertJson True schema + session specification get "/patterns" $ \assertJson endpoint -> do let schema = findSchema specification endpoint Http.status200 res <- Wai.request $ Wai.setPath Wai.defaultRequest "/patterns" diff --git a/test/Test/Kupo/Data/DatabaseSpec.hs b/test/Test/Kupo/Data/DatabaseSpec.hs index ab10d64f..dea9e374 100644 --- a/test/Test/Kupo/Data/DatabaseSpec.hs +++ b/test/Test/Kupo/Data/DatabaseSpec.hs @@ -17,6 +17,7 @@ import Database.SQLite.Simple ( Connection , Query (..) , SQLData (..) + , execute , executeMany , execute_ , query_ @@ -78,6 +79,7 @@ import Kupo.Data.Cardano , getOutputIndex , getPointSlotNo , getValue + , mkOutputReference , policyIdToBytes , slotNoToText ) @@ -88,7 +90,8 @@ import Kupo.Data.Configuration , getLongestRollback ) import Kupo.Data.Database - ( SortDirection (..) + ( Input (..) + , SortDirection (..) , addressFromRow , addressToRow , datumFromRow @@ -190,6 +193,7 @@ import Test.QuickCheck.Property ( Testable ) +import qualified Data.ByteString as BS import qualified Data.Set as Set import qualified Data.Text as T import qualified Prelude @@ -225,6 +229,91 @@ spec = parallel $ do ] sort (rowToAddress <$> rows) `shouldBe` results + context "sub-transaction columns" $ do + specify "stores non-NULL values and lets markInputsQry write the spending top-level transaction" $ do + result <- generate genResult + let topLevel = BS.replicate 32 0xaa + let spender = BS.replicate 32 0xbb + let respender = BS.replicate 32 0xcc + let row = (resultToRow result) + { subTransactionIndex = Just 3 + , topLevelTransactionId = Just topLevel + , spentByTopLevelTransactionId = Just spender + } + let selectColumns = + "SELECT sub_transaction_index, top_level_transaction_id, \ + \spent_by_top_level_transaction_id FROM inputs" + (stored, marked) <- withInMemoryDatabase' identity InstallIndexesIfNotExist 10 $ \Database{..} -> do + runTransaction $ do + insertCheckpoints [createdAt result] + insertInputs [row] + runTransaction $ ReaderT $ \conn -> do + stored <- query_ conn selectColumns + execute conn (markInputsQry $ MatchOutputReference $ fst $ outputReference result) + [ SQLInteger 1, SQLNull, SQLNull, SQLBlob respender ] + marked <- query_ conn selectColumns + pure (stored, marked) + stored `shouldBe` [[SQLInteger 3, SQLBlob topLevel, SQLBlob spender]] + marked `shouldBe` [[SQLInteger 3, SQLBlob topLevel, SQLBlob respender]] + + specify "markInputs records the top-level transaction of a spending sub-transaction only" $ do + result <- generate genResult + (spentBySub, spentByTop) <- generate ((,) <$> genOutputReference <*> genOutputReference) + (spender, topLevel) <- generate ((,) <$> genTransactionId <*> genTransactionId) + let unspent ref = resultToRow result + { outputReference = (ref, snd (outputReference result)) + , spentAt = Nothing + , spentBy = Nothing + , spentWith = Nothing + , spentByTopLevelTransactionId = Nothing + } + let slotNo = getPointSlotNo (createdAt result) + spends <- withInMemoryDatabase' identity InstallIndexesIfNotExist 10 $ \Database{..} -> do + runTransaction $ do + insertCheckpoints [createdAt result] + insertInputs (unspent <$> [spentBySub, spentByTop]) + void $ markInputs (spender, Just topLevel, slotNo) [(MatchOutputReference spentBySub, 1, Nothing)] + void $ markInputs (topLevel, Nothing, slotNo) [(MatchOutputReference spentByTop, 0, Nothing)] + acc <- newIORef [] + runTransaction $ foldInputs (MatchAny IncludingBootstrap) Whole NoStatusFlag AsReference Asc + (\Result{outputReference = (ref, _), spentBy = by, spentByTopLevelTransactionId = byTopLevel} -> + modifyIORef' acc ((ref, by, byTopLevel) :) + ) + readIORef acc + sort spends `shouldBe` sort + [ (spentBySub, Just (mkOutputReference spender 1), Just topLevel) + , (spentByTop, Just (mkOutputReference topLevel 0), Nothing) + ] + + specify "orders sub-transaction outputs before top-level ones, and reverses it when descending" $ do + result <- generate genResult + let mkRow txId outputIndex subTransaction = (resultToRow result) + { extendedOutputReference = BS.replicate 32 txId <> BS.pack [0, outputIndex, 0, 7] + , spentAtSlotNo = Nothing + , spentAtHeaderHash = Nothing + , spentBy = Nothing + , spentWith = Nothing + , subTransactionIndex = subTransaction + , topLevelTransactionId = BS.replicate 32 0xee <$ subTransaction + } + let topLevel = mkRow 1 0 Nothing + let subOne = mkRow 2 0 (Just 1) + let subZeroLate = mkRow 3 5 (Just 0) + let subZeroEarly = mkRow 4 1 (Just 0) + let foldReferences direction Database{..} = do + ref <- newIORef [] + runTransaction $ foldInputs (MatchAny IncludingBootstrap) Whole NoStatusFlag AsReference direction + (\r -> modifyIORef' ref (extendedOutputReferenceToRow (outputReference r) :)) + reverse <$> readIORef ref + (asc, desc) <- withInMemoryDatabase' identity InstallIndexesIfNotExist 10 $ \db@Database{..} -> do + runTransaction $ do + insertCheckpoints [createdAt result] + insertInputs [topLevel, subOne, subZeroLate, subZeroEarly] + (,) <$> foldReferences Asc db <*> foldReferences Desc db + let expected = extendedOutputReference <$> [subZeroEarly, subZeroLate, subOne, topLevel] + asc `shouldBe` expected + desc `shouldBe` reverse expected + context "checkpoints" $ do let k = 100 prop "list checkpoints after inserting them" $ @@ -262,11 +351,14 @@ spec = parallel $ do let slot = getPointSlotNo . createdAt let txIx = snd . outputReference let outIx = getOutputIndex . fst . outputReference + let subIx = fmap snd . subTransactionOf + -- Outputs of sub-transactions come first, by sub-transaction index. + let batchIx x = (isNothing (subIx x), subIx x, outIx x) let oldestFirst current successor | slot current == slot successor = if txIx current == txIx successor then - label "same transaction index" (outIx current <= outIx successor) + label "same transaction index" (batchIx current <= batchIx successor) else property (txIx current < txIx successor) | otherwise = @@ -275,7 +367,7 @@ spec = parallel $ do let mostRecentFirst current successor | slot current == slot successor = if txIx current == txIx successor then - label "same transaction index" (outIx current >= outIx successor) + label "same transaction index" (batchIx current >= batchIx successor) else property (txIx current >= txIx successor) | otherwise = @@ -288,12 +380,13 @@ spec = parallel $ do shrinkList (const []) let showResults xs = toString $ unlines - [ "sl/tx/out" - , "---------" + [ "sl/tx/sub/out" + , "-------------" , T.intercalate "\n" $ fmap (\x -> T.intercalate "/" [ slotNoToText (slot x) , show (txIx x) + , maybe "-" show (subIx x) , show (outIx x) ] ) xs diff --git a/test/Test/Kupo/Data/Generators.hs b/test/Test/Kupo/Data/Generators.hs index 267d8b51..f6f5be91 100644 --- a/test/Test/Kupo/Data/Generators.hs +++ b/test/Test/Kupo/Data/Generators.hs @@ -40,6 +40,7 @@ import Kupo.Data.Cardano , ScriptHash , ScriptReference (..) , SlotNo (..) + , SubTransactionIndex , TransactionId , TransactionIndex , Value @@ -257,6 +258,10 @@ genTransactionIndex :: Gen TransactionIndex genTransactionIndex = fromIntegral <$> choose (0 :: Int, 255) +genSubTransactionIndex :: Gen SubTransactionIndex +genSubTransactionIndex = + fromIntegral <$> choose (0 :: Int, 255) + genPattern :: Gen Pattern genPattern = oneof [ MatchAny <$> elements [ IncludingBootstrap, OnlyShelley ] @@ -293,6 +298,8 @@ genResultWith genPoint = Result <*> frequency [(1, pure Nothing), (5, Just <$> genPoint)] <*> frequency [(1, pure Nothing), (5, Just <$> genOutputReference)] <*> frequency [(1, pure Nothing), (5, Just <$> genBinaryData)] + <*> frequency [(5, pure Nothing), (1, Just <$> ((,) <$> genTransactionId <*> genSubTransactionIndex))] + <*> frequency [(5, pure Nothing), (1, Just <$> genTransactionId)] genOutput :: Gen Output genOutput = mkOutput diff --git a/test/Test/Kupo/Data/Http/FilterMatchesBySpec.hs b/test/Test/Kupo/Data/Http/FilterMatchesBySpec.hs index 74d1fbcb..42db29d3 100644 --- a/test/Test/Kupo/Data/Http/FilterMatchesBySpec.hs +++ b/test/Test/Kupo/Data/Http/FilterMatchesBySpec.hs @@ -124,6 +124,60 @@ spec = parallel $ do ] , Nothing ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + ] + , Just (FilterByTopLevelTransactionId someTransactionId) + ) + , ( [ "foo" .= "bar" + , "top_level_transaction_id" .= transactionIdToText someTransactionId + ] + , Just (FilterByTopLevelTransactionId someTransactionId) + ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + , "top_level_transaction_id" .= transactionIdToText someOtherTransactionId + ] + , Nothing + ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + , "transaction_id" .= transactionIdToText someOtherTransactionId + ] + , Nothing + ) + , ( [ "transaction_id" .= transactionIdToText someOtherTransactionId + , "top_level_transaction_id" .= transactionIdToText someTransactionId + ] + , Nothing + ) + , ( [ "policy_id" .= policyIdToText somePolicyId + , "top_level_transaction_id" .= transactionIdToText someTransactionId + ] + , Nothing + ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + , "policy_id" .= policyIdToText somePolicyId + ] + , Nothing + ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + , "output_index" .= "14" + ] + , Nothing + ) + , ( [ "output_index" .= "14" + , "top_level_transaction_id" .= transactionIdToText someTransactionId + ] + , Nothing + ) + , ( [ "top_level_transaction_id" .= transactionIdToText someTransactionId + , "policy_id" .= policyIdToText somePolicyId + , "asset_name" .= assetNameToText someAssetName + ] + , Nothing + ) + , ( [ "top_level_transaction_id" .= "foo" + ] + , Nothing + ) ] -- diff --git a/test/Test/Kupo/Data/PatternSpec.hs b/test/Test/Kupo/Data/PatternSpec.hs index cdb466c0..bf0d57e6 100644 --- a/test/Test/Kupo/Data/PatternSpec.hs +++ b/test/Test/Kupo/Data/PatternSpec.hs @@ -18,6 +18,12 @@ import Kupo.Data.Cardano , toComparableOutput , unsafeBinaryDataFromBytes ) +import Kupo.Data.Http.QuantityEncoding + ( QuantityEncoding (..) + ) +import Kupo.Data.Http.ReferenceFlag + ( ReferenceFlag (..) + ) import Kupo.Data.PartialBlock ( PartialBlock (..) , PartialTransaction (..) @@ -27,11 +33,13 @@ import Kupo.Data.Pattern , Match (consumed) , MatchBootstrap (..) , Pattern (..) + , Result (..) , includes , matchBlock , matching , overlaps , patternFromText + , resultToJson ) import Test.Hspec ( Spec @@ -43,9 +51,13 @@ import Test.Hspec import Test.Hspec.QuickCheck ( prop ) +import Test.Kupo.App.Http.Client + ( decodeResult + ) import Test.Kupo.Data.Generators ( genNonGenesisPoint , genOutputReference + , genResult , genTransactionId ) import Test.Kupo.Data.Pattern.Fixture @@ -59,11 +71,13 @@ import Test.QuickCheck , elements , forAll , shuffle + , suchThat , vectorOf , (===) , (==>) ) +import qualified Data.Aeson.Encoding as Json import qualified Data.ByteString as BS import qualified Data.Map as Map import qualified Data.Set as Set @@ -113,6 +127,15 @@ spec = parallel $ do p1 `includes` p2 ==> p1 `overlaps` (Set.singleton p2) + context "resultToJson" $ do + prop "encodes and decodes the sub-transaction fields" $ + forAll (genResult `suchThat` isSpentConsistently) $ \result -> do + let bytes = Json.encodingToLazyByteString (resultToJson InlineAll EncodeAsInteger result) + -- The spending parent is only reported for a spent output. + let expectedSpender = spentAt result *> spentByTopLevelTransactionId result + fmap (\r -> (subTransactionOf r, spentByTopLevelTransactionId r)) (eitherDecodeJson decodeResult bytes) + === Right (subTransactionOf result, expectedSpender) + context "matchBlock" $ do prop "numbers spent inputs and their redeemers in ascending input order" $ forAll ((,,) <$> genNonGenesisPoint <*> genTransactionId <*> genSpentInputs) $ @@ -136,7 +159,7 @@ spec = parallel $ do , toPolicy = \_ _ -> () } let patterns' = Set.singleton (MatchAny IncludingBootstrap) - let got = Map.lookup (txId, getPointSlotNo pt) $ consumed $ matchBlock codecs patterns' blk + let got = Map.lookup (txId, Nothing, getPointSlotNo pt) $ consumed $ matchBlock codecs patterns' blk got === Just [ (MatchOutputReference ref, ix, Just (redeemer ix)) | (ix, ref) <- ascending @@ -146,6 +169,11 @@ spec = parallel $ do -- Helper -- +-- The decoder reads the spender of every spent output. +isSpentConsistently :: Result -> Bool +isSpentConsistently result = + isJust (spentAt result) == isJust (spentBy result) + matchAll :: Pattern -> [(ExtendedOutputReference, Output)] diff --git a/test/Test/Kupo/Data/SubTransactionSpec.hs b/test/Test/Kupo/Data/SubTransactionSpec.hs new file mode 100644 index 00000000..1e335f3d --- /dev/null +++ b/test/Test/Kupo/Data/SubTransactionSpec.hs @@ -0,0 +1,882 @@ +-- 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/. + +{-# LANGUAGE RecordWildCards #-} + +module Test.Kupo.Data.SubTransactionSpec + ( spec + ) where + +import Kupo.Prelude + +import Cardano.Crypto.DSIGN + ( deriveVerKeyDSIGN + , genKeyDSIGN + , signedDSIGN + ) +import Cardano.Crypto.KES + ( unsoundPureDeriveVerKeyKES + , unsoundPureGenKeyKES + , unsoundPureSignedKES + ) +import Cardano.Crypto.Seed + ( mkSeedFromBytes + ) +import Cardano.Crypto.VRF + ( deriveVerKeyVRF + , evalCertified + , genKeyVRF + ) +import Cardano.Ledger.Alonzo.TxWits + ( Redeemers (..) + , TxDats (..) + ) +import Cardano.Ledger.BaseTypes + ( Nonce (..) + , ProtVer (..) + , StrictMaybe (..) + , strictMaybe + ) +import Cardano.Ledger.Keys + ( VKey (..) + ) +import Cardano.Ledger.Plutus.Data + ( binaryDataToData + ) +import Cardano.Ledger.Plutus.ExUnits + ( ExUnits (..) + ) +import Cardano.Protocol.Praos.BlockHeader + ( Header (Header) + , HeaderBody (..) + ) +import Cardano.Protocol.Praos.VRF + ( mkInputVRF + ) +import Cardano.Protocol.TPraos.BlockHeader + ( PrevHash (..) + ) +import Cardano.Protocol.TPraos.OCert + ( KESPeriod (..) + , OCert (..) + , OCertSignable (..) + ) +import Control.Lens + ( (.~) + ) +import Data.Aeson.Lens + ( key + , _String + ) +import Kupo.App.Database + ( newDBPool + ) +import Kupo.App.Database.Types + ( DBPool (..) + , Database (..) + ) +import Kupo.App.Http + ( app + ) +import Kupo.Control.MonadLog + ( nullTracer + ) +import Kupo.Control.MonadSTM + ( MonadSTM (..) + ) +import Kupo.Data.Cardano + ( BinaryData + , Block + , BlockNo (..) + , DatumHash + , HasTransactionId (..) + , IsBlock (..) + , Metadata + , Output + , OutputReference + , Point + , Script + , ScriptHash + , SlotNo (..) + , SubTransactionIndex + , Transaction (..) + , TransactionId + , getPointSlotNo + , hashBinaryData + , hashMetadata + , hashScript + , metadataHashToText + , mkOutputReference + , slotNoToText + , transactionIdToText + ) +import Kupo.Data.Configuration + ( DatabaseLocation (..) + , DeferIndexesInstallation (..) + , LongestRollback (..) + ) +import Kupo.Data.Database + ( SortDirection (..) + , binaryDataToRow + , policyToRow + , resultToRow + , scriptToRow + ) +import Kupo.Data.Http.ReferenceFlag + ( ReferenceFlag (..) + ) +import Kupo.Data.Http.SlotRange + ( Range (..) + ) +import Kupo.Data.Http.StatusFlag + ( StatusFlag (..) + ) +import Kupo.Data.Pattern + ( Codecs (..) + , Match (..) + , MatchBootstrap (..) + , Pattern (..) + , Result (..) + , matchBlock + ) +import Ouroboros.Consensus.Cardano.Block + ( HardForkBlock (..) + ) +import Ouroboros.Consensus.Shelley.Ledger.Block + ( mkShelleyBlock + ) +import Test.Hspec + ( Spec + , context + , parallel + , shouldBe + , shouldReturn + , specify + ) +import Test.Kupo.App.Http.Client + ( decodeResult + ) +import Test.Kupo.App.HttpSpec + ( healthStub + ) +import Test.Kupo.Data.Generators + ( genBinaryData + , genMetadata + , genNonGenesisPoint + , genNonGenesisPointBetween + , genOutput + , genOutputReference + , genScript + ) +import Test.QuickCheck + ( Gen + , generate + , suchThat + , vectorOf + ) + +import qualified Cardano.Ledger.Block as Ledger +import qualified Cardano.Ledger.Dijkstra.Core as Ledger +import qualified Data.Aeson as Json +import qualified Data.Aeson.Types as Json +import qualified Data.ByteString as BS +import qualified Data.Map as Map +import qualified Data.Text as T +import qualified Network.HTTP.Types.Status as Http +import qualified Network.Wai as Wai +import qualified Network.Wai.Test as Wai + +spec :: Spec +spec = parallel $ do + context "IsBlock Block" $ do + specify "points at the slot of a Dijkstra block" $ do + SubTransactionBlock slot block _ _ _ _ _ _ <- newSubTransactionBlock + getPointSlotNo (getPoint block) `shouldBe` slot + + specify "folds over the top-level transactions of a Dijkstra block only, in block order" $ do + SubTransactionBlock _ block plain parent _ invalid _ _ <- newSubTransactionBlock + foldBlock (\ix tx -> ((ix, getTransactionId tx) :)) [] block + `shouldBe` + [ (0, topLevelId plain) + , (1, topLevelId parent) + , (2, topLevelId invalid) + ] + + specify "lists the sub-transactions of a phase-2 valid transaction in ledger order, and those of an invalid one as discarded" $ do + SubTransactionBlock _ block plain parent subs invalid invalidSubs _ <- newSubTransactionBlock + let listed tx = + ( getTransactionId tx + , getTransactionId <$> subTransactions @Block tx + , getTransactionId <$> discardedSubTransactions @Block tx + ) + foldBlock (\_ tx -> (listed tx :)) [] block + `shouldBe` + [ (topLevelId plain, [], []) + , (topLevelId parent, subId <$> subs, []) + , (topLevelId invalid, [], subId <$> invalidSubs) + ] + + specify "accepts a Dijkstra block with sub-transactions" $ do + SubTransactionBlock _ block _ _ _ _ _ _ <- newSubTransactionBlock + first displayException (checkSubTransactions block) `shouldBe` Right () + + specify "matches the outputs and spends of sub-transactions, and only the collateral of an invalid transaction" $ do + SubTransactionBlock slot block plain parent [sub0, sub1] invalid _ collateral <- newSubTransactionBlock + let Match{consumed, produced} = matchBlock codecs matchAll block + [ (outputReference, subTransactionOf) | Result{outputReference, subTransactionOf} <- produced ] + `shouldBe` + [ ((mkOutputReference (topLevelId plain) 0, 0), Nothing) + , ((mkOutputReference (subId sub0) 0, 1), Just (topLevelId parent, 0)) + , ((mkOutputReference (subId sub1) 0, 1), Just (topLevelId parent, 1)) + , ((mkOutputReference (topLevelId parent) 0, 1), Nothing) + -- The collateral return, indexed after the single output of the invalid transaction. + , ((mkOutputReference (topLevelId invalid) 1, 2), Nothing) + ] + Map.keys consumed `shouldBe` sort + [ (topLevelId plain, Nothing, slot) + , (subId sub0, Just (topLevelId parent), slot) + , (subId sub1, Just (topLevelId parent), slot) + , (topLevelId parent, Nothing, slot) + , (topLevelId invalid, Nothing, slot) + ] + Map.lookup (topLevelId invalid, Nothing, slot) consumed + `shouldBe` Just [(MatchOutputReference collateral, 0, Nothing)] + + context "matchBlock" $ do + specify "matches the outputs of sub-transactions, in ledger order, before those of their top-level transaction" $ do + pt <- generate genNonGenesisPoint + [plainInput, subInput0, subInput1, input] <- generate (vectorOf 4 genOutputReference) + [plainOutput, subOutput0, subOutput1, subOutput2, output] <- generate (vectorOf 5 genOutput) + let plain = mkTransaction [plainInput] [plainOutput] + let sub0 = mkTransaction [subInput0] [subOutput0] + let sub1 = mkTransaction [subInput1] [subOutput1, subOutput2] + let top = mkTransaction [input] [output] & withSubTransactions [sub0, sub1] + let Match{produced} = matchBlock codecs matchAll (DijkstraBlock pt [plain, top]) + [ (outputReference, subTransactionOf) | Result{outputReference, subTransactionOf} <- produced ] + `shouldBe` + [ ((mkOutputReference (topLevelId plain) 0, 0), Nothing) + , ((mkOutputReference (subId sub0) 0, 1), Just (topLevelId top, 0)) + , ((mkOutputReference (subId sub1) 0, 1), Just (topLevelId top, 1)) + , ((mkOutputReference (subId sub1) 1, 1), Just (topLevelId top, 1)) + , ((mkOutputReference (topLevelId top) 0, 1), Nothing) + ] + + specify "records the spends of a sub-transaction under its own id, input order and redeemers" $ do + pt <- generate genNonGenesisPoint + [subInput0, subInput1, input] <- generate (vectorOf 3 genOutputReference) + (redeemer, subRedeemer) <- generate genDistinctPair + let (lo, hi) = (min subInput0 subInput1, max subInput0 subInput1) + let sub = mkTransaction [hi, lo] [] & withSpendRedeemer 1 subRedeemer + let top = mkTransaction [input] [] + & withSpendRedeemer 0 redeemer + & withSubTransactions [sub] + let Match{consumed} = matchBlock codecs matchAll (DijkstraBlock pt [top]) + let slotNo = getPointSlotNo pt + consumed `shouldBe` fromList + [ ( (subId sub, Just (topLevelId top), slotNo) + , [ (MatchOutputReference lo, 0, Nothing) + , (MatchOutputReference hi, 1, Just subRedeemer) + ] + ) + , ( (topLevelId top, Nothing, slotNo) + , [ (MatchOutputReference input, 0, Just redeemer) + ] + ) + ] + + specify "collects only the datums and scripts of the sub-transactions of a phase-2 invalid transaction" $ do + pt <- generate genNonGenesisPoint + [subInput, input, collateral] <- generate (vectorOf 3 genOutputReference) + [subOutput, output, collateralReturn] <- generate (vectorOf 3 genOutput) + subDatum <- generate genBinaryData + script <- generate genScript + let sub = mkTransaction [subInput] [subOutput] & withDatum subDatum & withScript script + let top = mkTransaction [input] [output] + & withSubTransactions [sub] + & Ledger.isPhase2ValidTxL .~ Ledger.Phase2Invalid + & Ledger.bodyTxL . Ledger.collateralInputsTxBodyL .~ fromList [collateral] + & Ledger.bodyTxL . Ledger.collateralReturnTxBodyL .~ SJust collateralReturn + let Match{consumed, produced, datums, scripts} = matchBlock codecs matchAll (DijkstraBlock pt [top]) + consumed `shouldBe` fromList + [ ( (topLevelId top, Nothing, getPointSlotNo pt) + , [ (MatchOutputReference collateral, 0, Nothing) ] + ) + ] + [ (outputReference, subTransactionOf) | Result{outputReference, subTransactionOf} <- produced ] + `shouldBe` + [ ((mkOutputReference (topLevelId top) 1, 0), Nothing) ] + datums `shouldBe` [(hashBinaryData subDatum, subDatum)] + -- The outputs may carry reference scripts too. + Map.lookup (hashScript script) (fromList scripts) `shouldBe` Just script + + specify "matches *@ on the own id of a sub-transaction or top-level transaction" $ do + pt <- generate genNonGenesisPoint + [subInput, input] <- generate (vectorOf 2 genOutputReference) + [subOutput, output] <- generate (vectorOf 2 genOutput) + let sub = mkTransaction [subInput] [subOutput] + let top = mkTransaction [input] [output] & withSubTransactions [sub] + let matchedBy txId = + [ outputReference + | Result{outputReference} <- produced $ + matchBlock codecs (fromList [MatchTransactionId txId]) (DijkstraBlock pt [top]) + ] + matchedBy (subId sub) `shouldBe` [(mkOutputReference (subId sub) 0, 0)] + matchedBy (topLevelId top) `shouldBe` [(mkOutputReference (topLevelId top) 0, 0)] + + specify "collects the datums and scripts of the witness sets of sub-transactions" $ do + pt <- generate genNonGenesisPoint + [subInput, input] <- generate (vectorOf 2 genOutputReference) + (datum, subDatum) <- generate genDistinctPair + script <- generate genScript + let sub = mkTransaction [subInput] [] & withDatum subDatum & withScript script + let top = mkTransaction [input] [] & withDatum datum & withSubTransactions [sub] + let Match{datums, scripts} = matchBlock codecs matchAll (DijkstraBlock pt [top]) + (fromList datums :: Map DatumHash BinaryData) `shouldBe` fromList + [ (hashBinaryData datum, datum) + , (hashBinaryData subDatum, subDatum) + ] + scripts `shouldBe` [(hashScript script, script)] + + context "database" $ do + specify "stores the outputs and spends of sub-transactions with their top-level transaction" $ do + (pt1, pt2) <- generate $ (,) + <$> genNonGenesisPointBetween (1, 10) + <*> genNonGenesisPointBetween (11, 20) + [fundingInput, subInput, input] <- generate (vectorOf 3 genOutputReference) + [spent0, spent1, subOutput0, subOutput1, output] <- generate (vectorOf 5 genOutput) + let funding = mkTransaction [fundingInput] [spent0, spent1] + let sub0 = mkTransaction [mkOutputReference (topLevelId funding) 0] [subOutput0] + let sub1 = mkTransaction [mkOutputReference (topLevelId funding) 1, subInput] [subOutput1] + let top = mkTransaction [input] [output] & withSubTransactions [sub0, sub1] + let blocks = [DijkstraBlock pt1 [funding], DijkstraBlock pt2 [top]] + let databaseCodecs = Codecs + { toResult = resultToRow + , toBinaryData = binaryDataToRow + , toScript = scriptToRow + , toPolicy = policyToRow + } + results <- withInMemoryDatabase $ \Database{..} -> do + let Match{consumed, produced} = + foldMap (matchBlock databaseCodecs matchAll) blocks + runTransaction $ do + insertCheckpoints (getPoint <$> blocks) + insertInputs produced + void $ Map.traverseWithKey markInputs consumed + acc <- newIORef [] + runTransaction $ foldInputs (MatchAny IncludingBootstrap) Whole NoStatusFlag AsReference Asc + (\result -> modifyIORef' acc (result :)) + reverse <$> readIORef acc + let spendIndex = if mkOutputReference (topLevelId funding) 1 < subInput then 0 else 1 + [ (outputReference, subTransactionOf, spentBy, spentByTopLevelTransactionId) + | Result{outputReference, subTransactionOf, spentBy, spentByTopLevelTransactionId} <- results + ] + `shouldBe` + [ ( (mkOutputReference (topLevelId funding) 0, 0) + , Nothing + , Just (mkOutputReference (subId sub0) 0) + , Just (topLevelId top) + ) + , ( (mkOutputReference (topLevelId funding) 1, 0) + , Nothing + , Just (mkOutputReference (subId sub1) spendIndex) + , Just (topLevelId top) + ) + , ((mkOutputReference (subId sub0) 0, 0), Just (topLevelId top, 0), Nothing, Nothing) + , ((mkOutputReference (subId sub1) 0, 0), Just (topLevelId top, 1), Nothing, Nothing) + , ((mkOutputReference (topLevelId top) 0, 0), Nothing, Nothing, Nothing) + ] + + specify "spends the outputs that sub-transactions create within the same block" $ do + pt <- generate genNonGenesisPoint + [fundingInput, input] <- generate (vectorOf 2 genOutputReference) + [subOutput0, subOutput1, output] <- generate (vectorOf 3 genOutput) + let sub0 = mkTransaction [fundingInput] [subOutput0] + let sub1 = mkTransaction [mkOutputReference (subId sub0) 0] [subOutput1] + let top = mkTransaction [input, mkOutputReference (subId sub1) 0] [output] + & withSubTransactions [sub0, sub1] + let databaseCodecs = Codecs + { toResult = resultToRow + , toBinaryData = binaryDataToRow + , toScript = scriptToRow + , toPolicy = policyToRow + } + results <- withInMemoryDatabase $ \Database{..} -> do + let Match{consumed, produced} = + matchBlock databaseCodecs matchAll (DijkstraBlock pt [top]) + runTransaction $ do + insertCheckpoints [pt] + insertInputs produced + void $ Map.traverseWithKey markInputs consumed + acc <- newIORef [] + runTransaction $ foldInputs (MatchAny IncludingBootstrap) Whole NoStatusFlag AsReference Asc + (\result -> modifyIORef' acc (result :)) + reverse <$> readIORef acc + let inputIndex = if mkOutputReference (subId sub1) 0 < input then 0 else 1 + [ (outputReference, subTransactionOf, spentBy, spentByTopLevelTransactionId) + | Result{outputReference, subTransactionOf, spentBy, spentByTopLevelTransactionId} <- results + ] + `shouldBe` + [ ( (mkOutputReference (subId sub0) 0, 0) + , Just (topLevelId top, 0) + , Just (mkOutputReference (subId sub1) 0) + , Just (topLevelId top) + ) + , ( (mkOutputReference (subId sub1) 0, 0) + , Just (topLevelId top, 1) + , Just (mkOutputReference (topLevelId top) inputIndex) + , Nothing + ) + , ((mkOutputReference (topLevelId top) 0, 0), Nothing, Nothing, Nothing) + ] + + context "http" $ do + specify "filters matches by the top-level transaction of the sub-transactions that created them" $ do + withIndexedBlocks $ \(Indexed funding sub0 sub1 top) application -> do + let path filter_ = "/matches?order=oldest_first&" <> filter_ <> "=" + creatorsAt application (path "top_level_transaction_id" <> transactionIdToText (topLevelId top)) + `shouldReturn` + [ (subId sub0, Just (topLevelId top, 0)) + , (subId sub1, Just (topLevelId top, 1)) + ] + creatorsAt application (path "top_level_transaction_id" <> transactionIdToText (topLevelId funding)) + `shouldReturn` [] + creatorsAt application (path "top_level_transaction_id" <> transactionIdToText (subId sub0)) + `shouldReturn` [] + + specify "rejects the top-level transaction filter combined with other filters or given twice" $ do + withIndexedBlocks $ \(Indexed _ _ _ top) application -> do + let topLevel = "top_level_transaction_id=" <> transactionIdToText (topLevelId top) + let policyId = T.replicate 56 "0" + forM_ + [ topLevel <> "&transaction_id=" <> transactionIdToText (topLevelId top) + , topLevel <> "&policy_id=" <> policyId + , topLevel <> "&policy_id=" <> policyId <> "&asset_name=00" + , topLevel <> "&output_index=0" + , "output_index=0&" <> topLevel + , topLevel <> "&" <> topLevel + , "top_level_transaction_id=foo" + ] $ \query -> do + response <- getResponse application ("/matches?" <> query) + (query, Http.statusCode (Wai.simpleStatus response)) `shouldBe` (query, 400) + + specify "matches by the id of a sub-transaction through the transaction_id filter and patterns" $ do + withIndexedBlocks $ \(Indexed _ _ sub1 top) application -> do + let expectedSub = [(subId sub1, Just (topLevelId top, 1))] + let subIdText = transactionIdToText (subId sub1) + creatorsAt application ("/matches?transaction_id=" <> subIdText) `shouldReturn` expectedSub + creatorsAt application ("/matches/*@" <> subIdText) `shouldReturn` expectedSub + creatorsAt application ("/matches/0@" <> subIdText) `shouldReturn` expectedSub + -- The id of the top-level transaction only matches its own outputs. + let topIdText = transactionIdToText (topLevelId top) + creatorsAt application ("/matches?transaction_id=" <> topIdText) + `shouldReturn` [(topLevelId top, Nothing)] + creatorsAt application ("/matches/*@" <> topIdText) + `shouldReturn` [(topLevelId top, Nothing)] + + specify "reports the sub-transaction of a match, and of its spender, as null or a value" $ do + withIndexedBlocks $ \(Indexed funding sub0 sub1 top) application -> do + let topIdText = transactionIdToText (topLevelId top) + let field name = (^? key name) + [subMatch] <- getJson application ("/matches/*@" <> transactionIdToText (subId sub1)) + field "sub_transaction_index" subMatch `shouldBe` Just (Json.Number 1) + field "top_level_transaction_id" subMatch `shouldBe` Just (Json.String topIdText) + [topMatch] <- getJson application ("/matches/*@" <> topIdText) + field "sub_transaction_index" topMatch `shouldBe` Just Json.Null + field "top_level_transaction_id" topMatch `shouldBe` Just Json.Null + [fundingMatch] <- getJson application + ("/matches?spent&transaction_id=" <> transactionIdToText (topLevelId funding) <> "&output_index=0") + (fundingMatch ^? key "spent_at" . key "transaction_id") + `shouldBe` Just (Json.String $ transactionIdToText $ subId sub0) + (fundingMatch ^? key "spent_at" . key "top_level_transaction_id") + `shouldBe` Just (Json.String topIdText) + + specify "reports an ordinary spender after a spending sub-transaction is rolled back" $ do + (pt1, pt2, pt3) <- generate $ (,,) + <$> genNonGenesisPointBetween (1, 10) + <*> genNonGenesisPointBetween (11, 20) + <*> genNonGenesisPointBetween (21, 30) + [fundingInput, input, otherInput] <- generate (vectorOf 3 genOutputReference) + [spent, subOutput, output] <- generate (vectorOf 3 genOutput) + let funding = mkTransaction [fundingInput] [spent] + let fundingRef = mkOutputReference (topLevelId funding) 0 + let sub = mkTransaction [fundingRef] [subOutput] + let top = mkTransaction [input] [output] & withSubTransactions [sub] + let ordinary = mkTransaction [fundingRef, otherInput] [] + let rowCodecs = Codecs + { toResult = resultToRow + , toBinaryData = binaryDataToRow + , toScript = scriptToRow + , toPolicy = policyToRow + } + withInMemoryDatabase $ \database@Database{..} -> do + let index block = do + let Match{consumed, produced} = matchBlock rowCodecs matchAll block + runTransaction $ do + insertCheckpoints [getPoint block] + insertInputs produced + void $ Map.traverseWithKey markInputs consumed + index (DijkstraBlock pt1 [funding]) + index (DijkstraBlock pt2 [top]) + let matchesPath = "/matches?spent&transaction_id=" <> transactionIdToText (topLevelId funding) + application2 <- newApplication database (DijkstraBlock pt2 [top]) + [before] <- getJson application2 matchesPath + (before ^? key "spent_at" . key "transaction_id") + `shouldBe` Just (Json.String $ transactionIdToText $ subId sub) + void $ runTransaction $ rollbackTo (getPointSlotNo pt1) + index (DijkstraBlock pt3 [ordinary]) + application3 <- newApplication database (DijkstraBlock pt3 [ordinary]) + [after] <- getJson application3 matchesPath + (after ^? key "spent_at" . key "transaction_id") + `shouldBe` Just (Json.String $ transactionIdToText $ topLevelId ordinary) + (after ^? key "spent_at" . key "top_level_transaction_id") + `shouldBe` Just Json.Null + + specify "lists the metadata of sub-transactions before that of their top-level transaction" $ do + withMetadataBlock $ \(MetadataBlock plain sub0 sub2 top invalidSub) slot application -> do + entriesAt application slot "" `shouldReturn` + [ entry (topLevelId plain) Nothing plain + , entry (subId sub0) (Just (topLevelId top)) sub0 + , entry (subId sub2) (Just (topLevelId top)) sub2 + , entry (topLevelId top) Nothing top + ] + entriesAt application slot ("?transaction_id=" <> transactionIdToText (subId sub2)) + `shouldReturn` [entry (subId sub2) (Just (topLevelId top)) sub2] + entriesAt application slot ("?transaction_id=" <> transactionIdToText (topLevelId top)) + `shouldReturn` [entry (topLevelId top) Nothing top] + -- The sub-transactions of a phase-2 invalid transaction are not applied. + entriesAt application slot ("?transaction_id=" <> transactionIdToText (subId invalidSub)) + `shouldReturn` [] + +-- +-- Helpers +-- + +matchAll :: Set Pattern +matchAll = + fromList [MatchAny IncludingBootstrap] + +codecs :: Codecs Result (DatumHash, BinaryData) (ScriptHash, Script) () +codecs = Codecs + { toResult = identity + , toBinaryData = (,) + , toScript = (,) + , toPolicy = \_ _ -> () + } + +withInMemoryDatabase + :: (Database IO -> IO a) + -> IO a +withInMemoryDatabase action = do + pool <- newDBPool nullTracer False (InMemory (Just ":memory:")) (LongestRollback 10) + withDatabaseExclusiveWriter pool InstallIndexesIfNotExist action + +topLevelId :: Ledger.Tx Ledger.TopTx DijkstraEra -> TransactionId +topLevelId = + getTransactionId . TransactionDijkstra + +subId :: Ledger.Tx Ledger.SubTx DijkstraEra -> TransactionId +subId = + getTransactionId . SubTransactionDijkstra + +-- +-- Fixtures +-- + +-- | A 'Block' at a slot, with a plain transaction, a transaction with two +-- sub-transactions, and a phase-2 invalid transaction with two sub-transactions, +-- in this order, and the collateral input of the invalid transaction. +data SubTransactionBlock = SubTransactionBlock + !SlotNo + !Block + !(Ledger.Tx Ledger.TopTx DijkstraEra) + !(Ledger.Tx Ledger.TopTx DijkstraEra) + ![Ledger.Tx Ledger.SubTx DijkstraEra] + !(Ledger.Tx Ledger.TopTx DijkstraEra) + ![Ledger.Tx Ledger.SubTx DijkstraEra] + !OutputReference + +newSubTransactionBlock :: IO SubTransactionBlock +newSubTransactionBlock = do + slot <- getPointSlotNo <$> generate genNonGenesisPoint + [plainInput, input, subInput0, subInput1, invalidInput, collateral, invalidSubInput0, invalidSubInput1] <- + generate (vectorOf 8 genOutputReference) + [plainOutput, output, subOutput0, subOutput1, invalidOutput, collateralReturn, invalidSubOutput0, invalidSubOutput1] <- + generate (vectorOf 8 genOutput) + let plain = mkTransaction [plainInput] [plainOutput] + -- Descending ids, so that the ledger order of the sub-transactions is not their id order. + let subs = sortOn (Down . subId) + [ mkTransaction [subInput0] [subOutput0] + , mkTransaction [subInput1] [subOutput1] + ] + let parent = mkTransaction [input] [output] & withSubTransactions subs + let invalidSubs = + [ mkTransaction [invalidSubInput0] [invalidSubOutput0] + , mkTransaction [invalidSubInput1] [invalidSubOutput1] + ] + let invalid = mkTransaction [invalidInput] [invalidOutput] + & withSubTransactions invalidSubs + & Ledger.isPhase2ValidTxL .~ Ledger.Phase2Invalid + & Ledger.bodyTxL . Ledger.collateralInputsTxBodyL .~ fromList [collateral] + & Ledger.bodyTxL . Ledger.collateralReturnTxBodyL .~ SJust collateralReturn + let block = mkDijkstraBlock slot [plain, parent, invalid] + pure $ SubTransactionBlock slot block plain parent subs invalid invalidSubs collateral + +-- | A Dijkstra 'Block' as cardano-node serves it. Its header is signed with keys +-- derived from fixed seeds, since Kupo does not verify headers. +mkDijkstraBlock + :: SlotNo + -> [Ledger.Tx Ledger.TopTx DijkstraEra] + -> Block +mkDijkstraBlock slot txs = + BlockDijkstra . mkShelleyBlock $ Ledger.Block (Header headerBody signature) body + where + body = Ledger.mkBasicBlockBody & Ledger.txSeqBlockBodyL .~ fromList txs + protocolVersion = ProtVer (Ledger.eraProtVerLow @DijkstraEra) 0 + coldKey = genKeyDSIGN (seed 0) + vrfKey = genKeyVRF (seed 1) + kesKey = unsoundPureGenKeyKES (seed 2) + hotKey = unsoundPureDeriveVerKeyKES kesKey + headerBody = HeaderBody + { hbBlockNo = BlockNo (unSlotNo slot) + , hbSlotNo = slot + , hbPrev = GenesisHash + , hbVk = VKey (deriveVerKeyDSIGN coldKey) + , hbVrfVk = deriveVerKeyVRF vrfKey + , hbVrfRes = evalCertified () (mkInputVRF slot NeutralNonce) vrfKey + , hbBodySize = fromIntegral (Ledger.blockBodySize protocolVersion body) + , hbBodyHash = Ledger.hashBlockBody body + , hbOCert = OCert hotKey 0 (KESPeriod 0) $ + signedDSIGN () (OCertSignable hotKey 0 (KESPeriod 0)) coldKey + , hbProtVer = protocolVersion + } + signature = unsoundPureSignedKES () 0 headerBody kesKey + seed = mkSeedFromBytes . BS.replicate 32 + +-- | A Dijkstra block reduced to its point and transactions, read like a 'Block'. +data DijkstraBlock = DijkstraBlock + { blockPoint :: !Point + , blockTransactions :: ![Ledger.Tx Ledger.TopTx DijkstraEra] + } + +instance IsBlock DijkstraBlock where + type BlockBody DijkstraBlock = Transaction + getPoint = + blockPoint + foldBlock fn result = + foldrWithIndex (\ix -> fn ix . TransactionDijkstra) result . blockTransactions + checkSubTransactions = + const (Right ()) + subTransactions = + subTransactions @Block + discardedSubTransactions = + discardedSubTransactions @Block + spentInputs = + spentInputs @Block + mapMaybeOutputs = + mapMaybeOutputs @Block + witnessedDatums = + witnessedDatums @Block + witnessedScripts = + witnessedScripts @Block + userDefinedMetadata = + userDefinedMetadata @Block + spendRedeemer = + spendRedeemer @Block + +mkTransaction + :: Typeable level + => [OutputReference] + -> [Output] + -> Ledger.Tx level DijkstraEra +mkTransaction inputs outputs = + Ledger.mkBasicTx $ Ledger.mkBasicTxBody + & Ledger.inputsTxBodyL .~ fromList inputs + & Ledger.outputsTxBodyL .~ fromList outputs + +withSubTransactions + :: [Ledger.Tx Ledger.SubTx DijkstraEra] + -> Ledger.Tx Ledger.TopTx DijkstraEra + -> Ledger.Tx Ledger.TopTx DijkstraEra +withSubTransactions subTxs = + Ledger.bodyTxL . Ledger.subTransactionsTxBodyL .~ fromList subTxs + +withDatum + :: BinaryData + -> Ledger.Tx level DijkstraEra + -> Ledger.Tx level DijkstraEra +withDatum datum = + Ledger.witsTxL . Ledger.datsTxWitsL .~ TxDats (fromList [(hashBinaryData datum, binaryDataToData datum)]) + +withScript + :: Script + -> Ledger.Tx level DijkstraEra + -> Ledger.Tx level DijkstraEra +withScript script = + Ledger.witsTxL . Ledger.scriptTxWitsL .~ fromList [(hashScript script, script)] + +withSpendRedeemer + :: Word32 + -> BinaryData + -> Ledger.Tx level DijkstraEra + -> Ledger.Tx level DijkstraEra +withSpendRedeemer ix redeemer = + Ledger.witsTxL . Ledger.rdmrsTxWitsL .~ Redeemers + (fromList [(Ledger.SpendingPurpose (Ledger.AsIx ix), (binaryDataToData redeemer, ExUnits 0 0))]) + +-- | A funding transaction, a top-level transaction spending its outputs from +-- two sub-transactions, all indexed in an in-memory database behind the HTTP +-- application. +data Indexed = Indexed + !(Ledger.Tx Ledger.TopTx DijkstraEra) + !(Ledger.Tx Ledger.SubTx DijkstraEra) + !(Ledger.Tx Ledger.SubTx DijkstraEra) + !(Ledger.Tx Ledger.TopTx DijkstraEra) + +withIndexedBlocks + :: (Indexed -> Wai.Application -> IO a) + -> IO a +withIndexedBlocks action = do + (pt1, pt2) <- generate $ (,) + <$> genNonGenesisPointBetween (1, 10) + <*> genNonGenesisPointBetween (11, 20) + [fundingInput, subInput, input] <- generate (vectorOf 3 genOutputReference) + [spent0, spent1, subOutput0, subOutput1, output] <- generate (vectorOf 5 genOutput) + let funding = mkTransaction [fundingInput] [spent0, spent1] + let sub0 = mkTransaction [mkOutputReference (topLevelId funding) 0] [subOutput0] + let sub1 = mkTransaction [mkOutputReference (topLevelId funding) 1, subInput] [subOutput1] + let top = mkTransaction [input] [output] & withSubTransactions [sub0, sub1] + let blocks = [DijkstraBlock pt1 [funding], DijkstraBlock pt2 [top]] + let rowCodecs = Codecs + { toResult = resultToRow + , toBinaryData = binaryDataToRow + , toScript = scriptToRow + , toPolicy = policyToRow + } + withInMemoryDatabase $ \database@Database{..} -> do + let Match{consumed, produced} = foldMap (matchBlock rowCodecs matchAll) blocks + runTransaction $ do + insertCheckpoints (getPoint <$> blocks) + insertInputs produced + void $ Map.traverseWithKey markInputs consumed + application <- newApplication database (DijkstraBlock pt2 [top]) + action (Indexed funding sub0 sub1 top) application + +-- | A block with metadata on a transaction, on two of the three +-- sub-transactions of another one, and on the sub-transaction of a phase-2 +-- invalid transaction. +data MetadataBlock = MetadataBlock + !(Ledger.Tx Ledger.TopTx DijkstraEra) + !(Ledger.Tx Ledger.SubTx DijkstraEra) + !(Ledger.Tx Ledger.SubTx DijkstraEra) + !(Ledger.Tx Ledger.TopTx DijkstraEra) + !(Ledger.Tx Ledger.SubTx DijkstraEra) + +withMetadataBlock + :: (MetadataBlock -> SlotNo -> Wai.Application -> IO a) + -> IO a +withMetadataBlock action = do + pt <- generate genNonGenesisPoint + [plainInput, subInput0, subInput1, subInput2, input, invalidInput, invalidSubInput] <- + generate (vectorOf 7 genOutputReference) + [plainMeta, meta0, meta2, topMeta, invalidSubMeta] <- generate (vectorOf 5 (snd <$> genMetadata)) + let plain = mkTransaction [plainInput] [] & withMetadata plainMeta + let sub0 = mkTransaction [subInput0] [] & withMetadata meta0 + let sub1 = mkTransaction [subInput1] [] + let sub2 = mkTransaction [subInput2] [] & withMetadata meta2 + let top = mkTransaction [input] [] + & withMetadata topMeta + & withSubTransactions [sub0, sub1, sub2] + let invalidSub = mkTransaction [invalidSubInput] [] & withMetadata invalidSubMeta + let invalid = mkTransaction [invalidInput] [] + & withSubTransactions [invalidSub] + & Ledger.isPhase2ValidTxL .~ Ledger.Phase2Invalid + withInMemoryDatabase $ \database -> do + application <- newApplication database (DijkstraBlock pt [plain, top, invalid]) + action (MetadataBlock plain sub0 sub2 top invalidSub) (getPointSlotNo pt) application + +newApplication + :: Database IO + -> DijkstraBlock + -> IO Wai.Application +newApplication database block = do + patternsVar <- newTVarIO mempty + pure $ app + (pure Nothing) + (\_send _mode callback -> callback database) + (\_point _handler -> pure ()) + (\_point reply -> reply (Just block)) + patternsVar + healthStub + +getResponse + :: Wai.Application + -> Text + -> IO Wai.SResponse +getResponse application path = + Wai.runSession + (Wai.request $ Wai.setPath Wai.defaultRequest (encodeUtf8 path)) + application + +getJson + :: Wai.Application + -> Text + -> IO [Json.Value] +getJson application path = do + response <- getResponse application path + Http.statusCode (Wai.simpleStatus response) `shouldBe` 200 + either fail pure $ Json.eitherDecode (Wai.simpleBody response) + +-- | The transaction that created each match, with its position in its top-level transaction. +creatorsAt + :: Wai.Application + -> Text + -> IO [(TransactionId, Maybe (TransactionId, SubTransactionIndex))] +creatorsAt application path = do + response <- getResponse application path + Http.statusCode (Wai.simpleStatus response) `shouldBe` 200 + results <- either fail pure $ + eitherDecodeJson (Json.listParser decodeResult) (Wai.simpleBody response) + pure + [ (getTransactionId (fst outputReference), subTransactionOf) + | Result{outputReference, subTransactionOf} <- results + ] + +-- | The transaction id, top-level transaction id and metadata hash of each /metadata entry. +entriesAt + :: Wai.Application + -> SlotNo + -> Text + -> IO [(Maybe Text, Maybe Json.Value, Maybe Text)] +entriesAt application slot query = do + entries <- getJson application ("/metadata/" <> slotNoToText slot <> query) + pure + [ (item ^? key "transaction_id" . _String, item ^? key "top_level_transaction_id", item ^? key "hash" . _String) + | item <- entries + ] + +entry + :: TransactionId + -> Maybe TransactionId + -> Ledger.Tx level DijkstraEra + -> (Maybe Text, Maybe Json.Value, Maybe Text) +entry transactionId topLevel tx = + ( Just (transactionIdToText transactionId) + , Just (maybe Json.Null (Json.String . transactionIdToText) topLevel) + , strictMaybe Nothing (Just . metadataHashToText . hashMetadata) (tx ^. Ledger.auxDataTxL) + ) + +withMetadata + :: Metadata + -> Ledger.Tx level DijkstraEra + -> Ledger.Tx level DijkstraEra +withMetadata metadata = + Ledger.auxDataTxL .~ SJust metadata + +-- +-- Generators +-- + +genDistinctPair :: Gen (BinaryData, BinaryData) +genDistinctPair = + ((,) <$> genBinaryData <*> genBinaryData) `suchThat` uncurry (/=)