@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,43 @@
1
+ /**
2
+ * Crawler event hooks (v2.1).
3
+ *
4
+ * Small listener registry that lets other subsystems (currently the wallet-worker
5
+ * confirmation tracker) observe crawler progress without the crawler importing
6
+ * them (dependency direction stays crawler ← consumer). The crawler emits:
7
+ * - `blockIndexed` after each successfully persisted block (with its tx hashes), and
8
+ * - `reorg` after a completed rollback (with the fork slot).
9
+ *
10
+ * Listener failures are logged and swallowed — a broken consumer must never
11
+ * stop the crawler.
12
+ */
13
+ export interface BlockIndexedEvent {
14
+ hash: string;
15
+ slot: number | null;
16
+ height: number | null;
17
+ txHashes: string[];
18
+ /** Latest known chain tip at the time of indexing (when the source reports one). */
19
+ tipSlot: number | null;
20
+ tipHeight: number | null;
21
+ }
22
+ export interface ReorgEvent {
23
+ /** Absolute slot of the fork point — everything after it was rolled back. */
24
+ forkSlot: number;
25
+ /** How many blocks the rollback removed (0 when the fork was already the tip). */
26
+ blocksRolledBack?: number;
27
+ /**
28
+ * Block height of the fork point, when known. Listeners tracking confirmation
29
+ * depth must clamp their tip to this — the pre-fork tip height no longer exists.
30
+ */
31
+ forkHeight: number | null;
32
+ }
33
+ export type BlockIndexedListener = (event: BlockIndexedEvent) => void;
34
+ export type ReorgListener = (event: ReorgEvent) => void;
35
+ export declare function registerBlockIndexedListener(listener: BlockIndexedListener): void;
36
+ export declare function unregisterBlockIndexedListener(listener: BlockIndexedListener): void;
37
+ export declare function registerReorgListener(listener: ReorgListener): void;
38
+ export declare function unregisterReorgListener(listener: ReorgListener): void;
39
+ /** True when at least one consumer observes crawler progress. */
40
+ export declare function hasBlockIndexedListeners(): boolean;
41
+ export declare function emitBlockIndexed(event: BlockIndexedEvent): void;
42
+ export declare function emitReorg(event: ReorgEvent): void;
43
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1,62 @@
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.registerBlockIndexedListener = registerBlockIndexedListener;
7
+ exports.unregisterBlockIndexedListener = unregisterBlockIndexedListener;
8
+ exports.registerReorgListener = registerReorgListener;
9
+ exports.unregisterReorgListener = unregisterReorgListener;
10
+ exports.hasBlockIndexedListeners = hasBlockIndexedListeners;
11
+ exports.emitBlockIndexed = emitBlockIndexed;
12
+ exports.emitReorg = emitReorg;
13
+ const cds_1 = __importDefault(require("@sap/cds"));
14
+ const service_events_1 = require("../../utils/service-events");
15
+ const logger = cds_1.default.log('CardanoCrawler');
16
+ const blockListeners = new Set();
17
+ const reorgListeners = new Set();
18
+ function registerBlockIndexedListener(listener) {
19
+ blockListeners.add(listener);
20
+ }
21
+ function unregisterBlockIndexedListener(listener) {
22
+ blockListeners.delete(listener);
23
+ }
24
+ function registerReorgListener(listener) {
25
+ reorgListeners.add(listener);
26
+ }
27
+ function unregisterReorgListener(listener) {
28
+ reorgListeners.delete(listener);
29
+ }
30
+ /** True when at least one consumer observes crawler progress. */
31
+ function hasBlockIndexedListeners() {
32
+ return blockListeners.size > 0;
33
+ }
34
+ function emitBlockIndexed(event) {
35
+ // Mirrored onto the CAP service so external consumers can subscribe; the
36
+ // in-process registry below stays the fast path for our own subsystems.
37
+ (0, service_events_1.emitServiceEvent)('CardanoIndexerService', 'blockIndexed', { ...event });
38
+ for (const listener of blockListeners) {
39
+ try {
40
+ listener(event);
41
+ }
42
+ catch (err) {
43
+ logger.warn('blockIndexed listener failed (ignored):', err);
44
+ }
45
+ }
46
+ }
47
+ function emitReorg(event) {
48
+ (0, service_events_1.emitServiceEvent)('CardanoIndexerService', 'reorg', {
49
+ forkSlot: event.forkSlot,
50
+ forkHeight: event.forkHeight,
51
+ blocksRolledBack: event.blocksRolledBack ?? 0,
52
+ });
53
+ for (const listener of reorgListeners) {
54
+ try {
55
+ listener(event);
56
+ }
57
+ catch (err) {
58
+ logger.warn('reorg listener failed (ignored):', err);
59
+ }
60
+ }
61
+ }
62
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1,26 @@
1
+ import type { CardanoClient } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ import { CardanoCrawler, type CrawlerConfig } from './crawler';
4
+ export interface StartCrawlerDeps {
5
+ client: CardanoClient;
6
+ indexer: CardanoIndexer;
7
+ network: string;
8
+ config: CrawlerConfig;
9
+ }
10
+ /**
11
+ * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
12
+ * returns once the ingest pipeline is launched, not when catch-up completes.
13
+ */
14
+ export declare function startCrawler(deps: StartCrawlerDeps, resumeCluster?: boolean): Promise<void>;
15
+ /**
16
+ * Stop the local crawler. `pauseCluster=true` additionally fences every instance via
17
+ * shared DB intent; ordinary app shutdown leaves the desired state intact for failover.
18
+ */
19
+ export declare function stopCrawler(pauseCluster?: boolean): Promise<void>;
20
+ /** Whether a crawler is currently running. */
21
+ export declare function isCrawlerRunning(): boolean;
22
+ /** The active crawler instance, or null. */
23
+ export declare function getCrawler(): CardanoCrawler | null;
24
+ /** Read the lease in a fresh transaction (control actions must not use a stale request snapshot). */
25
+ export declare function isCrawlerRunningInCluster(): Promise<boolean>;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,135 @@
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.startCrawler = startCrawler;
7
+ exports.stopCrawler = stopCrawler;
8
+ exports.isCrawlerRunning = isCrawlerRunning;
9
+ exports.getCrawler = getCrawler;
10
+ exports.isCrawlerRunningInCluster = isCrawlerRunningInCluster;
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const node_crypto_1 = require("node:crypto");
13
+ const crawler_1 = require("./crawler");
14
+ const sync_state_1 = require("./sync-state");
15
+ const logger = cds_1.default.log('CardanoCrawler');
16
+ /**
17
+ * Module-level singleton lifecycle for the chain crawler. Mirrors NIGHTGATE's
18
+ * srv/crawler/index.ts: one active crawler per process, started fire-and-forget from
19
+ * the server's `served` hook and controlled (pause/resume/status) via the indexer service.
20
+ */
21
+ let active = null;
22
+ let lifecycleQueue = Promise.resolve();
23
+ let standbyDeps = null;
24
+ let standbyTimer = null;
25
+ let standbyGeneration = 0;
26
+ const STANDBY_RETRY_MS = 5_000;
27
+ /**
28
+ * Start the crawler (idempotent — a no-op if one is already running). Fire-and-forget:
29
+ * returns once the ingest pipeline is launched, not when catch-up completes.
30
+ */
31
+ async function startCrawler(deps, resumeCluster = false) {
32
+ const generation = ++standbyGeneration;
33
+ standbyDeps = deps;
34
+ if (standbyTimer) {
35
+ clearTimeout(standbyTimer);
36
+ standbyTimer = null;
37
+ }
38
+ scheduleStandby(generation);
39
+ return startCrawlerAttempt(deps, resumeCluster, generation);
40
+ }
41
+ async function startCrawlerAttempt(deps, resumeCluster, generation) {
42
+ return serializeLifecycle(async () => {
43
+ if (generation !== standbyGeneration)
44
+ return;
45
+ if (resumeCluster) {
46
+ await cds_1.default.tx((tx) => (0, sync_state_1.setCrawlerDesiredRunning)(tx, true));
47
+ }
48
+ if (active?.isRunning()) {
49
+ logger.debug('startCrawler: already running');
50
+ return;
51
+ }
52
+ if (active) {
53
+ const previous = active;
54
+ await previous.stop();
55
+ if (active === previous)
56
+ active = null;
57
+ }
58
+ const candidate = new crawler_1.CardanoCrawler(deps.client, deps.indexer, deps.network, deps.config, `${process.pid}:${(0, node_crypto_1.randomUUID)()}`);
59
+ active = candidate;
60
+ try {
61
+ await candidate.start();
62
+ }
63
+ catch (err) {
64
+ if (active === candidate)
65
+ active = null;
66
+ throw err;
67
+ }
68
+ // A lease loser stays in standby, not as a misleading process-local singleton.
69
+ if (!candidate.isRunning() && active === candidate)
70
+ active = null;
71
+ });
72
+ }
73
+ /**
74
+ * Stop the local crawler. `pauseCluster=true` additionally fences every instance via
75
+ * shared DB intent; ordinary app shutdown leaves the desired state intact for failover.
76
+ */
77
+ async function stopCrawler(pauseCluster = false) {
78
+ ++standbyGeneration; // invalidate callbacks that already left the timer queue
79
+ standbyDeps = null;
80
+ if (standbyTimer) {
81
+ clearTimeout(standbyTimer);
82
+ standbyTimer = null;
83
+ }
84
+ return serializeLifecycle(async () => {
85
+ if (pauseCluster) {
86
+ await cds_1.default.tx((tx) => (0, sync_state_1.setCrawlerDesiredRunning)(tx, false));
87
+ }
88
+ const crawler = active;
89
+ if (!crawler)
90
+ return;
91
+ await crawler.stop();
92
+ // A queued/re-entrant start can never be erased by an older stop continuation.
93
+ if (active === crawler)
94
+ active = null;
95
+ });
96
+ }
97
+ /** Whether a crawler is currently running. */
98
+ function isCrawlerRunning() {
99
+ return active?.isRunning() ?? false;
100
+ }
101
+ /** The active crawler instance, or null. */
102
+ function getCrawler() {
103
+ return active;
104
+ }
105
+ /** Read the lease in a fresh transaction (control actions must not use a stale request snapshot). */
106
+ async function isCrawlerRunningInCluster() {
107
+ const cursor = await cds_1.default.tx((tx) => (0, sync_state_1.readCursor)(tx));
108
+ return (0, sync_state_1.isCrawlerLeaseActive)(cursor);
109
+ }
110
+ function serializeLifecycle(operation) {
111
+ const result = lifecycleQueue.then(operation, operation);
112
+ lifecycleQueue = result.catch(() => undefined);
113
+ return result;
114
+ }
115
+ /** Keep non-leader instances warm so an expired/released lease fails over automatically. */
116
+ function scheduleStandby(generation) {
117
+ if (standbyTimer || !standbyDeps)
118
+ return;
119
+ standbyTimer = setTimeout(() => {
120
+ standbyTimer = null;
121
+ if (generation !== standbyGeneration)
122
+ return;
123
+ const deps = standbyDeps;
124
+ if (!deps)
125
+ return;
126
+ void startCrawlerAttempt(deps, false, generation)
127
+ .catch((err) => logger.error('standby lease attempt failed:', err))
128
+ .finally(() => {
129
+ if (generation === standbyGeneration)
130
+ scheduleStandby(generation);
131
+ });
132
+ }, STANDBY_RETRY_MS);
133
+ standbyTimer.unref?.();
134
+ }
135
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,94 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ /**
3
+ * Chain crawler cursor helpers (v2.0 pre-sync).
4
+ *
5
+ * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
6
+ * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
7
+ *
8
+ * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
9
+ * STRINGS, not JS numbers — the same change that makes them strings over OData.
10
+ * Every read here therefore coerces numeric fields with `num()`; callers get a
11
+ * clean numeric `SyncCursor` and never have to think about it.
12
+ */
13
+ export declare const SINGLETON_ID = "SINGLETON";
14
+ /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
15
+ export declare const MAX_CONSECUTIVE_ERRORS = 10;
16
+ /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
17
+ export declare const CRAWLER_LEASE_TTL_MS = 15000;
18
+ export type CrawlSyncStatusValue = 'stopped' | 'syncing' | 'synced' | 'error';
19
+ /** A chain point the crawler can start from or roll back to. */
20
+ export interface CrawlPoint {
21
+ slot: number;
22
+ hash: string;
23
+ height?: number;
24
+ }
25
+ /** Normalized, number-typed view of the cursor row (numeric fields already coerced). */
26
+ export interface SyncCursor {
27
+ network: string | null;
28
+ startSlot: number | null;
29
+ startBlockHash: string | null;
30
+ lastSlot: number;
31
+ lastBlockHash: string | null;
32
+ lastHeight: number;
33
+ tipSlot: number | null;
34
+ tipHeight: number | null;
35
+ syncStatus: CrawlSyncStatusValue;
36
+ consecutiveErrors: number;
37
+ desiredRunning: boolean;
38
+ leaseOwner: string | null;
39
+ leaseUntil: string | null;
40
+ }
41
+ /**
42
+ * Idempotently ensure the singleton cursor row exists and return it.
43
+ * On first call (fresh DB) the row is created with the configured start point
44
+ * (if given) and status 'stopped'. Subsequent calls just return the current row.
45
+ * Safe to call from both the crawler and the control service.
46
+ */
47
+ export declare function ensureSyncStateSingleton(db: CapTransaction, network: string, start?: CrawlPoint): Promise<SyncCursor>;
48
+ /** Read the current cursor, or null if it has not been initialized yet. */
49
+ export declare function readCursor(db: CapTransaction): Promise<SyncCursor | null>;
50
+ /** Whether the shared lease currently represents a live cluster-wide crawler. */
51
+ export declare function isCrawlerLeaseActive(cursor: SyncCursor | null, now?: Date): boolean;
52
+ /**
53
+ * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
54
+ * The post-update read is intentional: CAP adapters consistently return the row
55
+ * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
56
+ */
57
+ export declare function tryAcquireCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
58
+ /**
59
+ * Renew/fence a lease. Call this inside the same transaction as every crawler write:
60
+ * the conditional UPDATE serializes a former leader against a newly elected one.
61
+ */
62
+ export declare function renewCrawlerLease(db: CapTransaction, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
63
+ /**
64
+ * Release only the caller's lease; a stale process can never clear a successor.
65
+ *
66
+ * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
67
+ * then refuses to start until an operator calls resumeCrawler. Reserve it for
68
+ * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
69
+ * crashed stream, a provider outage or a node restart must NOT latch: those are
70
+ * exactly the cases where coming back up should resume the pre-sync by itself.
71
+ */
72
+ export declare function releaseCrawlerLease(db: CapTransaction, owner: string, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
73
+ /** Persist the pause/resume intent shared by every app instance. */
74
+ export declare function setCrawlerDesiredRunning(db: CapTransaction, desiredRunning: boolean): Promise<void>;
75
+ /**
76
+ * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
77
+ * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
78
+ * lastIndexedAt. Optionally records the latest known tip (for progress).
79
+ */
80
+ export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
81
+ slot: number;
82
+ height?: number;
83
+ }, status?: CrawlSyncStatusValue): Promise<void>;
84
+ /** Reset the cursor to a rollback point (used by reorg handling). */
85
+ export declare function resetCursorTo(db: CapTransaction, point: CrawlPoint): Promise<void>;
86
+ /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
87
+ export declare function setSyncStatus(db: CapTransaction, status: CrawlSyncStatusValue, pauseCluster?: boolean): Promise<void>;
88
+ /**
89
+ * Record a crawler error. Increments the consecutive-error counter and flips status
90
+ * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
91
+ * length so the caller can decide whether to back off / stop.
92
+ */
93
+ export declare function recordError(db: CapTransaction, err: unknown, leaseOwner?: string): Promise<number>;
94
+ //# sourceMappingURL=sync-state.d.ts.map
@@ -0,0 +1,265 @@
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.CRAWLER_LEASE_TTL_MS = exports.MAX_CONSECUTIVE_ERRORS = exports.SINGLETON_ID = void 0;
7
+ exports.ensureSyncStateSingleton = ensureSyncStateSingleton;
8
+ exports.readCursor = readCursor;
9
+ exports.isCrawlerLeaseActive = isCrawlerLeaseActive;
10
+ exports.tryAcquireCrawlerLease = tryAcquireCrawlerLease;
11
+ exports.renewCrawlerLease = renewCrawlerLease;
12
+ exports.releaseCrawlerLease = releaseCrawlerLease;
13
+ exports.setCrawlerDesiredRunning = setCrawlerDesiredRunning;
14
+ exports.advanceCursor = advanceCursor;
15
+ exports.resetCursorTo = resetCursorTo;
16
+ exports.setSyncStatus = setSyncStatus;
17
+ exports.recordError = recordError;
18
+ const cds_1 = __importDefault(require("@sap/cds"));
19
+ const cardano_1 = require("#cds-models/odatano/cardano");
20
+ const errors_1 = require("../../utils/errors");
21
+ const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
22
+ const logger = cds_1.default.log('CardanoCrawler');
23
+ /**
24
+ * Chain crawler cursor helpers (v2.0 pre-sync).
25
+ *
26
+ * `CardanoSyncState` is a singleton row (key = SINGLETON_ID) that records how far
27
+ * the crawler has indexed the chain, so a restart resumes instead of re-crawling.
28
+ *
29
+ * NOTE (CAP 10): Integer64 / Decimal columns are read back from SQLite/HANA as
30
+ * STRINGS, not JS numbers — the same change that makes them strings over OData.
31
+ * Every read here therefore coerces numeric fields with `num()`; callers get a
32
+ * clean numeric `SyncCursor` and never have to think about it.
33
+ */
34
+ exports.SINGLETON_ID = 'SINGLETON';
35
+ /** Circuit-breaker threshold: pause crawling after this many back-to-back failures. */
36
+ exports.MAX_CONSECUTIVE_ERRORS = 10;
37
+ /** A short, renewable DB lease prevents two app instances from advancing one cursor. */
38
+ exports.CRAWLER_LEASE_TTL_MS = 15_000;
39
+ /**
40
+ * Coerce a CAP-10 numeric-as-string (or number/bigint/null) into a JS number.
41
+ * Separate optional/required helpers avoid overload declarations (and the
42
+ * no-redeclare lint false-positive they caused).
43
+ */
44
+ function optionalNum(v) {
45
+ if (v === null || v === undefined || v === '')
46
+ return null;
47
+ const n = Number(v);
48
+ return Number.isNaN(n) ? null : n;
49
+ }
50
+ function requiredNum(v, fallback = 0) {
51
+ return optionalNum(v) ?? fallback;
52
+ }
53
+ function timestamp(v) {
54
+ if (v === null || v === undefined || v === '')
55
+ return null;
56
+ if (v instanceof Date)
57
+ return v.toISOString();
58
+ return String(v);
59
+ }
60
+ function leaseDeadlineReached(cursor, owner, expectedMs) {
61
+ if (cursor?.desiredRunning !== true || cursor.leaseOwner !== owner || !cursor.leaseUntil)
62
+ return false;
63
+ const actualMs = Date.parse(cursor.leaseUntil);
64
+ // Some adapters normalize Timestamp precision/format. One second tolerance covers
65
+ // that representation change without accepting an old lease interval.
66
+ return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
67
+ }
68
+ /** Map a raw DB row into the normalized numeric cursor. */
69
+ function toCursor(row) {
70
+ return {
71
+ network: row.network ?? null,
72
+ startSlot: optionalNum(row.startSlot),
73
+ startBlockHash: row.startBlockHash ?? null,
74
+ lastSlot: requiredNum(row.lastSlot),
75
+ lastBlockHash: row.lastBlockHash ?? null,
76
+ lastHeight: requiredNum(row.lastHeight),
77
+ tipSlot: optionalNum(row.tipSlot),
78
+ tipHeight: optionalNum(row.tipHeight),
79
+ syncStatus: (row.syncStatus ?? 'stopped'),
80
+ consecutiveErrors: requiredNum(row.consecutiveErrors),
81
+ desiredRunning: row.desiredRunning !== false,
82
+ leaseOwner: row.leaseOwner ?? null,
83
+ leaseUntil: timestamp(row.leaseUntil),
84
+ };
85
+ }
86
+ /**
87
+ * Idempotently ensure the singleton cursor row exists and return it.
88
+ * On first call (fresh DB) the row is created with the configured start point
89
+ * (if given) and status 'stopped'. Subsequent calls just return the current row.
90
+ * Safe to call from both the crawler and the control service.
91
+ */
92
+ async function ensureSyncStateSingleton(db, network, start) {
93
+ const existing = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
94
+ if (existing) {
95
+ const cursor = toCursor(existing);
96
+ if (cursor.network !== network) {
97
+ throw new errors_1.ConfigError(`Crawler cursor network mismatch: persisted cursor tracks ${cursor.network ?? 'an unknown network'}, configured client is ${network}.`);
98
+ }
99
+ return cursor;
100
+ }
101
+ const row = {
102
+ ID: exports.SINGLETON_ID,
103
+ network,
104
+ startSlot: start?.slot ?? null,
105
+ startBlockHash: start?.hash ?? null,
106
+ lastSlot: start?.slot ?? 0,
107
+ lastBlockHash: start?.hash ?? null,
108
+ lastHeight: start?.height ?? 0,
109
+ tipSlot: null,
110
+ tipHeight: null,
111
+ syncStatus: 'stopped',
112
+ consecutiveErrors: 0,
113
+ desiredRunning: true,
114
+ leaseOwner: null,
115
+ leaseUntil: null,
116
+ };
117
+ await db.run(INSERT.into(cardano_1.CardanoSyncState).entries(row));
118
+ logger.info(`Sync cursor initialized (network=${network}, start=${start ? `${start.slot}/${start.hash}` : 'none'})`);
119
+ return toCursor(row);
120
+ }
121
+ /** Read the current cursor, or null if it has not been initialized yet. */
122
+ async function readCursor(db) {
123
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
124
+ return row ? toCursor(row) : null;
125
+ }
126
+ /** Whether the shared lease currently represents a live cluster-wide crawler. */
127
+ function isCrawlerLeaseActive(cursor, now = new Date()) {
128
+ if (!cursor?.desiredRunning || !cursor.leaseOwner || !cursor.leaseUntil)
129
+ return false;
130
+ const deadline = Date.parse(cursor.leaseUntil);
131
+ return Number.isFinite(deadline) && deadline > now.getTime();
132
+ }
133
+ /**
134
+ * Atomically acquire an expired/unowned lease with compare-and-swap semantics.
135
+ * The post-update read is intentional: CAP adapters consistently return the row
136
+ * for SELECT, whereas affected-row return shapes differ between SQLite and HANA.
137
+ */
138
+ async function tryAcquireCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
139
+ const raw = await db.run(SELECT.one.from(cardano_1.CardanoSyncState).where({ ID: exports.SINGLETON_ID }));
140
+ if (!raw)
141
+ return false;
142
+ const current = toCursor(raw);
143
+ if (!current.desiredRunning)
144
+ return false;
145
+ const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
146
+ if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
147
+ return false;
148
+ // CAS on the observed OWNER only (a plain string that round-trips identically
149
+ // on every adapter). If two instances race, the first writer changes leaseOwner
150
+ // and the loser's UPDATE matches 0 rows → its read-back verification fails.
151
+ // Deliberately NOT comparing leaseUntil: HANA/driver timestamp normalization can
152
+ // make the read-back representation differ from what the WHERE serializes, so a
153
+ // timestamp-equality CAS may NEVER match again after a leader crash — the lease
154
+ // would be stuck until the row is cleared by hand. The residual race (the old
155
+ // owner renewing concurrently) resolves via fencing: its next renew no longer
156
+ // matches leaseOwner and it halts.
157
+ const where = {
158
+ ID: exports.SINGLETON_ID,
159
+ leaseOwner: raw.leaseOwner ?? null,
160
+ };
161
+ if (Object.prototype.hasOwnProperty.call(raw, 'desiredRunning')) {
162
+ where.desiredRunning = raw.desiredRunning;
163
+ }
164
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
165
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseOwner: owner, leaseUntil }).where(where));
166
+ const verified = await readCursor(db);
167
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
168
+ }
169
+ /**
170
+ * Renew/fence a lease. Call this inside the same transaction as every crawler write:
171
+ * the conditional UPDATE serializes a former leader against a newly elected one.
172
+ */
173
+ async function renewCrawlerLease(db, owner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
174
+ const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
175
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({ leaseUntil }).where({
176
+ ID: exports.SINGLETON_ID,
177
+ leaseOwner: owner,
178
+ desiredRunning: true,
179
+ }));
180
+ const verified = await readCursor(db);
181
+ return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
182
+ }
183
+ /**
184
+ * Release only the caller's lease; a stale process can never clear a successor.
185
+ *
186
+ * `pauseCluster` clears `desiredRunning`, which no restart undoes — every instance
187
+ * then refuses to start until an operator calls resumeCrawler. Reserve it for
188
+ * failures a restart genuinely cannot fix (misconfiguration, no resume point). A
189
+ * crashed stream, a provider outage or a node restart must NOT latch: those are
190
+ * exactly the cases where coming back up should resume the pre-sync by itself.
191
+ */
192
+ async function releaseCrawlerLease(db, owner, status, pauseCluster = false) {
193
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
194
+ leaseOwner: null,
195
+ leaseUntil: null,
196
+ syncStatus: status,
197
+ ...(pauseCluster ? { desiredRunning: false } : {}),
198
+ }).where({ ID: exports.SINGLETON_ID, leaseOwner: owner }));
199
+ }
200
+ /** Persist the pause/resume intent shared by every app instance. */
201
+ async function setCrawlerDesiredRunning(db, desiredRunning) {
202
+ const set = { desiredRunning };
203
+ if (!desiredRunning)
204
+ set.syncStatus = 'stopped';
205
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
206
+ }
207
+ /**
208
+ * Advance the cursor to a freshly-indexed block. Sets the status (default 'syncing';
209
+ * pass 'synced' when the block is at the tip), clears the error streak, and refreshes
210
+ * lastIndexedAt. Optionally records the latest known tip (for progress).
211
+ */
212
+ async function advanceCursor(db, block, tip, status = 'syncing') {
213
+ const set = {
214
+ lastSlot: block.slot,
215
+ lastBlockHash: block.hash,
216
+ lastHeight: block.height ?? 0,
217
+ lastIndexedAt: new Date().toISOString(),
218
+ syncStatus: status,
219
+ consecutiveErrors: 0,
220
+ lastError: null,
221
+ };
222
+ if (tip) {
223
+ set.tipSlot = tip.slot;
224
+ if (tip.height !== undefined)
225
+ set.tipHeight = tip.height;
226
+ }
227
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
228
+ }
229
+ /** Reset the cursor to a rollback point (used by reorg handling). */
230
+ async function resetCursorTo(db, point) {
231
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
232
+ lastSlot: point.slot,
233
+ lastBlockHash: point.hash,
234
+ lastHeight: point.height ?? 0,
235
+ lastIndexedAt: new Date().toISOString(),
236
+ }).where({ ID: exports.SINGLETON_ID }));
237
+ logger.warn(`Sync cursor reset to fork point ${point.slot}/${point.hash}`);
238
+ }
239
+ /** Set the crawler status (e.g. 'synced' when caught up, 'stopped' on shutdown). */
240
+ async function setSyncStatus(db, status, pauseCluster = false) {
241
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
242
+ syncStatus: status,
243
+ ...(pauseCluster ? { desiredRunning: false } : {}),
244
+ }).where({ ID: exports.SINGLETON_ID }));
245
+ }
246
+ /**
247
+ * Record a crawler error. Increments the consecutive-error counter and flips status
248
+ * to 'error' once the circuit-breaker threshold is reached. Returns the new streak
249
+ * length so the caller can decide whether to back off / stop.
250
+ */
251
+ async function recordError(db, err, leaseOwner) {
252
+ if (leaseOwner && !(await renewCrawlerLease(db, leaseOwner)))
253
+ return -1;
254
+ const current = await readCursor(db);
255
+ const streak = (current?.consecutiveErrors ?? 0) + 1;
256
+ const message = err instanceof Error ? err.message : String(err);
257
+ await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set({
258
+ consecutiveErrors: streak,
259
+ lastError: message.slice(0, 500),
260
+ lastErrorAt: new Date().toISOString(),
261
+ syncStatus: streak >= exports.MAX_CONSECUTIVE_ERRORS ? 'error' : 'syncing',
262
+ }).where({ ID: exports.SINGLETON_ID }));
263
+ return streak;
264
+ }
265
+ //# sourceMappingURL=sync-state.js.map
@@ -1,4 +1,48 @@
1
1
  import { HsmConfig, HsmSignResult } from '../../utils/types';
