@odatano/core 1.11.0 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
  2. package/@cds-models/CardanoIndexerService/index.js +23 -0
  3. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  4. package/@cds-models/CardanoODataService/index.js +88 -390
  5. package/@cds-models/CardanoSignService/index.d.ts +443 -1574
  6. package/@cds-models/CardanoSignService/index.js +62 -293
  7. package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
  8. package/@cds-models/CardanoTransactionService/index.js +60 -271
  9. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  10. package/@cds-models/CardanoWorkerService/index.js +32 -0
  11. package/@cds-models/_/index.d.ts +70 -40
  12. package/@cds-models/_/index.js +17 -32
  13. package/@cds-models/cds/outbox/index.d.ts +28 -0
  14. package/@cds-models/index.d.ts +225 -522
  15. package/@cds-models/index.js +35 -218
  16. package/@cds-models/odatano/cardano/index.d.ts +896 -2947
  17. package/@cds-models/odatano/cardano/index.js +109 -536
  18. package/@cds-models/sap/common/index.d.ts +196 -600
  19. package/@cds-models/sap/common/index.js +28 -269
  20. package/README.md +136 -102
  21. package/db/schema.cds +283 -1
  22. package/db/types.cds +48 -0
  23. package/package.json +41 -32
  24. package/src/index.d.ts +1 -1
  25. package/src/index.js +10 -2
  26. package/src/plugin.js +12 -2
  27. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  28. package/srv/blockchain/backends/blockfrost-backend.js +68 -15
  29. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  30. package/srv/blockchain/backends/cardano-backend.js +13 -0
  31. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  32. package/srv/blockchain/backends/koios-backend.js +147 -15
  33. package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
  34. package/srv/blockchain/backends/ogmios-backend.js +254 -5
  35. package/srv/blockchain/cardano-client.d.ts +19 -0
  36. package/srv/blockchain/cardano-client.js +36 -0
  37. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  38. package/srv/blockchain/cardano-indexer.js +191 -0
  39. package/srv/blockchain/crawler/crawler.d.ts +151 -0
  40. package/srv/blockchain/crawler/crawler.js +677 -0
  41. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  42. package/srv/blockchain/crawler/hooks.js +62 -0
  43. package/srv/blockchain/crawler/index.d.ts +26 -0
  44. package/srv/blockchain/crawler/index.js +135 -0
  45. package/srv/blockchain/crawler/sync-state.d.ts +94 -0
  46. package/srv/blockchain/crawler/sync-state.js +265 -0
  47. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  48. package/srv/blockchain/signing/hsm-signer.js +8 -1
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  50. package/srv/blockchain/wallet-worker/build-request.js +341 -0
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
  53. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  54. package/srv/blockchain/wallet-worker/index.js +80 -0
  55. package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
  56. package/srv/blockchain/wallet-worker/job-store.js +564 -0
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  58. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  59. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  60. package/srv/blockchain/wallet-worker/signers.js +131 -0
  61. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  62. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  63. package/srv/cardano-indexer-service.cds +73 -0
  64. package/srv/cardano-indexer-service.d.ts +2 -0
  65. package/srv/cardano-indexer-service.js +76 -0
  66. package/srv/cardano-service.js +22 -1
  67. package/srv/cardano-tx-service.d.ts +1 -11
  68. package/srv/cardano-tx-service.js +11 -162
  69. package/srv/cardano-worker-service.cds +125 -0
  70. package/srv/cardano-worker-service.d.ts +2 -0
  71. package/srv/cardano-worker-service.js +199 -0
  72. package/srv/server.d.ts +32 -1
  73. package/srv/server.js +228 -2
  74. package/srv/utils/collections.d.ts +13 -0
  75. package/srv/utils/collections.js +24 -0
  76. package/srv/utils/crypto.d.ts +16 -0
  77. package/srv/utils/crypto.js +75 -0
  78. package/srv/utils/error-codes.d.ts +6 -0
  79. package/srv/utils/error-codes.js +6 -0
  80. package/srv/utils/errors.d.ts +12 -0
  81. package/srv/utils/errors.js +45 -0
  82. package/srv/utils/mappers.js +13 -3
  83. package/srv/utils/service-events.d.ts +26 -0
  84. package/srv/utils/service-events.js +46 -0
  85. package/srv/utils/tx-request-parsers.d.ts +58 -0
  86. package/srv/utils/tx-request-parsers.js +170 -0
  87. package/srv/utils/tx-utils.d.ts +2 -1
  88. package/srv/utils/tx-utils.js +3 -2
  89. package/srv/utils/types.d.ts +2 -1
  90. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  91. package/@cds-models/CardanoODataService/index.js.map +0 -1
  92. package/@cds-models/CardanoODataService/index.ts +0 -776
  93. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  94. package/@cds-models/CardanoSignService/index.js.map +0 -1
  95. package/@cds-models/CardanoSignService/index.ts +0 -569
  96. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  97. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  98. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  99. package/@cds-models/_/index.d.ts.map +0 -1
  100. package/@cds-models/_/index.js.map +0 -1
  101. package/@cds-models/_/index.ts +0 -96
  102. package/@cds-models/cds/outbox/index.ts +0 -27
  103. package/@cds-models/index.d.ts.map +0 -1
  104. package/@cds-models/index.js.map +0 -1
  105. package/@cds-models/index.ts +0 -245
  106. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  107. package/@cds-models/odatano/cardano/index.js.map +0 -1
  108. package/@cds-models/odatano/cardano/index.ts +0 -789
  109. package/@cds-models/sap/common/index.d.ts.map +0 -1
  110. package/@cds-models/sap/common/index.js.map +0 -1
  111. package/@cds-models/sap/common/index.ts +0 -249
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cds_1 = __importDefault(require("@sap/cds"));
7
+ const backend_request_handler_1 = require("./utils/backend-request-handler");
8
+ const errors_1 = require("./utils/errors");
9
+ const error_codes_1 = require("./utils/error-codes");
10
+ const validators_1 = require("./utils/validators");
11
+ const wallet_worker_1 = require("./blockchain/wallet-worker");
12
+ const job_store_1 = require("./blockchain/wallet-worker/job-store");
13
+ const server_1 = require("./server");
14
+ const logger = cds_1.default.log('CardanoWorkerService');
15
+ /**
16
+ * CardanoWorkerService handlers — thin control surface over the wallet-worker
17
+ * singleton (srv/blockchain/wallet-worker). Engine logic lives there; this only
18
+ * validates inputs, inserts/reads job rows and starts/stops the worker.
19
+ *
20
+ * Validation rejections happen BEFORE handleRequest (project convention); the
21
+ * job INSERT runs on the request's ambient transaction (NIGHTGATE lesson 1).
22
+ */
23
+ function isAdmin(req) {
24
+ return req.user?.is?.('Admin') ?? false;
25
+ }
26
+ /**
27
+ * A job on an HSM-backed wallet spends the same server-held key as the synchronous
28
+ * SignWithHsm path, so it inherits that path's role gate (enforceHsmRole in
29
+ * cardano-sign-service.ts) — 'authenticated-user' alone must not reach the HSM.
30
+ * Returns the role the caller is missing, or null when the wallet is not HSM-backed,
31
+ * no role is configured, or the caller holds it.
32
+ */
33
+ function missingHsmRole(req, signerType) {
34
+ if (signerType !== 'hsm')
35
+ return null;
36
+ const requiresRole = (0, server_1.getHsmConfig)()?.requiresRole;
37
+ if (!requiresRole || req.user?.is(requiresRole))
38
+ return null;
39
+ return requiresRole;
40
+ }
41
+ function toJobStatus(job) {
42
+ return {
43
+ jobId: job.ID,
44
+ walletId: job.walletId,
45
+ kind: job.kind,
46
+ status: job.status,
47
+ attempt: job.attempt,
48
+ txHash: job.txHash,
49
+ fee: job.fee != null ? String(job.fee) : null,
50
+ errorCode: job.errorCode,
51
+ errorMessage: job.errorMessage,
52
+ submittedAt: job.submittedAt,
53
+ confirmedAt: job.confirmedAt,
54
+ finishedAt: job.finishedAt,
55
+ };
56
+ }
57
+ module.exports = (srv) => {
58
+ // SubmitWalletJob — queue an async transaction job; returns the jobId immediately.
59
+ srv.on('SubmitWalletJob', async (req) => {
60
+ const { walletId, kind, requestJson, idempotencyKey, priority, notBefore } = req.data;
61
+ if (!walletId?.trim())
62
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'walletId is required', 'walletId');
63
+ if (!kind || !job_store_1.WALLET_JOB_KINDS.includes(kind)) {
64
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Invalid kind "${String(kind)}" — must be one of: ${job_store_1.WALLET_JOB_KINDS.join(', ')}`, 'kind');
65
+ }
66
+ if (!requestJson?.trim())
67
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'requestJson is required', 'requestJson');
68
+ const jsonResult = (0, validators_1.validateJsonWithLimits)(requestJson, 'requestJson');
69
+ if (!jsonResult.valid)
70
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', jsonResult.error, 'requestJson');
71
+ if (priority != null && (!Number.isInteger(priority) || priority < 0 || priority > 10_000)) {
72
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'priority must be an integer between 0 and 10000', 'priority');
73
+ }
74
+ if (notBefore != null && Number.isNaN(Date.parse(String(notBefore)))) {
75
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'notBefore must be a valid timestamp', 'notBefore');
76
+ }
77
+ if (idempotencyKey != null && String(idempotencyKey).length > 100) {
78
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'idempotencyKey exceeds 100 characters', 'idempotencyKey');
79
+ }
80
+ let config;
81
+ try {
82
+ config = (0, server_1.loadWalletWorkerConfigFromEnv)();
83
+ }
84
+ catch (err) {
85
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', err instanceof Error ? err.message : String(err));
86
+ }
87
+ if (!config.enabled) {
88
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', 'Wallet worker is not enabled — set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) with configured wallets.');
89
+ }
90
+ // Role gate on this instance's config, mirroring the sign service's 403.
91
+ const configuredRole = missingHsmRole(req, config.wallets.find((w) => w.walletId === walletId)?.signerType);
92
+ if (configuredRole) {
93
+ return req.reject(403, `SubmitWalletJob on HSM-backed wallet "${walletId}" requires role '${configuredRole}'`);
94
+ }
95
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
96
+ const wallet = await (0, job_store_1.readWallet)(db, walletId);
97
+ if (!wallet)
98
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Unknown wallet "${walletId}" — configured wallets are registered at worker start`, 'walletId');
99
+ if (!wallet.enabled)
100
+ return (0, errors_1.rejectInvalid)(req, 'SubmitWalletJob', `Wallet "${walletId}" is disabled`, 'walletId');
101
+ // Registered row too: another instance may run the HSM wallet this one has no config for.
102
+ const registeredRole = missingHsmRole(req, wallet.signerType);
103
+ if (registeredRole) {
104
+ throw new errors_1.BackendError(`Wallet "${walletId}" is HSM-backed and requires role '${registeredRole}'`, 403, error_codes_1.ERROR_CODES.FORBIDDEN, undefined, undefined, 'walletId');
105
+ }
106
+ const result = await (0, job_store_1.insertJob)(db, {
107
+ walletId,
108
+ kind: kind,
109
+ request: requestJson,
110
+ idempotencyKey: idempotencyKey ?? null,
111
+ priority,
112
+ notBefore: notBefore ? new Date(notBefore).toISOString() : null,
113
+ maxAttempts: config.defaultMaxAttempts,
114
+ createdBy: req.user?.id ?? null,
115
+ });
116
+ logger.info(`Job ${result.jobId} accepted (wallet=${walletId}, kind=${kind}, dedup=${result.deduplicated})`);
117
+ return result;
118
+ });
119
+ });
120
+ // CancelJob — pending jobs only; scoped to the creator unless Admin.
121
+ srv.on('CancelJob', async (req) => {
122
+ const { jobId } = req.data;
123
+ if (!jobId)
124
+ return (0, errors_1.rejectInvalid)(req, 'CancelJob', 'jobId is required', 'jobId');
125
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
126
+ const job = await (0, job_store_1.getJobById)(db, jobId);
127
+ if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
128
+ // Same 404 for "not found" and "not yours" — no existence oracle.
129
+ // THROW, don't req.reject: we are inside handleRequest, whose catch would
130
+ // see a plain CAP error and remap it to 500 (mapError). A BackendError
131
+ // carries its status through.
132
+ throw new errors_1.NotFoundError(`Job ${jobId}`);
133
+ }
134
+ const cancelled = await (0, job_store_1.markCancelled)(db, jobId);
135
+ if (!cancelled) {
136
+ return (0, errors_1.rejectInvalid)(req, 'CancelJob', `Job ${jobId} is ${job.status} — only pending jobs can be cancelled`, 'jobId');
137
+ }
138
+ return true;
139
+ });
140
+ });
141
+ // GetJobStatus — scoped to the creator unless Admin.
142
+ srv.on('GetJobStatus', async (req) => {
143
+ const { jobId } = req.data;
144
+ if (!jobId)
145
+ return (0, errors_1.rejectInvalid)(req, 'GetJobStatus', 'jobId is required', 'jobId');
146
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
147
+ const job = await (0, job_store_1.getJobById)(db, jobId);
148
+ if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
149
+ throw new errors_1.NotFoundError(`Job ${jobId}`); // see CancelJob: reject() here becomes a 500
150
+ }
151
+ return toJobStatus(job);
152
+ });
153
+ });
154
+ // GetWorkerStatus — live summary of the local worker instance.
155
+ srv.on('GetWorkerStatus', async (req) => {
156
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
157
+ const worker = (0, wallet_worker_1.getWalletWorker)();
158
+ const summary = worker?.getStatusSummary() ?? {
159
+ running: false, wallets: [], executing: [], awaitingConfirmation: 0,
160
+ };
161
+ const pending = await (0, job_store_1.findDueJobs)(db, new Date(8640000000000000)); // all pending, ignore notBefore
162
+ return { ...summary, pendingJobs: pending.length };
163
+ });
164
+ });
165
+ // PauseWorker — stop the local instance; queued jobs stay pending.
166
+ srv.on('PauseWorker', async (req) => {
167
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
168
+ await (0, wallet_worker_1.stopWalletWorker)();
169
+ logger.info('Wallet worker paused via control action');
170
+ return true;
171
+ });
172
+ });
173
+ // ResumeWorker — (re)start the local instance from config. Gated on enabled,
174
+ // mirroring resumeCrawler.
175
+ srv.on('ResumeWorker', async (req) => {
176
+ let config;
177
+ try {
178
+ config = (0, server_1.loadWalletWorkerConfigFromEnv)();
179
+ }
180
+ catch (err) {
181
+ return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', err instanceof Error ? err.message : String(err));
182
+ }
183
+ if (!config.enabled) {
184
+ return (0, errors_1.rejectInvalid)(req, 'ResumeWorker', 'Wallet worker is not enabled — set cds.requires.odatano-core.walletWorker.enabled (or WALLET_WORKER_ENABLED=true) before resuming.');
185
+ }
186
+ return (0, backend_request_handler_1.handleRequest)(req, async () => {
187
+ const client = (0, server_1.getCardanoClient)();
188
+ await (0, wallet_worker_1.startWalletWorker)({
189
+ client,
190
+ indexer: (0, server_1.getCardanoIndexer)(),
191
+ network: client.network,
192
+ config,
193
+ });
194
+ logger.info('Wallet worker resumed via control action');
195
+ return (0, wallet_worker_1.isWalletWorkerRunning)();
196
+ });
197
+ });
198
+ };
199
+ //# sourceMappingURL=cardano-worker-service.js.map
package/srv/server.d.ts CHANGED
@@ -2,6 +2,8 @@ import { CardanoClient, CardanoClientConfig, BackendName, TransactionBuilderName
2
2
  import { CardanoIndexer } from './blockchain/cardano-indexer';
3
3
  import { CardanoTransactionBuilder } from './blockchain/cardano-tx-builder';
4
4
  import type { LedgerProtocolParameters, HsmConfig } from './utils/types';
5
+ import type { CrawlerConfig } from './blockchain/crawler/crawler';
6
+ import type { WalletWorkerConfig } from './blockchain/wallet-worker';
5
7
  /**
6
8
  * Application context holding initialized blockchain components
7
9
  * These are created once during CAP bootstrap and shared across services
@@ -86,12 +88,41 @@ export declare function loadConfigFromEnv(): CardanoClientConfig;
86
88
  * @returns HsmConfig or undefined
87
89
  */
88
90
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
91
+ /**
92
+ * Load the chain-crawler configuration from CDS config or environment variables.
93
+ * Returns { enabled:false } when the crawler is not switched on (the default), so
94
+ * existing deployments are unaffected.
95
+ *
96
+ * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
97
+ * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
98
+ */
99
+ export declare function loadCrawlerConfigFromEnv(): CrawlerConfig;
100
+ /**
101
+ * Start the chain crawler if it is enabled and the app context is ready. Never throws
102
+ * (crawler failure must not affect request serving) — errors are logged. Idempotent:
103
+ * startCrawler() is a no-op when one is already running.
104
+ */
105
+ export declare function startCrawlerIfConfigured(): Promise<void>;
106
+ /**
107
+ * Load the wallet-worker configuration from CDS config or environment variables.
108
+ * Returns { enabled:false } when the worker is not switched on (the default).
109
+ *
110
+ * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
111
+ * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
112
+ */
113
+ export declare function loadWalletWorkerConfigFromEnv(): WalletWorkerConfig;
114
+ /**
115
+ * Start the wallet worker if it is enabled and the app context is ready. Never
116
+ * throws (worker failure must not affect request serving) — errors are logged.
117
+ * Idempotent: startWalletWorker() is a no-op when one is already running.
118
+ */
119
+ export declare function startWalletWorkerIfConfigured(): Promise<void>;
89
120
  /**
90
121
  * Re-drive deferred submissions that were claimed (status 'submitting' with
91
122
  * persisted signedTxCbor) but whose detached submit never ran because the
92
123
  * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
93
124
  * submitted tx finalizes via the TransactionAlreadySubmittedError path.
94
- * Non-fatal.
125
+ * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
95
126
  */
96
127
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
97
128
  export {};
package/srv/server.js CHANGED
@@ -47,6 +47,10 @@ exports.createTestContext = createTestContext;
47
47
  exports.shutdownAppContext = shutdownAppContext;
48
48
  exports.loadConfigFromEnv = loadConfigFromEnv;
49
49
  exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
50
+ exports.loadCrawlerConfigFromEnv = loadCrawlerConfigFromEnv;
51
+ exports.startCrawlerIfConfigured = startCrawlerIfConfigured;
52
+ exports.loadWalletWorkerConfigFromEnv = loadWalletWorkerConfigFromEnv;
53
+ exports.startWalletWorkerIfConfigured = startWalletWorkerIfConfigured;
50
54
  exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
51
55
  const cds_1 = __importDefault(require("@sap/cds"));
52
56
  const cardano_client_1 = require("./blockchain/cardano-client");
@@ -55,10 +59,31 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
55
59
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
56
60
  const errors_1 = require("./utils/errors");
57
61
  const network_context_1 = require("./utils/network-context");
62
+ const crawler_1 = require("./blockchain/crawler");
63
+ const wallet_worker_1 = require("./blockchain/wallet-worker");
58
64
  const process_1 = require("process");
59
65
  const logger = cds_1.default.log('ODATANO');
60
66
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
61
67
  const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios'];
68
+ const CRAWLER_LIMITS = {
69
+ batchSize: { min: 1, max: 100 },
70
+ confirmationDepth: { min: 0, max: 2160 },
71
+ pollIntervalMs: { min: 1000, max: 3_600_000 },
72
+ };
73
+ /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
74
+ function crawlerInteger(raw, name, min, max, defaultValue) {
75
+ if (raw == null)
76
+ return defaultValue;
77
+ if ((typeof raw !== 'number' && typeof raw !== 'string')
78
+ || (typeof raw === 'string' && raw.trim() === '')) {
79
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
80
+ }
81
+ const parsed = typeof raw === 'number' ? raw : Number(raw);
82
+ if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
83
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
84
+ }
85
+ return parsed;
86
+ }
62
87
  let appContext = null;
