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

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 +15 -4
  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 +35 -43
  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
@@ -10,15 +10,19 @@ const cds_1 = __importDefault(require("@sap/cds"));
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
12
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
- const transaction_presence_1 = require("../transaction-presence");
13
+ const submission_finalizer_1 = require("../signing/submission-finalizer");
14
+ const external_signer_1 = require("../signing/external-signer");
15
+ const cbor_1 = require("../../cbor");
14
16
  const cardano_1 = require("#cds-models/odatano/cardano");
15
17
  const confirmation_tracker_1 = require("./confirmation-tracker");
16
18
  const lease_heartbeat_1 = require("./lease-heartbeat");
17
19
  const build_request_1 = require("./build-request");
18
20
  const service_events_1 = require("../../utils/service-events");
19
21
  const signers_1 = require("./signers");
22
+ const landing_proof_1 = require("../signing/landing-proof");
23
+ const invalidation_1 = require("./invalidation");
20
24
  const job_store_1 = require("./job-store");
21
- const { SELECT } = cds_1.default.ql;
25
+ const { SELECT, UPDATE } = cds_1.default.ql;
22
26
  const logger = cds_1.default.log('CardanoWalletWorker');
23
27
  /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
24
28
  function retryBackoffMs(attempt) {
@@ -50,12 +54,22 @@ class CardanoWalletWorker {
50
54
  executionPromises = new Set();
51
55
  tracker;
52
56
  dispatchTimer = null;
57
+ /** Earliest next reconcile per job with an open submit, and how often it was tried. */
58
+ reconcileBackoff = new Map();
59
+ /** Jobs whose transaction has no expiry, has not landed and still can: the unspent inputs, by job. */
60
+ staleJobs = new Map();
61
+ /** Earliest next look at a job's invalidation, and the tip height an own output was first seen at. */
62
+ invalidationNotBefore = new Map();
63
+ invalidationSeen = new Map();
64
+ /** Sends of a stored self-transfer not seen on chain yet, and the earliest next one. */
65
+ invalidationResend = new Map();
53
66
  running = false;
54
67
  tickInFlight = null;
55
68
  constructor(deps) {
56
69
  this.deps = deps;
57
70
  this.tracker = new confirmation_tracker_1.ConfirmationTracker({
58
71
  client: deps.client,
72
+ indexer: deps.indexer,
59
73
  options: {
60
74
  confirmationDepth: deps.config.confirmationDepth,
61
75
  confirmationTimeoutMs: deps.config.confirmationTimeoutMs,
@@ -65,15 +79,31 @@ class CardanoWalletWorker {
65
79
  onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
66
80
  logger.debug(`Wallet ${walletId} unblocked (job ${outcome}), next tick dispatches`);
67
81
  // Terminal outcomes only, after the commit, so subscribers reading the row see the announced state.
68
- (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
82
+ const event = outcome === 'confirmed' ? 'jobConfirmed' : outcome === 'failed' ? 'jobFailed' : 'jobUnresolved';
83
+ (0, service_events_1.emitServiceEvent)('CardanoWorkerService', event, {
69
84
  jobId,
70
85
  walletId,
71
86
  kind,
72
87
  txHash,
73
- ...(outcome === 'failed' ? { errorCode: errorCode ?? null, errorMessage: errorMessage ?? null } : {}),
88
+ ...(outcome === 'failed' ? { errorCode: errorCode ?? null } : {}),
89
+ ...(outcome !== 'confirmed' ? { errorMessage: errorMessage ?? null } : {}),
74
90
  });
75
91
  void this.tickSafe();
76
92
  },
93
+ onStale: ({ jobId, walletId }, unspentInputs) => {
94
+ this.staleJobs.set(jobId, { walletId, unspentInputs });
95
+ },
96
+ });
97
+ }
98
+ /** A terminal outcome after its commit, so subscribers reading the row see the announced state. */
99
+ announce(job, outcome, errorCode, err) {
100
+ (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'failed' ? 'jobFailed' : 'jobUnresolved', {
101
+ jobId: job.ID,
102
+ walletId: job.walletId,
103
+ kind: job.kind,
104
+ txHash: job.txHash,
105
+ ...(outcome === 'failed' ? { errorCode } : {}),
106
+ errorMessage: err instanceof Error ? err.message : err != null ? String(err) : null,
77
107
  });
78
108
  }
79
109
  isRunning() {
@@ -123,26 +153,18 @@ class CardanoWalletWorker {
123
153
  logger.error('Wallet worker not started: no wallet signer could be initialized');
124
154
  return;
125
155
  }
156
+ // a confirmation needs a transaction lookup or a ledger read of the transaction's outputs
157
+ if (!this.deps.client.supports('getTransaction') && !this.deps.client.supports('isUtxoUnspent')) {
158
+ logger.error('Wallet worker not started: no backend can confirm a transaction (getTransaction or isUtxoUnspent)');
159
+ return;
160
+ }
126
161
  // 2. Crash recovery: fail interrupted builds, re-watch submitted jobs; `submitting`
127
162
  // rows are reconciled by the first tick.
128
163
  const recovery = await cds_1.default.tx((tx) => (0, job_store_1.recoverInterruptedJobs)(tx));
129
164
  if (recovery.submittingToReconcile.length) {
130
165
  logger.warn(`${recovery.submittingToReconcile.length} job(s) with an unresolved submit will be reconciled on the next dispatch tick`);
131
166
  }
132
- for (const job of recovery.submittedToReconcile) {
133
- if (!job.txHash)
134
- continue; // defensive: submitted implies txHash
135
- this.tracker.track({
136
- jobId: job.ID,
137
- walletId: job.walletId,
138
- kind: job.kind,
139
- txHash: job.txHash,
140
- signedTxCbor: job.signedTxCbor,
141
- submittedAt: job.submittedAt,
142
- confirmedSlot: job.confirmedSlot,
143
- confirmedHeight: job.confirmedHeight,
144
- });
145
- }
167
+ this.trackSubmitted(recovery.submittedToReconcile);
146
168
  // 3. Go.
147
169
  this.running = true;
148
170
  this.tracker.start();
@@ -185,6 +207,10 @@ class CardanoWalletWorker {
185
207
  async tick() {
186
208
  // Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
187
209
  await this.reconcileOrphanedSubmissions();
210
+ // Submitted jobs of a stopped or crashed instance are watched here too. track() is idempotent.
211
+ await this.adoptSubmittedJobs();
212
+ // Transactions without an expiry that can still land get an input spent by a self-transfer.
213
+ await this.invalidateStaleJobs();
188
214
  // The next due job of every idle wallet this instance signs for: one row per wallet.
189
215
  const idle = this.getWalletIds().filter(walletId => !this.executing.has(walletId));
190
216
  if (!idle.length)
@@ -225,6 +251,27 @@ class CardanoWalletWorker {
225
251
  this.spawn(walletId, () => this.executeJob(job, signer));
226
252
  }
227
253
  }
254
+ /** Watch every submitted job of the wallets this instance signs for until it confirms or fails. */
255
+ async adoptSubmittedJobs() {
256
+ const rows = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findSubmittedJobs)(tx)));
257
+ this.trackSubmitted(rows.filter((row) => this.signers.has(row.walletId)));
258
+ }
259
+ trackSubmitted(rows) {
260
+ for (const job of rows) {
261
+ if (!job.txHash)
262
+ continue; // submitted implies txHash
263
+ this.tracker.track({
264
+ jobId: job.ID,
265
+ walletId: job.walletId,
266
+ kind: job.kind,
267
+ txHash: job.txHash,
268
+ signedTxCbor: job.signedTxCbor,
269
+ submittedAt: job.submittedAt,
270
+ confirmedSlot: job.confirmedSlot,
271
+ confirmedHeight: job.confirmedHeight,
272
+ });
273
+ }
274
+ }
228
275
  /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
229
276
  async reconcileOrphanedSubmissions() {
230
277
  const { instanceId } = this.deps;
@@ -237,7 +284,7 @@ class CardanoWalletWorker {
237
284
  continue;
238
285
  const orphan = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
239
286
  const stuck = await (0, job_store_1.findOrphanedSubmittingJob)(tx, walletId);
240
- if (!stuck)
287
+ if (!stuck || (this.reconcileBackoff.get(stuck.ID)?.notBefore ?? 0) > Date.now())
241
288
  return null;
242
289
  return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, instanceId)) ? stuck : null;
243
290
  }));
