@odatano/core 1.8.0 → 1.9.0

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 (193) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +66 -42
  2. package/@cds-models/CardanoODataService/index.d.ts.map +1 -1
  3. package/@cds-models/CardanoODataService/index.js.map +1 -1
  4. package/@cds-models/CardanoODataService/index.ts +11 -7
  5. package/@cds-models/odatano/cardano/index.d.ts +70 -46
  6. package/@cds-models/odatano/cardano/index.d.ts.map +1 -1
  7. package/@cds-models/odatano/cardano/index.js +2 -2
  8. package/@cds-models/odatano/cardano/index.js.map +1 -1
  9. package/@cds-models/odatano/cardano/index.ts +13 -13
  10. package/db/schema.cds +18 -18
  11. package/db/types.cds +3 -3
  12. package/package.json +17 -2
  13. package/src/index.d.ts +29 -0
  14. package/src/index.js +1 -0
  15. package/src/plugin.d.ts +2 -0
  16. package/src/plugin.js +6 -0
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +155 -0
  18. package/srv/blockchain/backends/blockfrost-backend.js +19 -8
  19. package/srv/blockchain/backends/cardano-backend.d.ts +182 -0
  20. package/srv/blockchain/backends/koios-backend.d.ts +171 -0
  21. package/srv/blockchain/backends/koios-backend.js +69 -27
  22. package/srv/blockchain/backends/ogmios-backend.d.ts +188 -0
  23. package/srv/blockchain/backends/ogmios-backend.js +175 -108
  24. package/srv/blockchain/cardano-client.d.ts +279 -0
  25. package/srv/blockchain/cardano-client.js +134 -33
  26. package/srv/blockchain/cardano-indexer.d.ts +330 -0
  27. package/srv/blockchain/cardano-indexer.js +51 -8
  28. package/srv/blockchain/cardano-tx-builder.d.ts +113 -0
  29. package/srv/blockchain/cardano-tx-builder.js +61 -54
  30. package/srv/blockchain/circuit-breaker.d.ts +37 -0
  31. package/srv/blockchain/circuit-breaker.js +11 -2
  32. package/srv/blockchain/request-coalescer.d.ts +23 -0
  33. package/srv/blockchain/signing/external-signer.d.ts +146 -0
  34. package/srv/blockchain/signing/external-signer.js +23 -0
  35. package/srv/blockchain/signing/hsm-signer.d.ts +74 -0
  36. package/srv/blockchain/signing/hsm-signer.js +20 -5
  37. package/srv/blockchain/signing/signature-verifier.d.ts +56 -0
  38. package/srv/blockchain/signing/signature-verifier.js +11 -2
  39. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +236 -0
  40. package/srv/blockchain/transaction-building/buildooor-tx.js +626 -187
  41. package/srv/blockchain/transaction-building/cardano-tx.d.ts +47 -0
  42. package/srv/cardano-service.cds +23 -3
  43. package/srv/cardano-service.d.ts +2 -0
  44. package/srv/cardano-service.js +25 -5
  45. package/srv/cardano-sign-service.d.ts +2 -0
  46. package/srv/cardano-sign-service.js +219 -131
  47. package/srv/cardano-tx-service.d.ts +12 -0
  48. package/srv/cardano-tx-service.js +152 -110
  49. package/srv/cbor/index.d.ts +2 -0
  50. package/srv/cbor/parse.d.ts +64 -0
  51. package/srv/server.d.ts +90 -0
  52. package/srv/server.js +27 -9
  53. package/srv/utils/backend-request-handler.d.ts +20 -0
  54. package/srv/utils/const.d.ts +183 -0
  55. package/srv/utils/const.js +13 -6
  56. package/srv/utils/error-codes.d.ts +79 -0
  57. package/srv/utils/errors.d.ts +259 -0
  58. package/srv/utils/errors.js +22 -7
  59. package/srv/utils/mappers.d.ts +260 -0
  60. package/srv/utils/mappers.js +34 -10
  61. package/srv/utils/plutus-placeholders.d.ts +35 -0
  62. package/srv/utils/plutus-placeholders.js +5 -15
  63. package/srv/utils/signing-helper.d.ts +23 -0
  64. package/srv/utils/signing-helper.js +5 -2
  65. package/srv/utils/tx-build-helper.d.ts +76 -0
  66. package/srv/utils/tx-build-helper.js +10 -37
  67. package/srv/utils/types.d.ts +653 -0
  68. package/srv/utils/validators.d.ts +145 -0
  69. package/srv/utils/validators.js +28 -1
  70. package/@cds-models/CardanoWatcherAdminService/index.js +0 -109
  71. package/@cds-models/CardanoWatcherAdminService/index.js.map +0 -1
  72. package/@cds-models/CardanoWatcherAdminService/index.ts +0 -263
  73. package/@cds-models/cds/outbox/index.js.map +0 -1
  74. package/@cds-models/cds/xt/MTXServices/index.js +0 -8
  75. package/@cds-models/cds/xt/MTXServices/index.js.map +0 -1
  76. package/@cds-models/cds/xt/MTXServices/index.ts +0 -4
  77. package/@cds-models/odatano/reeve/index.js +0 -77
  78. package/@cds-models/odatano/reeve/index.js.map +0 -1
  79. package/@cds-models/odatano/reeve/index.ts +0 -57
  80. package/@cds-models/odatano/transactions/index.js +0 -55
  81. package/@cds-models/odatano/transactions/index.js.map +0 -1
  82. package/@cds-models/odatano/transactions/index.ts +0 -18
  83. package/@cds-models/odatano/watch/index.js +0 -114
  84. package/@cds-models/odatano/watch/index.js.map +0 -1
  85. package/@cds-models/odatano/watch/index.ts +0 -110
  86. package/config/preview/cardano-node/alonzo-genesis.json +0 -196
  87. package/config/preview/cardano-node/byron-genesis.json +0 -117
  88. package/config/preview/cardano-node/config.json +0 -117
  89. package/config/preview/cardano-node/conway-genesis.json +0 -297
  90. package/config/preview/cardano-node/peer-snapshot.json +0 -890
  91. package/config/preview/cardano-node/shelley-genesis.json +0 -68
  92. package/config/preview/cardano-node/topology.json +0 -24
  93. package/output/sora/iter0_base.json +0 -32
  94. package/output/sora/iter0_base.mp4 +0 -0
  95. package/output/sora/logo_ref_1280x720.png +0 -0
  96. package/output/sora/odatano_full_logo_sky_ref_1280x720.png +0 -0
  97. package/output/sora/odatano_full_logo_transparent.png +0 -0
  98. package/output/sora/odatano_full_logo_transparent_dark.png +0 -0
  99. package/output/sora/odatano_full_logo_v4_8s.json +0 -32
  100. package/output/sora/odatano_full_logo_v4_8s.mp4 +0 -0
  101. package/output/sora/odatano_full_logo_v5_create.json +0 -15
  102. package/output/sora/odatano_full_logo_v5_fixes.json +0 -15
  103. package/output/sora/odatano_full_logo_v5_fixes.mp4 +0 -0
  104. package/output/sora/odatano_logo_v1.json +0 -32
  105. package/output/sora/odatano_logo_v1.mp4 +0 -0
  106. package/output/sora/odatano_o_only_clean.png +0 -0
  107. package/output/sora/odatano_o_sky_ref_1280x720.png +0 -0
  108. package/output/sora/odatano_o_sky_v2_8s.json +0 -32
  109. package/output/sora/odatano_o_sky_v2_8s.mp4 +0 -0
  110. package/output/sora/odatano_o_sky_v3_create.json +0 -15
  111. package/output/sora/odatano_o_sky_v3_splash_text.json +0 -15
  112. package/output/sora/odatano_o_sky_v3_splash_text.mp4 +0 -0
  113. package/output/sora/odatano_v6_composite_exact_logo.mp4 +0 -0
  114. package/output/sora/odatano_v6_composite_exact_logo_clean.mp4 +0 -0
  115. package/output/sora/odatano_v6_composite_exact_logo_final.mp4 +0 -0
  116. package/output/sora/odatano_v6_endframe.jpg +0 -0
  117. package/output/sora/odatano_v6_endframe_clean.jpg +0 -0
  118. package/output/sora/odatano_v6_endframe_final.jpg +0 -0
  119. package/output/sora/odatano_v7_1_earlylogo_fadeoldtext.mp4 +0 -0
  120. package/output/sora/odatano_v7_1_end.jpg +0 -0
  121. package/output/sora/odatano_v7_1_transition.jpg +0 -0
  122. package/output/sora/odatano_v7_2_original2d_keep_sky.mp4 +0 -0
  123. package/output/sora/odatano_v7_endframe_nobg.jpg +0 -0
  124. package/output/sora/odatano_v7_endframe_nobg_cleanend.jpg +0 -0
  125. package/output/sora/odatano_v7_spin_splash_logo_nobg.mp4 +0 -0
  126. package/output/sora/odatano_v7_spin_splash_logo_nobg_cleanend.mp4 +0 -0
  127. package/prod.mtaext +0 -17
  128. package/prod.mtaext.example +0 -27
  129. package/review.md +0 -42
  130. package/src/index.d.ts.map +0 -1
  131. package/src/index.js.map +0 -1
  132. package/src/plugin.d.ts.map +0 -1
  133. package/src/plugin.js.map +0 -1
  134. package/srv/blockchain/backends/blockfrost-backend.d.ts.map +0 -1
  135. package/srv/blockchain/backends/blockfrost-backend.js.map +0 -1
  136. package/srv/blockchain/backends/cardano-backend.d.ts.map +0 -1
  137. package/srv/blockchain/backends/cardano-backend.js.map +0 -1
  138. package/srv/blockchain/backends/koios-backend.d.ts.map +0 -1
  139. package/srv/blockchain/backends/koios-backend.js.map +0 -1
  140. package/srv/blockchain/backends/ogmios-backend.d.ts.map +0 -1
  141. package/srv/blockchain/backends/ogmios-backend.js.map +0 -1
  142. package/srv/blockchain/cardano-client.d.ts.map +0 -1
  143. package/srv/blockchain/cardano-client.js.map +0 -1
  144. package/srv/blockchain/cardano-indexer.d.ts.map +0 -1
  145. package/srv/blockchain/cardano-indexer.js.map +0 -1
  146. package/srv/blockchain/cardano-tx-builder.d.ts.map +0 -1
  147. package/srv/blockchain/cardano-tx-builder.js.map +0 -1
  148. package/srv/blockchain/circuit-breaker.d.ts.map +0 -1
  149. package/srv/blockchain/circuit-breaker.js.map +0 -1
  150. package/srv/blockchain/request-coalescer.d.ts.map +0 -1
  151. package/srv/blockchain/request-coalescer.js.map +0 -1
  152. package/srv/blockchain/signing/external-signer.d.ts.map +0 -1
  153. package/srv/blockchain/signing/external-signer.js.map +0 -1
  154. package/srv/blockchain/signing/hsm-signer.d.ts.map +0 -1
  155. package/srv/blockchain/signing/hsm-signer.js.map +0 -1
  156. package/srv/blockchain/signing/signature-verifier.d.ts.map +0 -1
  157. package/srv/blockchain/signing/signature-verifier.js.map +0 -1
  158. package/srv/blockchain/transaction-building/buildooor-tx.d.ts.map +0 -1
  159. package/srv/blockchain/transaction-building/buildooor-tx.js.map +0 -1
  160. package/srv/blockchain/transaction-building/cardano-tx.d.ts.map +0 -1
  161. package/srv/blockchain/transaction-building/cardano-tx.js.map +0 -1
  162. package/srv/cardano-service.d.ts.map +0 -1
  163. package/srv/cardano-service.js.map +0 -1
  164. package/srv/cardano-sign-service.d.ts.map +0 -1
  165. package/srv/cardano-sign-service.js.map +0 -1
  166. package/srv/cardano-tx-service.d.ts.map +0 -1
  167. package/srv/cardano-tx-service.js.map +0 -1
  168. package/srv/cbor/index.d.ts.map +0 -1
  169. package/srv/cbor/index.js.map +0 -1
  170. package/srv/cbor/parse.d.ts.map +0 -1
  171. package/srv/cbor/parse.js.map +0 -1
  172. package/srv/server.d.ts.map +0 -1
  173. package/srv/server.js.map +0 -1
  174. package/srv/utils/backend-request-handler.d.ts.map +0 -1
  175. package/srv/utils/backend-request-handler.js.map +0 -1
  176. package/srv/utils/const.d.ts.map +0 -1
  177. package/srv/utils/const.js.map +0 -1
  178. package/srv/utils/error-codes.d.ts.map +0 -1
  179. package/srv/utils/error-codes.js.map +0 -1
  180. package/srv/utils/errors.d.ts.map +0 -1
  181. package/srv/utils/errors.js.map +0 -1
  182. package/srv/utils/mappers.d.ts.map +0 -1
  183. package/srv/utils/mappers.js.map +0 -1
  184. package/srv/utils/plutus-placeholders.d.ts.map +0 -1
  185. package/srv/utils/plutus-placeholders.js.map +0 -1
  186. package/srv/utils/signing-helper.d.ts.map +0 -1
  187. package/srv/utils/signing-helper.js.map +0 -1
  188. package/srv/utils/tx-build-helper.d.ts.map +0 -1
  189. package/srv/utils/tx-build-helper.js.map +0 -1
  190. package/srv/utils/types.d.ts.map +0 -1
  191. package/srv/utils/types.js.map +0 -1
  192. package/srv/utils/validators.d.ts.map +0 -1
  193. package/srv/utils/validators.js.map +0 -1
