@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -18,50 +18,37 @@ const tx_utils_1 = require("./utils/tx-utils");
18
18
  const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
19
19
  const { SELECT, UPDATE } = cds_1.default.ql;
20
20
  const logger = cds_1.default.log('CardanoSignService');
21
- /**
22
- * Verify that a build exists and, when an address is provided, that it matches
23
- * the build's senderAddress. Always fetches the build from DB.
24
- */
21
+ /** Load a build and, when an address is given, check it matches the build's senderAddress. */
25
22
  async function verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, actionName) {
26
23
  const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
27
24
  if (!build)
28
25
  (0, errors_1.rejectInvalid)(req, actionName, 'Build not found', 'buildId');
29
- // rejectInvalid returns `never` → build is narrowed to non-null here
30
26
  if (address && build.senderAddress !== address) {
31
27
  (0, errors_1.rejectInvalid)(req, actionName, 'Address does not match build owner', 'address');
32
28
  }
33
29
  return build;
34
30
  }
35
31
  /**
36
- * Check if a signing request has expired and update its status.
32
+ * Expire a pending signing request past its TTL.
37
33
  * @returns true if expired, false otherwise
38
34
  */
39
35
  async function checkAndExpireSigningRequest(db, signingRequest, SigningRequests) {
40
36
  const now = new Date().toISOString();
41
37
  const result = await db.run(UPDATE.entity(SigningRequests)
42
38
  .set({ status: 'expired' })
43
- // status filter: only PENDING requests may expire — without it an old
44
- // 'submitted'/'verified' record would be flipped to 'expired' here
39
+ // Only pending requests may expire; never flip a 'submitted'/'verified' row.
45
40
  .where({ id: signingRequest.id, status: 'pending', expiresAt: { '<=': now } }));
46
41
  if (result > 0) {
47
42
  signingRequest.status = 'expired';
48
43
  return true;
49
44
  }
50
- // NOTE: when the surrounding request is subsequently rejected, CAP rolls the
51
- // managed transaction back — including this update. The expiry status is
52
- // then re-applied on the next touch; reads always re-check expiresAt.
45
+ // A later req.reject rolls this update back; the next touch re-applies it.
53
46
  return false;
54
47
  }
55
48
  /**
56
- * Resolve the key hashes that MUST witness a signing request:
57
- * - the `required_signers` declared in the unsigned tx body (extra_signatories)
58
- * - the payment KEY hash of the associated build's senderAddress (the fee
59
- * payer's inputs require its witness on-chain anyway; script credentials
60
- * are skipped — scripts witness via redeemers, not vkeys)
61
- *
62
- * Previously NONE of this was checked: any valid signature from ANY key
63
- * flipped the request to 'verified' / let SubmitVerifiedTransaction proceed.
64
- * Returns undefined when nothing is derivable (no over-restriction).
49
+ * Key hashes that must witness a signing request: the body's `required_signers` plus the
50
+ * payment key hash of the build's senderAddress (script credentials skipped).
51
+ * Returns undefined when nothing is derivable.
65
52
  */
66
53
  async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
67
54
  const signers = new Set();
@@ -71,7 +58,7 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
71
58
  signers.add(s.toLowerCase());
72
59
  }
73
60
  catch (err) {
74
- // body-hash verification still protects integrity; just log
61
+ // Body-hash verification still protects integrity.
75
62
  logger.warn(`Could not parse unsigned tx for required_signers: ${err instanceof Error ? err.message : String(err)}`);
76
63
  }
77
64
  if (signingRequest.build_id) {
@@ -84,30 +71,18 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
84
71
  }
85
72
  return signers.size > 0 ? [...signers] : undefined;
86
73
  }
87
- // submitAndFinalize + FinalizeParams moved to blockchain/signing/submission-finalizer.ts
88
- // (shared with the boot-time redrive of interrupted deferred submissions).
89
- /**
90
- * Enforce HSM role check if hsm.requiresRole is configured.
91
- * Rejects with 403 if the user lacks the required role.
92
- */
74
+ /** 403 unless the user holds hsm.requiresRole (no-op when none is configured). */
93
75
  function enforceHsmRole(req, actionName) {
94
76
  const hsmConfig = (0, server_1.getHsmConfig)();
95
77
  if (hsmConfig?.requiresRole && !req.user?.is(hsmConfig.requiresRole)) {
96
78
  req.reject(403, `Action '${actionName}' requires role '${hsmConfig.requiresRole}'`);
97
79
  }
98
80
  }
