@odatano/core 1.9.5 → 1.11.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.
@@ -4,13 +4,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.BuildooorTxBuilder = void 0;
7
+ // Coin selection uses this.txBuilder.keepRelevant again since buildooor 0.2.9
8
+ // ships the fixed implementation (our PR); the vendored keep-relevant.ts is gone.
7
9
  const buildooor_1 = require("@harmoniclabs/buildooor");
8
10
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
9
11
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
10
12
  const errors_1 = require("../../utils/errors");
11
13
  const plutus_placeholders_1 = require("../../utils/plutus-placeholders");
12
- // Vendored coin selection (buildooor PR #12 fix) — NOT this.txBuilder.keepRelevant; see keep-relevant.ts
13
- const keep_relevant_1 = require("./keep-relevant");
14
14
  const cds_1 = __importDefault(require("@sap/cds"));
15
15
  const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
16
16
  // Metadata classes are imported from the DIST paths ON PURPOSE: buildooor's
@@ -221,7 +221,7 @@ class BuildooorTxBuilder {
221
221
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
222
222
  const candidateInputs = rest.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
223
223
  // Coin selection on candidates only; forced inputs are prepended unconditionally
224
- const selected = (0, keep_relevant_1.keepRelevant)(outputValue, candidateInputs);
224
+ const selected = this.txBuilder.keepRelevant(outputValue, candidateInputs);
225
225
  const inputs = [...forcedInputs, ...selected];
226
226
  logger.debug(`Coin selection: ${selected.length}/${candidateInputs.length} UTxOs selected (${forcedInputs.length} forced) for ${label}`);
227
227
  const metadata = req.metadataJson !== undefined && req.metadataJson !== null
@@ -266,7 +266,7 @@ class BuildooorTxBuilder {
266
266
  const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
267
267
  // Coin selection: only need enough ADA from funding UTxOs (minted tokens come from thin air)
268
268
  const requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
269
- const selectedFunding = (0, keep_relevant_1.keepRelevant)(requiredFundingValue, allFundingInputs);
269
+ const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
270
270
  const inputs = [...forcedInputs, ...selectedFunding];
271
271
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
272
272
  // FR-3: resolve __INPUT_IDX__ placeholders in mintRedeemer + inlineDatum after final input order is known.
@@ -360,7 +360,7 @@ class BuildooorTxBuilder {
360
360
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
361
361
  }
362
362
  }
363
- const selectedFundingInputs = (0, keep_relevant_1.keepRelevant)(requiredFundingValue, allFundingInputs);
363
+ const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
364
364
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
365
365
  // FR-3: compute the final input order (replicates Buildooor's lex sort) and resolve any
366
366
  // __INPUT_IDX__ placeholders in redeemer / datum / output datums BEFORE PlutusData encoding.
@@ -675,16 +675,13 @@ class BuildooorTxBuilder {
675
675
  /**
676
676
  * Replace the redeemers' execution units and recompute scriptDataHash.
677
677
  *
678
- * Not implemented via TxBuilder.overrideTxRedeemers: that method computes the script
679
- * data hash from the OLD witness set (library bug), which would yield a phase-1
680
- * rejection (PPViewHashesDontMatch). We rebuild the witness set first and hash it with
681
- * the same exported getScriptDataHash the build itself uses.
682
- *
683
- * The hash is recomputed even when the target units already match: Buildooor's
684
- * internal hash comes from the named-key cost models, which clamp the chain array
685
- * to the parameter count the library release knows — wrong on networks whose cost
686
- * model has grown past that (ScriptIntegrityHashMismatch at submit). This recompute
687
- * with _languageViewCostModels (raw chain arrays) is where the hash becomes correct.
678
+ * Still not implemented via TxBuilder.overrideTxRedeemers, although buildooor
679
+ * 0.2.9 fixed its old-witness-set hashing (our PR): that method hashes with the
680
+ * builder's named-key cost models, which clamp the chain array to the parameter
681
+ * count the library release knows — wrong whenever the on-chain cost model has
682
+ * grown past that (ScriptIntegrityHashMismatch at submit). This recompute with
683
+ * _languageViewCostModels (raw chain arrays) stays governance-proof, so the hash
684
+ * is recomputed here even when the target units already match.
688
685
  */
689
686
  _stampExecUnits(tx, targets) {
690
687
  const rdmrs = tx.witnesses.redeemers ?? [];
@@ -81,7 +81,10 @@ service CardanoSignService @(impl: './cardano-sign-service') {
81
81
  signerInfo: String(100),
82
82
  @title: 'Sender Address'
83
83
  @description: 'Optional sender address for ownership verification. When provided, verifies the signing request belongs to this address.'
84
- address: Bech32) returns TransactionSubmissions;
84
+ address: Bech32,
85
+ @title: 'Defer Submit'
86
+ @description: 'When true, verify + claim run on the caller''s transaction and the network submit happens detached AFTER the caller''s commit. Returns immediately with the tx hash (= tx body hash) and status ''pending''. Designed for in-process CAP consumers whose request transaction would otherwise deadlock the pooled sqlite connection (KNOWN_ISSUES #11). Track the outcome via the signing request / submission status.'
87
+ deferSubmit: Boolean) returns TransactionSubmissions;
85
88
 
86
89
 
87
90
  // ---------------------------------------------------------------------------
@@ -159,7 +162,10 @@ service CardanoSignService @(impl: './cardano-sign-service') {
159
162
  buildId: UUID,
160
163
  @title: 'Sender Address'
161
164
  @description: 'Optional sender address for ownership verification. When provided, verifies the build belongs to this address.'
162
- address: Bech32) returns TransactionSubmissions;
165
+ address: Bech32,
166
+ @title: 'Defer Submit'
167
+ @description: 'When true, sign + verify + claim run on the caller''s transaction and the network submit happens detached AFTER the caller''s commit (see SubmitVerifiedTransaction.deferSubmit).'
168
+ deferSubmit: Boolean) returns TransactionSubmissions;
163
169
 
164
170
  @title : 'Get HSM Status'
165
171
  @description: 'Check the current status of the HSM connection and key availability.'
@@ -14,7 +14,8 @@ const external_signer_1 = require("./blockchain/signing/external-signer");
14
14
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
15
15
  const cose_verifier_1 = require("./blockchain/signing/cose-verifier");
16
16
  const signing_helper_1 = require("./utils/signing-helper");
17
- const tx_build_helper_1 = require("./utils/tx-build-helper");
17
+ const tx_utils_1 = require("./utils/tx-utils");
18
+ const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
18
19
  const { SELECT, UPDATE } = cds_1.default.ql;
19
20
  const logger = cds_1.default.log('CardanoSignService');
20
21
  /**
@@ -83,62 +84,8 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
83
84
  }
84
85
  return signers.size > 0 ? [...signers] : undefined;
85
86
  }
86
- /**
87
- * Submit a verified+claimed signing request to the blockchain and persist the
88
- * outcome — DELIBERATELY outside the caller's request transaction.
89
- *
90
- * The caller must already have durably committed `status:'submitting'` (the
91
- * claim). This function then:
92
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
93
- * submits serialized and the SQLite busy-timeout could fire mid-network),
94
- * 2. on submit failure: marks the request 'failed' in its own committed tx
95
- * and rethrows (NOT rolled back to a pre-submit status — losing the
96
- * attempt would hide a tx the node may have accepted),
97
- * 3. on success: persists the submission + 'submitted' status in a committed
98
- * transaction.
99
- *
100
- * Crash window: a process death between (1) and (3) leaves the request durably
101
- * at 'submitting' — the operator/poller checks the chain — instead of silently
102
- * reverting to 'pending'/'verified' with no on-chain trace.
103
- */
104
- async function submitAndFinalize(SigningRequests, params, afterFinalize) {
105
- // Persist the submission + 'submitted' status in its own committed transaction.
106
- const finalizeSubmitted = () => cds_1.default.tx(async (db) => {
107
- const submission = await (0, server_1.getCardanoIndexer)().indexVerifiedTransactionSubmission(db, params);
108
- if (afterFinalize)
109
- await afterFinalize(db);
110
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
111
- // must never roll back the durable submission record.
112
- try {
113
- await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
114
- }
115
- catch (invalidateErr) {
116
- logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
117
- }
118
- return submission;
119
- });
120
- try {
121
- await (0, server_1.getCardanoClient)().submitTransaction(params.fullSignedTxCbor);
122
- }
123
- catch (submitErr) {
124
- // Already-submitted means the tx reached the mempool — e.g. the first backend accepted
125
- // it but its response was lost and a fallback observed the duplicate. That is SUCCESS,
126
- // not failure: finalize it as 'submitted' (same as the happy path) instead of durably
127
- // recording a spurious 'failed' for a tx the node already holds.
128
- if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
129
- logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
130
- return finalizeSubmitted();
131
- }
132
- try {
133
- await cds_1.default.tx((db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'failed' }).where({ id: params.signingRequestId })));
134
- }
135
- catch (markErr) {
136
- logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
137
- }
138
- throw submitErr;
139
- }
140
- return finalizeSubmitted();
141
- }
87
+ // submitAndFinalize + FinalizeParams moved to blockchain/signing/submission-finalizer.ts
88
+ // (shared with the boot-time redrive of interrupted deferred submissions).
142
89
  /**
143
90
  * Enforce HSM role check if hsm.requiresRole is configured.
144
91
  * Rejects with 403 if the user lacks the required role.
@@ -311,6 +258,7 @@ module.exports = (srv) => {
311
258
  srv.on('SubmitVerifiedTransaction', async (req) => {
312
259
  logger.debug('SubmitVerifiedTransaction Action handler called');
313
260
  const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
261
+ const deferSubmit = req.data.deferSubmit === true;
314
262
  const errors = (0, validators_1.validateTransactionInputs)({ signingRequestId, signedTxCbor }, ['signingRequestId', 'signedTxCbor']);
315
263
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
316
264
  if (address && !(0, validators_1.isValidBech32Address)(address))
@@ -318,30 +266,29 @@ module.exports = (srv) => {
318
266
  // Three committed phases instead of one request-long transaction (see
319
267
  // submitAndFinalize): the network submit must NOT run inside an open DB
320
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.
321
274
  try {
322
- // PHASE 1 (committed): atomically claim → 'submitting' and fully verify.
323
- // A reject/verification failure here rolls the claim back, so a bad
324
- // signature never strands the request in 'submitting'.
325
- const prep = await cds_1.default.tx(async (db) => {
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.
282
+ const phase1 = async (db) => {
326
283
  const now = new Date().toISOString();
327
- const claimed = await db.run(UPDATE.entity(SigningRequests)
328
- .set({ status: 'submitting' })
329
- .where({
330
- id: signingRequestId,
331
- status: { in: ['pending', 'verified'] },
332
- expiresAt: { '>': now },
333
- }));
334
- if (claimed === 0) {
335
- // Claim failed — fetch to provide a specific error message
336
- const existing = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
337
- if (!existing)
338
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request not found', 'signingRequestId');
339
- if (existing.expiresAt <= now)
340
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has expired', 'signingRequestId');
341
- (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${existing.status}', expected 'pending' or 'verified'`, 'signingRequestId');
342
- }
343
- // Re-fetch the full record (now with status='submitting')
344
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
+ }
345
292
  // Ownership check: verify address matches build owner (defense-in-depth)
346
293
  if (address && signingRequest.build_id) {
347
294
  await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
@@ -358,11 +305,25 @@ module.exports = (srv) => {
358
305
  // actually witness this transaction (required_signers + fee payer)
359
306
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
360
307
  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.
311
+ const claimed = await db.run(UPDATE.entity(SigningRequests)
312
+ .set({
313
+ status: 'submitting',
314
+ ...(deferSubmit ? { signedTxCbor: fullSignedTxCbor, signerType, signerInfo } : {}),
315
+ })
316
+ .where({
317
+ id: signingRequestId,
318
+ status: { in: ['pending', 'verified'] },
319
+ expiresAt: { '>': now },
320
+ }));
321
+ if (claimed === 0) {
322
+ (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request was claimed by a concurrent submission', 'signingRequestId');
323
+ }
361
324
  return { buildId: signingRequest.build_id, txHash: signingRequest.txBodyHash, fullSignedTxCbor, verificationResult };
362
- });
363
- logger.info({ signingRequestId, witnessCount: prep.verificationResult.witnessCount }, 'Signature verified, proceeding with submission');
364
- // PHASES 2+3: submit outside any DB tx, then finalize in its own tx
365
- const submissionRecord = await submitAndFinalize(SigningRequests, {
325
+ };
326
+ const finalizeParams = (prep) => ({
366
327
  signingRequestId,
367
328
  buildId: prep.buildId,
368
329
  fullSignedTxCbor: prep.fullSignedTxCbor,
@@ -371,6 +332,26 @@ module.exports = (srv) => {
371
332
  signerType,
372
333
  signerInfo,
373
334
  });
335
+ 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.
339
+ const prep = await phase1(cds_1.default.tx(req));
340
+ (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');
342
+ return {
343
+ id: null,
344
+ build_id: prep.buildId,
345
+ txHash: prep.txHash,
346
+ signedTxCbor: prep.fullSignedTxCbor,
347
+ status: 'pending',
348
+ submittedAt: null,
349
+ };
350
+ }
351
+ const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
352
+ 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
354
+ const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
374
355
  logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
375
356
  return submissionRecord;
376
357
  }
@@ -503,6 +484,7 @@ module.exports = (srv) => {
503
484
  logger.debug('SignAndSubmitWithHsm Action handler called');
504
485
  enforceHsmRole(req, 'SignAndSubmitWithHsm');
505
486
  const { buildId, address } = req.data;
487
+ const deferSubmit = req.data.deferSubmit === true;
506
488
  // Validate input
507
489
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
508
490
  (0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
@@ -515,8 +497,10 @@ module.exports = (srv) => {
515
497
  }
516
498
  try {
517
499
  // PHASE 1 (committed): fetch build, sign with HSM, verify. A failure
518
- // here rolls back the freshly-created signing request.
519
- const prep = await cds_1.default.tx(async (db) => {
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.)
503
+ const phase1 = async (db) => {
520
504
  // 1. Fetch the build (with ownership check)
521
505
  const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
522
506
  // HSM can only sign builds for its own address
@@ -538,14 +522,17 @@ module.exports = (srv) => {
538
522
  logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed — aborting submission');
539
523
  (0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
540
524
  }
541
- // Claim the request as 'submitting' in this same committed phase
542
- await db.run(UPDATE.entity(SigningRequests).set({ status: 'submitting', hsmKeyId: hsmKeyIdentifier }).where({ id: signingRequestRecord.id }));
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.
528
+ await db.run(UPDATE.entity(SigningRequests).set({
529
+ status: 'submitting',
530
+ hsmKeyId: hsmKeyIdentifier,
531
+ ...(deferSubmit ? { signedTxCbor, signerType: 'hsm', signerInfo: `HSM key: ${hsmKeyIdentifier}` } : {}),
532
+ }).where({ id: signingRequestRecord.id }));
543
533
  return { signingRequestId: signingRequestRecord.id, signedTxCbor, txHash: build.txBodyHash, verificationResult, hsmKeyIdentifier };
544
- });
545
- logger.info({ signingRequestId: prep.signingRequestId, witnessCount: prep.verificationResult.witnessCount, hsmKey: prep.hsmKeyIdentifier }, 'HSM signature verified, proceeding with submission');
546
- // PHASES 2+3: submit outside any DB tx, then finalize (re-set hsmKeyId,
547
- // which indexVerifiedTransactionSubmission does not touch)
548
- const submissionRecord = await submitAndFinalize(SigningRequests, {
534
+ };
535
+ const finalizeParams = (prep) => ({
549
536
  signingRequestId: prep.signingRequestId,
550
537
  buildId,
551
538
  fullSignedTxCbor: prep.signedTxCbor,
@@ -553,7 +540,28 @@ module.exports = (srv) => {
553
540
  verificationResult: prep.verificationResult,
554
541
  signerType: 'hsm',
555
542
  signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
556
- }, (db) => db.run(UPDATE.entity(SigningRequests).set({ hsmKeyId: prep.hsmKeyIdentifier }).where({ id: prep.signingRequestId })).then(() => undefined));
543
+ });
544
+ 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.
548
+ const prep = await phase1(cds_1.default.tx(req));
549
+ (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');
551
+ return {
552
+ id: null,
553
+ build_id: buildId,
554
+ txHash: prep.txHash,
555
+ signedTxCbor: prep.signedTxCbor,
556
+ status: 'pending',
557
+ submittedAt: null,
558
+ };
559
+ }
560
+ const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
561
+ 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)
564
+ 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));
557
565
  logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
558
566
  return submissionRecord;
559
567
  }
package/srv/server.d.ts CHANGED
@@ -86,5 +86,13 @@ export declare function loadConfigFromEnv(): CardanoClientConfig;
86
86
  * @returns HsmConfig or undefined
87
87
  */