@@ -208,12 +208,17 @@ class CardanoTransactionBuilder {
208
208
  if (!scriptOutput) {
209
209
  throw new errors_1.TransactionValidationError(`Script UTxO output ${scriptRef.txHash}#${scriptRef.outputIndex} not found in transaction`);
210
210
  }
211
+ // spending an already-consumed script UTxO is the most common replay mistake —
212
+ // catch it here with a clear 400 instead of a node-side rejection at submit
213
+ await this._assertUnspent(scriptRef, scriptOutput.address, 'scriptUtxo', new Map());
211
214
  allUtxos.push({
212
215
  txHash: scriptRef.txHash,
213
216
  outputIndex: scriptRef.outputIndex,
214
217
  address: scriptOutput.address,
215
218
  amount: scriptOutput.amount,
216
219
  inlineDatum: scriptOutput.inlineDatum,
220
+ datumHash: scriptOutput.dataHash ?? undefined,
221
+ scriptRef: scriptOutput.referenceScriptHash ?? undefined,
217
222
  });
218
223
  }
219
224
  // Resolve forced inputs (may overlap with sender UTxOs or the script UTxO — dedup below).
@@ -242,68 +247,65 @@ class CardanoTransactionBuilder {
242
247
  return txBuildResult;
243
248
  }