@@ -280,20 +327,22 @@ class CardanoWalletWorker {
280
327
  let signedTxCbor;
281
328
  let fee = null;
282
329
  let buildId = null;
330
+ const request = (0, build_request_1.parseJobRequest)(job.request);
331
+ if (!request)
332
+ throw new errors_1.BackendError('requestJson must be a JSON object', 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, 'requestJson');
283
333
  if (job.kind === 'submitSigned') {
284
- const request = JSON.parse(job.request ?? '{}');
285
- if (!request.signedTxCbor) {
286
- throw new errors_1.BackendError('submitSigned job has no signedTxCbor in its request', 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
287
- }
334
+ // jobs queued before the expiry rule are refused here, before anything is sent
335
+ const problem = (0, build_request_1.submitSignedProblem)(request, this.deps.network);
336
+ if (problem)
337
+ throw new errors_1.BackendError(problem, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, 'requestJson');
288
338
  signedTxCbor = request.signedTxCbor;
289
339
  }
290
340
  else {
291
- const rawReq = JSON.parse(job.request ?? '{}');
341
+ const rawReq = request;
292
342
  // The worker wallet is always the sender and change target. It never spends from foreign addresses.
293
343
  rawReq.network = this.deps.network;
294
344
  rawReq.senderAddress = signer.getAddress();
295
- if (!rawReq.changeAddress)
296
- rawReq.changeAddress = signer.getAddress();
345
+ rawReq.changeAddress = signer.getAddress();
297
346
  const build = this.buildOf(job, rawReq);
298
347
  // Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
299
348
  if (!(await heartbeat.fence())) {
@@ -305,6 +354,9 @@ class CardanoWalletWorker {
305
354
  fee = buildResult.fee ?? null;
306
355
  buildId = buildResult.id ?? null;
307
356
  signedTxCbor = signer.signTransaction(unsignedTxCbor, buildResult.txBodyHash);
357
+ // a signature that misses a key the body requires is refused by the node: fail before sending
358
+ const requiredSigners = new Set([signer.getPublicKeyHash(), ...((0, cbor_1.parseTransaction)(unsignedTxCbor).requiredSigners ?? [])].map((k) => k.toLowerCase()));
359
+ (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(signedTxCbor, buildResult.txBodyHash, { requiredSigners: [...requiredSigners] });
308
360
  }
309
361
  // Hash from the signed bytes, so the row can name the tx before anyone has seen it.
310
362
  const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
@@ -381,54 +433,186 @@ class CardanoWalletWorker {
381
433
  return;
382
434
  }
383
435
  logger.warn(`Job ${job.ID}: reconciling interrupted submit of tx ${job.txHash}`);
384
- let submitError;
385
- try {
386
- const txHash = await this.submitWithAlreadyKnownTolerance(job.signedTxCbor);
387
- await this.adoptSubmitted(job, txHash, job.signedTxCbor);
388
- logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}), now awaiting confirmation`);
436
+ // The same bytes again while young, later the chain alone. 'failed' only with proof that it cannot land.
437
+ const sentAtMs = job.submittedAt ? Date.parse(job.submittedAt) : NaN;
438
+ const ageMs = Number.isFinite(sentAtMs) ? Date.now() - sentAtMs : 0;
439
+ const { outcome, error, finalRefusal, unspentInputs } = await (0, submission_finalizer_1.attemptSubmit)(job.signedTxCbor, job.txHash, !(ageMs > submission_finalizer_1.RESUBMIT_WINDOW_MS), this.deps.indexer, this.deps.client, Number.isFinite(sentAtMs) ? sentAtMs : null);
440
+ if (outcome === 'accepted') {
441
+ this.reconcileBackoff.delete(job.ID);
442
+ await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
443
+ logger.info(`Job ${job.ID}: tx ${job.txHash} is with the node or on chain, now awaiting confirmation`);
389
444
  return;
390
445
  }
391
- catch (err) {
392
- submitError = err;
446
+ if (outcome === 'unknown') {
447
+ if (unspentInputs)
448
+ this.staleJobs.set(job.ID, { walletId: job.walletId, unspentInputs });
449
+ const attempts = (this.reconcileBackoff.get(job.ID)?.attempts ?? 0) + 1;
450
+ this.reconcileBackoff.set(job.ID, { attempts, notBefore: Date.now() + retryBackoffMs(attempts) });
451
+ logger.warn(`Job ${job.ID}: tx ${job.txHash} may still land, next check in ${retryBackoffMs(attempts) / 1000}s:`, error);
452
+ return;
393
453
  }
394
- // A rejection may mean the tx is already on-chain (inputs spent), so the chain decides.
395
- let onChain;
396
- try {
397
- // null: no backend can look transactions up, so the re-submit above is the only evidence
398
- onChain = await (0, transaction_presence_1.isTransactionOnChain)(this.deps.indexer, this.deps.client, job.txHash) === true;
454
+ this.reconcileBackoff.delete(job.ID);
455
+ if (outcome === 'unresolved') {
456
+ logger.error(`Job ${job.ID}: tx ${job.txHash} can no longer land and nothing shows whether it did; unresolved, an operator resolves it:`, error);
457
+ const marked = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markUnresolved)(tx, job.ID, error ?? new Error('unresolved'))))
458
+ .catch((persistErr) => { logger.error(`Job ${job.ID}: unresolved persist failed:`, persistErr); return false; });
459
+ if (marked)
460
+ this.announce(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, error);
461
+ return;
462
+ }
463
+ // It landed with failing scripts, or it can never land. The job fails and keeps its idempotency key.
464
+ const code = outcome === 'scriptFailed' ? job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED
465
+ : finalRefusal ? job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED : job_store_1.JOB_ERROR_CODES.TX_DROPPED;
466
+ logger.error(`Job ${job.ID}: tx ${job.txHash} fails as ${code}:`, error);
467
+ await this.failReconciled(job, code, error);
468
+ }
469
+ finally {
470
+ heartbeat.stop();
471
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
472
+ .catch(() => undefined);
473
+ }
474
+ }
475
+ async failReconciled(job, code, err) {
476
+ const transitioned = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
477
+ const done = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, code, err ?? new Error(code));
478
+ if (done) {
479
+ await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
480
+ if (job.txHash)
481
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'failed' }).where({ txHash: job.txHash, status: { in: ['submitted', 'pending'] } }));
399
482
  }
400
- catch (lookupErr) {
401
- logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive, retrying next tick:`, lookupErr);
483
+ return done;
484
+ })).catch((persistErr) => { logger.error(`Job ${job.ID}: failure persist failed:`, persistErr); return false; });
485
+ if (transitioned)
486
+ this.announce(job, 'failed', code, err);
487
+ }
488
+ /** One invalidation per wallet at a time: the job already being invalidated first, else a stale one. */
489
+ async invalidateStaleJobs() {
490
+ const { instanceId } = this.deps;
491
+ const now = Date.now();
492
+ for (const walletId of this.getWalletIds()) {
493
+ if (!this.running)
494
+ return;
495
+ if (this.executing.size >= this.deps.config.maxConcurrentWallets)
496
+ return;
497
+ if (this.executing.has(walletId))
498
+ continue;
499
+ const signer = this.signers.get(walletId);
500
+ const target = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
501
+ const inProgress = (await (0, job_store_1.findInvalidatingJobs)(tx, walletId))[0];
502
+ const staleId = [...this.staleJobs].find(([, s]) => s.walletId === walletId)?.[0];
503
+ const id = inProgress?.ID ?? staleId;
504
+ if (!id || (this.invalidationNotBefore.get(id) ?? 0) > now)
505
+ return null;
506
+ if (!(await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, instanceId)))
507
+ return null;
508
+ // read under the lease: another instance may have stored a self-transfer meanwhile
509
+ return (0, job_store_1.getJobById)(tx, id);
510
+ }));
511
+ if (!target)
512
+ continue;
513
+ this.invalidationNotBefore.set(target.ID, now + 60_000);
514
+ this.spawn(walletId, () => this.handleInvalidation(target, signer));
515
+ }
516
+ }
517
+ // The job's own transaction first: landed means the tracker takes it. Then its self-transfer:
518
+ // deep enough fails the job as INVALIDATED, unable to land sends a new one.
519
+ async handleInvalidation(job, signer) {
520
+ const heartbeat = this.leaseHeartbeat(job.walletId);
521
+ try {
522
+ if (!job.signedTxCbor || !job.txHash || (job.status !== 'submitted' && job.status !== 'submitting')) {
523
+ this.staleJobs.delete(job.ID);
402
524
  return;
403
525
  }
404
- if (onChain) {
405
- logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit, awaiting confirmation`);
406
- await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
526
+ const sentAtMs = job.submittedAt ? Date.parse(job.submittedAt) : NaN;
527
+ const own = await (0, landing_proof_1.judgeLanding)(job.signedTxCbor, job.txHash, this.deps, Number.isFinite(sentAtMs) ? sentAtMs : null);
528
+ if (own.verdict === 'onChain' || own.verdict === 'scriptFailed') {
529
+ this.staleJobs.delete(job.ID);
530
+ if (job.status === 'submitting')
531
+ await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
407
532
  return;
408
533
  }
409
- const ageMs = job.submittedAt ? Date.now() - Date.parse(job.submittedAt) : 0;
410
- const expired = ageMs > this.deps.config.confirmationTimeoutMs;
411
- if (isTransientJobError(submitError) && !expired) {
412
- logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain, retrying next tick:`, submitError);
534
+ const unspentInputs = own.verdict === 'stale' ? own.unspentInputs : this.staleJobs.get(job.ID)?.unspentInputs ?? [];
535
+ if (job.invalidationTxHash && job.invalidationTxCbor) {
536
+ const state = await (0, invalidation_1.checkInvalidation)(this.deps, job, this.invalidationSeen);
537
+ if (state === 'confirmed')
538
+ return await this.finishInvalidated(job);
539
+ if (state === 'unknown') {
540
+ const err = new Error(`Transaction ${job.txHash} has no expiry; the input its self-transfer ${job.invalidationTxHash} spends is spent and nothing shows by which transaction`);
541
+ const marked = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markUnresolved)(tx, job.ID, err)));
542
+ if (marked) {
543
+ this.tracker.untrack(job.ID);
544
+ this.announce(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, err);
545
+ }
546
+ return;
547
+ }
548
+ if (state === 'included')
549
+ return;
550
+ if (state === 'waiting')
551
+ return await this.resendWaitingInvalidation(job, heartbeat);
552
+ this.invalidationResend.delete(job.ID);
553
+ }
554
+ if (own.verdict !== 'stale')
555
+ return; // not stale (any more): nothing to spend
556
+ const { input, held } = await (0, invalidation_1.pickInvalidationInput)(this.deps, signer.getAddress(), unspentInputs);
557
+ if (!input) {
558
+ // every input is unspent and none is the wallet's: it cannot take the wallet funds
559
+ this.staleJobs.delete(job.ID);
560
+ this.invalidationNotBefore.set(job.ID, Date.now() + 60 * 60_000);
561
+ const released = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSpendsNoWalletUtxo)(tx, job.ID)));
562
+ if (released)
563
+ logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and can still land, but spends no UTxO of the wallet; it stays open and no longer holds the wallet queue`);
564
+ return;
565
+ }
566
+ if (!(await heartbeat.fence()))
567
+ return;
568
+ const keep = [...this.staleJobs].filter(([id, s]) => id !== job.ID && s.walletId === job.walletId).flatMap(([, s]) => s.unspentInputs);
569
+ await (0, invalidation_1.sendInvalidation)(this.deps, job, signer, input, { held, keep });
570
+ }
571
+ catch (err) {
572
+ if (err instanceof invalidation_1.InvalidationUnfundedError) {
573
+ this.invalidationNotBefore.set(job.ID, Date.now() + 60 * 60_000);
574
+ logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and can still land; the wallet cannot fund the self-transfer that would end it (${err.message}). Next try in an hour`);
413
575
  return;
