@odatano/core 2.0.0-rc.5 → 2.0.0-rc.51

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 (239) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const cds_1 = __importDefault(require("@sap/cds"));
7
7
  const backend_request_handler_1 = require("./utils/backend-request-handler");
8
8
  const errors_1 = require("./utils/errors");
9
+ const error_codes_1 = require("./utils/error-codes");
9
10
  const mappers_1 = require("./utils/mappers");
10
11
  const validators_1 = require("./utils/validators");
11
12
  const cbor_1 = require("./cbor");
@@ -15,54 +16,40 @@ const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
15
16
  const cose_verifier_1 = require("./blockchain/signing/cose-verifier");
16
17
  const signing_helper_1 = require("./utils/signing-helper");
17
18
  const tx_utils_1 = require("./utils/tx-utils");
19
+ const paging_1 = require("./utils/paging");
20
+ const result_numbers_1 = require("./utils/result-numbers");
18
21
  const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
22
+ const landing_proof_1 = require("./blockchain/signing/landing-proof");
23
+ const resolution_1 = require("./utils/resolution");
24
+ const cardano_1 = require("#cds-models/odatano/cardano");
19
25
  const { SELECT, UPDATE } = cds_1.default.ql;
20
26
  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
- */
27
+ /** Load a build and, when an address is given, check it matches the build's senderAddress. */
25
28
  async function verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, actionName) {
26
29
  const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
27
30
  if (!build)
28
31
  (0, errors_1.rejectInvalid)(req, actionName, 'Build not found', 'buildId');
29
- // rejectInvalid returns `never` → build is narrowed to non-null here
30
32
  if (address && build.senderAddress !== address) {
31
33
  (0, errors_1.rejectInvalid)(req, actionName, 'Address does not match build owner', 'address');
32
34
  }
33
35
  return build;
34
36
  }
35
- /**
36
- * Check if a signing request has expired and update its status.
37
- * @returns true if expired, false otherwise
38
- */
37
+ /** Expires a pending signing request past its TTL. Returns true if it expired. */
39
38
  async function checkAndExpireSigningRequest(db, signingRequest, SigningRequests) {
40
39
  const now = new Date().toISOString();
41
40
  const result = await db.run(UPDATE.entity(SigningRequests)
42
41
  .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
42
+ // Only pending requests may expire; never flip a 'submitted'/'verified' row.
45
43
  .where({ id: signingRequest.id, status: 'pending', expiresAt: { '<=': now } }));
46
44
  if (result > 0) {
47
45
  signingRequest.status = 'expired';
48
46
  return true;
49
47
  }
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.
48
+ // A later req.reject rolls this update back; the next touch re-applies it.
53
49
  return false;
54
50
  }
55
- /**
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).
65
- */
51
+ // Key hashes that must sign: the body's required_signers plus the sender's payment key hash.
52
+ // Script credentials are skipped. Returns undefined when nothing can be derived.
66
53
  async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
67
54
  const signers = new Set();