244
249
  /**
245
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
246
- * Prefers matching against already-fetched sender UTxOs to avoid extra backend calls.
247
- * Throws TransactionValidationError if any ref cannot be resolved (missing or spent).
248
- * Deduplicates input refs before lookup.
250
+ * Verify that a transaction output resolved via getTransaction is still unspent,
251
+ * by checking the live UTxO set of its address. getTransaction only proves the
252
+ * output EXISTED — a spent output would otherwise surface as a cryptic node-side
253
+ * rejection at submit instead of a clear 400 here.
249
254
  *
250
- * @param refs forced-input refs from the request
251
- * @param senderUtxos sender UTxOs already fetched (for cheap matching)
252
- * @returns resolved UTxOs, in the same order as deduped refs
255
+ * Lookup failures are logged and tolerated (the check is best-effort; refusing to
256
+ * build on a flaky backend would be a new failure mode).
253
257
  */
254
- async _resolveForceInputs(refs, senderUtxos) {
255
- if (!refs || refs.length === 0)
256
- return [];
257
- // Dedup by "txHash#index" key
258
- const seen = new Set();
259
- const dedupedRefs = refs.filter(r => {
260
- const key = `${r.txHash}#${r.outputIndex}`;
261
- if (seen.has(key))
262
- return false;
263
- seen.add(key);
264
- return true;
265
- });
266
- const resolved = [];
267
- for (const ref of dedupedRefs) {
268
- // 1) Cheap path: already in sender UTxOs
269
- const local = senderUtxos.find(u => u.txHash === ref.txHash && u.outputIndex === ref.outputIndex);
270
- if (local) {
271
- resolved.push(local);
272
- continue;
273
- }
274
- // 2) Fallback: fetch the producing transaction and look up the output.
275
- // If the output does not exist OR the UTxO has already been spent, treat as missing.
276
- let tx;
277
- try {
278
- tx = await this.client.getTransaction(ref.txHash);
258
+ async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
+ let live;
260
+ try {
261
+ const cached = liveUtxoCache.get(address);
262
+ if (cached) {
263
+ live = cached;
279
264
  }
280
- catch (err) {
281
- throw new errors_1.TransactionValidationError(`forceInput ${ref.txHash}#${ref.outputIndex} not found on-chain`, err);
265
+ else {
266
+ live = await this.client.getAddressUtxos(address);
267
+ liveUtxoCache.set(address, live);
282
268
  }
283
- const output = tx?.outputs?.find(o => o.outputIndex === ref.outputIndex);
284
- if (!output) {
285
- throw new errors_1.TransactionValidationError(`forceInput ${ref.txHash}#${ref.outputIndex} not found on-chain`);
286
- }
287
- resolved.push({
288
- txHash: ref.txHash,
289
- outputIndex: ref.outputIndex,
290
- address: output.address,
291
- amount: output.amount,
292
- inlineDatum: output.inlineDatum,
293
- datumHash: output.dataHash ?? undefined,
294
- scriptRef: output.referenceScriptHash ?? undefined,
295
- });
296
269
  }
297
- return resolved;
270
+ catch (err) {
271
+ logger.warn(`Could not verify ${kind} ${ref.txHash}#${ref.outputIndex} is unspent: ${err instanceof Error ? err.message : String(err)}`);
272
+ return;
273
+ }
274
+ const isLive = live.some(u => u.txHash === ref.txHash && u.outputIndex === ref.outputIndex);
275
+ if (!isLive) {
276
+ throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
+ }
278
+ }
279
+ /**
280
+ * Resolve forced-input refs (consumed) to full UTxO records.
281
+ * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
+ */
283
+ _resolveForceInputs(refs, senderUtxos) {
284
+ return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
+ }
286
+ /**
287
+ * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
+ * coin-selection set) to full UTxO records.
289
+ */
290
+ _resolveReferenceInputs(refs, knownUtxos) {
291
+ return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
298
292
  }
299
293
  /**
300
- * Resolve CIP-31 reference input refs to full UTxO records.
301
- * Same resolution logic as _resolveForceInputs but with distinct error messages.
302
- * Reference inputs are read-only — they are NOT merged into the coin-selection set.
294
+ * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
295
+ * Prefers matching against already-known UTxOs to avoid extra backend calls;
296
+ * otherwise fetches the producing transaction and verifies the output is
297
+ * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
298
+ * cannot be resolved (missing or spent). Deduplicates refs before lookup.
299
+ *
300
+ * @param refs input refs from the request
301
+ * @param knownUtxos UTxOs already fetched (cheap-match pool)
302
+ * @param kind label used in error messages / the spent-check
303
+ * @returns resolved UTxOs, in the same order as the deduped refs
303
304
  */
304
- async _resolveReferenceInputs(refs, knownUtxos) {
305
+ async _resolveInputRefs(refs, knownUtxos, kind) {
305
306
  if (!refs || refs.length === 0)
306
307
  return [];
308
+ // Dedup by "txHash#index" key
307
309
  const seen = new Set();
308
310
  const dedupedRefs = refs.filter(r => {
309
311
  const key = `${r.txHash}#${r.outputIndex}`;
@@ -312,24 +314,29 @@ class CardanoTransactionBuilder {
312
314
  seen.add(key);
313
315
  return true;
314
316
  });
317
+ const liveUtxoCache = new Map();
315
318
  const resolved = [];
316
319
  for (const ref of dedupedRefs) {
320
+ // 1) Cheap path: already known
317
321
  const local = knownUtxos.find(u => u.txHash === ref.txHash && u.outputIndex === ref.outputIndex);
318
322
  if (local) {
319
323
  resolved.push(local);
320
324
  continue;
321
325
  }
326
+ // 2) Fallback: fetch the producing transaction and look up the output.
322
327
  let tx;
323
328
  try {
324
329
  tx = await this.client.getTransaction(ref.txHash);
325
330
  }
326
331
  catch (err) {
327
- throw new errors_1.TransactionValidationError(`referenceInput ${ref.txHash}#${ref.outputIndex} not found on-chain`, err);
332
+ throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} not found on-chain`, err);
328
333
  }
329
334
  const output = tx?.outputs?.find(o => o.outputIndex === ref.outputIndex);
330
335
  if (!output) {
331
- throw new errors_1.TransactionValidationError(`referenceInput ${ref.txHash}#${ref.outputIndex} not found on-chain`);
336
+ throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} not found on-chain`);
332
337
  }
338
+ // getTransaction proves existence, not spendability
339
+ await this._assertUnspent(ref, output.address, kind, liveUtxoCache);
333
340
  resolved.push({
334
341
  txHash: ref.txHash,
335
342
  outputIndex: ref.outputIndex,
@@ -0,0 +1,37 @@
1
+ export type CircuitState = 'closed' | 'open' | 'half-open';
2
+ export interface CircuitBreakerConfig {
3
+ /** Number of failures before opening the circuit (default: 5) */
4
+ failureThreshold: number;
5
+ /** Number of successes in half-open before closing (default: 2) */
6
+ successThreshold: number;
7
+ /** Time in ms before transitioning from open to half-open (default: 30000) */
8
+ resetTimeoutMs: number;
9
+ }
10
+ /**
11
+ * Circuit Breaker for backend failover.
12
+ * Tracks per-backend failure counts and prevents hammering unhealthy backends.
13
+ *
14
+ * States:
15
+ * closed → normal operation, requests pass through
16
+ * open → backend is unhealthy, requests are skipped
17
+ * half-open → probe period, limited requests allowed to test recovery
18
+ */
19
+ export declare class CircuitBreakerManager {
20
+ private circuits;
21
+ private config;
22
+ constructor(config?: Partial<CircuitBreakerConfig>);
23
+ /**
24
+ * Check if a backend should be attempted.
25
+ * Transitions open → half-open if reset timeout has elapsed.
26
+ */
27
+ shouldAttempt(backendName: string): boolean;
28
+ /** Record a successful call to a backend. */
29
+ recordSuccess(backendName: string): void;
30
+ /** Record a failed call to a backend. */
31
+ recordFailure(backendName: string): void;
32
+ /** Get the current state of a backend's circuit. */
33
+ getState(backendName: string): CircuitState;
34
+ /** Reset all circuit states (for testing). */
35
+ reset(): void;
36
+ }
37
+ //# sourceMappingURL=circuit-breaker.d.ts.map
@@ -41,12 +41,18 @@ class CircuitBreakerManager {
41
41
  if (elapsed >= this.config.resetTimeoutMs) {
42
42
  entry.state = 'half-open';
43
43
  entry.successes = 0;
44
+ entry.halfOpenProbes = 1; // this caller takes the first probe slot
44
45
  logger.debug(`Circuit half-open for ${backendName} after ${elapsed}ms`);
45
46
  return true;
46
47
  }
47
48
  return false;
48
49
  }
49
- // half-open: allow probe requests
50
+ // half-open: cap in-flight probes at successThreshold — previously a burst
51
+ // of concurrent requests all probed a barely-recovering backend at once
52
+ if (entry.halfOpenProbes >= this.config.successThreshold) {
53
+ return false;
54
+ }
55
+ entry.halfOpenProbes++;
50
56
  return true;
51
57
  }
52
58
  /** Record a successful call to a backend. */
@@ -55,11 +61,13 @@ class CircuitBreakerManager {
55
61
  if (!entry)
56
62
  return;
57
63
  if (entry.state === 'half-open') {
64
+ entry.halfOpenProbes = Math.max(0, entry.halfOpenProbes - 1); // release probe slot
58
65
  entry.successes++;
59
66
  if (entry.successes >= this.config.successThreshold) {
60
67
  entry.state = 'closed';
61
68
  entry.failures = 0;
62
69
  entry.successes = 0;
70
+ entry.halfOpenProbes = 0;
63
71
  logger.info(`Circuit closed for ${backendName} (recovered)`);
64
72
  }
65
73
  }
@@ -72,7 +80,7 @@ class CircuitBreakerManager {
72
80
  recordFailure(backendName) {
73
81
  let entry = this.circuits.get(backendName);
74
82
  if (!entry) {
75
- entry = { state: 'closed', failures: 0, successes: 0, lastFailureTime: 0 };
83
+ entry = { state: 'closed', failures: 0, successes: 0, lastFailureTime: 0, halfOpenProbes: 0 };
76
84
  this.circuits.set(backendName, entry);
77
85
  }
78
86
  entry.failures++;
@@ -81,6 +89,7 @@ class CircuitBreakerManager {
81
89
  // Any failure in half-open reopens the circuit
82
90
  entry.state = 'open';
83
91
  entry.successes = 0;
92
+ entry.halfOpenProbes = 0;
84
93
  logger.warn(`Circuit re-opened for ${backendName} (failed during probe)`);
85
94
  }
86
95
  else if (entry.state === 'closed' && entry.failures >= this.config.failureThreshold) {
@@ -0,0 +1,23 @@
1
+ /**
2
+ * RequestCoalescer — Deduplicates concurrent requests for the same resource key.
3
+ *
4
+ * When multiple callers request the same key simultaneously (e.g., same txHash
5
+ * during parallel address indexing), only one backend call is made. All callers
6
+ * receive the same Promise/result.
7
+ */
8
+ export declare class RequestCoalescer<T> {
9
+ private pending;
10
+ /**
11
+ * Get a value by key, deduplicating concurrent requests.
12
+ * If a request for this key is already in-flight, returns the existing Promise.
13
+ * Otherwise, calls the fetcher and caches the Promise until it resolves.
14
+ *
15
+ * @param key Unique identifier (e.g., txHash, bech32 address)
16
+ * @param fetcher Function that performs the actual fetch
17
+ * @returns The fetched value
18
+ */
19
+ get(key: string, fetcher: () => Promise<T>): Promise<T>;
20
+ /** Number of currently in-flight requests */
21
+ get size(): number;
22
+ }
23
+ //# sourceMappingURL=request-coalescer.d.ts.map
@@ -0,0 +1,146 @@
1
+ import { SignatureVerifier } from './signature-verifier';
2
+ import { ExternalSignerType, UnsignedTxExportPayload, SignedTxPayload, SigningWorkflowState, SignatureVerificationResult, VerificationOptions } from '../../utils/types';
3
+ /**
4
+ * ExternalSignerModule - Manages the external signing workflow
5
+ *
6
+ * This module orchestrates the complete flow:
7
+ * 1. Create signing request from build result
8
+ * 2. Export unsigned transaction for external signing
9
+ * 3. Receive and verify signed transaction
10
+ * 4. Prepare for submission
11
+ *
12
+ * Key security principles:
13
+ * - NO private keys are ever handled by this service
14
+ * - Signature verification ensures transaction integrity
15
+ * - Complete audit trail of the signing workflow
16
+ */
17
+ export declare class ExternalSignerModule {
18
+ private verifier;
19
+ private signingTtlMs;
20
+ constructor(options?: {
21
+ signingTtlMs?: number;
22
+ });
23
+ /**
24
+ * Create an unsigned transaction export payload for external signing
25
+ *
26
+ * This is the entry point for the external signing workflow.
27
+ * Call this after building a transaction to get a standardized
28
+ * payload that external signers can use.
29
+ *
30
+ * @param buildId - The build ID from TransactionBuilds
31
+ * @param unsignedTxCbor - The unsigned transaction CBOR
32
+ * @param txBodyHash - The transaction body hash
33
+ * @param network - The Cardano network
34
+ * @param options - Additional options
35
+ * @returns Unsigned transaction export payload
36
+ */
37
+ createSigningRequest(buildId: string, unsignedTxCbor: string, txBodyHash: string, network: string, message: string, options?: {
38
+ requiredSigners?: string[];
39
+ signerTypeHint?: ExternalSignerType;
40
+ }): UnsignedTxExportPayload;
41
+ /**
42
+ * Generate signing instructions for different signer types
43
+ */
44
+ private generateSigningInstructions;
45
+ /**
46
+ * Verify a signed transaction
47
+ *
48
+ * Call this after receiving a signed transaction from an external signer.
49
+ * This verifies the signature integrity before submission.
50
+ *
51
+ * @param signedTxCbor - The signed transaction CBOR
52
+ * @param expectedTxBodyHash - The expected transaction body hash (from the build)
53
+ * @param options - Additional verification options
54
+ * @returns Verification result
55
+ */
56
+ verifySignedTransaction(signedTxCbor: string, expectedTxBodyHash: string, options?: Omit<VerificationOptions, 'expectedTxBodyHash'> & {
57
+ expiresAt?: string;
58
+ }): SignatureVerificationResult;
59
+ /**
60
+ * Verify signed transaction and throw on failure
61
+ *
62
+ * @param signedTxCbor - The signed transaction CBOR
63
+ * @param expectedTxBodyHash - The expected transaction body hash
64
+ * @param options - Additional verification options
65
+ * @throws {TransactionValidationError} if verification fails
66
+ */
67
+ verifyOrThrow(signedTxCbor: string, expectedTxBodyHash: string, options?: Omit<VerificationOptions, 'expectedTxBodyHash'>): SignatureVerificationResult;
68
+ /**
69
+ * Create a complete signing workflow state
70
+ *
71
+ * This creates a trackable workflow state that can be stored
72
+ * and updated throughout the signing process.
73
+ *
74
+ * @param signingRequest - The unsigned transaction export payload
75
+ * @returns Initial workflow state
76
+ */
77
+ createWorkflowState(signingRequest: UnsignedTxExportPayload): SigningWorkflowState;
78
+ /**
79
+ * Update workflow state after signing
80
+ *
81
+ * @param state - Current workflow state
82
+ * @param signedTxCbor - The signed transaction CBOR
83
+ * @returns Updated workflow state
84
+ */
85
+ markAsSigned(state: SigningWorkflowState, signedTxCbor: string): SigningWorkflowState;
86
+ /**
87
+ * Update workflow state after verification
88
+ *
89
+ * @param state - Current workflow state
90
+ * @param verificationResult - The verification result
91
+ * @returns Updated workflow state
92
+ */
93
+ markAsVerified(state: SigningWorkflowState, verificationResult: SignatureVerificationResult): SigningWorkflowState;
94
+ /**
95
+ * Update workflow state after submission
96
+ *
97
+ * @param state - Current workflow state
98
+ * @param txHash - The submitted transaction hash
99
+ * @returns Updated workflow state
100
+ */
101
+ markAsSubmitted(state: SigningWorkflowState, txHash: string): SigningWorkflowState;
102
+ /**
103
+ * Update workflow state on failure
104
+ *
105
+ * @param state - Current workflow state
106
+ * @param errorMessage - The error message
107
+ * @returns Updated workflow state
108
+ */
109
+ markAsFailed(state: SigningWorkflowState, errorMessage: string): SigningWorkflowState;
110
+ /**
111
+ * Check if a signing request has expired
112
+ *
113
+ * @param expiresAt - The expiration timestamp (ISO 8601)
114
+ * @returns true if expired
115
+ */
116
+ isExpired(expiresAt: string): boolean;
117
+ /**
118
+ * Validate a signed transaction payload before submission
119
+ *
120
+ * This performs all pre-submission checks:
121
+ * 1. Verify the signature
122
+ * 2. Check transaction hasn't been tampered with
123
+ * 3. Ensure the build ID matches
124
+ *
125
+ * @param payload - The signed transaction payload
126
+ * @param originalBuildTxBodyHash - The original transaction body hash from the build
127
+ * @returns Validation result with verification details
128
+ * @throws {TransactionValidationError} if validation fails
129
+ */
130
+ validateForSubmission(payload: SignedTxPayload, originalBuildTxBodyHash: string): SignatureVerificationResult;
131
+ /**
132
+ * Get the signature verifier instance
133
+ */
134
+ getVerifier(): SignatureVerifier;
135
+ }
136
+ /**
137
+ * Get the singleton ExternalSignerModule instance
138
+ */
139
+ export declare function getExternalSignerModule(): ExternalSignerModule;
140
+ /**
141
+ * Create a new ExternalSignerModule instance with custom options
142
+ */
143
+ export declare function createExternalSignerModule(options?: {
144
+ signingTtlMs?: number;
145
+ }): ExternalSignerModule;
146
+ //# sourceMappingURL=external-signer.d.ts.map
@@ -15,6 +15,28 @@ const logger = cds_1.default.log('ExternalSigner');
15
15
  * Default TTL for signing requests (30 minutes)
16
16
  */
17
17
  const DEFAULT_SIGNING_TTL_MS = 30 * 60 * 1000;
18
+ /** Network flag for cardano-cli (mainnet vs testnet-magic). */
19
+ const CLI_NETWORK_FLAG = {
20
+ mainnet: '--mainnet',
21
+ preprod: '--testnet-magic 1',
22
+ preview: '--testnet-magic 2',
23
+ };
24
+ /**
25
+ * Build a copy-pasteable cardano-cli signing recipe for the unsigned tx.
26
+ * Templated (the caller supplies their own signing key file); the network flag
27
+ * and the unsigned CBOR are filled in. Previously this was always NULL despite
28
+ * the schema exposing a `cardanoCliCommand` field.
29
+ */
30
+ function buildCardanoCliCommand(network, unsignedTxCbor) {
31
+ const netFlag = CLI_NETWORK_FLAG[network] ?? '--testnet-magic <MAGIC>';
32
+ return [
33
+ '# 1) Save the unsigned transaction to a file:',
34
+ `echo '{"type":"Unwitnessed Tx ConwayEra","description":"","cborHex":"${unsignedTxCbor}"}' > tx.unsigned`,
35
+ '# 2) Sign it with your payment key:',
36
+ `cardano-cli conway transaction sign --tx-file tx.unsigned --signing-key-file payment.skey ${netFlag} --out-file tx.signed`,
37
+ '# 3) Submit the cborHex from tx.signed via SubmitSignedTransaction / SubmitVerifiedTransaction',
38
+ ].join('\n');
39
+ }
18
40
  /**
19
41
  * ExternalSignerModule - Manages the external signing workflow
20
42
  *
@@ -87,6 +109,7 @@ class ExternalSignerModule {
87
109
  txCbor: unsignedTxCbor,
88
110
  partialSign: false,
89
111
  },
112
+ cardanoCliCommand: buildCardanoCliCommand(network, unsignedTxCbor),
90
113
  };
91
114
  }
92
115
  /**
@@ -0,0 +1,74 @@
1
+ import { HsmConfig, HsmSignResult } from '../../utils/types';
2
+ export declare class HsmSigner {
3
+ private pkcs11;
4
+ private session;
5
+ private privateKeyHandle;
6
+ private publicKeyBytes;
7
+ private publicKeyHashHex;
8
+ private cardanoAddress;
9
+ private config;
10
+ private connected;
11
+ constructor(config: HsmConfig);
12
+ /**
13
+ * Initialize PKCS#11 session and locate the signing key.
14
+ * Called once during plugin startup.
15
+ *
16
+ * @param network - Cardano network (mainnet, preview, preprod) for address derivation
17
+ */
18
+ init(network: 'mainnet' | 'preview' | 'preprod' | string): Promise<void>;
19
+ /**
20
+ * Sign a 32-byte transaction body hash using the HSM.
21
+ * Returns the Ed25519 signature + public key for witness construction.
22
+ *
23
+ * @param txBodyHash - 32-byte hash of the transaction body
24
+ * @returns HsmSignResult with signature, public key, and key hash
25
+ */
26
+ sign(txBodyHash: Buffer): HsmSignResult;
27
+ /**
28
+ * Sign a transaction and produce a complete signed transaction CBOR.
29
+ *
30
+ * Takes the unsigned transaction CBOR, signs the body hash via HSM,
31
+ * builds a VKey witness [publicKey, signature], and merges it into
32
+ * the transaction's witness set using raw CBOR manipulation.
33
+ *
34
+ * @param unsignedTxCbor - Unsigned transaction CBOR (hex)
35
+ * @param txBodyHash - Transaction body hash (hex, 64 chars)
36
+ * @returns Signed transaction CBOR (hex)
37
+ */
38
+ signTransaction(unsignedTxCbor: string, txBodyHash: string): string;
39
+ /** Get the HSM-derived Cardano enterprise address */
40
+ getAddress(): string;
41
+ /** Get the public key hash (for requiredSigners) */
42
+ getPublicKeyHash(): string;
43
+ /** Check connection status */
44
+ isConnected(): boolean;
45
+ /** Get status for monitoring */
46
+ getStatus(): {
47
+ connected: boolean;
48
+ keyId?: string;
49
+ keyLabel?: string;
50
+ publicKeyHash?: string;
51
+ address?: string;
52
+ };
53
+ /** Graceful shutdown — close PKCS#11 session */
54
+ shutdown(): void;
55
+ /**
56
+ * Find a key object (private or public) in the HSM by label and/or ID
57
+ */
58
+ private _findKey;
59
+ /**
60
+ * Export the Ed25519 public key from the HSM.
61
+ * Handles both DER-wrapped (04 20 <32 bytes>) and raw 32-byte formats.
62
+ */
63
+ private _exportPublicKey;
64
+ }
65
+ /**
66
+ * Get the initialized HsmSigner instance.
67
+ * Returns null if HSM is not configured.
68
+ */
69
+ export declare function getHsmSigner(): HsmSigner | null;
70
+ /**
71
+ * Set the HsmSigner instance (called during initialization and shutdown).
72
+ */
73
+ export declare function setHsmSigner(signer: HsmSigner | null): void;
74
+ //# sourceMappingURL=hsm-signer.d.ts.map
@@ -50,10 +50,13 @@ class HsmSigner {
50
50
  this.pkcs11.load(this.config.pkcs11Module);
51
51
  this.pkcs11.C_Initialize();
52
52
  logger.info({ module: this.config.pkcs11Module }, 'PKCS#11 module loaded');
53
- // 2. Open session on configured slot
53
+ // 2. Open session on configured slot.
54
+ // NOTE: `config.slot` is the 0-based INDEX into the list of slots-with-token
55
+ // returned by C_GetSlotList(true), NOT the PKCS#11 slot ID (which need not be
56
+ // contiguous or zero-based). Configure it as a position, not a hardware slot id.
54
57
  const slots = this.pkcs11.C_GetSlotList(true);
55
58
  if (this.config.slot >= slots.length) {
56
- throw new errors_1.HsmError(`HSM slot ${this.config.slot} not found. Available slots: ${slots.length}`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
59
+ throw new errors_1.HsmError(`HSM slot index ${this.config.slot} not found. ${slots.length} slot(s) with a token present (valid indices 0..${slots.length - 1}).`, 503, error_codes_1.ERROR_CODES.HSM_UNAVAILABLE);
57
60
  }
58
61
  this.session = this.pkcs11.C_OpenSession(slots[this.config.slot], pkcs11js.CKF_SERIAL_SESSION | pkcs11js.CKF_RW_SESSION);
59
62
  logger.debug({ slot: this.config.slot }, 'PKCS#11 session opened');
@@ -62,9 +65,21 @@ class HsmSigner {
62
65
  this.pkcs11.C_Login(this.session, pkcs11js.CKU_USER, this.config.pin);
63
66
  }
64
67
  finally {
65
- // Clear PIN from memory regardless of login outcome — PIN is no longer needed
66
- // even on failure (preventing in-memory PIN residue for crash-dump / heap-inspection scenarios)
67
- this.config = { ...this.config, pin: '' };
68
+ // Zero the PIN everywhere it could residue after login (crash-dump /
69
+ // heap-inspection hardening), regardless of login outcome:
70
+ // - this.config (shared reference with the server-side hsmConfigInstance
71
+ // singleton) — mutate IN PLACE, not reassign, so the singleton clears too
72
+ // - the HSM_PIN environment variable
73
+ // - the CAP config (cds.env.requires['odatano-core'].hsm.pin)
74
+ this.config.pin = '';
75
+ if (process.env.HSM_PIN)
76
+ delete process.env.HSM_PIN;
77
+ try {
78
+ const hsmCds = cds_1.default.env?.requires?.['odatano-core']?.hsm;
79
+ if (hsmCds && 'pin' in hsmCds)
80
+ hsmCds.pin = '';
81
+ }
82
+ catch { /* best effort */ }
68
83
  }
69
84
  logger.debug('PKCS#11 login successful');
70
85
  // 4. Find private key by label or ID
@@ -0,0 +1,56 @@
1
+ import { SignatureVerificationResult, VerificationOptions } from '../../utils/types';
2
+ /**
3
+ * SignatureVerifier - Verifies transaction signatures without accessing private keys
4
+ *
5
+ * This module provides signature verification for externally signed transactions.
6
+ * It ensures:
7
+ * 1. The signed CBOR is valid and parseable
8
+ * 2. The transaction body hash matches the expected hash (integrity check)
9
+ * 3. Required signatures are present (when specified)
10
+ * 4. No tampering occurred between build and sign steps
11
+ */
12
+ export declare class SignatureVerifier {
13
+ /**
14
+ * Verify a signed transaction
15
+ *
16
+ * @param signedTxCbor - The signed transaction in CBOR hex format
17
+ * @param options - Verification options
18
+ * @returns Verification result with details
19
+ */
20
+ verify(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
21
+ /**
22
+ * Verify signature and throw on failure
23
+ *
24
+ * @param signedTxCbor - The signed transaction in CBOR hex format
25
+ * @param options - Verification options
26
+ * @throws {TransactionValidationError} if verification fails
27
+ */
28
+ verifyOrThrow(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
29
+ /**
30
+ * Extract transaction body hash from unsigned or signed CBOR
31
+ *
32
+ * @param txCbor - Transaction CBOR (signed or unsigned)
33
+ * @returns Transaction body hash as hex string
34
+ * @throws {Error} if CBOR is invalid
35
+ */
36
+ extractTxBodyHash(txCbor: string): string;
37
+ /**
38
+ * Check if a transaction is signed (has witnesses)
39
+ *
40
+ * @param txCbor - Transaction CBOR
41
+ * @returns true if transaction has at least one witness
42
+ */
43
+ isSigned(txCbor: string): boolean;
44
+ /**
45
+ * Get witness count from transaction
46
+ *
47
+ * @param txCbor - Transaction CBOR
48
+ * @returns Number of witnesses
49
+ */
50
+ getWitnessCount(txCbor: string): number;
51
+ }
52
+ /**
53
+ * Get the singleton SignatureVerifier instance
54
+ */
55
+ export declare function getSignatureVerifier(): SignatureVerifier;
56
+ //# sourceMappingURL=signature-verifier.d.ts.map
@@ -46,14 +46,23 @@ function extractVkeyWitnesses(txBytes) {
46
46
  // would otherwise throw a TypeError and surface as an opaque internal error. Skip
47
47
  // any entry that isn't a [vkey, signature] pair of byte strings.
48
48
  const witnesses = [];
49
+ let skipped = 0;
49
50
  for (const pair of arr.array) {
50
- if (!(pair instanceof cbor_1.CborArray) || pair.array.length !== 2)
51
+ if (!(pair instanceof cbor_1.CborArray) || pair.array.length !== 2) {
52
+ skipped++;
51
53
  continue;
54
+ }
52
55
  const [vk, sg] = pair.array;
53
- if (!(vk instanceof cbor_1.CborBytes) || !(sg instanceof cbor_1.CborBytes))
56
+ if (!(vk instanceof cbor_1.CborBytes) || !(sg instanceof cbor_1.CborBytes)) {
57
+ skipped++;
54
58
  continue;
59
+ }
55
60
  witnesses.push({ pubKey: vk.bytes, signature: sg.bytes });
56
61
  }
62
+ if (skipped > 0) {
63
+ // not fatal, but a malformed witness in a signed tx is suspicious — surface it
64
+ logger.warn(`Skipped ${skipped} malformed vkey witness entr${skipped === 1 ? 'y' : 'ies'} while verifying (expected [vkey, signature] byte pairs)`);
65
+ }
57
66
  return witnesses;
58
67
  }
59
68
  /**