Repository navigation
Add Dijkstra fields to experimental TxBodyContent and draft SubTx type - #1361
Conversation
4802af1 to
95db9b4
Compare
95db9b4 to
85d6275
Compare
a84f8e2 to
4dd2c90
Compare
Temporarily pin cardano-api to the branch of IntersectMBO/cardano-api#1361 via a source-repository-package stanza, to pick up sub-transaction support ahead of a cardano-api release. That branch moves key and operational certificate code into the new cardano-keys package, which changes two things cardano-cli relied on: - getKesPeriod now returns the KESPeriod newtype rather than Word, so the KES period info query unwraps it with unKESPeriod. - textEnvelopeType is no longer a method of HasTextEnvelope but a standalone function, so the golden text envelope tests import it directly.
carbolymer
left a comment
There was a problem hiding this comment.
Nice work! I think we should stop for a sec and think which abstraction do we pick for subtransactions: https://github.com/IntersectMBO/cardano-api/pull/1361/changes#r4136646496
| -- Compared to the top-level 'TxBodyContent', a sub-transaction has no collateral inputs, | ||
| -- no total/return collateral, no fee, no required signer key hashes (replaced by guards) | ||
| -- and no script validity flag. | ||
| data SubTx era |
There was a problem hiding this comment.
SubTx repeats 20 of the 28 fields of TxBodyContent with the same names and types. The eight it leaves out are exactly the ones a sub-transaction body cannot carry on the wire: collateral, fee, extra key witnesses, script validity, sub-transactions and starting balance intervals. Before this shape becomes public API through Cardano.Api.Experimental, we should decide how the two levels share one definition. The options I see:
-
One record indexed by the ledger's transaction level, with the eight top-level fields grouped in one extension field that is a GADT. Shared-field access stays as it is, and the second record with its setters and default goes away.
data TxBodyContent (l :: L.TxLevel) era = TxBodyContent { txIns :: [(TxIn, AnyWitness era)] -- + 19 shared fields , txTopLevel :: TopLevelFields l era } data TopLevelFields l era where TopLevelFields :: {txFee :: L.Coin {- + 7 -}} -> TopLevelFields L.TopTx era NoTopLevelFields :: TopLevelFields L.SubTx era
-
The same level index, but each of the eight fields wrapped in a type family that reduces to the field type at the top level and to unit for sub-transactions. Flat record, eight type-family applications, a deriving context for each.
type family TopOnly (l :: L.TxLevel) a where TopOnly L.TopTx a = a TopOnly L.SubTx a = () data TxBodyContent l era = TxBodyContent {txFee :: TopOnly l L.Coin {- ... -}}
-
The same level index with a per-field GADT, present or absent. Cleaner types than the type family, more churn at every use of the eight fields.
data TopOnly l a where Present :: a -> TopOnly L.TopTx a Absent :: TopOnly L.SubTx a
-
A two-constructor GADT with 28 and 20 fields, which is what the ledger's raw Dijkstra body does. Keeps the duplication and makes the eight selectors partial.
data TxBodyContent l era where TopTxBodyContent :: {txIns :: _ {- 20 shared -}, txFee :: L.Coin {- + 7 -}} -> TxBodyContent L.TopTx era SubTxBodyContent :: {txIns :: _ {- the same 20 -}} -> TxBodyContent L.SubTx era
-
Composition: a common record embedded in the top-level record. Same deduplication, but it nests the twenty fields everyone touches rather than the eight few do.
data TxBodyCommon era = TxBodyCommon {txIns :: [(TxIn, AnyWitness era)] {- + 19 -}} data TxBodyContent era = TxBodyContent {txCommon :: TxBodyCommon era, txFee :: L.Coin {- + 7 -}} type SubTx era = TxBodyCommon era
-
Keep the copy. Then
SubTx (..),defaultSubTxand the setters should not be exported fromCardano.Api.Experimentalyet, so the later change is not breaking.
My preference is option 2. Whatever we pick will apply to every future level-dependent field, so an ADR seems the right place to record the decision and the reasons.
There was a problem hiding this comment.
I'd propose a seventh option: keep two data definitions and share the common fields through a typeclass of accessors.
class HasCommonBodyFields (body :: Type -> Type) where
txInsL :: Lens' (body era) [(TxIn, AnyWitness era)]
txInsReferenceL :: Lens' (body era) (TxInsReference era)
txOutsL :: Lens' (body era) [TxOut era]
-- one lens per shared field, 20 in total
instance HasCommonBodyFields TxBodyContent
instance HasCommonBodyFields SubTx
Shared setters, collectScriptWitnessRequirements and the key witness code are then written once against the class. The setSubTx* functions, collectSubTxScriptWitnessRequirements and makeSubTxKeyWitness all go away.
Why this over option 2:
What actually costs us is duplicated behaviour, not duplicated declarations. The class removes the behaviour duplication and keeps the data honest: a sub-transaction simply has no fee field, rather than a fee field of type ().
It is also non-breaking. TxBodyContent era keeps its kind, its name and every selector, whereas option 2 changes the kind and breaks every current user of the experimental API.
There was a problem hiding this comment.
Having instances makes a lot of sense for implementing the lens overloading. But it does not avoid the duplicated data definitions (like you say). So it would be possible to combine it with 5 or 1. But I am not sure how much breakage that would create. It would probably be an easy refactoring, but if it breaks user's code it is not that nice
There was a problem hiding this comment.
@Jimbo4350 Your lens version is superior to plain datatype duplication. But you will still have to keep in sync duplicated declarations, their serialisation. I'm worried about maintenance cost1.
With TopOnly type family (option 2) you can avoid breakage with:
type family TopOnly (l :: L.TxLevel) a where
TopOnly L.TopTx a = a
TopOnly L.SubTx a = ()
type TxBodyContent era = NestedTxBodyContent L.TopTx era
type SubTxBodyContent era = NestedTxBodyContent L.SubTx era
data NestedTxBodyContent l era = TxBodyContent {txFee :: TopOnly l L.Coin {- ... -}}To my knowledge SubTx fields set will be a subset of TopTx fields set.
The only wart is to having to deal with () for fields non-existent in SubTxs. This can be smoothed out with default values, smart constructors and lenses.
clanker's breakage analysis
Checked against the current consumers of the experimental TxBodyContent: cardano-api itself (including the tests and the gen library), cardano-cli and cardano-node.
What keeps compiling with type TxBodyContent era = NestedTxBodyContent L.TopTx era
TxBodyContent erastays a type of the same name and kind, so every signature in cardano-cli, cardano-node and the tests is untouched.- The constructor keeps its name and all 28 selectors, so the existing record pattern in
Fee.hs(TxBodyContent{txInsCollateral, txReturnCollateral, txTotalCollateral}) and the 28-field positional
match in the same module still typecheck. At the top levelTopOnly L.TopTx areduces toa, sotxFee bcis still aCoinand record update still works. - No consumer imports
TxBodyContent (..), no consumer writes an instance for it, no consumer uses the name unsaturated, and the record has no deriving clause today, so there is noEq/Showcontext
to invent. - The ledger's Dijkstra CDDL makes the sub body a strict subset of the top body (top-only keys: 2, 13, 16, 17, 23, 27; nothing is sub-only), so the subset assumption holds. CIP-0118 differs only on key
24, which it puts on the sub body alone, and the ledger is what cardano-api builds against.
Residual edges, none hit by current code
import ... (TxBodyContent (..))no longer brings the constructor and fields into scope, because a type synonym has no(..). Anyone who wants them importsNestedTxBodyContent (..). The
Cardano.Api.Experimental.Txexport list needs the same change.- Building a value with the bare constructor in a context that does not fix the level is ambiguous: a type family is not injective, so
TopOnly l Coin ~ Coindoes not tell GHC thatl ~ L.TopTx.
Values built throughdefaultTxBodyContentand the setters are fine, which is the construction path the experimental API already prescribes. - Any future higher-kinded use of
TxBodyContentas a bare type constructor, such as aclass HasCommonBodyFields (body :: Type -> Type), has to nameNestedTxBodyContent linstead.
So the kind change breaks users only if the data type is renamed without the synonym. With the synonym, the breakage is limited to the three edges above.
Footnotes
-
juggling boilerplate with LLMs is stupid easy but 1) the human at the end has to review more lines 2) I don't take LLMs for granted ↩
There was a problem hiding this comment.
I think you're right about the maintenance for the two types I was suggesting. Thinking about it some more I prefer option 1:
-- | Body content at either transaction level. The eight fields that exist only
-- on a top-level body live behind 'txTopLevel'.
data BodyContent (l :: L.TxLevel) era = BodyContent
{ txIns :: [(TxIn, AnyWitness era)]
, txInsReference :: TxInsReference era
, txOuts :: [TxOut era]
, txValidityLowerBound :: Maybe L.SlotNo
, txValidityUpperBound :: Maybe L.SlotNo
, txMetadata :: TxMetadata
, txAuxScripts :: [SimpleScript era]
, txProtocolParams :: Maybe (L.PParams era)
, txWithdrawals :: TxWithdrawals era
, txCertificates :: TxCertificates era
, txMintValue :: TxMintValue era
, txProposalProcedures :: Maybe (TxProposalProcedures era)
, txVotingProcedures :: Maybe (TxVotingProcedures era)
, txCurrentTreasuryValue :: Maybe L.Coin
, txTreasuryDonation :: Maybe L.Coin
, txSupplementalDatums :: Map L.DataHash (L.Data era)
-- Fields below are new in the Dijkstra era.
, txGuards :: OSet (L.Credential L.Guard)
, txRequiredTopLevelGuards :: Map (L.Credential L.Guard) (StrictMaybe (L.Data era))
, txDirectDeposits :: L.DirectDeposits
, txAccountBalanceIntervals :: L.AccountBalanceIntervals era
, txTopLevel :: TopLevelFields l era
}
-- | Fields a sub-transaction body cannot carry on the wire.
data TopLevelFields (l :: L.TxLevel) era where
TopLevelFields
:: { tlInsCollateral :: [TxIn]
, tlTotalCollateral :: Maybe TxTotalCollateral
, tlReturnCollateral :: Maybe (TxReturnCollateral era)
, tlFee :: L.Coin
, tlExtraKeyWits :: TxExtraKeyWitnesses
, tlScriptValidity :: ScriptValidity
, tlSubTransactions :: LOMap.OMap L.TxId (L.Tx L.SubTx era)
, tlStartingAccountBalanceIntervals :: L.AccountBalanceIntervals era
}
-> TopLevelFields L.TopTx era
NoTopLevelFields :: TopLevelFields L.SubTx era
type TxBodyContent era = BodyContent L.TopTx era
type SubTxBodyContent era = BodyContent L.SubTx era
We don't get the () fields and a type family field cannot tell you which level you hold, so every polymorphic function must be handed that proof from outside, whereas a GADT field carries the proof in the value and is matched for free
There was a problem hiding this comment.
A type family field does not carry the level, agreed. But the proof does not have to live in a GADT field, because the ledger already hands it out for free. L.withSTxBothLevels builds the STxBothLevels singleton from Typeable l, which every type has, and matching STopTx or SSubTx refines l so the family reduces in each branch:
bodyFee :: forall l era. Typeable l => NestedTxBodyContent l era -> Maybe L.Coin
bodyFee bc = L.withSTxBothLevels @l @era $ \case
L.STopTx -> Just (txFee bc) -- l ~ TopTx here, so txFee bc :: L.Coin
L.SSubTx -> NothingSo "every polymorphic function must be handed the proof from outside" comes down to one constraint that call sites discharge automatically, and only functions that actually branch on the level need it. Code over the twenty shared fields needs nothing in either design.
The GADT field is not free either. It gives you the proof only once you hold a value. Anything that produces a BodyContent l era generically, such as a decoder or an Arbitrary instance polymorphic in l, still needs the same witness to choose between TopLevelFields and NoTopLevelFields.
On breakage the two sketches are now equal. Both keep TxBodyContent era as a synonym, and I checked cardano-cli and cardano-node: nothing outside cardano-api reads the eight top-level selectors, everything goes through the setters. Your rename of those fields only touches our own tests and the gen library.
That leaves ergonomics: () fields on sub-level values, or a nested record for the eight top-level fields. If we go with option 1, two things keep it cheap:
- Keep
type TxBodyContent era = BodyContent L.TopTx eraand all the currentsetTx*functions with their present types. Then nothing outside cardano-api changes. - When a function is polymorphic in the level and has to branch on it, get the witness from the ledger with
L.withSTxBothLevelsand matchL.STopTxorL.SSubTx. We do not need a witness type of our own.
There was a problem hiding this comment.
One more thing about option 1: it inverts the structure. BodyContent is really the sub-transaction body, and a top-level transaction becomes a sub-transaction plus an extension record, with fee and collateral one level down as tlFee behind txTopLevel.
The CDDL and the ledger go the other way: the top-level body is the full one, a sub-transaction body is the same body minus some keys, and the ledger's top-level-only lenses are just typed TxBody TopTx era rather than reached through a nested record. Option 2 keeps that shape, which is a point in its favour for me.
There was a problem hiding this comment.
Alright, I'm going to go the GADT. It avoids a Typeable constraint and a ledger call at every consumer that branches on the level, and it avoids unit fields on sub-transaction bodies.
There was a problem hiding this comment.
@Jimbo4350 fine with me 👍🏻 . I just wanted to be sure that we're aware of pros and cons of each solution. Ping me for final review please.
| H.assert . isLeft $ Api.deserialiseFromCBOR (Exp.AsUnsignedSubTx Api.AsConwayEra) bytes | ||
| H.assert . isLeft $ Api.deserialiseFromCBOR (Exp.AsSignedSubTx Api.AsConwayEra) bytes | ||
|
|
||
| prop_sign_sub_tx_preserves_id :: Property |
There was a problem hiding this comment.
With signSubTx [] [] this passes even if signing did nothing, and the generated value may already carry key witnesses. Sign with a real key instead, genShelleyWitnessSigningKey from the gen module through makeSubTxKeyWitness, and check both that the id is unchanged and that the witness set of the result contains the new witness.
More broadly, nothing here goes through makeUnsignedSubTx or embeds a sub-transaction in a top-level body, so the construction path this PR adds is untested. One property covers it: build the content with the setters, makeUnsignedSubTx, sign, embed with setTxSignedSubTransactions, run makeUnsignedTx DijkstraEra, then assert the ledger body holds the sub-transaction under its id.
Temporarily pin cardano-api to the branch of IntersectMBO/cardano-api#1361 via a source-repository-package stanza, to pick up sub-transaction support ahead of a cardano-api release. That branch moves key and operational certificate code into the new cardano-keys package and re-exports DijkstraEra from the experimental API, which changes three things cardano-cli relied on: - getKesPeriod now returns the KESPeriod newtype rather than Word, so the KES period info query unwraps it with unKESPeriod. - textEnvelopeType is no longer a method of HasTextEnvelope but a standalone function, so the golden text envelope tests import it directly. - DijkstraEra no longer needs importing from Cardano.Api where the experimental API is already imported.
palas
left a comment
There was a problem hiding this comment.
I am just posting two small issues so far. I still need to look some more to understand the whole PR better
| -- ------------------------------------------------------------ | ||
| -- Fields below are new in the Dijkstra era. | ||
| -- ------------------------------------------------------------ | ||
| , txGuards :: OSet (L.Credential L.Guard) |
There was a problem hiding this comment.
We should count keys in txGuards in knowableKeyHashes in estimateTransactionKeyWitnessCount too (here)
There was a problem hiding this comment.
Agreed, key-hash guards are required signers (Dijkstra's reqSignerHashesTxBodyG reads them back out of guardsTxBodyL). We will target transaction balancing, including this estimate, in a follow-up PR.
palas
left a comment
There was a problem hiding this comment.
It is looking good. I added two more potential improvements. And maybe it would be good to add a couple of tests: one for exercising makeUnsignedSubTx, and one for the MakeUnsignedTxSubTransactionsUnsupported error. But other than that, it looks pretty solid
e169268 to
22f9767
Compare
f5fec5a to
86920a6
Compare
Move BodyContent.New to TopTx.BodyContent and add the Dijkstra-era fields (guards, sub-transactions, direct deposits, account balance intervals). Add Experimental.Tx.Internal.SubTransaction with a draft SubTx content type mirroring the ledger's DijkstraSubTxBodyRaw.
Split ledger body construction into an era-agnostic stage and an era-specific stage. Move the required-signers-or-guards translation into the era-specific stage and set guards, sub-transactions, direct deposits and account balance intervals for Dijkstra. Use the ledger's OMap for txSubTransactions.
Sub-transactions share the witnessable body fields with the top-level body and need the same script witness requirement collection. Lift the body of collectTxBodyScriptWitnessRequirements into collectScriptWitnessRequirements, taking the shared fields as arguments, so both can call it.
Add defaultSubTx, setters, UnsignedSubTx, makeUnsignedSubTx, makeSubTxKeyWitness, signSubTx and makeSignedSubTx. Add setters for the new Dijkstra fields on TxBodyContent.
Proposal and voting procedures, treasury donation and current treasury value have lenses in every supported era, so set them in the era-agnostic stage of makeUnsignedTx. eraSpecificLedgerTxBody now only handles required signer hashes (Conway) and the Dijkstra-only fields.
Index UnsignedSubTx by the API era and add SignedSubTx, mirroring SignedTx. Give both HasTypeProxy, SerialiseAsCBOR and HasTextEnvelope instances. Decoding is refused in Conway, which has no sub-transactions. Add getUnsignedSubTxId, getSignedSubTxId, unsignedSubTxFromSomeTypes, signedSubTxFromSomeTypes and setTxSignedSubTransactions, and re-export the sub-transaction API from Cardano.Api.Experimental.Tx and Cardano.Api.Experimental. Set txRequiredTopLevelGuards and txStartingAccountBalanceIntervals on the top-level Dijkstra body. Add generators and roundtrip, envelope type and tx id tests.
ee5d96e to
a475880
Compare
Replace the separate `SubTx` record with `BodyContent l era`, indexed by the ledger transaction level. The twenty fields shared by both levels live in the record; the eight that exist only in a top-level body live in the `TopTxOnlyFields` GADT, whose `AbsentInSubTx` constructor says a sub-transaction body has none of them. Matching that constructor tells you the level, so no `Typeable` constraint or ledger singleton is needed to branch on it. `TxBodyContent` and `SubTxBodyContent` are type synonyms for the two levels, and record pattern synonyms of the same names present each as a flat record. Field access, record patterns and record updates on `TxBodyContent` are unchanged, and the top-level-only setters keep their `TxBodyContent era` type. Setters of shared fields are now typed `BodyContent l era` and work on both levels, so the `setSubTx*` copies, `defaultSubTx` and `collectSubTxScriptWitnessRequirements` go away. The module moves from `Tx.Internal.TopTx.BodyContent` to `Tx.Internal.BodyContent`, since it no longer describes only the top level. The changelog fragment description is collapsed to one line.
Dijkstra is the only era with sub-transactions, so UnsignedSubTx and SignedSubTx are no longer indexed by the era. This removes the Conway branches from the decoders and from makeUnsignedSubTx, the constraints packed into both constructors, the MakeUnsignedTxSubTransactionsUnsupported error, the per-era envelope name, the FromSomeType lists and the test that Conway cannot decode a sub-transaction. Adding the index back once a second era has sub-transactions is mechanical.
makeSubTxKeyWitness and signSubTx repeated makeKeyWitness and signTx line for line, because hashTxBody was fixed to the top level. hashTxBody is now generalised over the transaction level and lives in Cardano.Api.Tx.Internal.Sign alongside two new helpers: one that signs a body hash with a Shelley key, and one that adds key witnesses to a transaction at either level. All four functions call those.
The body content record is shared by Conway and Dijkstra, so the six fields that exist only from Dijkstra onwards (guards, sub-transactions, required top-level guards, direct deposits and the two account balance interval maps) could be set on a Conway body and were dropped silently by eraSpecificLedgerTxBody. That function now throws an error naming the fields that were set, and makeUnsignedTx forces it so the error surfaces when the transaction is built.
…pported in the era eraSpecificLedgerTxBody now returns Either MakeUnsignedTxError. A new MakeUnsignedTxFieldsNotSupportedInEra constructor carries the era and the names of the offending fields, replacing the error call and the strictness workaround in makeUnsignedTx.
a475880 to
8f94be0
Compare
Temporarily pin cardano-api to the branch of IntersectMBO/cardano-api#1361 via a source-repository-package stanza, to pick up sub-transaction support ahead of a cardano-api release. That branch moves key and operational certificate code into the new cardano-keys package and re-exports DijkstraEra from the experimental API, which changes three things cardano-cli relied on: - getKesPeriod now returns the KESPeriod newtype rather than Word, so the KES period info query unwraps it with unKESPeriod. - textEnvelopeType is no longer a method of HasTextEnvelope but a standalone function, so the golden text envelope tests import it directly. - DijkstraEra no longer needs importing from Cardano.Api where the experimental API is already imported.
…ction commands Point cardano-api (and cardano-rpc) at IntersectMBO/cardano-api@c9943eb3, which is master after IntersectMBO/cardano-api#1328 (ouroboros-consensus 5.0, cardano-ledger-core 1.22) and IntersectMBO/cardano-api#1361 (the Dijkstra sub-transaction API), replacing the input-output-hk fork pin. Point cardano-cli at IntersectMBO/cardano-cli@c5062645, the head of IntersectMBO/cardano-cli#1453 ("Add transaction sub-transaction commands (Dijkstra)") on top of the 11.2 bounds update, so that the cardano-cli in the build plan has the `dijkstra transaction sub-transaction` commands the "Nested transaction swap" test needs. Previously the test could only run with CARDANO_CLI pointing at a separate build of that PR, and a build against the old ledger at that, since its `create-testnet-data` writes a Dijkstra genesis without `minPoolMargin`. With these pins both Dijkstra tests pass with no environment overrides. The cardano-cli pin is temporary: replace it once #1453 is released.
…ction commands Point cardano-api (and cardano-rpc) at IntersectMBO/cardano-api@c9943eb3, which is master after IntersectMBO/cardano-api#1328 (ouroboros-consensus 5.0, cardano-ledger-core 1.22) and IntersectMBO/cardano-api#1361 (the Dijkstra sub-transaction API), replacing the input-output-hk fork pin. Point cardano-cli at IntersectMBO/cardano-cli@c5062645, the head of IntersectMBO/cardano-cli#1453 ("Add transaction sub-transaction commands (Dijkstra)") on top of the 11.2 bounds update, so that the cardano-cli in the build plan has the `dijkstra transaction sub-transaction` commands the "Nested transaction swap" test needs. Previously the test could only run with CARDANO_CLI pointing at a separate build of that PR, and a build against the old ledger at that, since its `create-testnet-data` writes a Dijkstra genesis without `minPoolMargin`. With these pins both Dijkstra tests pass with no environment overrides. The cardano-cli pin is temporary: replace it once #1453 is released.
Changelog
Context
Groundwork for Dijkstra sub-transactions in the experimental transaction API.
BodyContent.NewtoTopTx.BodyContent.TxBodyContentwith setters. Ledger body construction now has an era-agnostic stage anderaSpecificLedgerTxBody, which cases on era. Conway is behaviourally unchanged; Dijkstra sets guards, sub-transactions, direct deposits and account balance intervals.SubTxcontent,makeUnsignedSubTx,makeSubTxKeyWitness,signSubTxandmakeSignedSubTx. Script witness requirement collection is shared with the top-level body viacollectScriptWitnessRequirements.txRequiredTopLevelGuardsandtxStartingAccountBalanceIntervalsare declared but not written: cardano-ledger-dijkstra 0.3.0.0 has no top-level lens for them.How to trust this PR
cabal build cardano-apisucceeds.eraSpecificLedgerTxBodyis the only place that cases on era when building the body, and its Conway branch sets the same fields as before.Checklist
.changes/🤖 Generated with Claude Code