68
55
  try {
@@ -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,92 @@ 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
- req.reject(403, `Action '${actionName}' requires role '${hsmConfig.requiresRole}'`);
78
+ (0, mappers_1.mapError)(req, new errors_1.BackendError(`Action '${actionName}' requires role '${hsmConfig.requiresRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN), actionName);
97
79
  }
98
80
  }
99
- /**
100
- * Cardano Sign Service Implementation
101
- * Handles transaction signing operations & some additional data queries.
102
- */
81
+ /** The connected HSM signer. 503 when none is configured or connected: the request is valid, the server lacks the signer. */
82
+ function connectedHsm(req, actionName) {
83
+ const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
84
+ if (!hsmSigner || !hsmSigner.isConnected()) {
85
+ (0, mappers_1.mapError)(req, new errors_1.BackendError('HSM is not configured or not connected', 503, error_codes_1.ERROR_CODES.HSM_NOT_CONFIGURED, undefined, undefined, 'hsm'), actionName);
86
+ }
87
+ return hsmSigner;
88
+ }
89
+ // Loads the signing request, runs `gate` on it, checks that the build belongs to `address` when one
90
+ // is given, and completes a CIP-30 witness set into the full transaction.
91
+ async function prepareExternalSignature(req, db, actionName, { signingRequestId, signedTxCbor, address }, SigningRequests, TransactionBuilds, gate) {
92
+ const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
93
+ if (!signingRequest)
94
+ (0, errors_1.rejectInvalid)(req, actionName, 'Signing request not found', 'signingRequestId');
95
+ gate?.(signingRequest);
96
+ if (address && signingRequest.build_id) {
97
+ await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, actionName);
98
+ }
99
+ // A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
100
+ const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
101
+ // Verification is bound to the keys that must witness this tx.
102
+ const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
103
+ return { signingRequest, fullSignedTxCbor, requiredSigners };
104
+ }
105
+ // The change of an HSM build must go back to the HSM, or the remainder goes to whoever built it.
106
+ // The stored outputs mark the change, and each must equal the output of the unsigned body at its index.
107
+ async function assertChangeToHsm(req, db, build, hsmAddress, actionName) {
108
+ const changeAddress = build.changeAddress ?? build.senderAddress;
109
+ if (changeAddress !== hsmAddress) {
110
+ (0, errors_1.rejectInvalid)(req, actionName, `Build change address '${changeAddress}' is not the HSM address '${hsmAddress}'`, 'buildId');
111
+ }
112
+ const stored = await db.run(SELECT.from(cardano_1.TransactionBuildOutputs).columns('outputIndex', 'address', 'isChange').where({ build_id: build.id }));
113
+ if (!stored.length)
114
+ return;
115
+ let body;
116
+ try {
117
+ body = (0, cbor_1.parseTransaction)(build.unsignedTxCbor).outputs;
118
+ }
119
+ catch {
120
+ return (0, errors_1.rejectInvalid)(req, actionName, 'The unsigned transaction of the build cannot be read', 'buildId');
121
+ }
122
+ for (const output of stored) {
123
+ if (body[output.outputIndex]?.address !== output.address) {
124
+ (0, errors_1.rejectInvalid)(req, actionName, `Stored output ${output.outputIndex} of the build does not match its transaction`, 'buildId');
125
+ }
126
+ if (output.isChange && output.address !== hsmAddress) {
127
+ (0, errors_1.rejectInvalid)(req, actionName, `Build change output ${output.outputIndex} goes to '${output.address}', not to the HSM address '${hsmAddress}'`, 'buildId');
128
+ }
129
+ }
130
+ }
131
+ // Signs a build with the HSM after checking that it spends from the HSM address and returns its
132
+ // change there. A signature that does not verify against the required signers rolls back.
133
+ async function signBuildWithHsm(req, db, hsmSigner, actionName, { buildId, address, message }, TransactionBuilds) {
134
+ const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, actionName);
135
+ const hsmAddress = hsmSigner.getAddress();
136
+ if (build.senderAddress !== hsmAddress) {
137
+ (0, errors_1.rejectInvalid)(req, actionName, `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
138
+ }
139
+ await assertChangeToHsm(req, db, build, hsmAddress, actionName);
140
+ const signerModule = (0, external_signer_1.getExternalSignerModule)();
141
+ const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, message);
142
+ const signingRequest = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, { buildId, signingPayload });
143
+ const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
144
+ const requiredSigners = await resolveRequiredSigners(db, { unsignedTxCbor: build.unsignedTxCbor, build_id: build.id }, TransactionBuilds);
145
+ const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash, { requiredSigners });
146
+ const hsmStatus = hsmSigner.getStatus();
147
+ const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
148
+ if (!verificationResult.isValid) {
149
+ logger.error({ signingRequestId: signingRequest.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed');
150
+ (0, errors_1.rejectInvalid)(req, actionName, 'HSM signature verification failed', 'signedTxCbor');
151
+ }
152
+ return { build, signingRequestId: signingRequest.id, signedTxCbor, verificationResult, hsmKeyIdentifier };
153
+ }
154
+ /** CardanoSignService handlers: external and HSM signing, verification, submission. */
103
155
  module.exports = (srv) => {
156
+ (0, result_numbers_1.answerNumbersAsText)(srv);
104
157
  logger.info('Module loaded - registering handlers');
105
158
  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
- */
159
+ // before-READ: bulk-expire pending requests past their TTL, at most once per minute.
111
160
  let lastExpiryCheck = 0;
112
161
  const EXPIRY_CHECK_INTERVAL_MS = 60_000;
113
162
  srv.before('READ', SigningRequests, async (req) => {
@@ -119,33 +168,26 @@ module.exports = (srv) => {
119
168
  .set({ status: 'expired' })
120
169
  .where({ status: 'pending', expiresAt: { '<=': new Date().toISOString() } }));
121
170
  });
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
- */
171
+ // CreateSigningRequest: persist a signing request for a build (idempotent per pending build).
128
172
  srv.on('CreateSigningRequest', async (req) => {
129
173
  logger.debug('CreateSigningRequest Action handler called');
130
174
  const { buildId, message } = req.data;
131
- // Validate inputs
132
175
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
133
176
  (0, errors_1.throwIfValidationErrors)(req, 'CreateSigningRequest', errors);
134
177
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
135
- // Fetch the build
136
178
  const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
137
179
  if (!build)
138
180
  (0, errors_1.rejectInvalid)(req, 'CreateSigningRequest', 'Build not found', 'buildId');
139
- // Check if signing request already exists for this build
140
- const existingRequest = await db.run(SELECT.one.from(SigningRequests).where({ build_id: buildId, status: 'pending' }));
181
+ // a pending request past its TTL is expired first, so it is never handed out again
182
+ const now = new Date().toISOString();
183
+ await db.run(UPDATE.entity(SigningRequests).set({ status: 'expired' }).where({ build_id: buildId, status: 'pending', expiresAt: { '<=': now } }));
184
+ const existingRequest = await db.run(SELECT.one.from(SigningRequests).where({ build_id: buildId, status: 'pending', expiresAt: { '>': now } }));
141
185
  if (existingRequest) {
142
186
  logger.info({ buildId, signingRequestId: existingRequest.id }, 'Returning existing signing request');
143
187
  return existingRequest;
144
188
  }
145
- // Create signing request using external signer module
146
189
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
147
190
  const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, message);
148
- // Delegate persistence to indexer
149
191
  const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
150
192
  buildId,
151
193
  signingPayload,
@@ -154,34 +196,23 @@ module.exports = (srv) => {
154
196
  return signingRequestRecord;
155
197
  });
156
198
  });