99
- /**
100
- * Cardano Sign Service Implementation
101
- * Handles transaction signing operations & some additional data queries.
102
- */
81
+ /** CardanoSignService handlers: external and HSM signing, verification, submission. */
103
82
  module.exports = (srv) => {
104
83
  logger.info('Module loaded - registering handlers');
105
84
  const { SigningRequests, AddressSigningRequests, TransactionBuilds, } = require('#cds-models/CardanoSignService');
106
- /**
107
- * before-READ handler for SigningRequests: bulk expiration check
108
- * Atomically expires all pending requests past their TTL (handles both single and collection reads)
109
- * Throttled to run at most once per 60 seconds to avoid write amplification on every READ.
110
- */
85
+ // before-READ: bulk-expire pending requests past their TTL, at most once per minute.
111
86
  let lastExpiryCheck = 0;
112
87
  const EXPIRY_CHECK_INTERVAL_MS = 60_000;
113
88
  srv.before('READ', SigningRequests, async (req) => {
@@ -119,33 +94,23 @@ module.exports = (srv) => {
119
94
  .set({ status: 'expired' })
120
95
  .where({ status: 'pending', expiresAt: { '<=': new Date().toISOString() } }));
121
96
  });
122
- /**
123
- * Create a new signing request for external signing
124
- * Persists the request for audit trail and workflow tracking
125
- * @param req - CDS request object (with buildId)
126
- * @returns {SigningRequest} Signing request entity
127
- */
97
+ // CreateSigningRequest — persist a signing request for a build (idempotent per pending build).
128
98
  srv.on('CreateSigningRequest', async (req) => {
129
99
  logger.debug('CreateSigningRequest Action handler called');
130
100
  const { buildId, message } = req.data;
131
- // Validate inputs
132
101
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
133
102
  (0, errors_1.throwIfValidationErrors)(req, 'CreateSigningRequest', errors);
134
103
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
135
- // Fetch the build
136
104
  const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
137
105
  if (!build)
138
106
  (0, errors_1.rejectInvalid)(req, 'CreateSigningRequest', 'Build not found', 'buildId');
139
- // Check if signing request already exists for this build
140
107
  const existingRequest = await db.run(SELECT.one.from(SigningRequests).where({ build_id: buildId, status: 'pending' }));
141
108
  if (existingRequest) {
142
109
  logger.info({ buildId, signingRequestId: existingRequest.id }, 'Returning existing signing request');
143
110
  return existingRequest;
144
111
  }
145
- // Create signing request using external signer module
146
112
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
147
113
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, message);
148
- // Delegate persistence to indexer
149
114
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
150
115
  buildId,
151
116
  signingPayload,
@@ -154,34 +119,23 @@ module.exports = (srv) => {
154
119
  return signingRequestRecord;
155
120
  });
156
121
  });
157
- /**
158
- * Get an existing signing request by ID
159
- * @param req - CDS request object (with signingRequestId)
160
- * @returns {SigningRequest} signing request entity
161
- */
122
+ // GetSigningRequest — by id; expires a pending request past its TTL on read.
162
123
  srv.on('GetSigningRequest', async (req) => {
163
124
  logger.debug('GetSigningRequest Action handler called');
164
125
  const { signingRequestId } = req.data;
165
- // Validate inputs
166
126
  const errors = (0, validators_1.validateTransactionInputs)({ signingRequestId }, ['signingRequestId']);
167
127
  (0, errors_1.throwIfValidationErrors)(req, 'GetSigningRequest', errors);
168
- // Fetch the signing request within transaction context
169
128
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
170
129
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
171
130
  if (!signingRequest)
172
131
  (0, errors_1.rejectInvalid)(req, 'GetSigningRequest', 'Signing request not found', 'signingRequestId');
173
- // Check if expired and update status if needed
174
132
  if (signingRequest.status === 'pending') {
175
133
  await checkAndExpireSigningRequest(db, signingRequest, SigningRequests);
176
134
  }
177
135
  return signingRequest;
178
136
  });
179
137
  });
