@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
@@ -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,13 @@ 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)
221
- let fullSignedTxCbor;
222
- if ((0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)) {
223
- // CIP-30 wallet returns only witness set — combine with unsigned tx
224
- fullSignedTxCbor = (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor);
225
- logger.debug({ signingRequestId }, 'Combined witness set with unsigned transaction for verification');
226
- }
227
- else {
228
- // Full signed transaction provided (e.g., from cardano-cli)
229
- fullSignedTxCbor = signedTxCbor;
230
- }
231
- // Verify the signature — bound to the keys that must actually witness
232
- // this transaction (declared required_signers + the build's fee payer)
169
+ // A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
170
+ const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
171
+ // Verification is bound to the keys that must witness this tx.
233
172
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
234
173
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
235
174
  const result = signerModule.verifySignedTransaction(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
236
- // Delegate persistence to indexer (store full signed tx for later submission)
175
+ // Store the full signed tx for later submission
237
176
  const verificationRecord = await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
238
177
  signingRequestId,
239
178
  signedTxCbor: fullSignedTxCbor,
@@ -250,11 +189,7 @@ module.exports = (srv) => {
250
189
  return verificationRecord;
251
190
  });
252
191
  });
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
- */
192
+ // SubmitVerifiedTransaction — verify and submit in one step.
258
193
  srv.on('SubmitVerifiedTransaction', async (req) => {
259
194
  logger.debug('SubmitVerifiedTransaction Action handler called');
260
195
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
@@ -263,22 +198,12 @@ module.exports = (srv) => {
263
198
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
264
199
  if (address && !(0, validators_1.isValidBech32Address)(address))
265
200
  (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.
201
+ // Three committed phases (see submitAndFinalize): the network submit must not run inside
202
+ // an open DB transaction. With deferSubmit, phase 1 joins the caller's transaction, the
203
+ // response carries the tx hash (= body hash) and the submit runs after the caller's commit.
274
204
  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.
205
+ // Phase 1: verify, then atomically claim → 'submitting'. The claim is the last statement
206
+ // so a verification failure swallowed by the caller never leaves a stranded claim behind.
282
207
  const phase1 = async (db) => {
283
208
  const now = new Date().toISOString();
284
209
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
@@ -289,25 +214,20 @@ module.exports = (srv) => {
289
214
  if (!['pending', 'verified'].includes(signingRequest.status)) {
290
215
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${signingRequest.status}', expected 'pending' or 'verified'`, 'signingRequestId');
291
216
  }
292
- // Ownership check: verify address matches build owner (defense-in-depth)
217
+ // Ownership check (defense in depth)
293
218
  if (address && signingRequest.build_id) {
294
219
  await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
295
220
  }
296
- // Check if build association exists
297
221
  if (!signingRequest.build_id) {
298
222
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
299
223
  }
300
- // Detect if signedTxCbor is a witness set (CIP-30) or a full signed transaction (cardano-cli)
301
- const fullSignedTxCbor = (0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)
302
- ? (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor)
303
- : signedTxCbor;
304
- // Verify signature (throws on failure) — bound to the keys that must
305
- // actually witness this transaction (required_signers + fee payer)
224
+ // CIP-30 witness set or full signed tx
225
+ const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
226
+ // Throws on failure; bound to the keys that must witness this tx.
306
227
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
307
228
  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.
229
+ // Atomic claim. Deferred path also persists the signed CBOR + signer metadata so an
230
+ // interrupted submission can be re-driven after a restart.
311
231
  const claimed = await db.run(UPDATE.entity(SigningRequests)
312
232
  .set({
313
233
  status: 'submitting',
@@ -333,9 +253,7 @@ module.exports = (srv) => {
333
253
  signerInfo,
334
254
  });
335
255
  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.
256
+ // Phase 1 on the caller's transaction; validation errors stay synchronous.
339
257
  const prep = await phase1(cds_1.default.tx(req));
340
258
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
341
259
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed — submit deferred until after the caller commits');
@@ -350,7 +268,7 @@ module.exports = (srv) => {
350
268
  }
351
269
  const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
352
270
  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
271
+ // Phases 2+3: submit outside any DB tx, then finalize in its own tx
354
272
  const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
355
273
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
356
274
  return submissionRecord;
@@ -360,17 +278,11 @@ module.exports = (srv) => {
360
278
  return (0, mappers_1.mapError)(req, e, 'SubmitVerifiedTransaction');
361
279
  }
362
280
  });
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
- */
281
+ // VerifyDataSignature — stateless CIP-30 signData (COSE_Sign1) check for wallet login.
282
+ // Public (@requires:'any') because the caller is not yet authenticated.
370
283
  srv.on('VerifyDataSignature', async (req) => {
371
284
  logger.debug('VerifyDataSignature Action handler called');
372
285
  const { address, coseSignature, coseKey, expectedPayload } = req.data;
373
- // Validate inputs before the crypto check
374
286
  if (!address)
375
287
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'address');
376
288
  if (!(0, validators_1.isValidBech32Address)(address))
@@ -379,80 +291,60 @@ module.exports = (srv) => {
379
291
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseSignature');
380
292
  if (!coseKey)
381
293
  (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.
294
+ // Never throws: a bad signature is a 200 with valid:false + reason.
384
295
  return (0, cose_verifier_1.verifyDataSignature)({ address, coseSignature, coseKey, expectedPayload });
385
296
  });
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
- */
297
+ // GetSigningRequestsByAddress — address ↔ signing request associations.
391
298
  srv.on('GetSigningRequestsByAddress', async (req) => {
392
299
  logger.debug('GetSigningRequestsByAddress Action handler called');
393
300
  const { address } = req.data;
394
- // Validate input before business logic
395
301
  if (!address)
396
302
  (0, errors_1.rejectMissing)(req, 'GetSigningRequestsByAddress', 'address');
397
303
  if (!(0, validators_1.isValidBech32Address)(address))
398
304
  (0, errors_1.rejectInvalid)(req, 'GetSigningRequestsByAddress', 'Invalid bech32 address format', 'address');
399
- // Fetch the address-signing request associations
400
305
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
401
306
  return db.run(SELECT.from(AddressSigningRequests).where({ address_address: address }));
402
307
  });
403
308
  });
404
309
  // ---------------------------------------------------------------------------
405
- // HSM (Hardware Security Module) Signing Actions
310
+ // HSM signing actions
406
311
  // ---------------------------------------------------------------------------
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
- */
312
+ // SignWithHsm — create a signing request, sign with the HSM, verify; returns the request.
413
313
  srv.on('SignWithHsm', async (req) => {
414
314
  logger.debug('SignWithHsm Action handler called');
415
315
  enforceHsmRole(req, 'SignWithHsm');
416
316
  const { buildId, address } = req.data;
417
- // Validate input
418
317
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
419
318
  (0, errors_1.throwIfValidationErrors)(req, 'SignWithHsm', errors);
420
319
  if (address && !(0, validators_1.isValidBech32Address)(address))
421
320
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'Invalid bech32 address format', 'address');
422
- // Check HSM is available (before handleRequest — same pattern as validation)
423
321
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
424
322
  if (!hsmSigner || !hsmSigner.isConnected()) {
425
323
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM is not configured or not connected', 'hsm');
426
324
  }
427
325
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
428
- // 1. Fetch the build (with ownership check)
429
326
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignWithHsm');
430
- // HSM can only sign builds for its own address
327
+ // The HSM can only sign builds for its own address
431
328
  const hsmAddress = hsmSigner.getAddress();
432
329
  if (build.senderAddress !== hsmAddress) {
433
330
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
434
331
  }
435
- // 2. Create signing request internally (reuse external signer module)
436
332
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
437
333
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing');
438
334
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
439
335
  buildId,
440
336
  signingPayload,
441
337
  });
442
- // 3. Sign with HSM
443
338
  const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
444
- // 4. Verify the HSM signature (same verification path as external signing)
339
+ // Same verification path as external signing
445
340
  const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
446
341
  const hsmStatus = hsmSigner.getStatus();
447
342
  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.
343
+ // A failed HSM verification is a server fault: reject (rolls back) rather than 200 'failed'.
451
344
  if (!verificationResult.isValid) {
452
345
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed');
453
346
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM signature verification failed', 'signedTxCbor');
454
347
  }
455
- // 5. Persist verification
456
348
  await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
457
349
  signingRequestId: signingRequestRecord.id,
458
350
  signedTxCbor,
@@ -460,7 +352,7 @@ module.exports = (srv) => {
460
352
  signerType: 'hsm',
461
353
  signerInfo: `HSM key: ${hsmKeyIdentifier}`,
462
354
  });
463
- // 6. Update HSM audit field
355
+ // HSM audit field
464
356
  await db.run(UPDATE.entity(SigningRequests)
465
357
  .set({ hsmKeyId: hsmKeyIdentifier })
466
358
  .where({ id: signingRequestRecord.id }));
@@ -470,51 +362,38 @@ module.exports = (srv) => {
470
362
  isValid: verificationResult.isValid,
471
363
  hsmKey: hsmKeyIdentifier,
472
364
  }, 'Transaction signed with HSM');
473
- // Return updated signing request
474
365
  return db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestRecord.id }));