63
88
  let bootstrapError = null;
64
89
  /**
@@ -214,6 +239,20 @@ protocolParams) {
214
239
  * Closes all backend connections to allow process to exit cleanly
215
240
  */
216
241
  async function shutdownAppContext() {
242
+ // Stop the wallet worker first — its in-flight submit must not hit a torn-down client.
243
+ try {
244
+ await (0, wallet_worker_1.stopWalletWorker)();
245
+ }
246
+ catch (err) {
247
+ logger.warn('Wallet worker shutdown failed (continuing):', err);
248
+ }
249
+ // Stop the crawler so its in-flight block writes don't hit a torn-down client.
250
+ try {
251
+ await (0, crawler_1.stopCrawler)();
252
+ }
253
+ catch (err) {
254
+ logger.warn('Crawler shutdown failed (continuing):', err);
255
+ }
217
256
  if (appContext) {
218
257
  logger.info('Shutting down application context...');
219
258
  // Shutdown HSM signer if active
@@ -345,12 +384,195 @@ function loadHsmConfigFromEnv() {
345
384
  requiresRole,
346
385
  };
347
386
  }
387
+ /**
388
+ * Load the chain-crawler configuration from CDS config or environment variables.
389
+ * Returns { enabled:false } when the crawler is not switched on (the default), so
390
+ * existing deployments are unaffected.
391
+ *
392
+ * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
393
+ * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
394
+ */
395
+ function loadCrawlerConfigFromEnv() {
396
+ const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
397
+ const c = cdsConfig.crawler ?? {};
398
+ // A CDS value, including explicit `false`, wins over the environment.
399
+ const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
400
+ let enabled = false;
401
+ if (enabledRaw === true || enabledRaw === 'true') {
402
+ enabled = true;
403
+ }
404
+ else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
405
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
406
+ }
407
+ const startSlot = crawlerInteger(c.startSlot ?? process_1.env.CRAWLER_START_SLOT, 'CRAWLER_START_SLOT', 0, Number.MAX_SAFE_INTEGER);
408
+ const startHeight = crawlerInteger(c.startHeight ?? process_1.env.CRAWLER_START_HEIGHT, 'CRAWLER_START_HEIGHT', 0, Number.MAX_SAFE_INTEGER);
409
+ const startBlockHashRaw = c.startBlockHash ?? process_1.env.CRAWLER_START_HASH;
410
+ if (startBlockHashRaw != null && (typeof startBlockHashRaw !== 'string' || !/^[0-9a-f]{64}$/i.test(startBlockHashRaw.trim()))) {
411
+ throw new errors_1.ConfigError('Invalid CRAWLER_START_HASH. Must be exactly 64 hexadecimal characters.');
412
+ }
413
+ const startBlockHash = startBlockHashRaw?.trim() || undefined;
414
+ const source = (c.source ?? process_1.env.CRAWLER_SOURCE ?? 'auto');
415
+ const batchSize = crawlerInteger(c.batchSize ?? process_1.env.CRAWLER_BATCH_SIZE, 'CRAWLER_BATCH_SIZE', CRAWLER_LIMITS.batchSize.min, CRAWLER_LIMITS.batchSize.max, 20);
416
+ const confirmationDepth = crawlerInteger(c.confirmationDepth ?? process_1.env.CRAWLER_CONFIRMATION_DEPTH, 'CRAWLER_CONFIRMATION_DEPTH', CRAWLER_LIMITS.confirmationDepth.min, CRAWLER_LIMITS.confirmationDepth.max, 3);
417
+ const pollIntervalMs = crawlerInteger(c.pollIntervalMs ?? process_1.env.CRAWLER_POLL_INTERVAL_MS, 'CRAWLER_POLL_INTERVAL_MS', CRAWLER_LIMITS.pollIntervalMs.min, CRAWLER_LIMITS.pollIntervalMs.max, 20_000);
418
+ if (enabled && (startSlot == null || Number.isNaN(startSlot) || !startBlockHash)) {
419
+ throw new errors_1.ConfigError('Crawler is enabled but no start block is configured — set crawler.startSlot + crawler.startBlockHash ' +
420
+ '(or CRAWLER_START_SLOT + CRAWLER_START_HASH).');
421
+ }
422
+ if (!['ogmios', 'pagination', 'auto'].includes(source)) {
423
+ throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
424
+ }
425
+ return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
426
+ }
427
+ /**
428
+ * Start the chain crawler if it is enabled and the app context is ready. Never throws
429
+ * (crawler failure must not affect request serving) — errors are logged. Idempotent:
430
+ * startCrawler() is a no-op when one is already running.
431
+ */
432
+ async function startCrawlerIfConfigured() {
433
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
434
+ return;
435
+ let config;
436
+ try {
437
+ config = loadCrawlerConfigFromEnv();
438
+ }
439
+ catch (err) {
440
+ logger.error('Invalid crawler configuration — crawler not started:', err);
441
+ return;
442
+ }
443
+ if (!config.enabled)
444
+ return;
445
+ try {
446
+ await (0, crawler_1.startCrawler)({
447
+ client: appContext.cardanoClient,
448
+ indexer: appContext.cardanoIndexer,
449
+ network: appContext.cardanoClient.network,
450
+ config,
451
+ });
452
+ logger.info(`Chain crawler started (source=${config.source}, start=${config.startBlockHash})`);
453
+ }
454
+ catch (err) {
455
+ logger.error('Failed to start chain crawler (non-fatal):', err);
456
+ }
457
+ }
458
+ const WALLET_WORKER_LIMITS = {
459
+ maxConcurrentWallets: { min: 1, max: 64 },
460
+ confirmationDepth: { min: 1, max: 2160 },
461
+ confirmationTimeoutMs: { min: 30_000, max: 86_400_000 },
462
+ pollIntervalMs: { min: 500, max: 3_600_000 },
463
+ maxAttempts: { min: 1, max: 10 },
464
+ };
465
+ /**
466
+ * Load the wallet-worker configuration from CDS config or environment variables.
467
+ * Returns { enabled:false } when the worker is not switched on (the default).
468
+ *
469
+ * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
470
+ * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
471
+ */
472
+ function loadWalletWorkerConfigFromEnv() {
473
+ const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
474
+ const w = cdsConfig.walletWorker ?? {};
475
+ const enabledRaw = w.enabled !== undefined ? w.enabled : process_1.env.WALLET_WORKER_ENABLED;
476
+ let enabled = false;
477
+ if (enabledRaw === true || enabledRaw === 'true') {
478
+ enabled = true;
479
+ }
480
+ else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
481
+ throw new errors_1.ConfigError(`Invalid WALLET_WORKER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
482
+ }
483
+ let walletsRaw = w.wallets ?? undefined;
484
+ if (walletsRaw === undefined && process_1.env.WALLET_WORKER_WALLETS) {
485
+ try {
486
+ walletsRaw = JSON.parse(process_1.env.WALLET_WORKER_WALLETS);
487
+ }
488
+ catch {
489
+ throw new errors_1.ConfigError('Invalid WALLET_WORKER_WALLETS — must be a JSON array of { walletId, signerType, keyEnv? }.');
490
+ }
491
+ }
492
+ const wallets = [];
493
+ if (walletsRaw !== undefined) {
494
+ if (!Array.isArray(walletsRaw)) {
495
+ throw new errors_1.ConfigError('Invalid walletWorker.wallets — must be an array of { walletId, signerType, keyEnv? }.');
496
+ }
497
+ for (const entry of walletsRaw) {
498
+ const walletId = typeof entry?.walletId === 'string' ? entry.walletId.trim() : '';
499
+ const signerType = entry?.signerType;
500
+ if (!walletId || (signerType !== 'hsm' && signerType !== 'software')) {
501
+ throw new errors_1.ConfigError(`Invalid wallet entry ${JSON.stringify(entry)} — walletId and signerType (hsm|software) are required.`);
502
+ }
503
+ if (signerType === 'software' && (typeof entry.keyEnv !== 'string' || !entry.keyEnv.trim())) {
504
+ throw new errors_1.ConfigError(`Wallet "${walletId}" is signerType=software but has no keyEnv (name of the env var holding the signing key).`);
505
+ }
506
+ if (wallets.some((existing) => existing.walletId === walletId)) {
507
+ throw new errors_1.ConfigError(`Duplicate walletId "${walletId}" in walletWorker.wallets.`);
508
+ }
509
+ wallets.push({ walletId, signerType, keyEnv: entry.keyEnv });
510
+ }
511
+ }
512
+ const maxConcurrentWallets = crawlerInteger(w.maxConcurrentWallets ?? process_1.env.WALLET_WORKER_MAX_CONCURRENT, 'WALLET_WORKER_MAX_CONCURRENT', WALLET_WORKER_LIMITS.maxConcurrentWallets.min, WALLET_WORKER_LIMITS.maxConcurrentWallets.max, 4);
513
+ const confirmationDepth = crawlerInteger(w.confirmationDepth ?? process_1.env.WALLET_WORKER_CONFIRMATION_DEPTH, 'WALLET_WORKER_CONFIRMATION_DEPTH', WALLET_WORKER_LIMITS.confirmationDepth.min, WALLET_WORKER_LIMITS.confirmationDepth.max, 3);
514
+ const confirmationTimeoutMs = crawlerInteger(w.confirmationTimeoutMs ?? process_1.env.WALLET_WORKER_CONFIRMATION_TIMEOUT_MS, 'WALLET_WORKER_CONFIRMATION_TIMEOUT_MS', WALLET_WORKER_LIMITS.confirmationTimeoutMs.min, WALLET_WORKER_LIMITS.confirmationTimeoutMs.max, 600_000);
515
+ const pollIntervalMs = crawlerInteger(w.pollIntervalMs ?? process_1.env.WALLET_WORKER_POLL_INTERVAL_MS, 'WALLET_WORKER_POLL_INTERVAL_MS', WALLET_WORKER_LIMITS.pollIntervalMs.min, WALLET_WORKER_LIMITS.pollIntervalMs.max, 2_000);
516
+ const defaultMaxAttempts = crawlerInteger(w.defaultMaxAttempts ?? process_1.env.WALLET_WORKER_MAX_ATTEMPTS, 'WALLET_WORKER_MAX_ATTEMPTS', WALLET_WORKER_LIMITS.maxAttempts.min, WALLET_WORKER_LIMITS.maxAttempts.max, 3);
517
+ const resubmitRaw = w.resubmitOnRollback !== undefined ? w.resubmitOnRollback : process_1.env.WALLET_WORKER_RESUBMIT_ON_ROLLBACK;
518
+ let resubmitOnRollback = true;
519
+ if (resubmitRaw === false || resubmitRaw === 'false') {
520
+ resubmitOnRollback = false;
521
+ }
522
+ else if (resubmitRaw !== undefined && resubmitRaw !== true && resubmitRaw !== 'true') {
523
+ throw new errors_1.ConfigError(`Invalid WALLET_WORKER_RESUBMIT_ON_ROLLBACK "${String(resubmitRaw)}". Must be true or false.`);
524
+ }
525
+ if (enabled && wallets.length === 0) {
526
+ throw new errors_1.ConfigError('Wallet worker is enabled but no wallets are configured — set walletWorker.wallets (or WALLET_WORKER_WALLETS).');
527
+ }
528
+ return {
529
+ enabled,
530
+ wallets,
531
+ maxConcurrentWallets,
532
+ confirmationDepth,
533
+ confirmationTimeoutMs,
534
+ pollIntervalMs,
535
+ defaultMaxAttempts,
536
+ resubmitOnRollback,
537
+ };
538
+ }
539
+ /**
540
+ * Start the wallet worker if it is enabled and the app context is ready. Never
541
+ * throws (worker failure must not affect request serving) — errors are logged.
542
+ * Idempotent: startWalletWorker() is a no-op when one is already running.
543
+ */
544
+ async function startWalletWorkerIfConfigured() {
545
+ if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
546
+ return;
547
+ let config;
548
+ try {
549
+ config = loadWalletWorkerConfigFromEnv();
550
+ }
551
+ catch (err) {
552
+ logger.error('Invalid wallet-worker configuration — worker not started:', err);
553
+ return;
554
+ }
555
+ if (!config.enabled)
556
+ return;
557
+ try {
558
+ await (0, wallet_worker_1.startWalletWorker)({
559
+ client: appContext.cardanoClient,
560
+ indexer: appContext.cardanoIndexer,
561
+ network: appContext.cardanoClient.network,
562
+ config,
563
+ });
564
+ logger.info(`Wallet worker started (wallets=${config.wallets.map((w2) => w2.walletId).join(',')})`);
565
+ }
566
+ catch (err) {
567
+ logger.error('Failed to start wallet worker (non-fatal):', err);
568
+ }
569
+ }
348
570
  /**
349
571
  * Re-drive deferred submissions that were claimed (status 'submitting' with
350
572
  * persisted signedTxCbor) but whose detached submit never ran because the
351
573
  * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
352
574
  * submitted tx finalizes via the TransactionAlreadySubmittedError path.
353
- * Non-fatal.
575
+ * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
354
576
  */
355
577
  async function redriveInterruptedSubmissionsIfConfigured() {
356
578
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
@@ -394,12 +616,16 @@ cds_1.default.on('served', async () => {
394
616
  // instead of the raw "Application not initialized" Error landing as a generic 500.
395
617
  bootstrapError = err instanceof Error ? err : new Error(String(err));
396
618
  // Write to stderr directly so the cause stays visible even when test runners
397
- // suppress console.error (jest.setup.ts in this repo silences it).
619
+ // suppress console.error (vitest.setup.ts in this repo silences it).
398
620
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
399
621
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
400
622
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
401
623
  logger.error('Failed to initialize blockchain components:', err);
402
624
  }
625
+ // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
626
+ await startCrawlerIfConfigured();
627
+ // Start the wallet worker if configured (standalone mode). Non-fatal.
628
+ await startWalletWorkerIfConfigured();
403
629
  // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
404
630
  await redriveInterruptedSubmissionsIfConfigured();
405
631
  });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Small collection helpers shared across the blockchain layer.
3
+ */
4
+ /**
5
+ * Split an array into fixed-size chunks. Used to keep CQL IN-lists below DB driver
6
+ * bind-variable limits (SQLite caps at 999 on older builds / 32766 on node:sqlite).
7
+ * @param arr source array (not mutated)
8
+ * @param size chunk size (must be > 0; guarded to avoid an infinite loop)
9
+ */
10
+ export declare function chunk<T>(arr: T[], size: number): T[][];
11
+ /** Max bind variables per IN-list — well below every supported driver's cap. */
12
+ export declare const IN_CHUNK = 500;
13
+ //# sourceMappingURL=collections.d.ts.map
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * Small collection helpers shared across the blockchain layer.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.IN_CHUNK = void 0;
7
+ exports.chunk = chunk;
8
+ /**
9
+ * Split an array into fixed-size chunks. Used to keep CQL IN-lists below DB driver
10
+ * bind-variable limits (SQLite caps at 999 on older builds / 32766 on node:sqlite).
11
+ * @param arr source array (not mutated)
12
+ * @param size chunk size (must be > 0; guarded to avoid an infinite loop)
13
+ */
14
+ function chunk(arr, size) {
15
+ if (size <= 0)
16
+ throw new RangeError(`chunk size must be > 0, got ${size}`);
17
+ const out = [];
18
+ for (let i = 0; i < arr.length; i += size)
19
+ out.push(arr.slice(i, i + size));
20
+ return out;
21
+ }
22
+ /** Max bind variables per IN-list — well below every supported driver's cap. */
23
+ exports.IN_CHUNK = 500;
24
+ //# sourceMappingURL=collections.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Derive the 32-byte encryption key from the environment.
3
+ * Production: ENCRYPTION_KEY is required. Development: process-scoped fallback.
4
+ */
5
+ export declare function getEncryptionKey(): Buffer;
6
+ /**
7
+ * Encrypt plaintext with AES-256-GCM.
8
+ * Returns the combined format `base64(iv):base64(authTag):base64(ciphertext)`.
9
+ */
10
+ export declare function encrypt(plaintext: string, key: Buffer): string;
11
+ /**
12
+ * Decrypt a combined `iv:authTag:ciphertext` string back to plaintext.
13
+ * Throws on authentication failure (tampered ciphertext or wrong key).
14
+ */
15
+ export declare function decrypt(combined: string, key: Buffer): string;
16
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getEncryptionKey = getEncryptionKey;
7
+ exports.encrypt = encrypt;
8
+ exports.decrypt = decrypt;
9
+ const node_crypto_1 = __importDefault(require("node:crypto"));
10
+ const node_os_1 = __importDefault(require("node:os"));
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const logger = cds_1.default.log('CardanoWalletWorker');
13
+ /**
14
+ * AES-256-GCM utilities for secrets at rest (v2.0 wallet worker).
15
+ *
16
+ * Ported from NIGHTGATE's srv/utils/crypto.ts. Used to decrypt operator-provided
17
+ * software signing keys (`iv:authTag:ciphertext`, all base64). Keys are derived
18
+ * from the ENCRYPTION_KEY environment variable; production refuses to start
19
+ * without it, development falls back to a process-scoped key.
20
+ */
21
+ const ALGORITHM = 'aes-256-gcm';
22
+ const IV_LENGTH = 12; // 96 bits, recommended for GCM
23
+ const AUTH_TAG_LENGTH = 16; // 128 bits
24
+ /**
25
+ * Derive the 32-byte encryption key from the environment.
26
+ * Production: ENCRYPTION_KEY is required. Development: process-scoped fallback.
27
+ */
28
+ function getEncryptionKey() {
29
+ const envKey = process.env.ENCRYPTION_KEY;
30
+ if (envKey) {
31
+ return node_crypto_1.default.createHash('sha256').update(envKey).digest();
32
+ }
33
+ if (process.env.NODE_ENV === 'production') {
34
+ throw new Error('ENCRYPTION_KEY must be set in production. Refusing to start with a fallback key.');
35
+ }
36
+ logger.warn('ENCRYPTION_KEY not set — using dev fallback key. Set ENCRYPTION_KEY for production.');
37
+ const fallback = `odatano-core-${process.pid}-${node_os_1.default.hostname()}`;
38
+ return node_crypto_1.default.createHash('sha256').update(fallback).digest();
39
+ }
40
+ /**
41
+ * Encrypt plaintext with AES-256-GCM.
42
+ * Returns the combined format `base64(iv):base64(authTag):base64(ciphertext)`.
43
+ */
44
+ function encrypt(plaintext, key) {
45
+ const iv = node_crypto_1.default.randomBytes(IV_LENGTH);
46
+ const cipher = node_crypto_1.default.createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
47
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
48
+ const authTag = cipher.getAuthTag();
49
+ return `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`;
50
+ }
51
+ /**
52
+ * Decrypt a combined `iv:authTag:ciphertext` string back to plaintext.
53
+ * Throws on authentication failure (tampered ciphertext or wrong key).
54
+ */
55
+ function decrypt(combined, key) {
56
+ const parts = combined.split(':');
57
+ if (parts.length !== 3) {
58
+ throw new Error('Invalid encrypted format: expected iv:authTag:ciphertext');
59
+ }
60
+ const [ivB64, tagB64, dataB64] = parts;
61
+ const iv = Buffer.from(ivB64, 'base64');
62
+ const authTag = Buffer.from(tagB64, 'base64');
63
+ const encrypted = Buffer.from(dataB64, 'base64');
64
+ if (iv.length !== IV_LENGTH) {
65
+ throw new Error(`Invalid IV length: expected ${IV_LENGTH} bytes, got ${iv.length}`);
66
+ }
67
+ if (authTag.length !== AUTH_TAG_LENGTH) {
68
+ throw new Error(`Invalid auth tag length: expected ${AUTH_TAG_LENGTH} bytes, got ${authTag.length}`);
69
+ }
70
+ const decipher = node_crypto_1.default.createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
71
+ decipher.setAuthTag(authTag);
72
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
73
+ return decrypted.toString('utf8');
74
+ }
75
+ //# sourceMappingURL=crypto.js.map