157
- /**
158
- * Get an existing signing request by ID
159
- * @param req - CDS request object (with signingRequestId)
160
- * @returns {SigningRequest} signing request entity
161
- */
199
+ // GetSigningRequest: by id; expires a pending request past its TTL on read.
162
200
  srv.on('GetSigningRequest', async (req) => {
163
201
  logger.debug('GetSigningRequest Action handler called');
164
202
  const { signingRequestId } = req.data;
165
- // Validate inputs
166
203
  const errors = (0, validators_1.validateTransactionInputs)({ signingRequestId }, ['signingRequestId']);
167
204
  (0, errors_1.throwIfValidationErrors)(req, 'GetSigningRequest', errors);
168
- // Fetch the signing request within transaction context
169
205
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
170
206
  const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
171
207
  if (!signingRequest)
172
208
  (0, errors_1.rejectInvalid)(req, 'GetSigningRequest', 'Signing request not found', 'signingRequestId');
173
- // Check if expired and update status if needed
174
209
  if (signingRequest.status === 'pending') {
175
210
  await checkAndExpireSigningRequest(db, signingRequest, SigningRequests);
176
211
  }
177
212
  return signingRequest;
178
213
  });
179
214
  });
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
- */
215
+ // VerifySignature: verify a signed tx or witness set against the request; persists the result.
185
216
  srv.on('VerifySignature', async (req) => {
186
217
  logger.debug('VerifySignature Action handler called');
187
218
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
@@ -190,26 +221,15 @@ module.exports = (srv) => {
190
221
  if (address && !(0, validators_1.isValidBech32Address)(address))
191
222
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Invalid bech32 address format', 'address');
192
223
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
193
- // Fetch the signing request (@from already validated by framework)
194
- const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
195
- if (!signingRequest)
196
- (0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Signing request not found', 'signingRequestId');
197
- // Ownership check: verify address matches build owner (defense-in-depth)
198
- if (address && signingRequest.build_id) {
199
- await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'VerifySignature');
200
- }
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.
224
+ const { signingRequest, fullSignedTxCbor, requiredSigners } = await prepareExternalSignature(req, db, 'VerifySignature', { signingRequestId, signedTxCbor, address }, SigningRequests, TransactionBuilds);
225
+ // Atomic claim (pending → 'signed') so concurrent verifies cannot both pass;
226
+ // persistSignatureVerification sets the final 'verified'/'failed'.
206
227
  const now = new Date().toISOString();
207
228
  const claimed = await db.run(UPDATE.entity(SigningRequests)
208
229
  .set({ status: 'signed' })
209
230
  .where({ id: signingRequestId, status: 'pending', expiresAt: { '>': now } }));
210
231
  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)
232
+ // Re-read for an accurate message; a concurrent verify may have moved it.
213
233
  const current = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
214
234
  if (current && current.status === 'pending' && current.expiresAt <= now) {
215
235
  await db.run(UPDATE.entity(SigningRequests).set({ status: 'expired' }).where({ id: signingRequestId, status: 'pending' }));
@@ -217,23 +237,9 @@ module.exports = (srv) => {
217
237
  }
218
238
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', `Signing request status is '${current?.status ?? 'unknown'}', expected 'pending'`, 'signingRequestId');
219
239
  }
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)
233
- const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
234
240
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
235
241
  const result = signerModule.verifySignedTransaction(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
236
- // Delegate persistence to indexer (store full signed tx for later submission)
242
+ // Store the full signed tx for later submission
237
243
  const verificationRecord = await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
238
244
  signingRequestId,
239
245
  signedTxCbor: fullSignedTxCbor,
@@ -250,11 +256,7 @@ module.exports = (srv) => {
250
256
  return verificationRecord;
251
257
  });
252
258
  });
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
- */
259
+ // SubmitVerifiedTransaction: verify and submit in one step.
258
260
  srv.on('SubmitVerifiedTransaction', async (req) => {
259
261
  logger.debug('SubmitVerifiedTransaction Action handler called');
260
262
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
@@ -263,56 +265,34 @@ module.exports = (srv) => {
263
265
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
264
266
  if (address && !(0, validators_1.isValidBech32Address)(address))
265
267
  (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.
268
+ // Three committed phases (see submitAndFinalize): the network submit must not run inside
269
+ // an open DB transaction. With deferSubmit, phase 1 joins the caller's transaction, the
270
+ // response carries the tx hash (= body hash) and the submit runs after the caller's commit.
274
271
  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.
272
+ // Phase 1: verify, then atomically claim → 'submitting'. The claim is the last statement
273
+ // so a verification failure swallowed by the caller never leaves a stranded claim behind.
282
274
  const phase1 = async (db) => {
283
275
  const now = new Date().toISOString();
284
- const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
285
- if (!signingRequest)
286
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request not found', 'signingRequestId');
287
- if (signingRequest.expiresAt <= now)
288
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has expired', 'signingRequestId');
289
- if (!['pending', 'verified'].includes(signingRequest.status)) {
290
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${signingRequest.status}', expected 'pending' or 'verified'`, 'signingRequestId');
291
- }
292
- // Ownership check: verify address matches build owner (defense-in-depth)
293
- if (address && signingRequest.build_id) {
294
- await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
295
- }
296
- // Check if build association exists
297
- if (!signingRequest.build_id) {
298
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
299
- }
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)
306
- const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
276
+ // the state of the request answers before the signed bytes are read
277
+ const { signingRequest, fullSignedTxCbor, requiredSigners } = await prepareExternalSignature(req, db, 'SubmitVerifiedTransaction', { signingRequestId, signedTxCbor, address }, SigningRequests, TransactionBuilds, (request) => {
278
+ if (request.expiresAt <= now)
279
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has expired', 'signingRequestId');
280
+ if (!['pending', 'verified'].includes(request.status)) {
281
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${request.status}', expected 'pending' or 'verified'`, 'signingRequestId');
282
+ }
283
+ if (!request.build_id)
284
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
285
+ });
286
+ // Throws on failure; bound to the keys that must witness this tx.
307
287
  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.
288
+ // a build stored before every build had an expiry can still lack one
289
+ const problem = (0, landing_proof_1.sendProblem)(fullSignedTxCbor, (0, server_1.getCardanoClient)().network);
290
+ if (problem)
291
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', problem, 'signingRequestId');
292
+ // Atomic claim. The signed CBOR, the signer and the claim time go with it, so an
293
+ // interrupted or unresolved submission can be resolved later.
311
294
  const claimed = await db.run(UPDATE.entity(SigningRequests)
312
- .set({
313
- status: 'submitting',
314
- ...(deferSubmit ? { signedTxCbor: fullSignedTxCbor, signerType, signerInfo } : {}),
315
- })
295
+ .set({ status: 'submitting', signedTxCbor: fullSignedTxCbor, signerType, signerInfo, signedAt: now })
316
296
  .where({
317
297
  id: signingRequestId,
318
298
  status: { in: ['pending', 'verified'] },
@@ -333,12 +313,10 @@ module.exports = (srv) => {
333
313
  signerInfo,
334
314
  });
335
315
  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.
316
+ // Phase 1 on the caller's transaction; validation errors stay synchronous.
339
317
  const prep = await phase1(cds_1.default.tx(req));
340
318
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
341
- logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed — submit deferred until after the caller commits');
319
+ logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed, submit deferred until after the caller commits');
342
320
  return {
343
321
  id: null,
344
322
  build_id: prep.buildId,
@@ -350,7 +328,7 @@ module.exports = (srv) => {
350
328
  }
351
329
  const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
352
330
  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
331
+ // Phases 2+3: submit outside any DB tx, then finalize in its own tx
354
332
  const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
355
333
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
356
334
  return submissionRecord;
@@ -360,198 +338,110 @@ module.exports = (srv) => {
360
338
  return (0, mappers_1.mapError)(req, e, 'SubmitVerifiedTransaction');
361
339
  }
362
340
  });
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
- */
341
+ // VerifyDataSignature: stateless CIP-30 signData (COSE_Sign1) check for wallet login.
342
+ // Public (@requires:'any') because the caller is not yet authenticated.
370
343
  srv.on('VerifyDataSignature', async (req) => {
371
344
  logger.debug('VerifyDataSignature Action handler called');
372
345
  const { address, coseSignature, coseKey, expectedPayload } = req.data;
373
- // Validate inputs before the crypto check
374
346
  if (!address)
375
347
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'address');
376
- if (!(0, validators_1.isValidBech32Address)(address))
348
+ if (!(0, validators_1.isValidBech32Address)(address) && !(0, validators_1.isValidBech32StakeAddress)(address)) {
377
349
  (0, errors_1.rejectInvalid)(req, 'VerifyDataSignature', 'Invalid bech32 address format', 'address');
350
+ }
378
351
  if (!coseSignature)
379
352
  (0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseSignature');
380
353
  if (!coseKey)
381
354
  (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.
355
+ // Never throws: a bad signature is a 200 with valid:false + reason.
384
356
  return (0, cose_verifier_1.verifyDataSignature)({ address, coseSignature, coseKey, expectedPayload });
385
357
  });
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
- */
358
+ // GetSigningRequestsByAddress: signing requests linked to an address.
391
359
  srv.on('GetSigningRequestsByAddress', async (req) => {
392
360
  logger.debug('GetSigningRequestsByAddress Action handler called');
393
361
  const { address } = req.data;
394
- // Validate input before business logic
395
362
  if (!address)
396
363
  (0, errors_1.rejectMissing)(req, 'GetSigningRequestsByAddress', 'address');
397
364
  if (!(0, validators_1.isValidBech32Address)(address))
398
365
  (0, errors_1.rejectInvalid)(req, 'GetSigningRequestsByAddress', 'Invalid bech32 address format', 'address');
399
- // Fetch the address-signing request associations
400
- return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
401
- return db.run(SELECT.from(AddressSigningRequests).where({ address_address: address }));
402
- });
366
+ const { limit, skip } = (0, paging_1.pageOf)(req.data, 1000);
367
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => db.run(SELECT.from(AddressSigningRequests).where({ address_address: address }).orderBy('signingRequest_id').limit(limit, skip)));
403
368
  });
404
369
  // ---------------------------------------------------------------------------
405
- // HSM (Hardware Security Module) Signing Actions
370
+ // HSM signing actions
406
371
  // ---------------------------------------------------------------------------
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
- */
372
+ // SignWithHsm: create a signing request, sign with the HSM, verify; returns the request.
413
373
  srv.on('SignWithHsm', async (req) => {
414
374
  logger.debug('SignWithHsm Action handler called');
415
375
  enforceHsmRole(req, 'SignWithHsm');
416
376
  const { buildId, address } = req.data;
417
- // Validate input
418
377
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
419
378
  (0, errors_1.throwIfValidationErrors)(req, 'SignWithHsm', errors);
420
379
  if (address && !(0, validators_1.isValidBech32Address)(address))
421
380
  (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'Invalid bech32 address format', 'address');
422
- // Check HSM is available (before handleRequest — same pattern as validation)
423
- const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
424
- if (!hsmSigner || !hsmSigner.isConnected()) {
425
- (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM is not configured or not connected', 'hsm');
426
- }
381
+ const hsmSigner = connectedHsm(req, 'SignWithHsm');
427
382
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
428
- // 1. Fetch the build (with ownership check)
429
- const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignWithHsm');
430
- // HSM can only sign builds for its own address
431
- const hsmAddress = hsmSigner.getAddress();
432
- if (build.senderAddress !== hsmAddress) {
433
- (0, errors_1.rejectInvalid)(req, 'SignWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
434
- }
435
- // 2. Create signing request internally (reuse external signer module)
436
- const signerModule = (0, external_signer_1.getExternalSignerModule)();
437
- const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing');
438
- const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
439
- buildId,
440
- signingPayload,
441
- });
442
- // 3. Sign with HSM
443
- const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
444
- // 4. Verify the HSM signature (same verification path as external signing)
445
- const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
446
- const hsmStatus = hsmSigner.getStatus();
447
- 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.
451
- if (!verificationResult.isValid) {
452
- logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed');
453
- (0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM signature verification failed', 'signedTxCbor');
454
- }
455
- // 5. Persist verification
383
+ const signed = await signBuildWithHsm(req, db, hsmSigner, 'SignWithHsm', { buildId, address, message: 'HSM signing' }, TransactionBuilds);
456
384
  await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
457
- signingRequestId: signingRequestRecord.id,
458
- signedTxCbor,
459
- verificationResult,
385
+ signingRequestId: signed.signingRequestId,
386
+ signedTxCbor: signed.signedTxCbor,
387
+ verificationResult: signed.verificationResult,
460
388
  signerType: 'hsm',
461
- signerInfo: `HSM key: ${hsmKeyIdentifier}`,
389
+ signerInfo: `HSM key: ${signed.hsmKeyIdentifier}`,
462
390
  });
463
- // 6. Update HSM audit field
464
- await db.run(UPDATE.entity(SigningRequests)
465
- .set({ hsmKeyId: hsmKeyIdentifier })
466
- .where({ id: signingRequestRecord.id }));
467
- logger.info({
468
- buildId,
469
- signingRequestId: signingRequestRecord.id,
470
- isValid: verificationResult.isValid,
471
- hsmKey: hsmKeyIdentifier,
472
- }, 'Transaction signed with HSM');
473
- // Return updated signing request
474
- return db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestRecord.id }));
391
+ // HSM audit field
392
+ await db.run(UPDATE.entity(SigningRequests).set({ hsmKeyId: signed.hsmKeyIdentifier }).where({ id: signed.signingRequestId }));
393
+ logger.info({ buildId, signingRequestId: signed.signingRequestId, hsmKey: signed.hsmKeyIdentifier }, 'Transaction signed with HSM');
394
+ return db.run(SELECT.one.from(SigningRequests).where({ id: signed.signingRequestId }));
475
395
  });