88
88
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
89
+ /**
90
+ * Re-drive deferred submissions that were claimed (status 'submitting' with
91
+ * persisted signedTxCbor) but whose detached submit never ran because the
92
+ * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
93
+ * submitted tx finalizes via the TransactionAlreadySubmittedError path.
94
+ * Non-fatal.
95
+ */
96
+ export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
89
97
  export {};
90
98
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
@@ -14,6 +47,7 @@ exports.createTestContext = createTestContext;
14
47
  exports.shutdownAppContext = shutdownAppContext;
15
48
  exports.loadConfigFromEnv = loadConfigFromEnv;
16
49
  exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
50
+ exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
17
51
  const cds_1 = __importDefault(require("@sap/cds"));
18
52
  const cardano_client_1 = require("./blockchain/cardano-client");
19
53
  const cardano_indexer_1 = require("./blockchain/cardano-indexer");
@@ -311,6 +345,26 @@ function loadHsmConfigFromEnv() {
311
345
  requiresRole,
312
346
  };
313
347
  }
348
+ /**
349
+ * Re-drive deferred submissions that were claimed (status 'submitting' with
350
+ * persisted signedTxCbor) but whose detached submit never ran because the
351
+ * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
352
+ * submitted tx finalizes via the TransactionAlreadySubmittedError path.
353
+ * Non-fatal.
354
+ */
355
+ async function redriveInterruptedSubmissionsIfConfigured() {
356
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
357
+ return;
358
+ try {
359
+ const { redriveInterruptedSubmissions } = await Promise.resolve().then(() => __importStar(require('./blockchain/signing/submission-finalizer')));
360
+ const attempted = await redriveInterruptedSubmissions();
361
+ if (attempted > 0)
362
+ logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);
363
+ }
364
+ catch (err) {
365
+ logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
366
+ }
367
+ }
314
368
  // Bootstrap hook - runs when CAP server has loaded all services
