@odatano/core 2.0.0-rc.50 → 2.0.0-rc.52

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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +23 -12
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +36 -44
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -0,0 +1,224 @@
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.PROVIDER_LAG_SLOTS = void 0;
7
+ exports.settleSlots = settleSlots;
8
+ exports.isFinalRefusal = isFinalRefusal;
9
+ exports.landingFacts = landingFacts;
10
+ exports.sendProblem = sendProblem;
11
+ exports.isExpired = isExpired;
12
+ exports.outputsToCheck = outputsToCheck;
13
+ exports.hasUnspentOutput = hasUnspentOutput;
14
+ exports.resetLandingMemory = resetLandingMemory;
15
+ exports.judgeLanding = judgeLanding;
16
+ const cds_1 = __importDefault(require("@sap/cds"));
17
+ const errors_1 = require("../../utils/errors");
18
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
19
+ const const_1 = require("../../utils/const");
20
+ const epoch_slots_1 = require("../../utils/epoch-slots");
21
+ const transaction_presence_1 = require("../transaction-presence");
22
+ const logger = cds_1.default.log('LandingProof');
23
+ // On chain needs positive evidence: the crawled chain, a backend that returns it, an own output unspent.
24
+ // Never lands needs the tip past the expiry by the rollback horizon and an input still unspent. Past
25
+ // that point without either proof the outcome is unresolved, and an operator decides it.
26
+ /** Slots an indexer may lag the node; added to the horizon when the ledger read came from one. */
27
+ exports.PROVIDER_LAG_SLOTS = 3600;
28
+ /** Outputs of the transaction looked up to see whether it landed, besides the last one (the change). */
29
+ const OUTPUTS_CHECKED = 10;
30
+ /** Slots past its expiry after which a transaction can no longer land on the chain the node follows. */
31
+ function settleSlots(network) {
32
+ return (0, epoch_slots_1.rollbackHorizonSlots)(network);
33
+ }
34
+ // Ogmios refusals that hold for the bytes at any time and in any ledger state: bad or missing
35
+ // signatures, metadata, no inputs, wrong network, minted ada, boot address attributes, an input also
36
+ // a reference, a pointer address in the collateral return.
37
+ const FINAL_CODES = new Set([3100, 3101, 3105, 3106, 3107, 3108, 3121, 3124, 3126, 3127, 3164, 3169]);
38
+ // The same failures as the ledger names them in the refusal text of Blockfrost and Koios.
39
+ const FINAL_TEXT = /InvalidWitnessesUTXOW|MissingVKeyWitnessesUTXOW|MissingTxBodyMetadataHash|MissingTxMetadata|ConflictingMetadataHash|InvalidMetadata|InputSetEmptyUTxO|WrongNetwork|TriesToForgeADA|OutputBootAddrAttrsTooBig|NonDisjointRefInputs/;
40
+ /** The errors an error carries: itself, its originalError and the errors it collects. */
41
+ function errorTree(err, depth = 0) {
42
+ if (depth > 4 || err == null || typeof err !== 'object')
43
+ return err == null ? [] : [err];
44
+ const nested = [err.originalError, ...(err.errors ?? [])];
45
+ return [err, ...nested.flatMap((e) => (e == null ? [] : errorTree(e, depth + 1)))];
46
+ }
47
+ /** JSON-RPC codes of node refusals (3000-3999) anywhere in the error. */
48
+ function nodeRefusalCodes(err) {
49
+ return errorTree(err)
50
+ .map((e) => e.code)
51
+ .filter((c) => typeof c === 'number' && c >= 3000 && c < 4000);
52
+ }
53
+ function errorText(err) {
54
+ return errorTree(err).map((e) => (e instanceof Error ? e.message : typeof e === 'string' ? e : '')).join(' ');
55
+ }
56
+ // True when the refusal holds for these bytes whatever the ledger holds, so the transaction can never
57
+ // land. A refusal over inputs, the validity interval, fees, scripts or protocol parameters is no
58
+ // verdict: a resend of a transaction that already landed gets those too. An unknown refusal is none.
59
+ function isFinalRefusal(err) {
60
+ if (!(0, errors_1.isSubmitRejection)(err))
61
+ return false;
62
+ const codes = nodeRefusalCodes(err);
63
+ if (codes.length)
64
+ return codes.some((c) => FINAL_CODES.has(c));
65
+ return FINAL_TEXT.test(errorText(err));
66
+ }
67
+ /** Expiry, inputs, outputs and collateral of a signed transaction. */
68
+ function landingFacts(signedTxCbor) {
69
+ const t = (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor);
70
+ return {
71
+ ttlSlot: t.ttlSlot ?? null,
72
+ inputs: t.inputs ?? [],
73
+ outputCount: t.outputCount ?? 0,
74
+ isValid: t.isValid !== false,
75
+ collateralInputs: t.collateralInputs ?? [],
76
+ hasCollateralReturn: t.hasCollateralReturn === true,
77
+ };
78
+ }
79
+ // Why ODATANO will not send these bytes, or null. The expiry is what lets a send without an answer
80
+ // be decided, and the cap bounds how long a record or a wallet queue can stay open. Bytes marked to
81
+ // fail their scripts would only spend the collateral.
82
+ function sendProblem(signedTxCbor, network, nowMs = Date.now()) {
83
+ const { ttlSlot, isValid } = landingFacts(signedTxCbor);
84
+ if (!isValid)
85
+ return 'The transaction is marked to fail its scripts (isValid false); sending it would only spend its collateral';
86
+ if (ttlSlot === null)
87
+ return 'The transaction has no expiry (body key 3, TTL); set one, so its outcome can be decided';
88
+ // valid only while the slot is below the TTL
89
+ if (ttlSlot <= (0, epoch_slots_1.posixToSlot)(network, nowMs))
90
+ return `The transaction expired at slot ${ttlSlot}; no node accepts it any more`;
91
+ const latest = (0, epoch_slots_1.posixToSlot)(network, nowMs + const_1.MAX_VALIDITY_MS);
92
+ if (ttlSlot > latest)
93
+ return `The transaction expires at slot ${ttlSlot}, more than ${const_1.MAX_VALIDITY_MS / 3_600_000} hours ahead (latest slot ${latest})`;
94
+ return null;
95
+ }
96
+ /** True once the expiry has passed by the wall clock: then no node accepts the bytes any more. */
97
+ function isExpired(signedTxCbor, network, nowMs = Date.now()) {
98
+ let ttlSlot;
99
+ try {
100
+ ttlSlot = landingFacts(signedTxCbor).ttlSlot;
101
+ }
102
+ catch {
103
+ return false; // unreadable bytes: the node answers for them
104
+ }
105
+ return ttlSlot !== null && (0, epoch_slots_1.posixToSlot)(network, nowMs) >= ttlSlot;
106
+ }
107
+ /** Own output indexes read for landing evidence: the last (the builder puts the change there), then the first. */
108
+ function outputsToCheck(outputCount) {
109
+ if (outputCount <= 0)
110
+ return [];
111
+ const first = Array.from({ length: Math.min(outputCount, OUTPUTS_CHECKED) }, (_, i) => i);
112
+ return [...new Set([outputCount - 1, ...first])];
113
+ }
114
+ /** True when one of the transaction's own outputs is unspent: then it landed with passing scripts. */
115
+ async function hasUnspentOutput(signedTxCbor, txHash, client) {
116
+ for (const i of outputsToCheck(landingFacts(signedTxCbor).outputCount)) {
117
+ if (await client.isUtxoUnspent(txHash, i))
118
+ return true;
119
+ }
120
+ return false;
121
+ }
122
+ // Tip slot at which inputs of a transaction without an expiry were first seen spent: some of them, or
123
+ // all. A spend counts once it is older than the rollback horizon, since a rollback could undo a younger one.
124
+ const someSpentSince = new Map();
125
+ const allSpentSince = new Map();
126
+ /** Forgets what this process remembers about spent inputs; for tests. */
127
+ function resetLandingMemory() {
128
+ someSpentSince.clear();
129
+ allSpentSince.clear();
130
+ }
131
+ /** The tip slot `seen` holds for a transaction, set to `tip` on the first look. */
132
+ function firstSeen(seen, txHash, tip) {
133
+ const since = seen.get(txHash);
134
+ if (since !== undefined)
135
+ return since;
136
+ seen.set(txHash, tip);
137
+ return tip;
138
+ }
139
+ // What an own output shows: on chain, landed with failing scripts (its collateral return, which the
140
+ // ledger puts after the outputs, is unspent), or nothing.
141
+ async function ownOutputEvidence(facts, signedTxCbor, txHash, client) {
142
+ if (await hasUnspentOutput(signedTxCbor, txHash, client))
143
+ return { verdict: 'onChain' };
144
+ if (facts.hasCollateralReturn && await client.isUtxoUnspent(txHash, facts.outputCount)) {
145
+ return { verdict: 'scriptFailed', reason: scriptFailedReason(txHash) };
146
+ }
147
+ return null;
148
+ }
149
+ function scriptFailedReason(txHash) {
150
+ return `Transaction ${txHash} is on chain with failing scripts: only its collateral was spent, the payment did not happen`;
151
+ }
152
+ // Reads the chain for a sent transaction. sentAtMs bounds a transaction without an expiry. A lookup
153
+ // that cannot answer proves nothing, and then nothing else decides either.
154
+ async function judgeLanding(signedTxCbor, txHash, { indexer, client }, sentAtMs = null, nowMs = Date.now()) {
155
+ try {
156
+ let presence;
157
+ try {
158
+ presence = await (0, transaction_presence_1.findOnChain)(indexer, client, txHash);
159
+ }
160
+ catch (lookupErr) {
161
+ logger.debug({ txHash, error: lookupErr instanceof Error ? lookupErr.message : String(lookupErr) }, 'Transaction lookup gave no answer');
162
+ return { verdict: 'open' };
163
+ }
164
+ if (presence)
165
+ return presence.scriptFailed ? { verdict: 'scriptFailed', reason: scriptFailedReason(txHash) } : { verdict: 'onChain' };
166
+ const facts = landingFacts(signedTxCbor);
167
+ const settle = settleSlots(client.network);
168
+ if (facts.ttlSlot === null)
169
+ return await judgeWithoutExpiry(facts, signedTxCbor, txHash, client, settle, sentAtMs, nowMs);
170
+ // the wall clock first, so no ledger read runs while the transaction may still land
171
+ if ((0, epoch_slots_1.posixToSlot)(client.network, nowMs) <= facts.ttlSlot + settle)
172
+ return { verdict: 'open' };
173
+ // tip, inputs and collateral from one source; an unknown outpoint is not unspent
174
+ const refs = [...facts.inputs, ...facts.collateralInputs];
175
+ const ledger = await client.readLedger(refs);
176
+ if (ledger.tip <= facts.ttlSlot + settle + (ledger.live ? 0 : exports.PROVIDER_LAG_SLOTS))
177
+ return { verdict: 'open' };
178
+ const own = await ownOutputEvidence(facts, signedTxCbor, txHash, client);
179
+ if (own)
180
+ return own;
181
+ // a landing spends every input, or with failing scripts every collateral input
182
+ const inputUnspent = ledger.unspent.slice(0, facts.inputs.length).includes(true);
183
+ const collateralUnspent = facts.collateralInputs.length === 0 || ledger.unspent.slice(facts.inputs.length).includes(true);
184
+ if (inputUnspent && collateralUnspent) {
185
+ return { verdict: 'neverLands', reason: `Transaction ${txHash} expired at slot ${facts.ttlSlot} and an input it spends is still unspent (tip ${ledger.tip})` };
186
+ }
187
+ return { verdict: 'unresolved', reason: `Transaction ${txHash} expired at slot ${facts.ttlSlot}; its inputs are spent and nothing shows whether by this transaction` };
188
+ }
189
+ catch (err) {
190
+ logger.warn({ txHash, error: err instanceof Error ? err.message : String(err) }, 'Chain read for a sent transaction was inconclusive');
191
+ return { verdict: 'open' };
192
+ }
193
+ }
194
+ // Without an expiry the bytes can land while every input is unspent: past the longest expiry plus the
195
+ // horizon that makes them stale. A landing spends every input, so some but not all spent past the horizon
196
+ // means it never lands, all spent means unresolved. Before that bound only own outputs decide.
197
+ async function judgeWithoutExpiry(facts, signedTxCbor, txHash, client, settle, sentAtMs, nowMs) {
198
+ if (sentAtMs == null || nowMs <= sentAtMs + const_1.MAX_VALIDITY_MS + settle * 1000)
199
+ return { verdict: 'open' };
200
+ const own = await ownOutputEvidence(facts, signedTxCbor, txHash, client);
201
+ if (own)
202
+ return own;
203
+ const ledger = await client.readLedger(facts.inputs);
204
+ const unspentInputs = facts.inputs.filter((_, i) => ledger.unspent[i]);
205
+ const margin = settle + (ledger.live ? 0 : exports.PROVIDER_LAG_SLOTS);
206
+ if (unspentInputs.length === facts.inputs.length) {
207
+ someSpentSince.delete(txHash);
208
+ allSpentSince.delete(txHash);
209
+ return { verdict: 'stale', reason: `Transaction ${txHash} has no expiry and has not landed; every input it spends is unspent, so it can still land`, unspentInputs };
210
+ }
211
+ if (unspentInputs.length) {
212
+ allSpentSince.delete(txHash);
213
+ if (ledger.tip < firstSeen(someSpentSince, txHash, ledger.tip) + margin)
214
+ return { verdict: 'open' };
215
+ someSpentSince.delete(txHash);
216
+ return { verdict: 'neverLands', reason: `Transaction ${txHash} has no expiry; one of its inputs is spent by another transaction and another is unspent, so it never landed and never can` };
217
+ }
218
+ someSpentSince.delete(txHash);
219
+ if (ledger.tip < firstSeen(allSpentSince, txHash, ledger.tip) + margin)
220
+ return { verdict: 'open' };
221
+ allSpentSince.delete(txHash);
222
+ return { verdict: 'unresolved', reason: `Transaction ${txHash} has no expiry; its inputs are spent and nothing shows whether by this transaction` };
223
+ }
224
+ //# sourceMappingURL=landing-proof.js.map
@@ -52,15 +52,6 @@ function readVkeyWitnesses(txBytes) {
52
52
  });