414
576
  }
415
- // Not on-chain and not submittable now. The job fails and keeps its idempotency key.
416
- const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
417
- logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}), failing:`, submitError);
418
- await this.failReconciled(job, code, submitError);
577
+ logger.warn(`Job ${job.ID}: invalidation step failed (next tick retries):`, err);
419
578
  }
420
579
  finally {
421
580
  heartbeat.stop();
422
- await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
581
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, this.deps.instanceId)))
423
582
  .catch(() => undefined);
424
583
  }
425
584
  }
426
- async failReconciled(job, code, err) {
427
- await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
428
- const transitioned = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, code, err ?? new Error(code));
429
- if (transitioned)
585
+ // The stored self-transfer, not on chain yet and not expired: the same bytes again, waiting 1, 2, 4
586
+ // and up to 30 minutes between sends.
587
+ async resendWaitingInvalidation(job, heartbeat) {
588
+ if ((0, landing_proof_1.isExpired)(job.invalidationTxCbor, this.deps.network))
589
+ return;
590
+ const state = this.invalidationResend.get(job.ID) ?? { attempts: 0, notBefore: 0 };
591
+ if (state.notBefore > Date.now() || !(await heartbeat.fence()))
592
+ return;
593
+ await (0, invalidation_1.resendInvalidation)(this.deps, job);
594
+ const attempts = state.attempts + 1;
595
+ this.invalidationResend.set(job.ID, { attempts, notBefore: Date.now() + Math.min(60_000 * 2 ** (attempts - 1), 30 * 60_000) });
596
+ }
597
+ async finishInvalidated(job) {
598
+ const err = new Error(`Self-transfer ${job.invalidationTxHash} spent an input of transaction ${job.txHash} and is past rollback depth; ${job.txHash} can never land`);
599
+ const transitioned = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
600
+ const done = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, job_store_1.JOB_ERROR_CODES.INVALIDATED, err);
601
+ if (done) {
430
602
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
431
- })).catch((persistErr) => logger.error(`Job ${job.ID}: failure persist failed:`, persistErr));
603
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'failed' }).where({ txHash: job.txHash, status: { in: ['submitted', 'pending'] } }));
604
+ }
605
+ return done;
606
+ }));
607
+ this.staleJobs.delete(job.ID);
608
+ this.invalidationSeen.delete(job.ID);
609
+ this.invalidationNotBefore.delete(job.ID);
610
+ this.invalidationResend.delete(job.ID);
611
+ this.tracker.untrack(job.ID);
612
+ if (transitioned) {
613
+ logger.warn(`Job ${job.ID}: failed as INVALIDATED`);
614
+ this.announce(job, 'failed', job_store_1.JOB_ERROR_CODES.INVALIDATED, err);
615
+ }
432
616
  }
433
617
  /** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
434
618
  buildOf(job, raw) {
@@ -42,7 +42,7 @@ service CardanoAgentService @(impl: './cardano-agent-service') {
42
42
  function GetGrantStatus() returns GrantStatus;
43
43
 
44
44
  @title : 'Create Agent Grant'
45
- @description: 'Issue a scoped bearer token for an agent. Admin only. The token is returned once and stored as SHA-256. allowedActions must be a non-empty subset of the grantable set. Worker wallets are closed to tokens.'
45
+ @description: 'Issue a scoped bearer token for an agent. Admin only. The token is returned once and stored as SHA-256. allowedActions must be a non-empty subset of the grantable set, each named Service.operation (a name without its service means the operation of the transaction or the sign service). Worker wallets are closed to tokens.'
46
46
  @requires : 'Admin'
47
47
  @odatano.agent: 'operator'
48
48
  action CreateAgentGrant(
@@ -2,10 +2,18 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const agent_grants_1 = require("./utils/agent-grants");
4
4
  const result_numbers_1 = require("./utils/result-numbers");
5
+ const config_1 = require("./config");
6
+ const errors_1 = require("./utils/errors");
5
7
  // Handlers live in srv/utils/agent-grants.ts, shared with the programmatic API.
6
8
  // The token enforcement hook is attached to all services in src/plugin.ts.
7
9
  module.exports = (srv) => {
8
10
  (0, result_numbers_1.answerNumbersAsText)(srv);
11
+ // Grants issued while the feature is off would turn into live tokens once it is switched on.
12
+ srv.before('*', (req) => {
13
+ if (!(0, config_1.loadAgentGrantsConfig)().enabled) {
14
+ return (0, errors_1.rejectInvalid)(req, String(req.event), 'Agent grants are not enabled: set cds.requires.odatano-core.agentGrants.enabled (or AGENT_GRANTS_ENABLED=true).');
15
+ }
16
+ });
9
17
  (0, agent_grants_1.registerAgentGrantHandlers)(srv);
10
18
  };
11
19
  //# sourceMappingURL=cardano-agent-service.js.map
@@ -18,7 +18,7 @@ service CardanoBackendService @(impl: './cardano-backend-service') {
18
18
  action GetNextBlocks(afterHash: String, @assert.range: [1, 500] count: Integer,
19
19
  @assert.range: [0, _] afterHeight: Integer64) returns LargeString;
20
20
  @odatano.agent: 'read'
21
- action GetBlockTransactions(blockHash: String) returns LargeString;
21
+ action GetBlockTransactions(blockHash: String, @assert.range: [0, _] txCount: Integer) returns LargeString;
22
22
  @odatano.agent: 'read'
23
23
  action GetLatestBlock() returns LargeString;
24
24
  @odatano.agent: 'read'
@@ -48,6 +48,9 @@ service CardanoBackendService @(impl: './cardano-backend-service') {
48
48
  @odatano.agent: 'read'
49
49
  action GetAccount(stakeAddress: String) returns LargeString;
50
50
  @odatano.agent: 'read'
51
+ @description: 'Whether the stake address is registered, as this instance decides: true, false, or null when no source can tell.'
52
+ action IsRewardAccountRegistered(stakeAddress: String) returns LargeString;
53
+ @odatano.agent: 'read'
51
54
  action GetPool(poolId: String) returns LargeString;
52
55
  @odatano.agent: 'read'
53
56
  action GetPoolIds() returns LargeString;
@@ -119,7 +119,7 @@ module.exports = (srv) => {
119
119
  const n = count == null ? 1 : Number(count);
120
120
  const { anchor, next, canonical } = await (0, tx_utils_1.readOutside)(db, async (d) => {
121
121
  const anchor = await (0, stored_chain_1.readBlock)(d, String(afterHash));
122
- const next = anchor?.height != null ? await (0, stored_chain_1.readNextBlocks)(d, anchor.height, n) : [];
122
+ const next = anchor?.height != null ? await (0, stored_chain_1.readNextBlocks)(d, anchor.height, n, anchor.hash) : [];
123
123
  const orphaned = !next.length && !anchor && afterHeight != null;
124
124
  return { anchor, next, canonical: orphaned ? await (0, stored_chain_1.readBlockByHeight)(d, Number(afterHeight)) : null };
125
125
  });
@@ -148,16 +148,22 @@ module.exports = (srv) => {
148
148
  // Nothing indexed past the cursor yet: the caller is at this instance's tip.
149
149
  if (anchor)
150
150
  return [];
151
- throw new errors_1.ChainPointMismatchError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
151
+ // A cursor outside the stored range is not proof of a reorg; only another block at its height is.
152
+ throw new errors_1.ProviderUnavailableError(`Block ${afterHash} is not stored here and no paging backend can follow it`, 'odatano');
152
153
  }, need(validators_1.isBlockHash, 'afterHash', 'block hash'));
153
- op('GetBlockTransactions', async ({ blockHash }, db) => {
154
- const stored = await (0, tx_utils_1.readOutside)(db, (d) => (0, stored_chain_1.readBlockTransactions)(d, String(blockHash)));
154
+ op('GetBlockTransactions', async ({ blockHash, txCount }, db) => {
155
+ const hash = String(blockHash);
156
+ const { stored, block } = await (0, tx_utils_1.readOutside)(db, async (d) => ({
157
+ stored: await (0, stored_chain_1.readBlockTransactions)(d, hash),
158
+ block: txCount == null ? await (0, stored_chain_1.readBlock)(d, hash) : null,
159
+ }));
155
160
  if (stored)
156
161
  return stored;
157
162
  const paging = client().getPaginatingBackend();
158
163
  if (!paging)
159
164
  throw new errors_1.ProviderUnavailableError(`Transactions of block ${blockHash} are not indexed here`, 'odatano');
160
- return paging.getBlockTransactions(String(blockHash));
165
+ // the count lets the backend refuse a short list instead of answering part of the block
166
+ return paging.getBlockTransactions(hash, txCount == null ? block?.txCount : Number(txCount));
161
167
  }, need(validators_1.isBlockHash, 'blockHash', 'block hash'));
162
168
  op('GetLatestBlock', async () => client().getLatestBlock());
163
169
  op('GetCurrentSlot', async () => client().getCurrentSlot());
@@ -186,7 +192,13 @@ module.exports = (srv) => {
186
192
  return found;
187
193
  }, jsonList('refs', isRef, 'output references'));
188
194
  // --- stake, governance, assets, network ------------------------------------------------------
189
- op('GetAccount', async ({ stakeAddress }, db) => indexer().resolveAccount(db, String(stakeAddress)), need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
195
+ // Addresses go out as { address } objects, the shape every consumer version reads.
196
+ op('GetAccount', async ({ stakeAddress }, db) => {
197
+ const account = await indexer().resolveAccount(db, String(stakeAddress));
198
+ return { ...account, addresses: account.addresses.map(address => ({ address })) };
199
+ }, need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
200
+ // the account read answers 404 for a registered account the node does not list; this does not
201
+ op('IsRewardAccountRegistered', async ({ stakeAddress }) => client().isRewardAccountRegistered(String(stakeAddress)), need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
190
202
  op('GetPool', async ({ poolId }, db) => indexer().resolvePool(db, String(poolId)), need(validators_1.isValidPoolId, 'poolId', 'pool id'));
191
203
  op('GetDrep', async ({ drepId }) => client().getDrep(String(drepId)), need(validators_1.isValidDrepId, 'drepId', 'DRep id'));
192
204
  op('GetPoolIds', async () => (await enumeration()).pools.map(p => p.poolId));
@@ -212,11 +224,16 @@ module.exports = (srv) => {
212
224
  return hash;
213
225
  }, cbor);
214
226
  // The full pool and DRep set, from Koios when configured, else from the Ogmios ledger.
215
- // Cached for a minute. Details are read in batches of ids.
227
+ // Cached for a minute, and one run is shared by the callers that arrive while it runs.
216
228
  let enumerated = null;
217
- async function enumeration() {
229
+ let enumerating = null;
230
+ function enumeration() {
218
231
  if (enumerated && Date.now() - enumerated.at < 60_000)
219
- return enumerated;
232
+ return Promise.resolve(enumerated);
233
+ enumerating ??= enumerate().finally(() => { enumerating = null; });
234
+ return enumerating;
235
+ }
236
+ async function enumerate() {
220
237
  const koios = client().getEnumeratingBackend();
221
238
  if (koios) {
222
239
  const [pools, dreps] = await Promise.all([