@odatano/core 2.0.0-rc.23 → 2.0.0-rc.25
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.
- package/@cds-models/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/CardanoODataService/index.d.ts +27 -2
- package/@cds-models/CardanoODataService/index.js +3 -0
- package/@cds-models/CardanoSignService/index.d.ts +23 -1
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +18 -0
- package/@cds-models/index.js +3 -0
- package/@cds-models/odatano/cardano/index.d.ts +49 -2
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/db/schema.cds +74 -3
- package/db/types.cds +27 -0
- package/package.json +182 -181
- package/srv/blockchain/backends/blockfrost-backend.js +4 -2
- package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
- package/srv/blockchain/backends/koios-backend.d.ts +1 -1
- package/srv/blockchain/backends/koios-backend.js +61 -14
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +166 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
- package/srv/blockchain/backends/ogmios-backend.js +91 -21
- package/srv/blockchain/cardano-client.d.ts +23 -9
- package/srv/blockchain/cardano-client.js +77 -25
- package/srv/blockchain/cardano-indexer.d.ts +61 -15
- package/srv/blockchain/cardano-indexer.js +248 -79
- package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
- package/srv/blockchain/cardano-tx-builder.js +59 -4
- package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/certificate-backfill.js +49 -30
- package/srv/blockchain/crawler/crawler.d.ts +3 -1
- package/srv/blockchain/crawler/crawler.js +12 -7
- package/srv/blockchain/crawler/sync-state.d.ts +3 -1
- package/srv/blockchain/crawler/sync-state.js +15 -2
- package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/transaction-backfill.js +283 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
- package/srv/blockchain/crawler/utxo-set-import.js +138 -47
- package/srv/blockchain/ledger-state.d.ts +16 -1
- package/srv/blockchain/ledger-state.js +38 -18
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- package/srv/blockchain/stored-chain.d.ts +33 -0
- package/srv/blockchain/stored-chain.js +234 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
- package/srv/blockchain/transaction-rows.d.ts +1 -1
- package/srv/blockchain/transaction-rows.js +2 -1
- package/srv/blockchain/wallet-worker/build-request.js +1 -1
- package/srv/cardano-backend-service.cds +52 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +244 -0
- package/srv/cardano-indexer-service.cds +201 -176
- package/srv/cardano-indexer-service.js +104 -10
- package/srv/cardano-service.cds +5 -0
- package/srv/cardano-tx-service.cds +39 -0
- package/srv/cardano-tx-service.js +88 -14
- package/srv/server.js +20 -2
- package/srv/utils/agent-grants.js +8 -0
- package/srv/utils/const.d.ts +5 -0
- package/srv/utils/const.js +6 -1
- package/srv/utils/error-codes.d.ts +2 -0
- package/srv/utils/error-codes.js +2 -0
- package/srv/utils/errors.d.ts +7 -0
- package/srv/utils/errors.js +11 -1
- package/srv/utils/mappers.d.ts +24 -2
- package/srv/utils/mappers.js +49 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +63 -0
- package/srv/utils/tx-build-helper.d.ts +2 -0
- package/srv/utils/tx-build-helper.js +12 -0
- package/srv/utils/tx-request-parsers.d.ts +46 -5
- package/srv/utils/tx-request-parsers.js +227 -16
- package/srv/utils/types.d.ts +59 -0
- package/srv/utils/validators.d.ts +5 -1
- package/srv/utils/validators.js +19 -9
|
@@ -18,6 +18,12 @@ class CardanoTransactionBuilder {
|
|
|
18
18
|
this.client = client;
|
|
19
19
|
logger.debug('CardanoTransactionBuilder instance created');
|
|
20
20
|
}
|
|
21
|
+
/** Unspent outputs of an address from local data (the crawled UTxO set); null = it cannot answer. */
|
|
22
|
+
addressUtxoSource = null;
|
|
23
|
+
/** Read sender UTxOs from `source` first; the node's address query is the fallback. */
|
|
24
|
+
setAddressUtxoSource(source) {
|
|
25
|
+
this.addressUtxoSource = source;
|
|
26
|
+
}
|
|
21
27
|
/** @param protocolParams optional; fetched from the backend when omitted */
|
|
22
28
|
async init(protocolParams) {
|
|
23
29
|
if (this.initialized && this.txBuilder)
|
|
@@ -110,7 +116,7 @@ class CardanoTransactionBuilder {
|
|
|
110
116
|
utxos: mergeUtxosUnique(senderUtxos, forcedUtxos),
|
|
111
117
|
protocolParameters: protocolParameters,
|
|
112
118
|
// Pass evaluator if Ogmios is available for dynamic execution unit calculation
|
|
113
|
-
evaluateTransaction: cardanoClient.
|
|
119
|
+
evaluateTransaction: cardanoClient.hasEvaluatingBackend()
|
|
114
120
|
? (cbor) => cardanoClient.evaluateTransaction(cbor)
|
|
115
121
|
: undefined,
|
|
116
122
|
referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
|
|
@@ -152,7 +158,7 @@ class CardanoTransactionBuilder {
|
|
|
152
158
|
const txContext = {
|
|
153
159
|
utxos: mergedUtxos,
|
|
154
160
|
protocolParameters: protocolParameters,
|
|
155
|
-
evaluateTransaction: cardanoClient.
|
|
161
|
+
evaluateTransaction: cardanoClient.hasEvaluatingBackend()
|
|
156
162
|
? (cbor) => cardanoClient.evaluateTransaction(cbor)
|
|
157
163
|
: undefined,
|
|
158
164
|
referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined
|
|
@@ -168,12 +174,41 @@ class CardanoTransactionBuilder {
|
|
|
168
174
|
logger.debug(`Built Plutus spending transaction successfully.`);
|
|
169
175
|
return txBuildResult;
|
|
170
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* Several script inputs in one transaction: resolve every script UTxO and every reference-script
|
|
179
|
+
* UTxO (one ledger lookup each), plus the sender's UTxOs, forced and reference inputs.
|
|
180
|
+
*/
|
|
181
|
+
async buildPlutusTransaction(req, protocolParameters) {
|
|
182
|
+
const builder = await this.ensureInitialized();
|
|
183
|
+
const cardanoClient = this.client;
|
|
184
|
+
const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
|
|
185
|
+
const scriptUtxos = await this._resolveInputRefs(req.scriptInputs.map(s => ({ txHash: s.txHash, outputIndex: s.outputIndex })), senderUtxos, 'scriptInput');
|
|
186
|
+
const allUtxos = mergeUtxosUnique(senderUtxos, scriptUtxos);
|
|
187
|
+
const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], allUtxos);
|
|
188
|
+
// Reference-script UTxOs always from the ledger: a known sender UTxO may carry only the script hash
|
|
189
|
+
const refScriptUtxos = await this._resolveInputRefs(req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : [])), [], 'referenceScript');
|
|
190
|
+
const callerRefUtxos = await this._resolveReferenceInputs(req.referenceInputs ?? [], allUtxos);
|
|
191
|
+
const referenceInputUtxos = mergeUtxosUnique(callerRefUtxos, refScriptUtxos);
|
|
192
|
+
const txContext = {
|
|
193
|
+
utxos: mergeUtxosUnique(allUtxos, forcedUtxos),
|
|
194
|
+
protocolParameters,
|
|
195
|
+
evaluateTransaction: cardanoClient.hasEvaluatingBackend()
|
|
196
|
+
? (cbor) => cardanoClient.evaluateTransaction(cbor)
|
|
197
|
+
: undefined,
|
|
198
|
+
referenceInputUtxos: referenceInputUtxos.length > 0 ? referenceInputUtxos : undefined,
|
|
199
|
+
};
|
|
200
|
+
logger.debug(`Prepared multi-script build context: ${senderUtxos.length} sender + ${scriptUtxos.length} script + ${forcedUtxos.length} forced UTxOs, ${referenceInputUtxos.length} reference inputs`);
|
|
201
|
+
return builder.buildUnsignedPlutusTransaction(req, txContext);
|
|
202
|
+
}
|
|
171
203
|
/**
|
|
172
204
|
* Resolve the script UTxO of a Plutus spend from the node's ledger, otherwise from its producing
|
|
173
205
|
* transaction. Spending an already-consumed script UTxO is the most common replay mistake —
|
|
174
206
|
* both paths reject it with a clear 400 instead of a node-side rejection at submit.
|
|
175
207
|
*/
|
|
176
208
|
async _resolveScriptUtxo(scriptRef) {
|
|
209
|
+
const by = this.client.pendingSpends?.spentBy(scriptRef.txHash, scriptRef.outputIndex);
|
|
210
|
+
if (by)
|
|
211
|
+
throw new errors_1.TransactionValidationError(`scriptUtxo ${outRefKey(scriptRef)} is spent by transaction ${by}, submitted and not yet on chain`);
|
|
177
212
|
const ledger = await this._lookupUnspent([scriptRef]);
|
|
178
213
|
if (ledger) {
|
|
179
214
|
const live = ledger.get(outRefKey(scriptRef));
|
|
@@ -257,6 +292,11 @@ class CardanoTransactionBuilder {
|
|
|
257
292
|
async _resolveInputRefs(refs, knownUtxos, kind) {
|
|
258
293
|
if (!refs || refs.length === 0)
|
|
259
294
|
return [];
|
|
295
|
+
for (const r of refs) {
|
|
296
|
+
const by = this.client.pendingSpends?.spentBy(r.txHash, r.outputIndex);
|
|
297
|
+
if (by)
|
|
298
|
+
throw new errors_1.TransactionValidationError(`${kind} ${r.txHash}#${r.outputIndex} is spent by transaction ${by}, submitted and not yet on chain`);
|
|
299
|
+
}
|
|
260
300
|
// Dedup by "txHash#index" key
|
|
261
301
|
const seen = new Set();
|
|
262
302
|
const dedupedRefs = refs.filter(r => {
|
|
@@ -315,10 +355,25 @@ class CardanoTransactionBuilder {
|
|
|
315
355
|
/** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
|
|
316
356
|
async _fetchUtxosForAddress(address) {
|
|
317
357
|
logger.debug(`Fetching UTxOs for address: ${address}`);
|
|
318
|
-
|
|
358
|
+
// The crawled set answers with an index lookup; the node's address query scans its whole
|
|
359
|
+
// UTxO set. An empty answer from the set is re-checked there (funded in the last block).
|
|
360
|
+
const local = await this.addressUtxoSource?.(address).catch((err) => {
|
|
361
|
+
logger.warn(`Local UTxO lookup for ${address} failed, asking the node: ${err instanceof Error ? err.message : String(err)}`);
|
|
362
|
+
return null;
|
|
363
|
+
});
|
|
364
|
+
const ledger = local && local.length > 0 ? local : await this.client.getAddressUtxos(address);
|
|
365
|
+
// the ledger view still lists what our own submitted transactions spend while they wait in the mempool
|
|
366
|
+
const all = this.client.pendingSpends?.apply(address, ledger) ?? ledger;
|
|
367
|
+
// A UTxO carrying a reference script is deployed on purpose, not change to spend; only a
|
|
368
|
+
// forced input consumes it (the fee of a spent reference script is also not counted by the builder).
|
|
369
|
+
const utxos = all.filter(u => !u.scriptRef && !u.scriptRefCbor);
|
|
370
|
+
if (utxos.length < all.length)
|
|
371
|
+
logger.debug(`${all.length - utxos.length} UTxO(s) with a reference script left out of coin selection`);
|
|
319
372
|
logger.debug(`Found ${utxos.length} UTxOs for address ${address.substring(0, 20)}...`);
|
|
320
373
|
if (utxos.length === 0) {
|
|
321
|
-
throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined,
|
|
374
|
+
throw new errors_1.InsufficientFundsError('lovelace', BigInt(0), BigInt(0), undefined, all.length > 0
|
|
375
|
+
? `address ${address} holds only UTxOs with a reference script — they are not spent as funding; pass one in forceInputsJson to consume it`
|
|
376
|
+
: `address ${address} has no UTxOs — verify this is the correct sender address and that it has been funded`);
|
|
322
377
|
}
|
|
323
378
|
return utxos;
|
|
324
379
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Transaction as CapTransaction } from '@sap/cds';
|
|
2
2
|
import type { CardanoClient } from '../cardano-client';
|
|
3
3
|
import type { ChainPoint } from '../backends/cardano-backend';
|
|
4
|
+
import type { BlockData, Transaction } from '../../utils/types';
|
|
4
5
|
/**
|
|
5
6
|
* Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
|
|
6
7
|
* holds, from a second chain-sync stream. Only those two tables are written, keyed so a
|
|
@@ -41,5 +42,26 @@ export interface CertificateBackfillResult extends CertificateBackfillProgress {
|
|
|
41
42
|
* they may lie far back or on a fork the node no longer knows.
|
|
42
43
|
*/
|
|
43
44
|
export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
|
|
45
|
+
/** One streamed block of a backfill, with what the collector took from it. */
|
|
46
|
+
export interface StreamedBlock<T> {
|
|
47
|
+
hash: string;
|
|
48
|
+
slot: number;
|
|
49
|
+
transactions: number;
|
|
50
|
+
payload: T;
|
|
51
|
+
}
|
|
52
|
+
export interface CrawledBlockStreamOptions {
|
|
53
|
+
client: CardanoClient;
|
|
54
|
+
fromSlot: number;
|
|
55
|
+
toSlot: number;
|
|
56
|
+
batchBlocks?: number;
|
|
57
|
+
/** Error class the range and backend checks throw. */
|
|
58
|
+
errorType?: new (message: string) => Error;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
|
|
62
|
+
* batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
|
|
63
|
+
* the index does not know (rolled back since) is skipped. Returns the intersection used.
|
|
64
|
+
*/
|
|
65
|
+
export declare function streamCrawledBlocks<T>(opts: CrawledBlockStreamOptions, collect: (block: BlockData, txs: Transaction[]) => T, writeBatch: (tx: CapTransaction, blocks: StreamedBlock<T>[]) => Promise<void>, afterBatch: (toSlot: number) => void): Promise<ChainPoint | 'origin'>;
|
|
44
66
|
export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
|
|
45
67
|
//# sourceMappingURL=certificate-backfill.d.ts.map
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.CertificateBackfillError = void 0;
|
|
7
7
|
exports.intersectionBefore = intersectionBefore;
|
|
8
|
+
exports.streamCrawledBlocks = streamCrawledBlocks;
|
|
8
9
|
exports.backfillCertificates = backfillCertificates;
|
|
9
10
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
11
|
const mappers_1 = require("../../utils/mappers");
|
|
@@ -42,23 +43,27 @@ async function intersectionBefore(db, slot) {
|
|
|
42
43
|
return { slot: floor, hash: cursor.startBlockHash };
|
|
43
44
|
return 'origin';
|
|
44
45
|
}
|
|
45
|
-
|
|
46
|
+
/**
|
|
47
|
+
* Streams the crawled range `fromSlot..toSlot` over a second chain-sync connection and hands
|
|
48
|
+
* batches of blocks the index holds to `writeBatch`, each in its own DB transaction. A block
|
|
49
|
+
* the index does not know (rolled back since) is skipped. Returns the intersection used.
|
|
50
|
+
*/
|
|
51
|
+
async function streamCrawledBlocks(opts, collect, writeBatch, afterBatch) {
|
|
46
52
|
const { client, fromSlot, toSlot } = opts;
|
|
53
|
+
const Err = opts.errorType ?? CertificateBackfillError;
|
|
47
54
|
if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
|
|
48
|
-
throw new
|
|
55
|
+
throw new Err(`Invalid slot range ${fromSlot}..${toSlot}`);
|
|
49
56
|
}
|
|
50
57
|
const backend = client.getChainSyncBackend();
|
|
51
58
|
if (!backend)
|
|
52
|
-
throw new
|
|
59
|
+
throw new Err('No chain-sync backend available (the backfill streams from Ogmios).');
|
|
53
60
|
const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
|
|
54
61
|
const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
|
|
55
62
|
const points = intersection === 'origin' ? 'origin' : [intersection];
|
|
56
|
-
const progress = { atSlot: intersection === 'origin' ? 0 : intersection.slot, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
|
|
57
63
|
let pending = [];
|
|
58
64
|
/**
|
|
59
65
|
* Writes a batch: the index's blocks of the batch's slot range are read once (a sequential
|
|
60
|
-
* index range, not one random lookup per block) and only
|
|
61
|
-
* are written; a block it never had (rolled back since) is skipped.
|
|
66
|
+
* index range, not one random lookup per block) and only blocks the index holds are passed on.
|
|
62
67
|
*/
|
|
63
68
|
const flush = async () => {
|
|
64
69
|
if (!pending.length)
|
|
@@ -69,26 +74,15 @@ async function backfillCertificates(opts) {
|
|
|
69
74
|
await cds_1.default.tx(async (tx) => {
|
|
70
75
|
const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
|
|
71
76
|
const known = new Set(rows.map((r) => r.hash));
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
withdrawals.push(...b.withdrawals);
|
|
80
|
-
progress.blocks++;
|
|
81
|
-
progress.transactions += b.transactions;
|
|
82
|
-
progress.certificates += b.certs.length;
|
|
83
|
-
progress.withdrawals += b.withdrawals.length;
|
|
84
|
-
}
|
|
85
|
-
if (certs.length)
|
|
86
|
-
await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
|
|
87
|
-
if (withdrawals.length)
|
|
88
|
-
await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
|
|
77
|
+
const held = batch.filter((b) => {
|
|
78
|
+
if (known.has(b.hash))
|
|
79
|
+
return true;
|
|
80
|
+
logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
|
|
81
|
+
return false;
|
|
82
|
+
});
|
|
83
|
+
await writeBatch(tx, held);
|
|
89
84
|
});
|
|
90
|
-
|
|
91
|
-
opts.onProgress?.({ ...progress });
|
|
85
|
+
afterBatch(toBatch);
|
|
92
86
|
};
|
|
93
87
|
let handle = null;
|
|
94
88
|
let settled = false;
|
|
@@ -112,11 +106,7 @@ async function backfillCertificates(opts) {
|
|
|
112
106
|
}
|
|
113
107
|
if (slot < fromSlot)
|
|
114
108
|
return; // between the intersection and the range: skipped, not counted
|
|
115
|
-
pending.push({
|
|
116
|
-
hash: block.hash, slot, transactions: txs.length,
|
|
117
|
-
certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
|
|
118
|
-
withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
|
|
119
|
-
});
|
|
109
|
+
pending.push({ hash: block.hash, slot, transactions: txs.length, payload: collect(block, txs) });
|
|
120
110
|
if (pending.length >= batchBlocks)
|
|
121
111
|
await flush();
|
|
122
112
|
if (slot === toSlot)
|
|
@@ -144,6 +134,35 @@ async function backfillCertificates(opts) {
|
|
|
144
134
|
catch { /* best effort */ }
|
|
145
135
|
}
|
|
146
136
|
}
|
|
137
|
+
return intersection;
|
|
138
|
+
}
|
|
139
|
+
async function backfillCertificates(opts) {
|
|
140
|
+
const { fromSlot, toSlot } = opts;
|
|
141
|
+
const progress = { atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
|
|
142
|
+
let started = false;
|
|
143
|
+
const intersection = await streamCrawledBlocks(opts, (_block, txs) => ({
|
|
144
|
+
certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
|
|
145
|
+
withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
|
|
146
|
+
}), async (tx, blocks) => {
|
|
147
|
+
const certs = blocks.flatMap((b) => b.payload.certs);
|
|
148
|
+
const withdrawals = blocks.flatMap((b) => b.payload.withdrawals);
|
|
149
|
+
for (const b of blocks) {
|
|
150
|
+
progress.blocks++;
|
|
151
|
+
progress.transactions += b.transactions;
|
|
152
|
+
}
|
|
153
|
+
progress.certificates += certs.length;
|
|
154
|
+
progress.withdrawals += withdrawals.length;
|
|
155
|
+
if (certs.length)
|
|
156
|
+
await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
|
|
157
|
+
if (withdrawals.length)
|
|
158
|
+
await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
|
|
159
|
+
}, (atSlot) => {
|
|
160
|
+
started = true;
|
|
161
|
+
progress.atSlot = atSlot;
|
|
162
|
+
opts.onProgress?.({ ...progress });
|
|
163
|
+
});
|
|
164
|
+
if (!started)
|
|
165
|
+
progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
|
|
147
166
|
logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals`);
|
|
148
167
|
return { ...progress, fromSlot, toSlot, intersection };
|
|
149
168
|
}
|
|
@@ -115,6 +115,8 @@ export declare class CardanoCrawler {
|
|
|
115
115
|
private snapshotRetryAfter;
|
|
116
116
|
private leaseHeld;
|
|
117
117
|
private leaseHeartbeat;
|
|
118
|
+
/** Last successful lease renewal by a block commit (epoch ms). */
|
|
119
|
+
private leaseRenewedAt;
|
|
118
120
|
private leaseWake;
|
|
119
121
|
constructor(client: CardanoClient, indexer: CardanoIndexer, network: string, config: CrawlerConfig,
|
|
120
122
|
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
@@ -217,7 +219,7 @@ export declare class CardanoCrawler {
|
|
|
217
219
|
* untouched), reset the cursor to the fork and write a CardanoReorgLog row.
|
|
218
220
|
*/
|
|
219
221
|
private handleReorg;
|
|
220
|
-
/** Renew the lease while
|
|
222
|
+
/** Renew the lease while no block commits; block writes renew it transactionally. */
|
|
221
223
|
private startLeaseHeartbeat;
|
|
222
224
|
/** Whether a persist error is deterministic for the block's data (see DATA_REJECTION_PATTERNS). */
|
|
223
225
|
static isDataRejection(err: unknown): boolean;
|
|
@@ -101,6 +101,8 @@ class CardanoCrawler {
|
|
|
101
101
|
snapshotRetryAfter = 0;
|
|
102
102
|
leaseHeld = false;
|
|
103
103
|
leaseHeartbeat = null;
|
|
104
|
+
/** Last successful lease renewal by a block commit (epoch ms). */
|
|
105
|
+
leaseRenewedAt = 0;
|
|
104
106
|
leaseWake = null;
|
|
105
107
|
constructor(client, indexer, network, config,
|
|
106
108
|
/** Present for production instances created by index.ts; omitted in engine unit tests. */
|
|
@@ -735,18 +737,18 @@ class CardanoCrawler {
|
|
|
735
737
|
return false;
|
|
736
738
|
try {
|
|
737
739
|
await cds_1.default.tx(async (tx) => {
|
|
738
|
-
if (this.leaseOwner) {
|
|
739
|
-
const renewed = await (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner);
|
|
740
|
-
if (!renewed)
|
|
741
|
-
throw new CrawlerLeaseLostError();
|
|
742
|
-
}
|
|
743
740
|
await this.indexer.indexBlockFull(tx, block, txs);
|
|
744
741
|
// Ledger progress marker: written in the same statement as the cursor, so "the
|
|
745
742
|
// cursor is ahead of the marker" always means blocks went by without the set.
|
|
746
743
|
const anchor = this.indexer.getUtxoAnchor();
|
|
747
744
|
const ledgerApplied = anchor != null && (block.slot ?? 0) > anchor.slot;
|
|
748
|
-
|
|
745
|
+
// The cursor UPDATE also renews and fences the lease; a lost lease rolls the block back.
|
|
746
|
+
const leaseHeld = await (0, sync_state_1.advanceCursor)(tx, { slot: block.slot ?? 0, hash: block.hash, height: block.height ?? 0 }, tip ? { slot: tip.slot, height: tip.height } : undefined, isAtTip ? 'synced' : 'syncing', ledgerApplied ? { utxoAppliedSlot: block.slot ?? 0 } : undefined, this.leaseOwner);
|
|
747
|
+
if (!leaseHeld)
|
|
748
|
+
throw new CrawlerLeaseLostError();
|
|
749
749
|
});
|
|
750
|
+
this.leaseRenewedAt = Date.now();
|
|
751
|
+
this.indexer.confirmBlockCommit();
|
|
750
752
|
if (CardanoCrawler.poison?.hash === block.hash)
|
|
751
753
|
CardanoCrawler.poison = null;
|
|
752
754
|
// A ledger invalidation decided inside the block transaction takes effect in memory
|
|
@@ -982,7 +984,7 @@ class CardanoCrawler {
|
|
|
982
984
|
(0, hooks_1.emitReorg)({ forkSlot, forkHeight: emittedForkHeight, blocksRolledBack });
|
|
983
985
|
logger.warn(`Reorg handled: rolled back ${blocksRolledBack} blocks (${txsRolledBack} txs) to slot ${forkSlot}`);
|
|
984
986
|
}
|
|
985
|
-
/** Renew the lease while
|
|
987
|
+
/** Renew the lease while no block commits; block writes renew it transactionally. */
|
|
986
988
|
startLeaseHeartbeat() {
|
|
987
989
|
if (!this.leaseOwner || this.leaseHeartbeat)
|
|
988
990
|
return;
|
|
@@ -992,6 +994,9 @@ class CardanoCrawler {
|
|
|
992
994
|
await this.leaseSleep(intervalMs);
|
|
993
995
|
if (!this.running)
|
|
994
996
|
return;
|
|
997
|
+
// Block commits renew the lease; the heartbeat only covers idle stretches.
|
|
998
|
+
if (Date.now() - this.leaseRenewedAt < intervalMs)
|
|
999
|
+
continue;
|
|
995
1000
|
try {
|
|
996
1001
|
const renewed = await cds_1.default.tx((tx) => (0, sync_state_1.renewCrawlerLease)(tx, this.leaseOwner));
|
|
997
1002
|
if (!renewed) {
|
|
@@ -81,13 +81,15 @@ export declare function latchPoisonBlock(db: CapTransaction, message: string): P
|
|
|
81
81
|
/**
|
|
82
82
|
* Advance the cursor to a freshly indexed block, clear the error streak and optionally
|
|
83
83
|
* record the latest known tip. Pass status 'synced' when the block is at the tip.
|
|
84
|
+
* With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
|
|
85
|
+
* @returns false when the lease is no longer held; the caller must roll back
|
|
84
86
|
*/
|
|
85
87
|
export declare function advanceCursor(db: CapTransaction, block: CrawlPoint, tip?: {
|
|
86
88
|
slot: number;
|
|
87
89
|
height?: number;
|
|
88
90
|
}, status?: CrawlSyncStatusValue,
|
|
89
91
|
/** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
|
|
90
|
-
extra?: Record<string, unknown
|
|
92
|
+
extra?: Record<string, unknown>, leaseOwner?: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
91
93
|
/**
|
|
92
94
|
* Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
|
|
93
95
|
* instance and a second import are refused while it is held. Does not require `desiredRunning`.
|
|
@@ -229,10 +229,12 @@ async function latchPoisonBlock(db, message) {
|
|
|
229
229
|
/**
|
|
230
230
|
* Advance the cursor to a freshly indexed block, clear the error streak and optionally
|
|
231
231
|
* record the latest known tip. Pass status 'synced' when the block is at the tip.
|
|
232
|
+
* With `leaseOwner` the same UPDATE renews and fences the crawler lease (see renewCrawlerLease).
|
|
233
|
+
* @returns false when the lease is no longer held; the caller must roll back
|
|
232
234
|
*/
|
|
233
235
|
async function advanceCursor(db, block, tip, status = 'syncing',
|
|
234
236
|
/** Extra cursor columns written in the same statement (e.g. the ledger's `utxoAppliedSlot`). */
|
|
235
|
-
extra) {
|
|
237
|
+
extra, leaseOwner, now = new Date(), ttlMs = exports.CRAWLER_LEASE_TTL_MS) {
|
|
236
238
|
const set = {
|
|
237
239
|
lastSlot: block.slot,
|
|
238
240
|
lastBlockHash: block.hash,
|
|
@@ -248,7 +250,18 @@ extra) {
|
|
|
248
250
|
if (tip.height !== undefined)
|
|
249
251
|
set.tipHeight = tip.height;
|
|
250
252
|
}
|
|
251
|
-
|
|
253
|
+
if (!leaseOwner) {
|
|
254
|
+
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({ ID: exports.SINGLETON_ID }));
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
set.leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
|
|
258
|
+
await db.run(UPDATE.entity(cardano_1.CardanoSyncState).set(set).where({
|
|
259
|
+
ID: exports.SINGLETON_ID,
|
|
260
|
+
leaseOwner,
|
|
261
|
+
desiredRunning: true,
|
|
262
|
+
}));
|
|
263
|
+
const verified = await readCursor(db);
|
|
264
|
+
return leaseDeadlineReached(verified, leaseOwner, now.getTime() + ttlMs);
|
|
252
265
|
}
|
|
253
266
|
/**
|
|
254
267
|
* Lease for the UTxO set import, on the crawler's lease columns: a crawler start on any
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Transaction as CapTransaction } from '@sap/cds';
|
|
2
|
+
import type { CardanoClient } from '../cardano-client';
|
|
3
|
+
import type { ChainPoint } from '../backends/cardano-backend';
|
|
4
|
+
import type { Transaction } from '../../utils/types';
|
|
5
|
+
import type { LedgerLookup } from '../ledger-state';
|
|
6
|
+
/**
|
|
7
|
+
* Completes transactions the crawl already holds from a second chain-sync stream: input
|
|
8
|
+
* outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
|
|
9
|
+
* hash, a missing input address, and the redeemers. Only empty input fields are filled; a
|
|
10
|
+
* transaction whose stored inputs do not line up with the stream is left as it is.
|
|
11
|
+
*/
|
|
12
|
+
export declare class TransactionBackfillError extends Error {
|
|
13
|
+
constructor(message: string);
|
|
14
|
+
}
|
|
15
|
+
export interface TransactionBackfillProgress {
|
|
16
|
+
/** Slot of the last block handled. */
|
|
17
|
+
atSlot: number;
|
|
18
|
+
blocks: number;
|
|
19
|
+
transactions: number;
|
|
20
|
+
/** Input rows that got at least one field. */
|
|
21
|
+
inputs: number;
|
|
22
|
+
redeemers: number;
|
|
23
|
+
/** Transactions whose stored rows differed from the ledger view (order, inputs or outputs the ledger did not apply) and were rewritten. */
|
|
24
|
+
rewritten: number;
|
|
25
|
+
/** Transactions left as they are: stored inputs differ from the stream. */
|
|
26
|
+
skipped: number;
|
|
27
|
+
}
|
|
28
|
+
/** Resolves bare chain-sync inputs from the index (CardanoIndexer.resolveInputs). */
|
|
29
|
+
export interface InputResolver {
|
|
30
|
+
resolveInputs(tx: CapTransaction, txs: Transaction[], ledger?: LedgerLookup): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
export interface TransactionBackfillOptions {
|
|
33
|
+
client: CardanoClient;
|
|
34
|
+
indexer: InputResolver;
|
|
35
|
+
fromSlot: number;
|
|
36
|
+
toSlot: number;
|
|
37
|
+
batchBlocks?: number;
|
|
38
|
+
onProgress?: (p: TransactionBackfillProgress) => void;
|
|
39
|
+
}
|
|
40
|
+
export interface TransactionBackfillResult extends TransactionBackfillProgress {
|
|
41
|
+
fromSlot: number;
|
|
42
|
+
toSlot: number;
|
|
43
|
+
intersection: ChainPoint | 'origin';
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
|
|
47
|
+
* COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
|
|
48
|
+
* UPDATE per row.
|
|
49
|
+
*/
|
|
50
|
+
export declare function inputFillStatement(kind: string): string | null;
|
|
51
|
+
export declare function backfillTransactions(opts: TransactionBackfillOptions): Promise<TransactionBackfillResult>;
|
|
52
|
+
//# sourceMappingURL=transaction-backfill.d.ts.map
|