@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
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 +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -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 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- 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 +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- 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 +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -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 +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -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/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -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 +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -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 +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- 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 +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -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 +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -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 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -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/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- 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/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -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 +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- 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 +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -15,54 +15,37 @@ 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
17
|
const tx_utils_1 = require("./utils/tx-utils");
|
|
18
|
+
const paging_1 = require("./utils/paging");
|
|
19
|
+
const result_numbers_1 = require("./utils/result-numbers");
|
|
18
20
|
const submission_finalizer_1 = require("./blockchain/signing/submission-finalizer");
|
|
19
21
|
const { SELECT, UPDATE } = cds_1.default.ql;
|
|
20
22
|
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
|
-
*/
|
|
23
|
+
/** Load a build and, when an address is given, check it matches the build's senderAddress. */
|
|
25
24
|
async function verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, actionName) {
|
|
26
25
|
const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
|
|
27
26
|
if (!build)
|
|
28
27
|
(0, errors_1.rejectInvalid)(req, actionName, 'Build not found', 'buildId');
|
|
29
|
-
// rejectInvalid returns `never` → build is narrowed to non-null here
|
|
30
28
|
if (address && build.senderAddress !== address) {
|
|
31
29
|
(0, errors_1.rejectInvalid)(req, actionName, 'Address does not match build owner', 'address');
|
|
32
30
|
}
|
|
33
31
|
return build;
|
|
34
32
|
}
|
|
35
|
-
/**
|
|
36
|
-
* Check if a signing request has expired and update its status.
|
|
37
|
-
* @returns true if expired, false otherwise
|
|
38
|
-
*/
|
|
33
|
+
/** Expires a pending signing request past its TTL. Returns true if it expired. */
|
|
39
34
|
async function checkAndExpireSigningRequest(db, signingRequest, SigningRequests) {
|
|
40
35
|
const now = new Date().toISOString();
|
|
41
36
|
const result = await db.run(UPDATE.entity(SigningRequests)
|
|
42
37
|
.set({ status: 'expired' })
|
|
43
|
-
//
|
|
44
|
-
// 'submitted'/'verified' record would be flipped to 'expired' here
|
|
38
|
+
// Only pending requests may expire; never flip a 'submitted'/'verified' row.
|
|
45
39
|
.where({ id: signingRequest.id, status: 'pending', expiresAt: { '<=': now } }));
|
|
46
40
|
if (result > 0) {
|
|
47
41
|
signingRequest.status = 'expired';
|
|
48
42
|
return true;
|
|
49
43
|
}
|
|
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.
|
|
44
|
+
// A later req.reject rolls this update back; the next touch re-applies it.
|
|
53
45
|
return false;
|
|
54
46
|
}
|
|
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
|
-
*/
|
|
47
|
+
// Key hashes that must sign: the body's required_signers plus the sender's payment key hash.
|
|
48
|
+
// Script credentials are skipped. Returns undefined when nothing can be derived.
|
|
66
49
|
async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
|
|
67
50
|
const signers = new Set();
|
|
68
51
|
try {
|
|
@@ -71,7 +54,7 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
|
|
|
71
54
|
signers.add(s.toLowerCase());
|
|
72
55
|
}
|
|
73
56
|
catch (err) {
|
|
74
|
-
//
|
|
57
|
+
// Body-hash verification still protects integrity.
|
|
75
58
|
logger.warn(`Could not parse unsigned tx for required_signers: ${err instanceof Error ? err.message : String(err)}`);
|
|
76
59
|
}
|
|
77
60
|
if (signingRequest.build_id) {
|
|
@@ -84,30 +67,19 @@ async function resolveRequiredSigners(db, signingRequest, TransactionBuilds) {
|
|
|
84
67
|
}
|
|
85
68
|
return signers.size > 0 ? [...signers] : undefined;
|
|
86
69
|
}
|
|
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
|
-
*/
|
|
70
|
+
/** 403 unless the user holds hsm.requiresRole (no-op when none is configured). */
|
|
93
71
|
function enforceHsmRole(req, actionName) {
|
|
94
72
|
const hsmConfig = (0, server_1.getHsmConfig)();
|
|
95
73
|
if (hsmConfig?.requiresRole && !req.user?.is(hsmConfig.requiresRole)) {
|
|
96
74
|
req.reject(403, `Action '${actionName}' requires role '${hsmConfig.requiresRole}'`);
|
|
97
75
|
}
|
|
98
76
|
}
|
|
99
|
-
/**
|
|
100
|
-
* Cardano Sign Service Implementation
|
|
101
|
-
* Handles transaction signing operations & some additional data queries.
|
|
102
|
-
*/
|
|
77
|
+
/** CardanoSignService handlers: external and HSM signing, verification, submission. */
|
|
103
78
|
module.exports = (srv) => {
|
|
79
|
+
(0, result_numbers_1.answerNumbersAsText)(srv);
|
|
104
80
|
logger.info('Module loaded - registering handlers');
|
|
105
81
|
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
|
-
*/
|
|
82
|
+
// before-READ: bulk-expire pending requests past their TTL, at most once per minute.
|
|
111
83
|
let lastExpiryCheck = 0;
|
|
112
84
|
const EXPIRY_CHECK_INTERVAL_MS = 60_000;
|
|
113
85
|
srv.before('READ', SigningRequests, async (req) => {
|
|
@@ -119,33 +91,23 @@ module.exports = (srv) => {
|
|
|
119
91
|
.set({ status: 'expired' })
|
|
120
92
|
.where({ status: 'pending', expiresAt: { '<=': new Date().toISOString() } }));
|
|
121
93
|
});
|
|
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
|
-
*/
|
|
94
|
+
// CreateSigningRequest: persist a signing request for a build (idempotent per pending build).
|
|
128
95
|
srv.on('CreateSigningRequest', async (req) => {
|
|
129
96
|
logger.debug('CreateSigningRequest Action handler called');
|
|
130
97
|
const { buildId, message } = req.data;
|
|
131
|
-
// Validate inputs
|
|
132
98
|
const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
|
|
133
99
|
(0, errors_1.throwIfValidationErrors)(req, 'CreateSigningRequest', errors);
|
|
134
100
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
135
|
-
// Fetch the build
|
|
136
101
|
const build = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
|
|
137
102
|
if (!build)
|
|
138
103
|
(0, errors_1.rejectInvalid)(req, 'CreateSigningRequest', 'Build not found', 'buildId');
|
|
139
|
-
// Check if signing request already exists for this build
|
|
140
104
|
const existingRequest = await db.run(SELECT.one.from(SigningRequests).where({ build_id: buildId, status: 'pending' }));
|
|
141
105
|
if (existingRequest) {
|
|
142
106
|
logger.info({ buildId, signingRequestId: existingRequest.id }, 'Returning existing signing request');
|
|
143
107
|
return existingRequest;
|
|
144
108
|
}
|
|
145
|
-
// Create signing request using external signer module
|
|
146
109
|
const signerModule = (0, external_signer_1.getExternalSignerModule)();
|
|
147
110
|
const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, message);
|
|
148
|
-
// Delegate persistence to indexer
|
|
149
111
|
const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
|
|
150
112
|
buildId,
|
|
151
113
|
signingPayload,
|
|
@@ -154,34 +116,23 @@ module.exports = (srv) => {
|
|
|
154
116
|
return signingRequestRecord;
|
|
155
117
|
});
|
|
156
118
|
});
|
|
157
|
-
|
|
158
|
-
* Get an existing signing request by ID
|
|
159
|
-
* @param req - CDS request object (with signingRequestId)
|
|
160
|
-
* @returns {SigningRequest} signing request entity
|
|
161
|
-
*/
|
|
119
|
+
// GetSigningRequest: by id; expires a pending request past its TTL on read.
|
|
162
120
|
srv.on('GetSigningRequest', async (req) => {
|
|
163
121
|
logger.debug('GetSigningRequest Action handler called');
|
|
164
122
|
const { signingRequestId } = req.data;
|
|
165
|
-
// Validate inputs
|
|
166
123
|
const errors = (0, validators_1.validateTransactionInputs)({ signingRequestId }, ['signingRequestId']);
|
|
167
124
|
(0, errors_1.throwIfValidationErrors)(req, 'GetSigningRequest', errors);
|
|
168
|
-
// Fetch the signing request within transaction context
|
|
169
125
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
170
126
|
const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
|
|
171
127
|
if (!signingRequest)
|
|
172
128
|
(0, errors_1.rejectInvalid)(req, 'GetSigningRequest', 'Signing request not found', 'signingRequestId');
|
|
173
|
-
// Check if expired and update status if needed
|
|
174
129
|
if (signingRequest.status === 'pending') {
|
|
175
130
|
await checkAndExpireSigningRequest(db, signingRequest, SigningRequests);
|
|
176
131
|
}
|
|
177
132
|
return signingRequest;
|
|
178
133
|
});
|
|
179
134
|
});
|
|
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
|
-
*/
|
|
135
|
+
// VerifySignature: verify a signed tx or witness set against the request; persists the result.
|
|
185
136
|
srv.on('VerifySignature', async (req) => {
|
|
186
137
|
logger.debug('VerifySignature Action handler called');
|
|
187
138
|
const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
|
|
@@ -190,26 +141,21 @@ module.exports = (srv) => {
|
|
|
190
141
|
if (address && !(0, validators_1.isValidBech32Address)(address))
|
|
191
142
|
(0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Invalid bech32 address format', 'address');
|
|
192
143
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
193
|
-
// Fetch the signing request (@from already validated by framework)
|
|
194
144
|
const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
|
|
195
145
|
if (!signingRequest)
|
|
196
146
|
(0, errors_1.rejectInvalid)(req, 'VerifySignature', 'Signing request not found', 'signingRequestId');
|
|
197
|
-
// Ownership check
|
|
147
|
+
// Ownership check (defense in depth)
|
|
198
148
|
if (address && signingRequest.build_id) {
|
|
199
149
|
await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'VerifySignature');
|
|
200
150
|
}
|
|
201
|
-
//
|
|
202
|
-
//
|
|
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.
|
|
151
|
+
// Atomic claim (pending → 'signed') so concurrent verifies cannot both pass;
|
|
152
|
+
// persistSignatureVerification sets the final 'verified'/'failed'.
|
|
206
153
|
const now = new Date().toISOString();
|
|
207
154
|
const claimed = await db.run(UPDATE.entity(SigningRequests)
|
|
208
155
|
.set({ status: 'signed' })
|
|
209
156
|
.where({ id: signingRequestId, status: 'pending', expiresAt: { '>': now } }));
|
|
210
157
|
if (claimed === 0) {
|
|
211
|
-
//
|
|
212
|
-
// verify may have moved it since our SELECT above)
|
|
158
|
+
// Re-read for an accurate message; a concurrent verify may have moved it.
|
|
213
159
|
const current = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
|
|
214
160
|
if (current && current.status === 'pending' && current.expiresAt <= now) {
|
|
215
161
|
await db.run(UPDATE.entity(SigningRequests).set({ status: 'expired' }).where({ id: signingRequestId, status: 'pending' }));
|
|
@@ -217,23 +163,13 @@ module.exports = (srv) => {
|
|
|
217
163
|
}
|
|
218
164
|
(0, errors_1.rejectInvalid)(req, 'VerifySignature', `Signing request status is '${current?.status ?? 'unknown'}', expected 'pending'`, 'signingRequestId');
|
|
219
165
|
}
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
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)
|
|
166
|
+
// A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
|
|
167
|
+
const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
|
|
168
|
+
// Verification is bound to the keys that must witness this tx.
|
|
233
169
|
const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
|
|
234
170
|
const signerModule = (0, external_signer_1.getExternalSignerModule)();
|
|
235
171
|
const result = signerModule.verifySignedTransaction(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
|
|
236
|
-
//
|
|
172
|
+
// Store the full signed tx for later submission
|
|
237
173
|
const verificationRecord = await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
|
|
238
174
|
signingRequestId,
|
|
239
175
|
signedTxCbor: fullSignedTxCbor,
|
|
@@ -250,11 +186,7 @@ module.exports = (srv) => {
|
|
|
250
186
|
return verificationRecord;
|
|
251
187
|
});
|
|
252
188
|
});
|
|
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
|
-
*/
|
|
189
|
+
// SubmitVerifiedTransaction: verify and submit in one step.
|
|
258
190
|
srv.on('SubmitVerifiedTransaction', async (req) => {
|
|
259
191
|
logger.debug('SubmitVerifiedTransaction Action handler called');
|
|
260
192
|
const { signingRequestId, signedTxCbor, signerType, signerInfo, address } = req.data;
|
|
@@ -263,22 +195,12 @@ module.exports = (srv) => {
|
|
|
263
195
|
(0, errors_1.throwIfValidationErrors)(req, 'SubmitVerifiedTransaction', errors);
|
|
264
196
|
if (address && !(0, validators_1.isValidBech32Address)(address))
|
|
265
197
|
(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.
|
|
198
|
+
// Three committed phases (see submitAndFinalize): the network submit must not run inside
|
|
199
|
+
// an open DB transaction. With deferSubmit, phase 1 joins the caller's transaction, the
|
|
200
|
+
// response carries the tx hash (= body hash) and the submit runs after the caller's commit.
|
|
274
201
|
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.
|
|
202
|
+
// Phase 1: verify, then atomically claim → 'submitting'. The claim is the last statement
|
|
203
|
+
// so a verification failure swallowed by the caller never leaves a stranded claim behind.
|
|
282
204
|
const phase1 = async (db) => {
|
|
283
205
|
const now = new Date().toISOString();
|
|
284
206
|
const signingRequest = await db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestId }));
|
|
@@ -289,30 +211,22 @@ module.exports = (srv) => {
|
|
|
289
211
|
if (!['pending', 'verified'].includes(signingRequest.status)) {
|
|
290
212
|
(0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', `Signing request status is '${signingRequest.status}', expected 'pending' or 'verified'`, 'signingRequestId');
|
|
291
213
|
}
|
|
292
|
-
// Ownership check
|
|
214
|
+
// Ownership check (defense in depth)
|
|
293
215
|
if (address && signingRequest.build_id) {
|
|
294
216
|
await verifyBuildOwnership(req, db, signingRequest.build_id, address, TransactionBuilds, 'SubmitVerifiedTransaction');
|
|
295
217
|
}
|
|
296
|
-
// Check if build association exists
|
|
297
218
|
if (!signingRequest.build_id) {
|
|
298
219
|
(0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
|
|
299
220
|
}
|
|
300
|
-
//
|
|
301
|
-
const fullSignedTxCbor = (0, signing_helper_1.
|
|
302
|
-
|
|
303
|
-
: signedTxCbor;
|
|
304
|
-
// Verify signature (throws on failure) — bound to the keys that must
|
|
305
|
-
// actually witness this transaction (required_signers + fee payer)
|
|
221
|
+
// CIP-30 witness set or full signed tx
|
|
222
|
+
const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
|
|
223
|
+
// Throws on failure; bound to the keys that must witness this tx.
|
|
306
224
|
const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
|
|
307
225
|
const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
|
|
308
|
-
// Atomic claim
|
|
309
|
-
//
|
|
310
|
-
// submission can be re-driven after a restart.
|
|
226
|
+
// Atomic claim. The signed CBOR, the signer and the claim time go with it, so an
|
|
227
|
+
// interrupted or unresolved submission can be resolved later.
|
|
311
228
|
const claimed = await db.run(UPDATE.entity(SigningRequests)
|
|
312
|
-
.set({
|
|
313
|
-
status: 'submitting',
|
|
314
|
-
...(deferSubmit ? { signedTxCbor: fullSignedTxCbor, signerType, signerInfo } : {}),
|
|
315
|
-
})
|
|
229
|
+
.set({ status: 'submitting', signedTxCbor: fullSignedTxCbor, signerType, signerInfo, signedAt: now })
|
|
316
230
|
.where({
|
|
317
231
|
id: signingRequestId,
|
|
318
232
|
status: { in: ['pending', 'verified'] },
|
|
@@ -333,12 +247,10 @@ module.exports = (srv) => {
|
|
|
333
247
|
signerInfo,
|
|
334
248
|
});
|
|
335
249
|
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.
|
|
250
|
+
// Phase 1 on the caller's transaction; validation errors stay synchronous.
|
|
339
251
|
const prep = await phase1(cds_1.default.tx(req));
|
|
340
252
|
(0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
|
|
341
|
-
logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed
|
|
253
|
+
logger.info({ signingRequestId, txHash: prep.txHash }, 'Verified and claimed, submit deferred until after the caller commits');
|
|
342
254
|
return {
|
|
343
255
|
id: null,
|
|
344
256
|
build_id: prep.buildId,
|
|
@@ -350,7 +262,7 @@ module.exports = (srv) => {
|
|
|
350
262
|
}
|
|
351
263
|
const prep = await (0, tx_utils_1.detachedTx)('claim + verify signing request', phase1);
|
|
352
264
|
logger.info({ signingRequestId, witnessCount: prep.verificationResult.witnessCount }, 'Signature verified, proceeding with submission');
|
|
353
|
-
//
|
|
265
|
+
// Phases 2+3: submit outside any DB tx, then finalize in its own tx
|
|
354
266
|
const submissionRecord = await (0, submission_finalizer_1.submitAndFinalize)(SigningRequests, finalizeParams(prep));
|
|
355
267
|
logger.info({ signingRequestId, txHash: prep.txHash }, 'Transaction submitted and all records updated');
|
|
356
268
|
return submissionRecord;
|
|
@@ -360,99 +272,73 @@ module.exports = (srv) => {
|
|
|
360
272
|
return (0, mappers_1.mapError)(req, e, 'SubmitVerifiedTransaction');
|
|
361
273
|
}
|
|
362
274
|
});
|
|
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
|
-
*/
|
|
275
|
+
// VerifyDataSignature: stateless CIP-30 signData (COSE_Sign1) check for wallet login.
|
|
276
|
+
// Public (@requires:'any') because the caller is not yet authenticated.
|
|
370
277
|
srv.on('VerifyDataSignature', async (req) => {
|
|
371
278
|
logger.debug('VerifyDataSignature Action handler called');
|
|
372
279
|
const { address, coseSignature, coseKey, expectedPayload } = req.data;
|
|
373
|
-
// Validate inputs before the crypto check
|
|
374
280
|
if (!address)
|
|
375
281
|
(0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'address');
|
|
376
|
-
if (!(0, validators_1.isValidBech32Address)(address))
|
|
282
|
+
if (!(0, validators_1.isValidBech32Address)(address) && !(0, validators_1.isValidBech32StakeAddress)(address)) {
|
|
377
283
|
(0, errors_1.rejectInvalid)(req, 'VerifyDataSignature', 'Invalid bech32 address format', 'address');
|
|
284
|
+
}
|
|
378
285
|
if (!coseSignature)
|
|
379
286
|
(0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseSignature');
|
|
380
287
|
if (!coseKey)
|
|
381
288
|
(0, errors_1.rejectMissing)(req, 'VerifyDataSignature', 'coseKey');
|
|
382
|
-
//
|
|
383
|
-
// valid:false + reason, not an error. Only malformed *inputs* reject above.
|
|
289
|
+
// Never throws: a bad signature is a 200 with valid:false + reason.
|
|
384
290
|
return (0, cose_verifier_1.verifyDataSignature)({ address, coseSignature, coseKey, expectedPayload });
|
|
385
291
|
});
|
|
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
|
-
*/
|
|
292
|
+
// GetSigningRequestsByAddress: signing requests linked to an address.
|
|
391
293
|
srv.on('GetSigningRequestsByAddress', async (req) => {
|
|
392
294
|
logger.debug('GetSigningRequestsByAddress Action handler called');
|
|
393
295
|
const { address } = req.data;
|
|
394
|
-
// Validate input before business logic
|
|
395
296
|
if (!address)
|
|
396
297
|
(0, errors_1.rejectMissing)(req, 'GetSigningRequestsByAddress', 'address');
|
|
397
298
|
if (!(0, validators_1.isValidBech32Address)(address))
|
|
398
299
|
(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
|
-
});
|
|
300
|
+
const { limit, skip } = (0, paging_1.pageOf)(req.data, 1000);
|
|
301
|
+
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
302
|
});
|
|
404
303
|
// ---------------------------------------------------------------------------
|
|
405
|
-
// HSM
|
|
304
|
+
// HSM signing actions
|
|
406
305
|
// ---------------------------------------------------------------------------
|
|
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
|
-
*/
|
|
306
|
+
// SignWithHsm: create a signing request, sign with the HSM, verify; returns the request.
|
|
413
307
|
srv.on('SignWithHsm', async (req) => {
|
|
414
308
|
logger.debug('SignWithHsm Action handler called');
|
|
415
309
|
enforceHsmRole(req, 'SignWithHsm');
|
|
416
310
|
const { buildId, address } = req.data;
|
|
417
|
-
// Validate input
|
|
418
311
|
const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
|
|
419
312
|
(0, errors_1.throwIfValidationErrors)(req, 'SignWithHsm', errors);
|
|
420
313
|
if (address && !(0, validators_1.isValidBech32Address)(address))
|
|
421
314
|
(0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'Invalid bech32 address format', 'address');
|
|
422
|
-
// Check HSM is available (before handleRequest — same pattern as validation)
|
|
423
315
|
const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
|
|
424
316
|
if (!hsmSigner || !hsmSigner.isConnected()) {
|
|
425
317
|
(0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM is not configured or not connected', 'hsm');
|
|
426
318
|
}
|
|
427
319
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
428
|
-
// 1. Fetch the build (with ownership check)
|
|
429
320
|
const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignWithHsm');
|
|
430
|
-
// HSM can only sign builds for its own address
|
|
321
|
+
// The HSM can only sign builds for its own address
|
|
431
322
|
const hsmAddress = hsmSigner.getAddress();
|
|
432
323
|
if (build.senderAddress !== hsmAddress) {
|
|
433
324
|
(0, errors_1.rejectInvalid)(req, 'SignWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
|
|
434
325
|
}
|
|
435
|
-
// 2. Create signing request internally (reuse external signer module)
|
|
436
326
|
const signerModule = (0, external_signer_1.getExternalSignerModule)();
|
|
437
327
|
const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing');
|
|
438
328
|
const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, {
|
|
439
329
|
buildId,
|
|
440
330
|
signingPayload,
|
|
441
331
|
});
|
|
442
|
-
// 3. Sign with HSM
|
|
443
332
|
const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
|
|
444
|
-
//
|
|
333
|
+
// Same verification path as external signing
|
|
445
334
|
const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
|
|
446
335
|
const hsmStatus = hsmSigner.getStatus();
|
|
447
336
|
const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
|
|
448
|
-
// A failed HSM verification is
|
|
449
|
-
// reject (rolls back) instead of returning 200 with status 'failed', matching
|
|
450
|
-
// SignAndSubmitWithHsm.
|
|
337
|
+
// A failed HSM verification is a server fault: reject (rolls back) rather than 200 'failed'.
|
|
451
338
|
if (!verificationResult.isValid) {
|
|
452
339
|
logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed');
|
|
453
340
|
(0, errors_1.rejectInvalid)(req, 'SignWithHsm', 'HSM signature verification failed', 'signedTxCbor');
|
|
454
341
|
}
|
|
455
|
-
// 5. Persist verification
|
|
456
342
|
await (0, server_1.getCardanoIndexer)().persistSignatureVerification(db, {
|
|
457
343
|
signingRequestId: signingRequestRecord.id,
|
|
458
344
|
signedTxCbor,
|
|
@@ -460,7 +346,7 @@ module.exports = (srv) => {
|
|
|
460
346
|
signerType: 'hsm',
|
|
461
347
|
signerInfo: `HSM key: ${hsmKeyIdentifier}`,
|
|
462
348
|
});
|
|
463
|
-
//
|
|
349
|
+
// HSM audit field
|
|
464
350
|
await db.run(UPDATE.entity(SigningRequests)
|
|
465
351
|
.set({ hsmKeyId: hsmKeyIdentifier })
|
|
466
352
|
.where({ id: signingRequestRecord.id }));
|
|
@@ -470,65 +356,54 @@ module.exports = (srv) => {
|
|
|
470
356
|
isValid: verificationResult.isValid,
|
|
471
357
|
hsmKey: hsmKeyIdentifier,
|
|
472
358
|
}, 'Transaction signed with HSM');
|
|
473
|
-
// Return updated signing request
|
|
474
359
|
return db.run(SELECT.one.from(SigningRequests).where({ id: signingRequestRecord.id }));
|
|
475
360
|
});
|
|
476
361
|
});
|
|
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
|
-
*/
|
|
362
|
+
// SignAndSubmitWithHsm: create a signing request, sign, verify and submit in one call.
|
|
483
363
|
srv.on('SignAndSubmitWithHsm', async (req) => {
|
|
484
364
|
logger.debug('SignAndSubmitWithHsm Action handler called');
|
|
485
365
|
enforceHsmRole(req, 'SignAndSubmitWithHsm');
|
|
486
366
|
const { buildId, address } = req.data;
|
|
487
367
|
const deferSubmit = req.data.deferSubmit === true;
|
|
488
|
-
// Validate input
|
|
489
368
|
const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
|
|
490
369
|
(0, errors_1.throwIfValidationErrors)(req, 'SignAndSubmitWithHsm', errors);
|
|
491
370
|
if (address && !(0, validators_1.isValidBech32Address)(address))
|
|
492
371
|
(0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'Invalid bech32 address format', 'address');
|
|
493
|
-
// Check HSM is available
|
|
494
372
|
const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
|
|
495
373
|
if (!hsmSigner || !hsmSigner.isConnected()) {
|
|
496
374
|
(0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM is not configured or not connected', 'hsm');
|
|
497
375
|
}
|
|
498
376
|
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.)
|
|
377
|
+
// Phase 1 (committed): fetch build, sign, verify. A failure rolls back the new signing
|
|
378
|
+
// request; on the deferred path a swallowed failure leaves a 'pending' row that expires via TTL.
|
|
503
379
|
const phase1 = async (db) => {
|
|
504
|
-
// 1. Fetch the build (with ownership check)
|
|
505
380
|
const build = await verifyBuildOwnership(req, db, buildId, address, TransactionBuilds, 'SignAndSubmitWithHsm');
|
|
506
|
-
// HSM can only sign builds for its own address
|
|
381
|
+
// The HSM can only sign builds for its own address
|
|
507
382
|
const hsmAddress = hsmSigner.getAddress();
|
|
508
383
|
if (build.senderAddress !== hsmAddress) {
|
|
509
384
|
(0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', `Build sender '${build.senderAddress}' does not match HSM address '${hsmAddress}'`, 'buildId');
|
|
510
385
|
}
|
|
511
|
-
// 2. Create signing request
|
|
512
386
|
const signerModule = (0, external_signer_1.getExternalSignerModule)();
|
|
513
387
|
const signingPayload = signerModule.createSigningRequest(build.id, build.unsignedTxCbor, build.txBodyHash, build.network, 'HSM signing + submit');
|
|
514
388
|
const signingRequestRecord = await (0, server_1.getCardanoIndexer)().persistSigningRequest(db, { buildId, signingPayload });
|
|
515
|
-
// 3. Sign with HSM
|
|
516
389
|
const signedTxCbor = hsmSigner.signTransaction(build.unsignedTxCbor, build.txBodyHash);
|
|
517
|
-
//
|
|
390
|
+
// Reject (rolls back) on an invalid signature before submitting
|
|
518
391
|
const verificationResult = signerModule.verifySignedTransaction(signedTxCbor, build.txBodyHash);
|
|
519
392
|
const hsmStatus = hsmSigner.getStatus();
|
|
520
393
|
const hsmKeyIdentifier = hsmStatus.keyLabel || hsmStatus.keyId || 'unknown';
|
|
521
394
|
if (!verificationResult.isValid) {
|
|
522
|
-
logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed
|
|
395
|
+
logger.error({ signingRequestId: signingRequestRecord.id, hsmKey: hsmKeyIdentifier }, 'HSM signature verification failed, aborting submission');
|
|
523
396
|
(0, errors_1.rejectInvalid)(req, 'SignAndSubmitWithHsm', 'HSM signature verification failed', 'signedTxCbor');
|
|
524
397
|
}
|
|
525
|
-
// Claim
|
|
526
|
-
//
|
|
527
|
-
// the boot-time redrive of interrupted submissions.
|
|
398
|
+
// Claim as 'submitting' with the signed CBOR, the signer and the claim time, so an
|
|
399
|
+
// interrupted or unresolved submission can be resolved later.
|
|
528
400
|
await db.run(UPDATE.entity(SigningRequests).set({
|
|
529
401
|
status: 'submitting',
|
|
530
402
|
hsmKeyId: hsmKeyIdentifier,
|
|
531
|
-
|
|
403
|
+
signedTxCbor,
|
|
404
|
+
signerType: 'hsm',
|
|
405
|
+
signerInfo: `HSM key: ${hsmKeyIdentifier}`,
|
|
406
|
+
signedAt: new Date().toISOString(),
|
|
532
407
|
}).where({ id: signingRequestRecord.id }));
|
|
533
408
|
return { signingRequestId: signingRequestRecord.id, signedTxCbor, txHash: build.txBodyHash, verificationResult, hsmKeyIdentifier };
|
|
534
409
|
};
|
|
@@ -542,12 +417,10 @@ module.exports = (srv) => {
|
|
|
542
417
|
signerInfo: `HSM key: ${prep.hsmKeyIdentifier}`,
|
|
543
418
|
});
|
|
544
419
|
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.
|
|
420
|
+
// Phase 1 on the caller's transaction; submit runs after its commit.
|
|
548
421
|
const prep = await phase1(cds_1.default.tx(req));
|
|
549
422
|
(0, submission_finalizer_1.scheduleDeferredSubmit)(req, SigningRequests, finalizeParams(prep));
|
|
550
|
-
logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed
|
|
423
|
+
logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed and claimed, submit deferred until after the caller commits');
|
|
551
424
|
return {
|
|
552
425
|
id: null,
|
|
553
426
|
build_id: buildId,
|
|
@@ -559,8 +432,8 @@ module.exports = (srv) => {
|
|
|
559
432
|
}
|
|
560
433
|
const prep = await (0, tx_utils_1.detachedTx)('HSM sign + claim signing request', phase1);
|
|
561
434
|
logger.info({ signingRequestId: prep.signingRequestId, witnessCount: prep.verificationResult.witnessCount, hsmKey: prep.hsmKeyIdentifier }, 'HSM signature verified, proceeding with submission');
|
|
562
|
-
//
|
|
563
|
-
//
|
|
435
|
+
// Phases 2+3: submit outside any DB tx, then finalize (re-sets hsmKeyId, which the
|
|
436
|
+
// generic finalizer does not touch)
|
|
564
437
|
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
438
|
logger.info({ signingRequestId: prep.signingRequestId, txHash: prep.txHash }, 'HSM-signed transaction submitted and all records updated');
|
|
566
439
|
return submissionRecord;
|
|
@@ -570,10 +443,7 @@ module.exports = (srv) => {
|
|
|
570
443
|
return (0, mappers_1.mapError)(req, e, 'SignAndSubmitWithHsm');
|
|
571
444
|
}
|
|
572
445
|
});
|
|
573
|
-
|
|
574
|
-
* Get HSM connection status and key information.
|
|
575
|
-
* Returns null fields if HSM is not configured.
|
|
576
|
-
*/
|
|
446
|
+
// GetHsmStatus: connection status and key info; null fields when no HSM is configured.
|
|
577
447
|
srv.on('GetHsmStatus', async (_req) => {
|
|
578
448
|
enforceHsmRole(_req, 'GetHsmStatus');
|
|
579
449
|
const hsmSigner = (0, hsm_signer_1.getHsmSigner)();
|