180
- /**
181
- * Verify signature of a signed transaction (unbound action)
182
- * @param req - CDS request with signingRequestId + signedTxCbor in data
183
- * @returns {SignatureVerification} Persisted signature verification entity
184
- */
138
+ // VerifySignature — verify a signed tx / witness set against the request; persists the result.
185
139
  srv.on('VerifySignature', async (req) => {
186
140
  logger.debug('VerifySignature Action handler called');
187
141
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
@@ -190,26 +144,21 @@ module.exports = (srv) => {
190
144
  if (address && !(0, validators_1.isValidBech32Address)(address))
191
145
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Invalid bech32 address format', 'address');
192
146
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
193
- // Fetch the signing request (@from already validated by framework)
194
147
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
195
148
  if (!signingRequest)
196
149
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Signing request not found', 'signingRequestId');
197
- // Ownership check: verify address matches build owner (defense-in-depth)
150
+ // Ownership check (defense in depth)
198
151
  if (address && signingRequest.build_id) {
199
152
  await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'VerifySignature');
200
153
  }
201
- // Atomically CLAIM the pending request (pending → 'signed' = verification
202
- // in progress). Replaces the read-then-check pattern that let two
203
- // concurrent verifies both pass `status === 'pending'` and double-insert
204
- // verification records (last-writer-wins on status). The final status is
205
- // overwritten to 'verified'/'failed' by persistSignatureVerification.
154
+ // Atomic claim (pending → 'signed') so concurrent verifies cannot both pass;
155
+ // persistSignatureVerification sets the final 'verified'/'failed'.
206
156
  const now = new Date().toISOString();
207
157
  const claimed = await db.run(UPDATE.entity(SigningRequests)
208
158
  .set({ status: 'signed' })
209
159
  .where({ id: signingRequestId, status: 'pending', expiresAt: { '>': now } }));
210
160
  if (claimed === 0) {
211
- // re-read the committed state for an accurate message (a concurrent
212
- // verify may have moved it since our SELECT above)
161
+ // Re-read for an accurate message; a concurrent verify may have moved it.
213
162
  const current = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
214
163
  if (current && current.status === 'pending' && current.expiresAt <= now) {
215
164
  await db.run(UPDATE.entity(SigningRequests).set({ status: 'expired' }).where({ id: signingRequestId, status: 'pending' }));
@@ -217,23 +166,20 @@ module.exports = (srv) => {
217
166
  }
218
167
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', `Signing request status is '${current?.status ?? 'unknown'}', expected 'pending'`, 'signingRequestId');
219
168
  }
220
- // Detect if signedTxCbor is a witness set (CIP-30) or a full signed transaction (cardano-cli)
169
+ // A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
221
170
  let fullSignedTxCbor;
222
171
  if ((0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)) {
223
- // CIP-30 wallet returns only witness set — combine with unsigned tx
224
172
  fullSignedTxCbor = (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor);
225
173
  logger.debug({ signingRequestId }, 'Combined witness set with unsigned transaction for verification');
226
174
  }
227
175
  else {
228
- // Full signed transaction provided (e.g., from cardano-cli)
229
176
  fullSignedTxCbor = signedTxCbor;
230
177
  }
231
- // Verify the signature — bound to the keys that must actually witness
232
- // this transaction (declared required_signers + the build's fee payer)
178
+ // Verification is bound to the keys that must witness this tx.
233
179
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
234
180
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
235
181
  const result = signerModule.verifySignedTransaction(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
236
- // Delegate persistence to indexer (store full signed tx for later submission)
182
+ // Store the full signed tx for later submission
237
183
  const verificationRecord = await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
238
184
  signingRequestId,
239
185
  signedTxCbor: fullSignedTxCbor,
@@ -250,11 +196,7 @@ module.exports = (srv) => {
250
196
  return verificationRecord;
251
197
  });
252
198
  });
253
- /**
254
- * Verify and submit a signed transaction in one step (unbound action)
255
- * @param req - CDS request with signingRequestId + signedTxCbor in data
256
- * @returns {TransactionSubmission} Transaction submission details
257
- */
199
+ // SubmitVerifiedTransaction — verify and submit in one step.
258
200
  srv.on('SubmitVerifiedTransaction', async (req) => {
259
201
  logger.debug('SubmitVerifiedTransaction Action handler called');
260
202
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
@@ -263,22 +205,12 @@ module.exports = (srv) => {
263
205
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
264
206
  if (address && !(0, validators_1.isValidBech32Address)(address))
265
207
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Invalid bech32 address format', 'address');
266
- // Three committed phases instead of one request-long transaction (see
267
- // submitAndFinalize): the network submit must NOT run inside an open DB
268
- // transaction. Errors are mapped the same way handleRequest would.
269
- //
270
- // deferSubmit (KNOWN_ISSUES #11, Layer 2): phase 1 instead JOINS the
271
- // caller's transaction (claim + signed CBOR commit with the caller), the
272
- // response returns immediately with the tx hash (= body hash), and the
273
- // network submit runs detached after the caller's commit.
208
+ // Three committed phases (see submitAndFinalize): the network submit must not run inside
209
+ // an open DB transaction. With deferSubmit, phase 1 joins the caller's transaction, the
210
+ // response carries the tx hash (= body hash) and the submit runs after the caller's commit.
274
211
  try {
275
- // PHASE 1 (committed): fully verify, then atomically claim → 'submitting'.
276
- // The claim is deliberately the LAST statement: on the deferred path
277
- // these statements run on the CALLER's transaction, and a verification
278
- // failure whose error the caller swallows (and then commits) must not
279
- // leave a stranded 'submitting' claim behind — everything before the
280
- // claim is read-only. The guarded UPDATE (status still pending/verified)
281
- // remains the atomic gate against concurrent submits on both paths.
212
+ // Phase 1: verify, then atomically claim → 'submitting'. The claim is the last statement
213
+ // so a verification failure swallowed by the caller never leaves a stranded claim behind.
282
214
  const phase1 = async (db) => {
283
215
  const now = new Date().toISOString();
284
216
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
@@ -289,25 +221,22 @@ module.exports = (srv) => {
289
221
  if (!['pending', 'verified'].includes(signingRequest.status)) {
290
222
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${signingRequest.status}', expected 'pending' or 'verified'`, 'signingRequestId');
291
223
  }
292
- // Ownership check: verify address matches build owner (defense-in-depth)
224
+ // Ownership check (defense in depth)
293
225
  if (address && signingRequest.build_id) {
294
226
  await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
295
227
  }
296
- // Check if build association exists
297
228
  if (!signingRequest.build_id) {
298
229
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
299
230
  }
300
- // Detect if signedTxCbor is a witness set (CIP-30) or a full signed transaction (cardano-cli)
231
+ // CIP-30 witness set or full signed tx
301
232
  const fullSignedTxCbor = (0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)
302
233
  ? (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor)
303
234
  : signedTxCbor;
304
- // Verify signature (throws on failure) — bound to the keys that must
305
- // actually witness this transaction (required_signers + fee payer)
235
+ // Throws on failure; bound to the keys that must witness this tx.
306
236
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
307
237
  const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
308
- // Atomic claim — last statement, see above. Deferred path: persist the
309
- // signed CBOR + signer metadata with the claim, so an interrupted
310
- // submission can be re-driven after a restart.
238
+ // Atomic claim. Deferred path also persists the signed CBOR + signer metadata so an
239
+ // interrupted submission can be re-driven after a restart.
311
240
  const claimed = await db.run(UPDATE.entity(SigningRequests)
312
241
  .set({
313
242
  status: 'submitting',
@@ -333,9 +262,7 @@ module.exports = (srv) => {
333
262
  signerInfo,
334
263
  });
335
264
  if (deferSubmit) {
336
- // Phase 1 on the CALLER's transaction: joins its pooled connection (no
337
- // deadlock), commits together with the caller. Validation errors stay
338
- // synchronous; the submit is scheduled for after the commit.
265
+ // Phase 1 on the caller's transaction; validation errors stay synchronous.
339
266
  const prep = await phase1(cds_1.default.tx(req));
340
267
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
341
268
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed — submit deferred until after the caller commits');
@@ -350,7 +277,7 @@ module.exports = (srv) => {
350
277
  }
351
278
  const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
352
279
  logger.info({ signingRequestId, witnessCount: prep.verificationResult.witnessCount }, 'Signature verified, proceeding with submission');
353
- // PHASES 2+3: submit outside any DB tx, then finalize in its own tx
280
+ // Phases 2+3: submit outside any DB tx, then finalize in its own tx
354
281
  const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
355
282
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
356
283
  return submissionRecord;
@@ -360,17 +287,11 @@ module.exports = (srv) => {
360
287
  return (0, mappers_1.mapError)(req, e, 'SubmitVerifiedTransaction');
361
288
  }
362
289
  });
363
- /**
364
- * Verify a CIP-30 signData (COSE_Sign1) message signature (unbound action).
365
- * Stateless crypto check behind wallet-based login — no DB write, no state.
366
- * Public (@requires:'any' in CDS) because the caller is not yet authenticated.
367
- * @param req - CDS request with address, coseSignature, coseKey, expectedPayload
368
- * @returns { valid, reason, signedPayload, signerVkh }
369
- */
290
+ // VerifyDataSignature — stateless CIP-30 signData (COSE_Sign1) check for wallet login.
291
+ // Public (@requires:'any') because the caller is not yet authenticated.
370
292
  srv.on('VerifyDataSignature', async (req) => {
371
293
  logger.debug('VerifyDataSignature Action handler called');
372
294
  const { address, coseSignature, coseKey, expectedPayload } = req.data;
373
- // Validate inputs before the crypto check
374
295
  if (!address)
375
296
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'address');
376
297
  if (!(0, validators_1.isValidBech32Address)(address))
@@ -379,80 +300,60 @@ module.exports = (srv) => {
379
300
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseSignature');
380
301
  if (!coseKey)
381
302
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseKey');
382
- // verifyDataSignature never throws: a bad/forged signature is a 200 with
383
- // valid:false + reason, not an error. Only malformed *inputs* reject above.
303
+ // Never throws: a bad signature is a 200 with valid:false + reason.
384
304
  return (0, cose_verifier_1.verifyDataSignature)({ address, coseSignature, coseKey, expectedPayload });
385
305
  });
386
- /**
387
- * Get all existing signing requests by address
388
- * @param req - CDS request object (with address)
389
- * @returns {AddressSigningRequests} Address signing request associations
390
- */
306
+ // GetSigningRequestsByAddress — address ↔ signing request associations.
391
307
  srv.on('GetSigningRequestsByAddress', async (req) => {
392
308
  logger.debug('GetSigningRequestsByAddress Action handler called');
393
309
  const { address } = req.data;
394
- // Validate input before business logic
395
310
  if (!address)
396
311
  (0, errors_1.rejectMissing)(req, 'GetSigningRequestsByAddress', 'address');
397
312
  if (!(0, validators_1.isValidBech32Address)(address))
398
313
  (0, errors_1.rejectInvalid)(req, 'GetSigningRequestsByAddress', 'Invalid bech32 address format', 'address');
399
- // Fetch the address-signing request associations
400
314
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
401
315
  return db.run(SELECT.from(AddressSigningRequests).where({ address_address: address }));
402
316
  });
403
317
  });
404
318
  // ---------------------------------------------------------------------------
405
- // HSM (Hardware Security Module) Signing Actions
319
+ // HSM signing actions
406
320
  // ---------------------------------------------------------------------------
407
- /**
408
- * Sign a transaction using the configured HSM.
409
- * Creates signing request, signs with HSM, verifies the signature.
410
- * @param req - CDS request object (with buildId)
411
- * @returns {SigningRequest} Signing request with status 'verified'
412
- */
321
+ // SignWithHsm — create a signing request, sign with the HSM, verify; returns the request.
413
322
  srv.on('SignWithHsm', async (req) => {
414
323
  logger.debug('SignWithHsm Action handler called');
415
324
  enforceHsmRole(req, 'SignWithHsm');
416
325
  const { buildId, address } = req.data;
417
- // Validate input
418
326
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
419
327
  (0, errors_1.throwIfValidationErrors)(req, 'SignWithHsm', errors);
420
328
  if (address && !(0, validators_1.isValidBech32Address)(address))
421
329
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'Invalid bech32 address format', 'address');
422
- // Check HSM is available (before handleRequest — same pattern as validation)
423
330
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
424
331
  if (!hsmSigner || !hsmSigner.isConnected()) {
425
332
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM is not configured or not connected', 'hsm');
426
333
  }
427
334
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
428
- // 1. Fetch the build (with ownership check)
429
335
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignWithHsm');
430
- // HSM can only sign builds for its own address
336
+ // The HSM can only sign builds for its own address
431
337
  const hsmAddress = hsmSigner.getAddress();
432
338
  if (build.senderAddress !== hsmAddress) {
433
339
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
434
340
  }
435
- // 2. Create signing request internally (reuse external signer module)
436
341
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
437
342
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing');
438
343
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
439
344
  buildId,
440
345
  signingPayload,
441
346
  });
442
- // 3. Sign with HSM
443
347
  const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
444
- // 4. Verify the HSM signature (same verification path as external signing)
348
+ // Same verification path as external signing
445
349
  const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
446
350
  const hsmStatus = hsmSigner.getStatus();
447
351
  const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
448
- // A failed HSM verification is an HSM/server fault, not a successful sign —
449
- // reject (rolls back) instead of returning 200 with status 'failed', matching
450
- // SignAndSubmitWithHsm.
352
+ // A failed HSM verification is a server fault: reject (rolls back) rather than 200 'failed'.
451
353
  if (!verificationResult.isValid) {
452
354
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed');
453
355
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM signature verification failed', 'signedTxCbor');
454
356
  }
455
- // 5. Persist verification
456
357
  await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
457
358
  signingRequestId: signingRequestRecord.id,
458
359
  signedTxCbor,
@@ -460,7 +361,7 @@ module.exports = (srv) => {
460
361
  signerType: 'hsm',
461
362
  signerInfo: `HSM key: ${hsmKeyIdentifier}`,
462
363
  });
463
- // 6. Update HSM audit field
364
+ // HSM audit field
464
365
  await db.run(UPDATE.entity(SigningRequests)
465
366
  .set({ hsmKeyId: hsmKeyIdentifier })
466
367
  .where({ id: signingRequestRecord.id }));
@@ -470,51 +371,38 @@ module.exports = (srv) => {
470
371
  isValid: verificationResult.isValid,
471
372
  hsmKey: hsmKeyIdentifier,
472
373
  }, 'Transaction signed with HSM');
473
- // Return updated signing request
474
374
  return db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestRecord.id }));