476
396
  });
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
- */
397
+ // SignAndSubmitWithHsm: create a signing request, sign, verify and submit in one call.
483
398
  srv.on('SignAndSubmitWithHsm', async (req) => {
484
399
  logger.debug('SignAndSubmitWithHsm Action handler called');
485
400
  enforceHsmRole(req, 'SignAndSubmitWithHsm');
486
401
  const { buildId, address } = req.data;
487
402
  const deferSubmit = req.data.deferSubmit === true;
488
- // Validate input
489
403
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
490
404
  (0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
491
405
  if (address && !(0, validators_1.isValidBech32Address)(address))
492
406
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'Invalid bech32 address format', 'address');
493
- // Check HSM is available
494
- const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
495
- if (!hsmSigner || !hsmSigner.isConnected()) {
496
- (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM is not configured or not connected', 'hsm');
497
- }
407
+ const hsmSigner = connectedHsm(req, 'SignAndSubmitWithHsm');
498
408
  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.)
409
+ // Phase 1 (committed): sign, verify and claim as 'submitting' with the signed CBOR, so an
410
+ // interrupted or unresolved submission can be resolved later. A failure rolls the request back.
503
411
  const phase1 = async (db) => {
504
- // 1. Fetch the build (with ownership check)
505
- const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
506
- // HSM can only sign builds for its own address
507
- const hsmAddress = hsmSigner.getAddress();
508
- if (build.senderAddress !== hsmAddress) {
509
- (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
510
- }
511
- // 2. Create signing request
512
- const signerModule = (0, external_signer_1.getExternalSignerModule)();
513
- const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing + submit');
514
- const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, { buildId, signingPayload });
515
- // 3. Sign with HSM
516
- const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
517
- // 4. Verify HSM signature — reject (rolls back) if invalid before submitting
518
- const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
519
- const hsmStatus = hsmSigner.getStatus();
520
- const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
521
- if (!verificationResult.isValid) {
522
- logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed — aborting submission');
523
- (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
524
- }
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.
412
+ const signed = await signBuildWithHsm(req, db, hsmSigner, 'SignAndSubmitWithHsm', { buildId, address, message: 'HSM signing + submit' }, TransactionBuilds);
413
+ // a build stored before every build had an expiry can still lack one
414
+ const problem = (0, landing_proof_1.sendProblem)(signed.signedTxCbor, (0, server_1.getCardanoClient)().network);
415
+ if (problem)
416
+ (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', problem, 'buildId');
528
417
  await db.run(UPDATE.entity(SigningRequests).set({
529
418
  status: 'submitting',
530
- hsmKeyId: hsmKeyIdentifier,
531
- ...(deferSubmit ? { signedTxCbor, signerType: 'hsm', signerInfo: `HSM key: ${hsmKeyIdentifier}` } : {}),
532
- }).where({ id: signingRequestRecord.id }));
533
- return { signingRequestId: signingRequestRecord.id, signedTxCbor, txHash: build.txBodyHash, verificationResult, hsmKeyIdentifier };
419
+ hsmKeyId: signed.hsmKeyIdentifier,
420
+ signedTxCbor: signed.signedTxCbor,
421
+ signerType: 'hsm',
422
+ signerInfo: `HSM key: ${signed.hsmKeyIdentifier}`,
423
+ signedAt: new Date().toISOString(),
424
+ }).where({ id: signed.signingRequestId }));
425
+ return signed;
534
426
  };
535
427
  const finalizeParams = (prep) => ({
536
428
  signingRequestId: prep.signingRequestId,
537
429
  buildId,
538
430
  fullSignedTxCbor: prep.signedTxCbor,
539
- txHash: prep.txHash,
431
+ txHash: prep.build.txBodyHash,
540
432
  verificationResult: prep.verificationResult,
541
433
  signerType: 'hsm',
542
434
  signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
543
435
  });
544
436
  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.
437
+ // Phase 1 on the caller's transaction; submit runs after its commit.
548
438
  const prep = await phase1(cds_1.default.tx(req));
549
439
  (0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
550
- logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed — submit deferred until after the caller commits');
440
+ logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.build.txBodyHash }, 'HSM-signed and claimed, submit deferred until after the caller commits');
551
441
  return {
552
442
  id: null,
553
443
  build_id: buildId,
554
- txHash: prep.txHash,
444
+ txHash: prep.build.txBodyHash,
555
445
  signedTxCbor: prep.signedTxCbor,
556
446
  status: 'pending',
557
447
  submittedAt: null,
@@ -559,10 +449,10 @@ module.exports = (srv) => {
559
449
  }
560
450
  const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
561
451
  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)