2
+ /**
3
+ * HsmSigner - PKCS#11 Hardware Security Module integration for Cardano transaction signing
4
+ *
5
+ * Wraps a PKCS#11 compliant HSM (YubiHSM 2, AWS CloudHSM, Thales Luna, etc.)
6
+ * to provide Ed25519 signing for Cardano transactions. Private keys never leave
7
+ * the HSM chip — only signatures are returned.
8
+ *
9
+ * Lifecycle:
10
+ * 1. constructor(config) — stores config
11
+ * 2. init(network) — connects to HSM, locates key, exports public key, derives Cardano address
12
+ * 3. sign() / signTransaction() — signing operations
13
+ * 4. shutdown() — closes session
14
+ */
15
+ /** Minimal PKCS#11 module surface used here. Loaded dynamically; no static type
16
+ * package is depended on. We narrow to the actual handful of methods invoked. */
17
+ interface PKCS11Instance {
18
+ load(path: string): void;
19
+ C_Initialize(): void;
20
+ C_Finalize(): void;
21
+ C_OpenSession(slot: Buffer, flags: number): Buffer;
22
+ C_CloseSession(session: Buffer): void;
23
+ C_Login(session: Buffer, userType: number, pin: string): void;
24
+ C_Logout(session: Buffer): void;
25
+ C_FindObjectsInit(session: Buffer, template: Pkcs11Attribute[]): void;
26
+ C_FindObjects(session: Buffer, count: number): Buffer[];
27
+ C_FindObjectsFinal(session: Buffer): void;
28
+ C_GetAttributeValue(session: Buffer, handle: Buffer, template: Pkcs11Attribute[]): Pkcs11Attribute[];
29
+ C_SignInit(session: Buffer, mechanism: {
30
+ mechanism: number;
31
+ }, key: Buffer): void;
32
+ C_Sign(session: Buffer, data: Buffer, signature: Buffer): Buffer;
33
+ C_GetSlotList(tokenPresent: boolean): Buffer[];
34
+ }
35
+ interface Pkcs11Attribute {
36
+ type: number;
37
+ value?: Buffer | number | boolean | string;
38
+ }
39
+ type Pkcs11JsModule = {
40
+ PKCS11: new () => PKCS11Instance;
41
+ [k: string]: unknown;
42
+ };
43
+ type Pkcs11Loader = () => Pkcs11JsModule;
44
+ /** Test seam: inject a fake pkcs11js module loader (null restores the default). */
45
+ export declare function setPkcs11Loader(loader: Pkcs11Loader | null): void;
2
46
  export declare class HsmSigner {
3
47
  private pkcs11;
4
48
  private session;
@@ -71,4 +115,5 @@ export declare function getHsmSigner(): HsmSigner | null;
71
115
  * Set the HsmSigner instance (called during initialization and shutdown).
72
116
  */
73
117
  export declare function setHsmSigner(signer: HsmSigner | null): void;
118
+ export {};
74
119
  //# sourceMappingURL=hsm-signer.d.ts.map