@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.
- package/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +358 -0
- package/@cds-models/CardanoBackendService/index.js +41 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
- package/@cds-models/CardanoIndexerService/index.js +74 -0
- package/@cds-models/CardanoODataService/index.d.ts +417 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +45 -19
- package/@cds-models/CardanoSignService/index.js +4 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
- package/@cds-models/CardanoTransactionService/index.js +5 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +114 -4
- package/@cds-models/index.js +20 -4
- package/@cds-models/odatano/cardano/index.d.ts +451 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +103 -167
- package/db/schema.cds +2455 -1705
- package/db/types.cds +456 -295
- package/package.json +41 -53
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +528 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
- package/srv/blockchain/backends/blockfrost-backend.js +125 -215
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +108 -170
- package/srv/blockchain/backends/koios-backend.js +488 -482
- package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
- package/srv/blockchain/backends/odatano-backend.js +211 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
- package/srv/blockchain/backends/ogmios-backend.js +683 -327
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +71 -241
- package/srv/blockchain/cardano-client.js +354 -322
- package/srv/blockchain/cardano-indexer.d.ts +295 -283
- package/srv/blockchain/cardano-indexer.js +1690 -502
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +2 -13
- package/srv/blockchain/circuit-breaker.js +11 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +173 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
- package/srv/blockchain/crawler/certificate-backfill.js +174 -0
- package/srv/blockchain/crawler/crawler.d.ts +125 -81
- package/srv/blockchain/crawler/crawler.js +738 -167
- package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
- package/srv/blockchain/crawler/credential-backfill.js +101 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +161 -0
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
- package/srv/blockchain/crawler/sync-state.d.ts +31 -47
- package/srv/blockchain/crawler/sync-state.js +135 -128
- package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/transaction-backfill.js +271 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +521 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +22 -131
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +71 -87
- package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
- package/srv/blockchain/signing/submission-finalizer.js +280 -86
- package/srv/blockchain/stored-chain.d.ts +19 -0
- package/srv/blockchain/stored-chain.js +258 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +12 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
- package/srv/blockchain/wallet-worker/build-request.js +40 -353
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
- package/srv/blockchain/wallet-worker/job-store.js +200 -273
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
- package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +12 -9
- package/srv/cardano-backend-service.cds +81 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +259 -0
- package/srv/cardano-indexer-service.cds +393 -18
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +477 -16
- package/srv/cardano-service.cds +426 -269
- package/srv/cardano-service.js +640 -217
- package/srv/cardano-sign-service.cds +211 -180
- package/srv/cardano-sign-service.js +210 -287
- package/srv/cardano-tx-service.cds +462 -370
- package/srv/cardano-tx-service.js +283 -800
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +141 -125
- package/srv/cardano-worker-service.js +104 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +117 -0
- package/srv/config.js +419 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +83 -405
- package/srv/utils/agent-access.d.ts +11 -0
- package/srv/utils/agent-access.js +86 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -237
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +62 -186
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +4 -10
- package/srv/utils/collections.js +14 -10
- package/srv/utils/const.d.ts +32 -75
- package/srv/utils/const.js +40 -80
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +11 -25
- package/srv/utils/db-indexes.d.ts +31 -0
- package/srv/utils/db-indexes.js +185 -0
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +14 -0
- package/srv/utils/epoch-slots.js +45 -0
- package/srv/utils/error-codes.d.ts +26 -75
- package/srv/utils/error-codes.js +27 -72
- package/srv/utils/errors.d.ts +55 -187
- package/srv/utils/errors.js +161 -235
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +111 -223
- package/srv/utils/mappers.js +432 -371
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +9 -15
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +25 -105
- package/srv/utils/tx-build-helper.js +108 -156
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +294 -232
- package/srv/utils/types.js +2 -22
- package/srv/utils/validators.d.ts +22 -92
- 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
|
-
//
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
-
|
|
88
|
-
// (shared with the boot-time redrive of interrupted deferred submissions).
|
|
89
|
-
/**
|
|
90
|
-
* Enforce HSM role check if hsm.requiresRole is configured.
|
|
91
|
-
* Rejects with 403 if the user lacks the required role.
|
|
92
|
-
*/
|
|
74
|
+
/** 403 unless the user holds hsm.requiresRole (no-op when none is configured). */
|
|
93
75
|
function enforceHsmRole(req, actionName) {
|
|
94
76
|
const hsmConfig = (0, server_1.getHsmConfig)();
|
|
95
77
|
if (hsmConfig?.requiresRole && !req.user?.is(hsmConfig.requiresRole)) {
|
|
96
|
-
|
|
78
|
+
(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
|
-
|
|
101
|
-
|
|
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
|
-
//
|
|
140
|
-
const
|
|
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
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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
|
|
267
|
-
//
|
|
268
|
-
//
|
|
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
|
-
//
|
|
276
|
-
//
|
|
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
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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
|
-
//
|
|
309
|
-
|
|
310
|
-
|
|
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
|
|
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
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
-
|
|
400
|
-
return (0, backend_request_handler_1.handleRequest)(req,
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
//
|
|
464
|
-
await db.run(UPDATE.entity(SigningRequests)
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
500
|
-
//
|
|
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
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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
|
-
//
|
|
563
|
-
//
|
|
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.
|
|
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
|
-
|
|
575
|
-
|
|
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)();
|