452
+ // Phases 2+3: submit outside any DB tx, then finalize; hsmKeyId is set again because the
453
+ // generic finalizer does not write it
564
454
  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
- logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
455
+ logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.build.txBodyHash }, 'HSM-signed transaction submitted and all records updated');
566
456
  return submissionRecord;
567
457
  }
568
458
  catch (e) {
@@ -570,10 +460,43 @@ module.exports = (srv) => {
570
460
  return (0, mappers_1.mapError)(req, e, 'SignAndSubmitWithHsm');
571
461
  }
572
462
  });
573
- /**
574
- * Get HSM connection status and key information.
575
- * Returns null fields if HSM is not configured.
576
- */
463
+ // ResolveSigningRequest (Admin): settles an unresolved request as an operator read it on the chain.
464
+ // Confirmed writes the submission record a submit writes; failed ends the request.
465
+ srv.on('ResolveSigningRequest', async (req) => {
466
+ const { signingRequestId, outcome, txHash, note } = req.data;
467
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
468
+ // read and ask the chain before the request takes its connection
469
+ const request = await (0, tx_utils_1.readOutside)(db, (d) => d.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId })));
470
+ if (!request)
471
+ throw new errors_1.NotFoundError(`Signing request '${signingRequestId}'`);
472
+ if (request.status !== 'unresolved') {
473
+ (0, errors_1.rejectInvalid)(req, 'ResolveSigningRequest', `Signing request status is '${request.status}': only an unresolved request can be resolved`, 'signingRequestId');
474
+ }
475
+ (0, resolution_1.checkResolvedTxHash)(req, 'ResolveSigningRequest', txHash, request.txBodyHash);
476
+ const resolved = outcome === 'confirmed' ? 'confirmed' : 'failed';
477
+ await (0, resolution_1.refuseFailedWhileItCanLand)('ResolveSigningRequest', resolved, request.signedTxCbor, (0, server_1.getCardanoClient)());
478
+ const resolution = (0, resolution_1.resolutionNote)(resolved, req.user?.id, note);
479
+ const won = await db.run(UPDATE.entity(SigningRequests)
480
+ .set(resolved === 'confirmed' ? { status: 'submitted', errorMessage: null, resolution } : { status: 'failed', resolution })
481
+ .where({ id: signingRequestId, status: 'unresolved' }));
482
+ if (won === 0)
483
+ throw (0, resolution_1.resolvedConcurrently)('ResolveSigningRequest');
484
+ if (resolved === 'confirmed') {
485
+ if (!request.signedTxCbor || !request.build_id) {
486
+ (0, errors_1.rejectInvalid)(req, 'ResolveSigningRequest', 'Signing request has no stored signed transaction or build', 'signingRequestId');
487
+ }
488
+ // the witness metadata the submission record keeps, from the stored bytes
489
+ const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(request.signedTxCbor, request.txBodyHash);
490
+ await (0, server_1.getCardanoIndexer)().indexVerifiedTransactionSubmission(db, {
491
+ signingRequestId, buildId: request.build_id, fullSignedTxCbor: request.signedTxCbor, txHash: request.txBodyHash,
492
+ verificationResult, signerType: request.signerType ?? undefined, signerInfo: request.signerInfo ?? undefined,
493
+ });
494
+ }
495
+ logger.warn({ signingRequestId, outcome: resolved, by: req.user?.id }, 'Unresolved signing request resolved by an operator');
496
+ return db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
497
+ });
498
+ });
499
+ // GetHsmStatus: connection status and key info; null fields when no HSM is configured.
577
500
  srv.on('GetHsmStatus', async (_req) => {
578
501
  enforceHsmRole(_req, 'GetHsmStatus');
579
502
  const hsmSigner = (0, hsm_signer_1.getHsmSigner)();