@odatano/core 2.0.0-rc.2 → 2.0.0-rc.21

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 (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. package/srv/utils/validators.js +31 -138
@@ -0,0 +1,383 @@
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.buildLedgerUtxoRows = buildLedgerUtxoRows;
7
+ exports.applyBlockToLedger = applyBlockToLedger;
8
+ exports.undoLedgerForTransactions = undoLedgerForTransactions;
9
+ exports.recountLedgerAddresses = recountLedgerAddresses;
10
+ exports.recountLedgerAccounts = recountLedgerAccounts;
11
+ const cds_1 = __importDefault(require("@sap/cds"));
12
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
+ const mappers_1 = require("../utils/mappers");
14
+ const collections_1 = require("../utils/collections");
15
+ const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
16
+ const logger = cds_1.default.log('LedgerState');
17
+ const outpoint = (txHash, outputIndex) => `${txHash}#${outputIndex}`;
18
+ const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
19
+ const nativeAssets = (amount) => (amount ?? []).filter(a => a.unit !== 'lovelace' && a.quantity !== '0');
20
+ const big = (v) => (v == null || v === '' ? 0n : BigInt(String(v)));
21
+ const num = (v) => Number(v ?? 0);
22
+ function decodeAssetName(hex) {
23
+ if (!hex)
24
+ return null;
25
+ try {
26
+ const text = Buffer.from(hex, 'hex').toString('utf8');
27
+ // printable only — a binary asset name has no useful decoded form
28
+ return /^[\x20-\x7e]*$/.test(text) ? text : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ /** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
35
+ function buildLedgerUtxoRows(o, createdSlot) {
36
+ const decoded = (0, mappers_1.decodeShelleyAddress)(o.address);
37
+ const assets = nativeAssets(o.amount).map((a) => ({
38
+ utxo_txHash: o.txHash,
39
+ utxo_outputIndex: o.outputIndex,
40
+ unit: a.unit,
41
+ asset_quantity: String(a.quantity),
42
+ asset_policyId: a.unit.length >= 56 ? a.unit.slice(0, 56) : null,
43
+ asset_assetNameHex: a.unit.length > 56 ? a.unit.slice(56) : '',
44
+ asset_assetName: a.unit.length > 56 ? decodeAssetName(a.unit.slice(56)) : null,
45
+ }));
46
+ return {
47
+ row: {
48
+ txHash: o.txHash,
49
+ outputIndex: o.outputIndex,
50
+ address: o.address,
51
+ stakeAddress: decoded.stakeAddress,
52
+ addressType: decoded.type,
53
+ isScript: decoded.isScript,
54
+ lovelace: lovelaceOf(o.amount).toString(),
55
+ createdSlot,
56
+ spentTxHash: null,
57
+ spentSlot: null,
58
+ utxo_dataHash: o.dataHash || null,
59
+ utxo_inlineDatum: o.inlineDatum || null,
60
+ utxo_referenceScriptHash: o.referenceScriptHash || null,
61
+ hasAssets: assets.length > 0,
62
+ },
63
+ assets,
64
+ };
65
+ }
66
+ /** Outputs the ledger actually produced: collateral return on a phase-2 failure, else the regular ones. */
67
+ function producedOutputs(t) {
68
+ return (t.outputs ?? []).filter(o => (t.spendsCollaterals ? o.isCollateral : !o.isCollateral));
69
+ }
70
+ /** Inputs the ledger actually consumed: collateral on a phase-2 failure, else the regular (non-reference) ones. */
71
+ function consumedInputs(t) {
72
+ return (t.inputs ?? [])
73
+ .filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
74
+ .map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
75
+ }
76
+ function deltaFor(map, row) {
77
+ let d = map.get(row.address);
78
+ if (!d) {
79
+ d = { lovelace: 0n, utxos: 0, assets: new Map(), stakeAddress: row.stakeAddress, addressType: row.addressType, isScript: row.isScript };
80
+ map.set(row.address, d);
81
+ }
82
+ return d;
83
+ }
84
+ function applyDelta(d, row, assets, sign) {
85
+ d.lovelace += sign * BigInt(row.lovelace);
86
+ d.utxos += Number(sign);
87
+ for (const a of assets ?? []) {
88
+ const unit = 'unit' in a ? a.unit : '';
89
+ const qty = 'asset_quantity' in a ? a.asset_quantity : a.quantity;
90
+ if (!unit)
91
+ continue;
92
+ d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
93
+ }
94
+ }
95
+ /**
96
+ * Apply one block to the ledger tables. Caller guarantees `block.slot > anchor.slot`.
97
+ * Never throws for a missing outpoint (it is counted and logged); DB errors propagate so the
98
+ * block transaction rolls back as a whole.
99
+ */
100
+ async function applyBlockToLedger(tx, block, txs) {
101
+ const slot = block.slot ?? 0;
102
+ // 1) everything this block produces
103
+ const created = new Map();
104
+ for (const t of txs) {
105
+ for (const o of producedOutputs(t)) {
106
+ const built = buildLedgerUtxoRows({ ...o, txHash: t.hash }, slot);
107
+ created.set(outpoint(t.hash, o.outputIndex), built);
108
+ }
109
+ }
110
+ // 2) everything this block consumes — same-block outputs first, the rest from the DB
111
+ const lookups = [];
112
+ const spentInBlock = new Set();
113
+ for (const t of txs) {
114
+ for (const i of consumedInputs(t)) {
115
+ const key = outpoint(i.txHash, i.outputIndex);
116
+ const own = created.get(key);
117
+ if (own) {
118
+ own.row.spentTxHash = t.hash;
119
+ own.row.spentSlot = slot;
120
+ spentInBlock.add(key);
121
+ }
122
+ else {
123
+ lookups.push({ key, txHash: i.txHash, outputIndex: i.outputIndex, spender: t.hash });
124
+ }
125
+ }
126
+ }
127
+ const dbRows = new Map();
128
+ const dbAssets = new Map();
129
+ const sourceHashes = [...new Set(lookups.map(l => l.txHash))];
130
+ for (const hashChunk of (0, collections_1.chunk)(sourceHashes, collections_1.IN_CHUNK)) {
131
+ const [rows, assets] = await Promise.all([
132
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } })),
133
+ tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } })),
134
+ ]);
135
+ for (const r of rows ?? [])
136
+ dbRows.set(outpoint(r.txHash, num(r.outputIndex)), r);
137
+ for (const a of assets ?? []) {
138
+ const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
139
+ const list = dbAssets.get(k) ?? [];
140
+ list.push(a);
141
+ dbAssets.set(k, list);
142
+ }
143
+ }
144
+ const spentRows = [];
145
+ let missing = 0;
146
+ for (const l of lookups) {
147
+ const row = dbRows.get(l.key);
148
+ if (!row || row.spentTxHash) {
149
+ missing++;
150
+ if (missing <= 3) {
151
+ logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}) — snapshot gap?`);
152
+ }
153
+ continue;
154
+ }
155
+ spentRows.push({
156
+ ...row,
157
+ outputIndex: num(row.outputIndex),
158
+ lovelace: String(row.lovelace),
159
+ createdSlot: row.createdSlot == null ? null : num(row.createdSlot),
160
+ isScript: Boolean(row.isScript),
161
+ hasAssets: Boolean(row.hasAssets),
162
+ spentTxHash: l.spender,
163
+ spentSlot: slot,
164
+ });
165
+ }
166
+ // 3) per-address deltas
167
+ const deltas = new Map();
168
+ for (const [key, { row, assets }] of created) {
169
+ const d = deltaFor(deltas, row);
170
+ applyDelta(d, row, assets, 1n);
171
+ if (spentInBlock.has(key))
172
+ applyDelta(d, row, assets, -1n);
173
+ }
174
+ for (const row of spentRows) {
175
+ applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
176
+ }
177
+ // 4) UTxO rows
178
+ const createdRows = [...created.values()];
179
+ for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
180
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
181
+ }
182
+ for (const rows of (0, collections_1.chunk)(createdRows.flatMap(c => c.assets), collections_1.IN_CHUNK)) {
183
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(rows));
184
+ }
185
+ for (const rows of (0, collections_1.chunk)(spentRows, collections_1.IN_CHUNK)) {
186
+ await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
187
+ }
188
+ // 5) addresses, address assets, accounts
189
+ const touched = [...deltas.keys()];
190
+ const stakeDeltas = new Map();
191
+ for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
192
+ const [existing, existingAssets] = await Promise.all([
193
+ tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
194
+ tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
195
+ ]);
196
+ const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
197
+ const assetQty = new Map();
198
+ for (const a of existingAssets ?? [])
199
+ assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
200
+ const addressRows = [];
201
+ const assetRows = [];
202
+ const assetDeletes = [];
203
+ for (const address of addrChunk) {
204
+ const d = deltas.get(address);
205
+ const prev = byAddress.get(address);
206
+ const total = big(prev?.totalLovelace) + d.lovelace;
207
+ const count = num(prev?.utxoCount) + d.utxos;
208
+ addressRows.push({
209
+ address,
210
+ stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
211
+ addressType: prev?.addressType ?? d.addressType,
212
+ isScript: prev ? Boolean(prev.isScript) : d.isScript,
213
+ totalLovelace: total.toString(),
214
+ utxoCount: count,
215
+ // null stays null: an address that came with the snapshot has no known first slot
216
+ firstSeenSlot: prev ? (prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot)) : slot,
217
+ lastActiveSlot: slot,
218
+ });
219
+ for (const [unit, delta] of d.assets) {
220
+ if (delta === 0n)
221
+ continue;
222
+ const k = `${address}|${unit}`;
223
+ const next = (assetQty.get(k) ?? 0n) + delta;
224
+ if (next === 0n) {
225
+ if (assetQty.has(k))
226
+ assetDeletes.push({ address_address: address, unit });
227
+ }
228
+ else {
229
+ assetRows.push({
230
+ address_address: address,
231
+ unit,
232
+ asset_quantity: next.toString(),
233
+ asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
234
+ asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
235
+ asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
236
+ });
237
+ }
238
+ }
239
+ const stake = prev?.stakeAddress ?? d.stakeAddress;
240
+ if (stake) {
241
+ const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, newAddresses: 0 };
242
+ s.lovelace += d.lovelace;
243
+ s.utxos += d.utxos;
244
+ if (!prev)
245
+ s.newAddresses++;
246
+ stakeDeltas.set(stake, s);
247
+ }
248
+ }
249
+ for (const rows of (0, collections_1.chunk)(addressRows, collections_1.IN_CHUNK))
250
+ await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries(rows));
251
+ for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
252
+ await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
253
+ for (const del of assetDeletes)
254
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where(del));
255
+ }
256
+ const stakes = [...stakeDeltas.keys()];
257
+ for (const stakeChunk of (0, collections_1.chunk)(stakes, collections_1.IN_CHUNK)) {
258
+ const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
259
+ const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
260
+ const rows = stakeChunk.map((stakeAddress) => {
261
+ const d = stakeDeltas.get(stakeAddress);
262
+ const prev = byStake.get(stakeAddress);
263
+ return {
264
+ stakeAddress,
265
+ controlledAmount: (big(prev?.controlledAmount) + d.lovelace).toString(),
266
+ addressCount: num(prev?.addressCount) + d.newAddresses,
267
+ utxoCount: num(prev?.utxoCount) + d.utxos,
268
+ lastActiveSlot: slot,
269
+ };
270
+ });
271
+ await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
272
+ }
273
+ return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
274
+ }
275
+ /**
276
+ * Reorg undo for a set of rolled-back transactions: drop what they created, reopen what
277
+ * they spent, then recount every address either side touched from the open rows.
278
+ * @returns the recounted addresses
279
+ */
280
+ async function undoLedgerForTransactions(tx, txHashes) {
281
+ if (!txHashes.length)
282
+ return [];
283
+ const touched = new Set();
284
+ for (const hashChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
285
+ const [createdRows, spentRows] = await Promise.all([
286
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ txHash: { in: hashChunk } })),
287
+ tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ spentTxHash: { in: hashChunk } })),
288
+ ]);
289
+ for (const r of [...(createdRows ?? []), ...(spentRows ?? [])])
290
+ touched.add(r.address);
291
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
292
+ await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
293
+ await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ spentTxHash: null, spentSlot: null }).where({ spentTxHash: { in: hashChunk } }));
294
+ }
295
+ const addresses = [...touched];
296
+ await recountLedgerAddresses(tx, addresses);
297
+ return addresses;
298
+ }
299
+ /**
300
+ * Recount running sums for the given addresses from their open UTxO rows, then the
301
+ * stake keys those addresses belong to. Also the repair path for a drifted sum.
302
+ */
303
+ async function recountLedgerAddresses(tx, addresses) {
304
+ const stakes = new Set();
305
+ for (const address of addresses) {
306
+ const open = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex', 'lovelace', 'hasAssets', 'stakeAddress')
307
+ .where({ address, spentTxHash: null }));
308
+ const openKeys = new Set((open ?? []).map(r => outpoint(r.txHash, num(r.outputIndex))));
309
+ let total = 0n;
310
+ for (const r of open ?? [])
311
+ total += big(r.lovelace);
312
+ const assetSums = new Map();
313
+ const withAssets = [...new Set((open ?? []).filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
314
+ for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
315
+ const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
316
+ for (const a of rows ?? []) {
317
+ if (!openKeys.has(outpoint(a.utxo_txHash, num(a.utxo_outputIndex))))
318
+ continue;
319
+ assetSums.set(a.unit, (assetSums.get(a.unit) ?? 0n) + big(a.asset_quantity));
320
+ }
321
+ }
322
+ const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
323
+ const decoded = (0, mappers_1.decodeShelleyAddress)(address);
324
+ const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
325
+ await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
326
+ address,
327
+ stakeAddress,
328
+ addressType: prev?.addressType ?? decoded.type,
329
+ isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
330
+ totalLovelace: total.toString(),
331
+ utxoCount: (open ?? []).length,
332
+ firstSeenSlot: prev?.firstSeenSlot == null ? null : num(prev.firstSeenSlot),
333
+ lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
334
+ }));
335
+ await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
336
+ const assetRows = [...assetSums].filter(([, q]) => q !== 0n).map(([unit, q]) => ({
337
+ address_address: address,
338
+ unit,
339
+ asset_quantity: q.toString(),
340
+ asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
341
+ asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
342
+ asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
343
+ }));
344
+ for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
345
+ await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
346
+ if (stakeAddress)
347
+ stakes.add(stakeAddress);
348
+ }
349
+ await recountLedgerAccounts(tx, [...stakes]);
350
+ }
351
+ /** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
352
+ async function recountLedgerAccounts(tx, stakeAddresses) {
353
+ for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
354
+ const [addrRows, existing] = await Promise.all([
355
+ tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('stakeAddress', 'totalLovelace', 'utxoCount')
356
+ .where({ stakeAddress: { in: stakeChunk } })),
357
+ tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } })),
358
+ ]);
359
+ const sums = new Map();
360
+ for (const r of addrRows ?? []) {
361
+ const k = String(r.stakeAddress);
362
+ const s = sums.get(k) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
363
+ s.lovelace += big(r.totalLovelace);
364
+ s.addresses += 1;
365
+ s.utxos += num(r.utxoCount);
366
+ sums.set(k, s);
367
+ }
368
+ const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
369
+ const rows = stakeChunk.map((stakeAddress) => {
370
+ const s = sums.get(stakeAddress) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
371
+ const prev = byStake.get(stakeAddress);
372
+ return {
373
+ stakeAddress,
374
+ controlledAmount: s.lovelace.toString(),
375
+ addressCount: s.addresses,
376
+ utxoCount: s.utxos,
377
+ lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
378
+ };
379
+ });
380
+ await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
381
+ }
382
+ }
383
+ //# sourceMappingURL=ledger-state.js.map
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Input to {@link verifyDataSignature}. Mirrors the CIP-30 `signData` result:
3
- * `coseSignature` is the hex `signature` field (COSE_Sign1), `coseKey` is the
4
- * hex `key` field (COSE_Key).
2
+ * Input to {@link verifyDataSignature}, mirroring the CIP-30 `signData` result:
3
+ * `coseSignature` = hex `signature` field (COSE_Sign1), `coseKey` = hex `key` field (COSE_Key).
5
4
  */
6
5
  export interface CoseVerifyInput {
7
6
  address: string;
@@ -20,15 +19,9 @@ export interface CoseVerifyResult {
20
19
  signerVkh: string;
21
20
  }
22
21
  /**
23
- * Verify a CIP-30 `signData` (COSE_Sign1) message signature against a bech32
24
- * address. Stateless crypto only & no nonce/replay/session handling.
25
- * Never throws: all failures are returned as `{ valid: false, reason }`.
26
- *
27
- * Checks, in order:
28
- * 1. COSE_Sign1 + COSE_Key parse
29
- * 2. signer key hash (blake2b-224) == the address payment credential (key, not script)
30
- * 3. (optional) signed payload == expectedPayload
31
- * 4. Ed25519 signature over the COSE Sig_structure
22
+ * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
23
+ * (blake2b-224) must equal the address payment key credential, optional payload check, then
24
+ * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
32
25
  */
33
26
  export declare function verifyDataSignature(input: CoseVerifyInput): CoseVerifyResult;
34
27
  //# sourceMappingURL=cose-verifier.d.ts.map
@@ -71,15 +71,9 @@ function buildSigStructure(protectedBytes, payload) {
71
71
  return cbor_1.Cbor.encode(sigStruct);
72
72
  }
73
73
  /**
74
- * Verify a CIP-30 `signData` (COSE_Sign1) message signature against a bech32
75
- * address. Stateless crypto only & no nonce/replay/session handling.
76
- * Never throws: all failures are returned as `{ valid: false, reason }`.
77
- *
78
- * Checks, in order:
79
- * 1. COSE_Sign1 + COSE_Key parse
80
- * 2. signer key hash (blake2b-224) == the address payment credential (key, not script)
81
- * 3. (optional) signed payload == expectedPayload
82
- * 4. Ed25519 signature over the COSE Sig_structure
74
+ * Verify a CIP-30 `signData` (COSE_Sign1) signature against a bech32 address: signer key hash
75
+ * (blake2b-224) must equal the address payment key credential, optional payload check, then
76
+ * Ed25519 over the Sig_structure. Stateless, no nonce/replay handling; never throws (`{ valid: false, reason }`).
83
77
  */
84
78
  function verifyDataSignature(input) {
85
79
  const result = { valid: false, reason: '', signedPayload: '', signerVkh: '' };
@@ -88,7 +82,7 @@ function verifyDataSignature(input) {
88
82
  const pubKey = parseCoseKey(input.coseKey);
89
83
  result.signedPayload = Buffer.from(payload).toString('utf8');
90
84
  result.signerVkh = (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_224)(pubKey));
91
- // 2. signer key hash must equal the address payment credential (key hash, not script)
85
+ // signer key hash must equal the address payment credential (key hash, not script)
92
86
  const cred = (0, validators_1.extractPaymentCredential)(input.address);
93
87
  if (!cred) {
94
88
  result.reason = 'Address could not be decoded or has no payment credential (base/enterprise key-hash address required)';
@@ -102,14 +96,14 @@ function verifyDataSignature(input) {
102
96
  result.reason = `Signer key hash ${result.signerVkh} does not match address payment credential ${cred.hash}`;
103
97
  return result;
104
98
  }
105
- // 3. optional anti-replay payload check
99
+ // optional anti-replay payload check
106
100
  if (input.expectedPayload !== undefined && input.expectedPayload !== null) {
107
101
  if (result.signedPayload !== input.expectedPayload) {
108
102
  result.reason = 'Signed payload does not match the expected payload';
109
103
  return result;
110
104
  }
111
105
  }
112
- // 4. Ed25519 signature over the rebuilt Sig_structure
106
+ // Ed25519 signature over the rebuilt Sig_structure
113
107
  const sigStructure = buildSigStructure(protectedBytes, payload);
114
108
  if (!(0, crypto_1.verifyEd25519Signature_sync)(signature, sigStructure, pubKey)) {
115
109
  result.reason = 'Ed25519 signature does not verify against the signed message';
@@ -1,18 +1,8 @@
1
1
  import { SignatureVerifier } from './signature-verifier';
2
2
  import { ExternalSignerType, UnsignedTxExportPayload, SignedTxPayload, SigningWorkflowState, SignatureVerificationResult, VerificationOptions } from '../../utils/types';
3
3
  /**
4
- * ExternalSignerModule - Manages the external signing workflow
5
- *
6
- * This module orchestrates the complete flow:
7
- * 1. Create signing request from build result
8
- * 2. Export unsigned transaction for external signing
9
- * 3. Receive and verify signed transaction
10
- * 4. Prepare for submission
11
- *
12
- * Key security principles:
13
- * - NO private keys are ever handled by this service
14
- * - Signature verification ensures transaction integrity
15
- * - Complete audit trail of the signing workflow
4
+ * External signing workflow: create signing request → export unsigned tx → verify the
5
+ * signed tx → prepare submission. No private keys are ever handled here.
16
6
  */
17
7
  export declare class ExternalSignerModule {
18
8
  private verifier;
@@ -20,126 +10,39 @@ export declare class ExternalSignerModule {
20
10
  constructor(options?: {
21
11
  signingTtlMs?: number;
22
12
  });
23
- /**
24
- * Create an unsigned transaction export payload for external signing
25
- *
26
- * This is the entry point for the external signing workflow.
27
- * Call this after building a transaction to get a standardized
28
- * payload that external signers can use.
29
- *
30
- * @param buildId - The build ID from TransactionBuilds
31
- * @param unsignedTxCbor - The unsigned transaction CBOR
32
- * @param txBodyHash - The transaction body hash
33
- * @param network - The Cardano network
34
- * @param options - Additional options
35
- * @returns Unsigned transaction export payload
36
- */
13
+ /** Create the unsigned-tx export payload that starts a signing request (workflow entry point). */
37
14
  createSigningRequest(buildId: string, unsignedTxCbor: string, txBodyHash: string, network: string, message: string, options?: {
38
15
  requiredSigners?: string[];
39
16
  signerTypeHint?: ExternalSignerType;
40
17
  }): UnsignedTxExportPayload;
41
- /**
42
- * Generate signing instructions for different signer types
43
- */
18
+ /** Signing instructions for the different signer types (CIP-30 request + cardano-cli recipe). */
44
19
  private generateSigningInstructions;
45
- /**
46
- * Verify a signed transaction
47
- *
48
- * Call this after receiving a signed transaction from an external signer.
49
- * This verifies the signature integrity before submission.
50
- *
51
- * @param signedTxCbor - The signed transaction CBOR
52
- * @param expectedTxBodyHash - The expected transaction body hash (from the build)
53
- * @param options - Additional verification options
54
- * @returns Verification result
55
- */
20
+ /** Verify a signed tx against the build's body hash; enforces the signing TTL when `expiresAt` is given. */
56
21
  verifySignedTransaction(signedTxCbor: string, expectedTxBodyHash: string, options?: Omit<VerificationOptions, 'expectedTxBodyHash'> & {
57
22
  expiresAt?: string;
58
23
  }): SignatureVerificationResult;
59
- /**
60
- * Verify signed transaction and throw on failure
61
- *
62
- * @param signedTxCbor - The signed transaction CBOR
63
- * @param expectedTxBodyHash - The expected transaction body hash
64
- * @param options - Additional verification options
65
- * @throws {TransactionValidationError} if verification fails
66
- */
24
+ /** Like verifySignedTransaction, but throws TransactionValidationError on failure. */
67
25
  verifyOrThrow(signedTxCbor: string, expectedTxBodyHash: string, options?: Omit<VerificationOptions, 'expectedTxBodyHash'>): SignatureVerificationResult;
68
- /**
69
- * Create a complete signing workflow state
70
- *
71
- * This creates a trackable workflow state that can be stored
72
- * and updated throughout the signing process.
73
- *
74
- * @param signingRequest - The unsigned transaction export payload
75
- * @returns Initial workflow state
76
- */
26
+ /** Initial (pending) workflow state for a signing request. */
77
27
  createWorkflowState(signingRequest: UnsignedTxExportPayload): SigningWorkflowState;
78
- /**
79
- * Update workflow state after signing
80
- *
81
- * @param state - Current workflow state
82
- * @param signedTxCbor - The signed transaction CBOR
83
- * @returns Updated workflow state
84
- */
28
+ /** Workflow state → signed. */
85
29
  markAsSigned(state: SigningWorkflowState, signedTxCbor: string): SigningWorkflowState;
86
- /**
87
- * Update workflow state after verification
88
- *
89
- * @param state - Current workflow state
90
- * @param verificationResult - The verification result
91
- * @returns Updated workflow state
92
- */
30
+ /** Workflow state → verified, or → failed when the verification result is invalid. */
93
31
  markAsVerified(state: SigningWorkflowState, verificationResult: SignatureVerificationResult): SigningWorkflowState;
94
- /**
95
- * Update workflow state after submission
96
- *
97
- * @param state - Current workflow state
98
- * @param txHash - The submitted transaction hash
99
- * @returns Updated workflow state
100
- */
32
+ /** Workflow state → submitted. */
101
33
  markAsSubmitted(state: SigningWorkflowState, txHash: string): SigningWorkflowState;
102
- /**
103
- * Update workflow state on failure
104
- *
105
- * @param state - Current workflow state
106
- * @param errorMessage - The error message
107
- * @returns Updated workflow state
108
- */
34
+ /** Workflow state → failed. */
109
35
  markAsFailed(state: SigningWorkflowState, errorMessage: string): SigningWorkflowState;
110
- /**
111
- * Check if a signing request has expired
112
- *
113
- * @param expiresAt - The expiration timestamp (ISO 8601)
114
- * @returns true if expired
115
- */
36
+ /** True when the ISO-8601 `expiresAt` lies in the past. */
116
37
  isExpired(expiresAt: string): boolean;
117
- /**
118
- * Validate a signed transaction payload before submission
119
- *
120
- * This performs all pre-submission checks:
121
- * 1. Verify the signature
122
- * 2. Check transaction hasn't been tampered with
123
- * 3. Ensure the build ID matches
124
- *
125
- * @param payload - The signed transaction payload
126
- * @param originalBuildTxBodyHash - The original transaction body hash from the build
127
- * @returns Validation result with verification details
128
- * @throws {TransactionValidationError} if validation fails
129
- */
38
+ /** Pre-submission check: signature + body-hash integrity against the build; throws TransactionValidationError. */
130
39
  validateForSubmission(payload: SignedTxPayload, originalBuildTxBodyHash: string): SignatureVerificationResult;
131
- /**
132
- * Get the signature verifier instance
133
- */
40
+ /** The underlying signature verifier. */
134
41
  getVerifier(): SignatureVerifier;
135
42
  }
136
- /**
137
- * Get the singleton ExternalSignerModule instance
138
- */
43
+ /** Singleton ExternalSignerModule. */
139
44
  export declare function getExternalSignerModule(): ExternalSignerModule;
140
- /**
141
- * Create a new ExternalSignerModule instance with custom options
142
- */
45
+ /** New ExternalSignerModule with custom options (not the singleton). */
143
46
  export declare function createExternalSignerModule(options?: {
144
47
  signingTtlMs?: number;
145
48
  }): ExternalSignerModule;