53
53
  return { witnesses, malformed };
54
54
  }
55
- /** Well-formed vkey witnesses; [] when the tx has none. Malformed entries are skipped with a warning. */
56
- function extractVkeyWitnesses(txBytes) {
57
- const { witnesses, malformed } = readVkeyWitnesses(txBytes);
58
- if (malformed > 0) {
59
- // Not fatal, but a malformed witness in a signed tx is suspicious.
60
- logger.warn(`Skipped ${malformed} malformed vkey witness entr${malformed === 1 ? 'y' : 'ies'} while verifying (expected [vkey, signature] byte pairs)`);
61
- }
62
- return witnesses;
63
- }
64
55
  /** Ed25519 check of one witness over the body hash; false for a key or signature of the wrong length. */
65
56
  function signatureValid(w, bodyHashBytes) {
66
57
  try {
@@ -121,9 +112,15 @@ class SignatureVerifier {
121
112
  }
122
113
  logger.debug('Transaction body hash verified successfully');
123
114
  }
124
- // Extract vkey witnesses (raw pubkey + signature bytes)
125
- const vkeyWitnesses = extractVkeyWitnesses(txBytes);
115
+ // Extract vkey witnesses (raw pubkey + signature bytes). The node refuses a transaction with a
116
+ // malformed entry, so it never verifies here either.
117
+ const { witnesses: vkeyWitnesses, malformed } = readVkeyWitnesses(txBytes);
126
118
  result.witnessCount = vkeyWitnesses.length;
119
+ if (malformed > 0) {
120
+ result.errorMessage = `${malformed} vkey witness entr${malformed === 1 ? 'y is' : 'ies are'} not a [vkey, signature] byte pair`;
121
+ logger.warn(result.errorMessage);
122
+ return result;
123
+ }
127
124
  if (vkeyWitnesses.length > 0) {
128
125
  // signer key hash = blake2b-224 of the Ed25519 public key
129
126
  for (const w of vkeyWitnesses) {
@@ -191,7 +188,7 @@ class SignatureVerifier {
191
188
  /** True when the tx carries at least one vkey witness. */
192
189
  isSigned(txCbor) {
193
190
  try {
194
- return extractVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).length > 0;
191
+ return readVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).witnesses.length > 0;
195
192
  }
196
193
  catch {
197
194
  return false;
@@ -200,7 +197,7 @@ class SignatureVerifier {
200
197
  /** Number of vkey witnesses in the tx (0 on invalid CBOR). */
201
198
  getWitnessCount(txCbor) {
202
199
  try {
203
- return extractVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).length;
200
+ return readVkeyWitnesses((0, uint8array_utils_1.fromHex)(txCbor)).witnesses.length;
204
201
  }
205
202
  catch {
206
203
  return 0;
@@ -1,5 +1,5 @@
1
1
  import cds, { Request } from '@sap/cds';
2
- import { type TransactionLookup } from '../transaction-presence';
2
+ import { type LandingClient } from './landing-proof';
3
3
  import type { CardanoIndexer } from '../cardano-indexer';
4
4
  import type { CardanoClient } from '../cardano-client';
5
5
  import { type TransactionSubmission } from '#cds-models/CardanoTransactionService';
@@ -19,13 +19,27 @@ export interface FinalizeParams {
19
19
  };
20
20
  signerType?: string;
21
21
  signerInfo?: string;
22
+ /** When the transaction was first sent; bounds a transaction without an expiry. */
23
+ sentAtMs?: number | null;
22
24
  }
23
- type SubmissionIndexer = Pick<CardanoIndexer, 'persistTransactionSubmission' | 'updateSubmissionStatus' | 'dropDuplicateSubmission' | 'invalidateUtxoCacheForTx' | 'findIndexedTransaction'>;
24
- type SubmissionClient = Pick<CardanoClient, 'submitTransaction'> & TransactionLookup;
25
+ type SubmissionIndexer = Pick<CardanoIndexer, 'persistTransactionSubmission' | 'updateSubmissionStatus' | 'dropDuplicateSubmission' | 'invalidateUtxoCacheForTx' | 'findCrawledTransaction'>;
26
+ type SubmissionClient = Pick<CardanoClient, 'submitTransaction'> & LandingClient;
25
27
  interface SubmissionDeps {
26
28
  indexer: SubmissionIndexer & Pick<CardanoIndexer, 'indexVerifiedTransactionSubmission'>;
27
29
  client: SubmissionClient;
28
30
  }
31
+ type SubmitOutcome = 'accepted' | 'rejected' | 'scriptFailed' | 'unresolved' | 'unknown';
32
+ /** Records the reconciler reads only once an hour: no expiry, not landed, an input still unspent. */
33
+ export declare function staleRecordIds(): string[];
34
+ export declare function attemptSubmit(signedTxCbor: string, txHash: string, send: boolean, indexer: Pick<CardanoIndexer, 'findCrawledTransaction'>, client: SubmissionClient, sentAtMs?: number | null): Promise<{
35
+ outcome: SubmitOutcome;
36
+ error?: unknown;
37
+ finalRefusal?: boolean;
38
+ unspentInputs?: Array<{
39
+ txHash: string;
40
+ outputIndex: number;
41
+ }>;
42
+ }>;
29
43
  export declare function submitAndFinalize(SigningRequests: unknown, params: FinalizeParams, afterFinalize?: (db: cds.Transaction) => Promise<void>, send?: boolean, { indexer, client }?: SubmissionDeps): Promise<unknown>;
30
44
  export declare function submitRecorded(params: {
31
45
  signedTxCbor: string;
@@ -4,6 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RESUBMIT_WINDOW_MS = void 0;
7
+ exports.staleRecordIds = staleRecordIds;
8
+ exports.attemptSubmit = attemptSubmit;
7
9
  exports.submitAndFinalize = submitAndFinalize;
8
10
  exports.submitRecorded = submitRecorded;
9
11
  exports.scheduleDeferredSubmit = scheduleDeferredSubmit;
@@ -15,7 +17,7 @@ const errors_1 = require("../../utils/errors");
15
17
  const tx_utils_1 = require("../../utils/tx-utils");
16
18
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
17
19
  const external_signer_1 = require("./external-signer");
18
- const transaction_presence_1 = require("../transaction-presence");
20
+ const landing_proof_1 = require("./landing-proof");
19
21
  const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
20
22
  const { SELECT, UPDATE } = cds_1.default.ql;
21
23
  const logger = cds_1.default.log('SubmissionFinalizer');
@@ -25,6 +27,17 @@ exports.RESUBMIT_WINDOW_MS = 10 * 60_000;
25
27
  const RECONCILE_INTERVAL_MS = 60_000;
26
28
  // Record ids this process is sending right now. The reconciler leaves them alone.
27
29
  const inFlight = new Set();
30
+ // Stale records (no expiry, can still land, key not held here) and when the reconciler reads them next.
31
+ const STALE_RECHECK_MS = 60 * 60_000;
32
+ const staleUntil = new Map();
33
+ function noteStale(id, txHash, unspentInputs) {
34
+ staleUntil.set(id, Date.now() + STALE_RECHECK_MS);
35
+ logger.warn({ id, txHash, unspentInputs: unspentInputs.map((r) => `${r.txHash}#${r.outputIndex}`) }, 'Transaction without an expiry has not landed and still can; only spending one of its inputs ends it. Read again in an hour');
36
+ }
37
+ /** Records the reconciler reads only once an hour: no expiry, not landed, an input still unspent. */
38
+ function staleRecordIds() {
39
+ return [...staleUntil.keys()];
40
+ }
28
41
  // Signing requests whose stored transaction no longer verifies. Reported once, then skipped.
29
42
  const unverifiable = new Set();
30
43
  // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
@@ -39,11 +52,11 @@ function messageOf(err) {
39
52
  return err instanceof Error ? err.message : String(err);
40
53
  }
41
54
  // Sends the transaction and says what the attempt proves. With send = false only the chain is read,
42
- // unless no backend can look transactions up: then the node's answer is the only evidence.
43
- // `error` is the failed submit, also when the transaction turned out to be known.
44
- async function attemptSubmit(signedTxCbor, txHash, send, indexer, client) {
45
- const sent = send || !client.supports('getTransaction');
46
- let error = new Error(`Transaction ${txHash} is not on chain ${exports.RESUBMIT_WINDOW_MS / 60_000} minutes after its submit`);
55
+ // unless no backend can look transactions up: then it is sent again, but never past its expiry. A
56
+ // refusal ends the record only where it holds for these bytes; `error` is the failed submit.
57
+ async function attemptSubmit(signedTxCbor, txHash, send, indexer, client, sentAtMs = null) {
58
+ const sent = (send || !client.supports('getTransaction')) && !(0, landing_proof_1.isExpired)(signedTxCbor, client.network);
59
+ let error;
47
60
  if (sent) {
48
61
  try {
49
62
  await client.submitTransaction(signedTxCbor);
@@ -55,16 +68,21 @@ async function attemptSubmit(signedTxCbor, txHash, send, indexer, client) {
55
68
  error = submitErr;
56
69
  }
57
70
  }
58
- // A refusal may mean the transaction is already on chain and its inputs are spent.
59
- try {
60
- if (await (0, transaction_presence_1.isTransactionOnChain)(indexer, client, txHash))
61
- return { outcome: 'accepted', error };
62
- }
63
- catch (lookupErr) {
64
- logger.warn({ txHash, error: messageOf(lookupErr) }, 'Chain lookup after a failed submit was inconclusive');
65
- return { outcome: 'unknown', error };
66
- }
67
- return { outcome: !sent || (0, errors_1.isSubmitRejection)(error) ? 'rejected' : 'unknown', error };
71
+ const landing = await (0, landing_proof_1.judgeLanding)(signedTxCbor, txHash, { indexer, client }, sentAtMs);
72
+ if (landing.verdict === 'onChain')
73
+ return { outcome: 'accepted', error };
74
+ if (landing.verdict === 'scriptFailed')
75
+ return { outcome: 'scriptFailed', error: new errors_1.TransactionValidationError(landing.reason, error) };
76
+ if (sent && (0, landing_proof_1.isFinalRefusal)(error))
77
+ return { outcome: 'rejected', error, finalRefusal: true };
78
+ if (landing.verdict === 'neverLands')
79
+ return { outcome: 'rejected', error: new errors_1.TransactionValidationError(landing.reason, error) };
80
+ if (landing.verdict === 'unresolved')
81
+ return { outcome: 'unresolved', error: new Error(landing.reason) };
82
+ // without an expiry it can still land: open, and the inputs that would let it are named
83
+ if (landing.verdict === 'stale')
84
+ return { outcome: 'unknown', error: new Error(landing.reason), unspentInputs: landing.unspentInputs };
85
+ return { outcome: 'unknown', error: error ?? new Error(`Transaction ${txHash} is not on chain yet and may still land`) };
68
86
  }
69
87
  // Outcomes are written in detached transactions, so no DB lock is held across the network call.
70
88
  // A refused transaction is marked 'failed' and the error rethrown. Without a verdict the request
@@ -92,16 +110,41 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize, send =
92
110
  });
93
111
  inFlight.add(params.signingRequestId);
94
112
  try {
95
- const { outcome, error } = await attemptSubmit(params.fullSignedTxCbor, params.txHash, send, indexer, client);
113
+ const { outcome, error, unspentInputs } = await attemptSubmit(params.fullSignedTxCbor, params.txHash, send, indexer, client, params.sentAtMs ?? null);
114
+ if (unspentInputs)
115
+ noteStale(params.signingRequestId, params.txHash, unspentInputs);
116
+ else
117
+ staleUntil.delete(params.signingRequestId);
96
118
  if (outcome === 'unknown') {
97
119
  logger.warn({ signingRequestId: params.signingRequestId, txHash: params.txHash, error: messageOf(error) }, 'Submit got no verdict; the signing request stays submitting');
98
120
  throw new errors_1.SubmitOutcomeUnknownError(params.txHash, error);
99
121
  }
100
- if (outcome === 'rejected') {
122
+ if (outcome === 'unresolved') {
101
123
  try {
102
- await (0, tx_utils_1.detachedTx)('mark signing request failed', (db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'failed', errorMessage: messageOf(error) })
124
+ await (0, tx_utils_1.detachedTx)('mark signing request unresolved', (db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'unresolved', errorMessage: messageOf(error) })
103
125
  .where({ id: params.signingRequestId, status: 'submitting' })));
104
126
  }
127
+ catch (markErr) {
128
+ logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not mark signing request unresolved');
129
+ }
130
+ logger.error({ signingRequestId: params.signingRequestId, txHash: params.txHash, error: messageOf(error) }, 'Submit outcome cannot be decided any more; the signing request is unresolved and needs an operator');
131
+ throw new errors_1.SubmitOutcomeUnknownError(params.txHash, error);
132
+ }
133
+ if (outcome === 'rejected' || outcome === 'scriptFailed') {
134
+ try {
135
+ await (0, tx_utils_1.detachedTx)('mark signing request failed', async (db) => {
136
+ const marked = await db.run(UPDATE.entity(SigningRequests).set({ status: 'failed', errorMessage: messageOf(error) })
137
+ .where({ id: params.signingRequestId, status: 'submitting' }));
138
+ // it landed and spent the collateral: the submission record keeps that on file
139
+ if (outcome !== 'scriptFailed' || Number(marked) === 0)
140
+ return;
141
+ const row = await indexer.persistTransactionSubmission(db, {
142
+ signedTxCbor: params.fullSignedTxCbor, txHash: params.txHash, buildId: params.buildId || null,
143
+ });
144
+ await indexer.updateSubmissionStatus(db, row.id, 'failed', messageOf(error));
145
+ await db.run(UPDATE.entity(SigningRequests).set({ submission_id: row.id }).where({ id: params.signingRequestId }));
146
+ });
147
+ }
105
148
  catch (markErr) {
106
149
  logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
107
150
  }
@@ -121,11 +164,16 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize, send =
121
164
  async function settleRecorded(row, send, indexer, client) {
122
165
  inFlight.add(row.id);
123
166
  try {
124
- const { outcome, error } = await attemptSubmit(row.signedTxCbor, row.txHash, send, indexer, client);
167
+ const { outcome, error, unspentInputs } = await attemptSubmit(row.signedTxCbor, row.txHash, send, indexer, client, row.sentAtMs);
168
+ if (unspentInputs)
169
+ noteStale(row.id, row.txHash, unspentInputs);
170
+ else
171
+ staleUntil.delete(row.id);
172
+ // every write changes only a row still pending: another instance may have settled it meanwhile
125
173
  if (outcome === 'accepted' && error === undefined) {
126
174
  logger.info({ txHash: row.txHash }, 'Transaction submitted to blockchain');
127
175
  await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
128
- await indexer.updateSubmissionStatus(db, row.id, 'submitted');
176
+ await indexer.updateSubmissionStatus(db, row.id, 'submitted', undefined, 'pending');
129
177
  // best-effort: a cache failure must not roll back the submitted status
130
178
  try {
131
179
  const senders = row.buildId
@@ -144,13 +192,15 @@ async function settleRecorded(row, send, indexer, client) {
144
192
  await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
145
193
  // the row stays pending with the last error; a refusal ends only a row that is still pending
146
194
  if (outcome === 'unknown')
147
- return indexer.updateSubmissionStatus(db, row.id, 'pending', errMsg);
148
- if (outcome === 'rejected')
195
+ return indexer.updateSubmissionStatus(db, row.id, 'pending', errMsg, 'pending');
196
+ if (outcome === 'unresolved')
197
+ return indexer.updateSubmissionStatus(db, row.id, 'unresolved', errMsg, 'pending');
198
+ if (outcome === 'rejected' || outcome === 'scriptFailed')
149
199
  return indexer.updateSubmissionStatus(db, row.id, 'failed', errMsg, 'pending');
150
200
  // A resubmit keeps one row per transaction: its own row goes when an earlier one exists.
151
201
  if (await indexer.dropDuplicateSubmission(db, row.id, row.txHash))
152
202
  return;
153
- return indexer.updateSubmissionStatus(db, row.id, 'submitted');
203
+ return indexer.updateSubmissionStatus(db, row.id, 'submitted', undefined, 'pending');
154
204
  });
155
205
  }
156
206
  catch (markErr) {
@@ -160,7 +210,11 @@ async function settleRecorded(row, send, indexer, client) {
160
210
  logger.warn({ txHash: row.txHash, error: errMsg }, 'Submit got no verdict; the submission stays pending');
161
211
  throw new errors_1.SubmitOutcomeUnknownError(row.txHash, error);
162
212
  }
163
- if (outcome === 'rejected') {
213
+ if (outcome === 'unresolved') {
214
+ logger.error({ txHash: row.txHash, error: errMsg }, 'Submission outcome cannot be decided any more; it is unresolved and needs an operator');
215
+ throw new errors_1.SubmitOutcomeUnknownError(row.txHash, error);
216
+ }
217
+ if (outcome === 'rejected' || outcome === 'scriptFailed') {
164
218
  logger.error({ txHash: row.txHash, error: errMsg }, 'Transaction submission failed');
165
219
  throw error;
166
220
  }
@@ -174,7 +228,7 @@ async function settleRecorded(row, send, indexer, client) {
174
228
  // The final status commits on its own and survives a rethrown error.
175
229
  async function submitRecorded(params, indexer = server().getCardanoIndexer(), client = server().getCardanoClient()) {
176
230
  const record = await (0, tx_utils_1.detachedTx)('record transaction submission', (db) => indexer.persistTransactionSubmission(db, params));
177
- await settleRecorded({ id: record.id, ...params }, true, indexer, client);
231
+ await settleRecorded({ id: record.id, ...params, sentAtMs: Date.now() }, true, indexer, client);
178
232
  return { ...record, status: 'submitted' };
179
233
  }
180
234
  // Submits only after the caller's transaction has committed and released its connection.
@@ -197,6 +251,11 @@ function scheduleDeferredSubmit(req, SigningRequests, params) {
197
251
  });
198
252
  });
199
253
  }
254
+ /** Milliseconds of a stored timestamp, or null when there is none. */
255
+ function msOrNull(value) {
256
+ const ms = value ? Date.parse(value) : NaN;
257
+ return Number.isFinite(ms) ? ms : null;
258
+ }
200
259
  function olderThanWindow(sinceMs) {
201
260
  return Number.isFinite(sinceMs) && Date.now() - sinceMs > exports.RESUBMIT_WINDOW_MS;
202
261
  }
@@ -206,11 +265,11 @@ async function redriveInterruptedSubmissions(deps = liveDeps()) {
206
265
  const requests = (await (0, tx_utils_1.detachedTx)('load open signing requests', (db) => db.run(SELECT.from(SIGNING_REQUESTS)
207
266
  .columns('id', 'build_id', 'txBodyHash', 'signedTxCbor', 'signerType', 'signerInfo', 'signedAt', 'createdAt')
208
267
  .where({ status: 'submitting' })
209
- .and('signedTxCbor is not null')))).filter((row) => !inFlight.has(row.id) && !unverifiable.has(row.id));
268
+ .and('signedTxCbor is not null')))).filter((row) => !inFlight.has(row.id) && !unverifiable.has(row.id) && (staleUntil.get(row.id) ?? 0) <= Date.now());
210
269
  const submissions = (await (0, tx_utils_1.detachedTx)('load open submissions', (db) => db.run(SELECT.from(CardanoTransactionService_1.TransactionSubmissions)
211
270
  .columns('id', 'build_id', 'txHash', 'signedTxCbor', 'submittedAt')
212
271
  .where({ status: 'pending' }))))
213
- .filter((row) => !inFlight.has(row.id));
272
+ .filter((row) => !inFlight.has(row.id) && (staleUntil.get(row.id) ?? 0) <= Date.now());
214
273
  if (!requests.length && !submissions.length)
215
274
  return 0;
216
275
  logger.info(`Resolving ${requests.length} open signing request(s) and ${submissions.length} open submission(s)`);
@@ -237,6 +296,7 @@ async function redriveInterruptedSubmissions(deps = liveDeps()) {
237
296
  verificationResult,
238
297
  signerType: row.signerType ?? undefined,
239
298
  signerInfo: row.signerInfo ?? undefined,
299
+ sentAtMs: msOrNull(row.signedAt ?? row.createdAt),
240
300
  }, undefined, send, deps);
241
301
  logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Open signing request resolved as submitted');
242
302
  }
@@ -250,7 +310,8 @@ async function redriveInterruptedSubmissions(deps = liveDeps()) {
250
310
  attempted++;
251
311
  const send = !olderThanWindow(Number(row.submittedAt) * 1000);
252
312
  try {
253
- await settleRecorded({ id: row.id, signedTxCbor: row.signedTxCbor, txHash: row.txHash, buildId: row.build_id ?? null }, send, deps.indexer, deps.client);
313
+ const sentAtMs = row.submittedAt == null ? null : Number(row.submittedAt) * 1000;
314
+ await settleRecorded({ id: row.id, signedTxCbor: row.signedTxCbor, txHash: row.txHash, buildId: row.build_id ?? null, sentAtMs }, send, deps.indexer, deps.client);
254
315
  logger.info({ submissionId: row.id, txHash: row.txHash }, 'Open submission resolved as submitted');
255
316
  }
256
317
  catch (err) {
@@ -7,8 +7,7 @@ export declare function blockRowToData(row: Row): BlockData;
7
7
  export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
8
8
  /** A stored block by height; null when not indexed. */
9
9
  export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
10
- /** Up to `count` stored blocks after `afterHeight`. Stops at the first gap, so callers never skip one. */
11
- export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
10
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number, afterHash?: string | null): Promise<BlockData[]>;
12
11
  /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
13
12
  export declare function lacksOutpoints(t: ProviderTransaction): boolean;
14
13
  /** Stored transactions by hash (missing hashes are absent from the map). */