475
375
  });
476
376
  });
477
- /**
478
- * Sign a transaction with HSM and submit to blockchain atomically.
479
- * Creates signing request, signs, verifies, and submits in one operation.
480
- * @param req - CDS request object (with buildId)
481
- * @returns {TransactionSubmission} Transaction submission details
482
- */
377
+ // SignAndSubmitWithHsm — create a signing request, sign, verify and submit in one call.
483
378
  srv.on('SignAndSubmitWithHsm', async (req) => {
484
379
  logger.debug('SignAndSubmitWithHsm Action handler called');
485
380
  enforceHsmRole(req, 'SignAndSubmitWithHsm');
486
381
  const { buildId, address } = req.data;
487
382
  const deferSubmit = req.data.deferSubmit === true;
488
- // Validate input
489
383
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
490
384
  (0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
491
385
  if (address && !(0, validators_1.isValidBech32Address)(address))
492
386
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'Invalid bech32 address format', 'address');
493
- // Check HSM is available
494
387
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
495
388
  if (!hsmSigner || !hsmSigner.isConnected()) {
496
389
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM is not configured or not connected', 'hsm');
497
390
  }
498
391
  try {
499
- // PHASE 1 (committed): fetch build, sign with HSM, verify. A failure
500
- // here rolls back the freshly-created signing request. (Deferred path:
501
- // the INSERT runs on the caller's tx; a swallowed failure leaves a
502
- // 'pending' row that expires via its TTL — harmless.)
392
+ // Phase 1 (committed): fetch build, sign, verify. A failure rolls back the new signing
393
+ // request; on the deferred path a swallowed failure leaves a 'pending' row that expires via TTL.
503
394
  const phase1 = async (db) => {
504
- // 1. Fetch the build (with ownership check)
505
395
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
506
- // HSM can only sign builds for its own address
396
+ // The HSM can only sign builds for its own address
507
397
  const hsmAddress = hsmSigner.getAddress();
508
398
  if (build.senderAddress !== hsmAddress) {
509
399
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
510
400
  }
511
- // 2. Create signing request
512
401
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
513
402
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing + submit');
514
403
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, { buildId, signingPayload });
515
- // 3. Sign with HSM
516
404
  const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
517
- // 4. Verify HSM signature — reject (rolls back) if invalid before submitting
405
+ // Reject (rolls back) on an invalid signature before submitting
518
406
  const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
519
407
  const hsmStatus = hsmSigner.getStatus();
520
408
  const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
@@ -522,9 +410,8 @@ module.exports = (srv) => {
522
410
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed — aborting submission');
523
411
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
524
412
  }
525
- // Claim the request as 'submitting' in this same committed phase.
526
- // Deferred path: also persist the signed CBOR + signer metadata for
527
- // the boot-time redrive of interrupted submissions.
413
+ // Claim as 'submitting'; deferred path also persists signed CBOR + signer metadata
414
+ // for the boot-time redrive of interrupted submissions.
528
415
  await db.run(UPDATE.entity(SigningRequests).set({
529
416
  status: 'submitting',
530
417
  hsmKeyId: hsmKeyIdentifier,
@@ -542,9 +429,7 @@ module.exports = (srv) => {
542
429
  signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
543
430
  });
544
431
  if (deferSubmit) {
545
- // Phase 1 on the CALLER's transaction (KNOWN_ISSUES #11, Layer 2):
546
- // sign + verify + claim commit with the caller; submit runs after its
547
- // commit. See SubmitVerifiedTransaction for the full rationale.
432
+ // Phase 1 on the caller's transaction; submit runs after its commit.
548
433
  const prep = await phase1(cds_1.default.tx(req));
549
434
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
550
435
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed — submit deferred until after the caller commits');
@@ -559,8 +444,8 @@ module.exports = (srv) => {
559
444
  }
560
445
  const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
561
446
  logger.info({ signingRequestId: prep.signingRequestId, witnessCount: prep.verificationResult.witnessCount, hsmKey: prep.hsmKeyIdentifier }, 'HSM signature verified, proceeding with submission');
562
- // PHASES 2+3: submit outside any DB tx, then finalize (re-set hsmKeyId,
563
- // which indexVerifiedTransactionSubmission does not touch)
447
+ // Phases 2+3: submit outside any DB tx, then finalize (re-sets hsmKeyId, which the
448
+ // generic finalizer does not touch)
564
449
  const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep), (db) => db.run(UPDATE.entity(SigningRequests).set({ hsmKeyId: prep.hsmKeyIdentifier }).where({ id: prep.signingRequestId })).then(() => undefined));
565
450
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
566
451
  return submissionRecord;
@@ -570,10 +455,7 @@ module.exports = (srv) => {
570
455
  return (0, mappers_1.mapError)(req, e, 'SignAndSubmitWithHsm');
571
456
  }
572
457
  });
573
- /**
574
- * Get HSM connection status and key information.
575
- * Returns null fields if HSM is not configured.
576
- */
458
+ // GetHsmStatus — connection status and key info; null fields when no HSM is configured.
577
459
  srv.on('GetHsmStatus', async (_req) => {
578
460
  enforceHsmRole(_req, 'GetHsmStatus');
579
461
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
@@ -216,7 +216,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
216
216
  @description: 'Optional JSON array of {txHash, outputIndex} UTxOs to include as CIP-31 reference inputs (read-only, not consumed). Use for oracle feeds, shared config UTxOs, or script reference UTxOs. Buildooor builder only.'
217
217
  referenceInputsJson: String,
218
218
  @title: 'Extra Outputs JSON'
219
- @description: 'Optional JSON array of additional outputs [{address, lovelaceAmount, assets?, inlineDatumJson?, referenceScriptHex?}] appended after the primary recipient output. When present, the extra outputs carry the minted assets (declare each minted unit in an entry''s assets) and the primary output stays ADA-only — used to place each minted token on its own output with its own inline datum (e.g. datum-bound predicate tokens). Each entry is independently min-ADA checked.'
219
+ @description: 'Optional JSON array of additional outputs [{address, lovelaceAmount, assets?, inlineDatumJson?, referenceScriptHex?}] appended after the primary recipient output. When present, the extra outputs carry the minted assets (declare each minted unit in an entry''s assets) and the primary output stays ADA-only — to place each minted token on its own output with its own inline datum (e.g. datum-bound predicate tokens). Each entry is independently min-ADA checked.'
220
220
  extraOutputsJson: String,
221
221
  @title: 'Metadata JSON'
222
222
  @description: 'Optional transaction metadata as JSON (CIP-20 / label-674 etc.). Object keyed by numeric label string. Attached as auxiliary_data to the mint tx so chain-watchers can correlate off-chain context (receipt IDs, free-form notes).'