315
369
  cds_1.default.on('served', async () => {
316
370
  // Skip if already initialized by plugin (src/plugin.ts runs first)
@@ -346,6 +400,8 @@ cds_1.default.on('served', async () => {
346
400
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
347
401
  logger.error('Failed to initialize blockchain components:', err);
348
402
  }
403
+ // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
404
+ await redriveInterruptedSubmissionsIfConfigured();
349
405
  });
350
406
  // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
351
407
  cds_1.default.on('shutdown', async () => {
@@ -71,6 +71,15 @@ export declare const ERROR_CODES: {
71
71
  * Indicates HSM signing was requested but HSM is not configured
72
72
  */
73
73
  readonly HSM_NOT_CONFIGURED: "ODATANO_HSM_NOT_CONFIGURED";
74
+ /**
75
+ * 503 – Detached transaction could not begin in time
76
+ * The sign-service could not acquire a pooled DB connection for one of its
77
+ * detached bookkeeping transactions. Most common cause: an in-process
78
+ * consumer awaits SubmitVerifiedTransaction/SignAndSubmitWithHsm while its
79
+ * own request transaction holds the (single) pooled sqlite connection —
80
+ * see docs/KNOWN_ISSUES.md issue 11.
81
+ */
82
+ readonly NESTED_TX_TIMEOUT: "ODATANO_NESTED_TX_TIMEOUT";
74
83
  };
75
84
  /**
76
85
  * EnumType representing all possible error codes
@@ -74,5 +74,14 @@ exports.ERROR_CODES = {
74
74
  * Indicates HSM signing was requested but HSM is not configured
75
75
  */
76
76
  HSM_NOT_CONFIGURED: 'ODATANO_HSM_NOT_CONFIGURED',
77
+ /**
78
+ * 503 – Detached transaction could not begin in time
79
+ * The sign-service could not acquire a pooled DB connection for one of its
80
+ * detached bookkeeping transactions. Most common cause: an in-process
81
+ * consumer awaits SubmitVerifiedTransaction/SignAndSubmitWithHsm while its
82
+ * own request transaction holds the (single) pooled sqlite connection —
83
+ * see docs/KNOWN_ISSUES.md issue 11.
84
+ */
85
+ NESTED_TX_TIMEOUT: 'ODATANO_NESTED_TX_TIMEOUT',
77
86
  };
78
87
  //# sourceMappingURL=error-codes.js.map
@@ -35,8 +35,7 @@ export interface TxCacheTargets {
35
35
  * Extract the consumed input refs and the output addresses from a transaction
36
36
  * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
37
37
  * UTxO cache. Works at the raw-CBOR level for the same reason as
38
- * getTxHashFromCbor (the high-level Tx.fromCbor rejects its own tag-259
39
- * AuxiliaryData builds).
38
+ * getTxHashFromCbor (byte-exact, no high-level Tx round-trip).
40
39
  *
41
40
  * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
42
41
  * addresses) are skipped — invalidation is best-effort per address.
@@ -58,9 +58,8 @@ function getTxHashFromCbor(txCbor) {
58
58
  }
59
59
  // Compute blake2b-256 over the ORIGINAL transaction-body bytes (CBOR array index 0).
60
60
  // subCborRef.toBuffer() returns the exact bytes as received — no re-serialization, so
61
- // the hash matches what was signed. Working at the raw-CBOR level also sidesteps the
62
- // @harmoniclabs/cardano-ledger-ts AuxiliaryData.fromCbor bug on metadata-only aux_data
63
- // (we never instantiate the high-level Tx type).
61
+ // the hash matches what was signed. We stay at the raw-CBOR level (never instantiate
62
+ // the high-level Tx type) for that byte-exactness.
64
63
  try {
65
64
  const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
66
65
  if (!(tx instanceof cbor_1.CborArray) || tx.array.length < 1 || !tx.array[0].subCborRef) {
@@ -78,8 +77,7 @@ function getTxHashFromCbor(txCbor) {
78
77
  * Extract the consumed input refs and the output addresses from a transaction
79
78
  * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
80
79
  * UTxO cache. Works at the raw-CBOR level for the same reason as
81
- * getTxHashFromCbor (the high-level Tx.fromCbor rejects its own tag-259
82
- * AuxiliaryData builds).
80
+ * getTxHashFromCbor (byte-exact, no high-level Tx round-trip).
83
81
  *
84
82
  * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
85
83
  * addresses) are skipped — invalidation is best-effort per address.
@@ -0,0 +1,32 @@
1
+ import cds from '@sap/cds';
2
+ /** Default acquire budget for detached bookkeeping transactions. */
3
+ export declare const DETACHED_TX_TIMEOUT_MS = 10000;
4
+ /**
5
+ * Run `fn` with `cds.context` cleared, so any `db.run(...)` inside it gets a
6
+ * fresh short-lived transaction instead of joining a long-lived ambient one.
7
+ * Under @cap-js/sqlite (pool.max=1) this is what keeps the single pooled
8
+ * connection free during long awaits (e.g. the deferred network submit).
9
+ */
10
+ export declare function runWithoutAmbientTx<T>(fn: () => Promise<T>): Promise<T>;
11
+ /**
12
+ * `cds.tx(fn)` with a deadlock guard: a NEW ROOT transaction that fails fast
13
+ * instead of hanging forever when no pooled connection becomes available.
14
+ *
15
+ * Why: the sign-service must commit its submit bookkeeping (claim, finalize,
16
+ * failure marker) independently of the caller's request transaction. When an
17
+ * in-process consumer awaits the action while its own request transaction
18
+ * holds the single pooled sqlite connection, the acquire can never succeed —
19
+ * without this guard that is a silent, zero-CPU, infinite hang.
20
+ *
21
+ * Guarantees:
22
+ * - On timeout, throws `BackendError` 503 `ODATANO_NESTED_TX_TIMEOUT` with a
23
+ * diagnosis pointing at KNOWN_ISSUES #11.
24
+ * - A late connection grant (after the timeout already fired) performs NO
25
+ * work: the callback forces the acquire via an explicit `begin()` and
26
+ * checks the abort flag right after it, so it rolls back immediately and
27
+ * the caller never observes an error for work that then silently happened
28
+ * anyway. (A flag check at callback ENTRY would run long before the lazy
29
+ * acquire and miss the timeout.)
30
+ */
31
+ export declare function detachedTx<T>(label: string, fn: (db: cds.Transaction) => Promise<T>, timeoutMs?: number): Promise<T>;
32
+ //# sourceMappingURL=tx-utils.d.ts.map