475
366
  });
476
367
  });
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
- */
368
+ // SignAndSubmitWithHsm — create a signing request, sign, verify and submit in one call.
483
369
  srv.on('SignAndSubmitWithHsm', async (req) => {
484
370
  logger.debug('SignAndSubmitWithHsm Action handler called');
485
371
  enforceHsmRole(req, 'SignAndSubmitWithHsm');
486
372
  const { buildId, address } = req.data;
487
373
  const deferSubmit = req.data.deferSubmit === true;
488
- // Validate input
489
374
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
490
375
  (0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
491
376
  if (address && !(0, validators_1.isValidBech32Address)(address))
492
377
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'Invalid bech32 address format', 'address');
493
- // Check HSM is available
494
378
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
495
379
  if (!hsmSigner || !hsmSigner.isConnected()) {
496
380
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM is not configured or not connected', 'hsm');
497
381
  }
498
382
  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.)
383
+ // Phase 1 (committed): fetch build, sign, verify. A failure rolls back the new signing
384
+ // request; on the deferred path a swallowed failure leaves a 'pending' row that expires via TTL.
503
385
  const phase1 = async (db) => {
504
- // 1. Fetch the build (with ownership check)
505
386
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
506
- // HSM can only sign builds for its own address
387
+ // The HSM can only sign builds for its own address
507
388
  const hsmAddress = hsmSigner.getAddress();
508
389
  if (build.senderAddress !== hsmAddress) {
509
390
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
510
391
  }
511
- // 2. Create signing request
512
392
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
513
393
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing + submit');
514
394
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, { buildId, signingPayload });
515
- // 3. Sign with HSM
516
395
  const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
517
- // 4. Verify HSM signature — reject (rolls back) if invalid before submitting
396
+ // Reject (rolls back) on an invalid signature before submitting
518
397
  const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
519
398
  const hsmStatus = hsmSigner.getStatus();
520
399
  const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
@@ -522,9 +401,8 @@ module.exports = (srv) => {
522
401
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed — aborting submission');
523
402
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
524
403
  }
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.
404
+ // Claim as 'submitting'; deferred path also persists signed CBOR + signer metadata
405
+ // for the boot-time redrive of interrupted submissions.
528
406
  await db.run(UPDATE.entity(SigningRequests).set({
529
407
  status: 'submitting',
530
408
  hsmKeyId: hsmKeyIdentifier,
@@ -542,9 +420,7 @@ module.exports = (srv) => {
542
420
  signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
543
421
  });
544
422
  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.
423
+ // Phase 1 on the caller's transaction; submit runs after its commit.
548
424
  const prep = await phase1(cds_1.default.tx(req));
549
425
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
550
426
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed — submit deferred until after the caller commits');
@@ -559,8 +435,8 @@ module.exports = (srv) => {
559
435
  }
560
436
  const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
561
437
  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)
438
+ // Phases 2+3: submit outside any DB tx, then finalize (re-sets hsmKeyId, which the
439
+ // generic finalizer does not touch)
564
440
  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
441
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
566
442
  return submissionRecord;
@@ -570,10 +446,7 @@ module.exports = (srv) => {
570
446
  return (0, mappers_1.mapError)(req, e, 'SignAndSubmitWithHsm');
571
447
  }
572
448
  });
573
- /**
574
- * Get HSM connection status and key information.
575
- * Returns null fields if HSM is not configured.
576
- */
449
+ // GetHsmStatus — connection status and key info; null fields when no HSM is configured.
577
450
  srv.on('GetHsmStatus', async (_req) => {
578
451
  enforceHsmRole(_req, 'GetHsmStatus');
579
452
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();