@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40
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/CardanoAgentService/index.d.ts +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
- package/@cds-models/CardanoIndexerService/index.js +25 -0
- package/@cds-models/CardanoODataService/index.d.ts +305 -7
- package/@cds-models/CardanoODataService/index.js +34 -0
- package/@cds-models/CardanoSignService/index.d.ts +28 -3
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +72 -0
- package/@cds-models/index.js +12 -0
- package/@cds-models/odatano/cardano/index.d.ts +408 -7
- package/@cds-models/odatano/cardano/index.js +42 -0
- package/README.md +64 -5
- package/db/schema.cds +2297 -1633
- package/db/types.cds +114 -0
- package/package.json +27 -6
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +18 -11
- package/src/index.js +44 -14
- package/src/plugin.js +42 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +53 -162
- package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
- package/srv/blockchain/backends/cardano-backend.js +19 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +376 -235
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +170 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
- package/srv/blockchain/backends/ogmios-backend.js +556 -201
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +87 -202
- package/srv/blockchain/cardano-client.js +210 -240
- package/srv/blockchain/cardano-indexer.d.ts +311 -242
- package/srv/blockchain/cardano-indexer.js +1238 -362
- package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
- package/srv/blockchain/cardano-tx-builder.js +173 -132
- package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
- package/srv/blockchain/crawler/certificate-backfill.js +169 -0
- package/srv/blockchain/crawler/crawler.d.ts +139 -54
- package/srv/blockchain/crawler/crawler.js +478 -96
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +46 -28
- package/srv/blockchain/crawler/sync-state.js +128 -43
- 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 +78 -0
- package/srv/blockchain/crawler/utxo-set-import.js +363 -0
- package/srv/blockchain/ledger-state.d.ts +101 -0
- package/srv/blockchain/ledger-state.js +432 -0
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
- package/srv/blockchain/signing/signature-verifier.js +73 -76
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -49
- 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 +111 -173
- package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
- package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
- package/srv/blockchain/transaction-building/caller-datums.js +139 -0
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +43 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +18 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- 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 -73
- package/srv/cardano-indexer-service.js +280 -11
- package/srv/cardano-service.cds +65 -2
- package/srv/cardano-service.js +170 -129
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +57 -184
- package/srv/cardano-tx-service.cds +439 -370
- package/srv/cardano-tx-service.js +231 -190
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.js +7 -15
- package/srv/cbor/index.d.ts +1 -1
- package/srv/cbor/parse.d.ts +27 -0
- package/srv/cbor/parse.js +63 -2
- package/srv/server.d.ts +28 -86
- package/srv/server.js +132 -135
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +922 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +30 -67
- package/srv/utils/const.js +32 -72
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +94 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/epoch-slots.d.ts +20 -0
- package/srv/utils/epoch-slots.js +43 -0
- package/srv/utils/error-codes.d.ts +20 -73
- package/srv/utils/error-codes.js +19 -70
- package/srv/utils/errors.d.ts +50 -177
- package/srv/utils/errors.js +94 -218
- package/srv/utils/legacy-service-paths.d.ts +11 -0
- package/srv/utils/legacy-service-paths.js +58 -0
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +40 -0
- package/srv/utils/mappers.d.ts +128 -214
- package/srv/utils/mappers.js +354 -299
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +62 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +56 -0
- package/srv/utils/plutus-placeholders.d.ts +23 -16
- package/srv/utils/plutus-placeholders.js +63 -27
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +6 -16
- package/srv/utils/signing-helper.js +36 -60
- package/srv/utils/tx-build-helper.d.ts +28 -93
- package/srv/utils/tx-build-helper.js +75 -124
- package/srv/utils/tx-request-parsers.d.ts +101 -28
- package/srv/utils/tx-request-parsers.js +410 -43
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +252 -179
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +24 -90
- package/srv/utils/validators.js +50 -147
|
@@ -0,0 +1,283 @@
|
|
|
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.TransactionBackfillError = void 0;
|
|
7
|
+
exports.inputFillStatement = inputFillStatement;
|
|
8
|
+
exports.backfillTransactions = backfillTransactions;
|
|
9
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
|
+
const mappers_1 = require("../../utils/mappers");
|
|
11
|
+
const collections_1 = require("../../utils/collections");
|
|
12
|
+
const certificate_backfill_1 = require("./certificate-backfill");
|
|
13
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
14
|
+
const { SELECT, UPDATE, UPSERT, DELETE } = cds_1.default.ql;
|
|
15
|
+
const logger = cds_1.default.log('TransactionBackfill');
|
|
16
|
+
/**
|
|
17
|
+
* Completes transactions the crawl already holds from a second chain-sync stream: input
|
|
18
|
+
* outpoints (spentTxHash / spentOutputIndex), the spent output's datum and reference-script
|
|
19
|
+
* hash, a missing input address, and the redeemers. Only empty input fields are filled; a
|
|
20
|
+
* transaction whose stored inputs do not line up with the stream is left as it is.
|
|
21
|
+
*/
|
|
22
|
+
class TransactionBackfillError extends Error {
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'TransactionBackfillError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.TransactionBackfillError = TransactionBackfillError;
|
|
29
|
+
const key = (txSeq, inputIndex) => `${Number(txSeq)}#${Number(inputIndex)}`;
|
|
30
|
+
const lovelaceOf = (i) => i.amount?.find((a) => a.unit === 'lovelace')?.quantity ?? null;
|
|
31
|
+
/**
|
|
32
|
+
* Stored input and streamed input describe the same outpoint: same flags, same outpoint where
|
|
33
|
+
* one is stored, same address and lovelace where both sides know them. A stored address the
|
|
34
|
+
* stream cannot resolve is unverifiable, so it does not match.
|
|
35
|
+
*/
|
|
36
|
+
function sameInput(row, fresh, storedLovelace) {
|
|
37
|
+
if (Boolean(row.isCollateral) !== Boolean(fresh.isCollateral) || Boolean(row.isReference) !== Boolean(fresh.isReference))
|
|
38
|
+
return false;
|
|
39
|
+
if (row.spentTxHash != null) {
|
|
40
|
+
return row.spentTxHash === fresh.txHash && Number(row.spentOutputIndex) === fresh.outputIndex;
|
|
41
|
+
}
|
|
42
|
+
if (!row.address_address)
|
|
43
|
+
return true;
|
|
44
|
+
if (!fresh.address)
|
|
45
|
+
return false;
|
|
46
|
+
if (row.address_address !== fresh.address)
|
|
47
|
+
return false;
|
|
48
|
+
const freshLovelace = lovelaceOf(fresh);
|
|
49
|
+
return storedLovelace == null || freshLovelace == null || String(storedLovelace) === String(freshLovelace);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Stored rows in the stream's order when they hold the same outpoints with the same flags, each
|
|
53
|
+
* once; null otherwise (a row without outpoint cannot be placed).
|
|
54
|
+
*/
|
|
55
|
+
function reorderByOutpoint(rows, fresh) {
|
|
56
|
+
if (rows.length !== fresh.length || rows.some((r) => r.spentTxHash == null))
|
|
57
|
+
return null;
|
|
58
|
+
const byOutpoint = new Map();
|
|
59
|
+
for (const r of rows) {
|
|
60
|
+
const k = `${r.spentTxHash}#${Number(r.spentOutputIndex)}#${Boolean(r.isCollateral)}#${Boolean(r.isReference)}`;
|
|
61
|
+
byOutpoint.set(k, [...(byOutpoint.get(k) ?? []), r]);
|
|
62
|
+
}
|
|
63
|
+
const ordered = [];
|
|
64
|
+
for (const f of fresh) {
|
|
65
|
+
const k = `${f.txHash}#${f.outputIndex}#${Boolean(f.isCollateral)}#${Boolean(f.isReference)}`;
|
|
66
|
+
const r = byOutpoint.get(k)?.shift();
|
|
67
|
+
if (!r)
|
|
68
|
+
return null;
|
|
69
|
+
ordered.push(r);
|
|
70
|
+
}
|
|
71
|
+
return ordered;
|
|
72
|
+
}
|
|
73
|
+
/** Columns of `row` that are empty and `fresh` can fill. */
|
|
74
|
+
function missingFields(row, fresh) {
|
|
75
|
+
const set = {};
|
|
76
|
+
if (row.spentTxHash == null && fresh.txHash) {
|
|
77
|
+
set.spentTxHash = fresh.txHash;
|
|
78
|
+
set.spentOutputIndex = fresh.outputIndex;
|
|
79
|
+
}
|
|
80
|
+
if (row.utxoData_dataHash == null && fresh.dataHash)
|
|
81
|
+
set.utxoData_dataHash = fresh.dataHash;
|
|
82
|
+
if (row.utxoData_inlineDatum == null && fresh.inlineDatum)
|
|
83
|
+
set.utxoData_inlineDatum = fresh.inlineDatum;
|
|
84
|
+
if (row.utxoData_referenceScriptHash == null && fresh.referenceScriptHash)
|
|
85
|
+
set.utxoData_referenceScriptHash = fresh.referenceScriptHash;
|
|
86
|
+
if (!row.address_address && fresh.address) {
|
|
87
|
+
set.address_address = fresh.address;
|
|
88
|
+
set.hasAddresses = true;
|
|
89
|
+
set.hasAssets = (fresh.amount ?? []).length > 0;
|
|
90
|
+
}
|
|
91
|
+
return set;
|
|
92
|
+
}
|
|
93
|
+
const INPUTS_TABLE = 'odatano_cardano_TransactionInputs';
|
|
94
|
+
/** Rows per statement; one JSON parameter each. */
|
|
95
|
+
const FILL_CHUNK = 5000;
|
|
96
|
+
/** Fill columns in the order the JSON records and the SET list use them. */
|
|
97
|
+
const FILL_COLUMNS = [
|
|
98
|
+
['spentTxHash', 'text'],
|
|
99
|
+
['spentOutputIndex', 'integer'],
|
|
100
|
+
['utxoData_dataHash', 'text'],
|
|
101
|
+
['utxoData_inlineDatum', 'text'],
|
|
102
|
+
['utxoData_referenceScriptHash', 'text'],
|
|
103
|
+
['address_address', 'text'],
|
|
104
|
+
['hasAddresses', 'boolean'],
|
|
105
|
+
['hasAssets', 'boolean'],
|
|
106
|
+
];
|
|
107
|
+
/**
|
|
108
|
+
* One UPDATE per chunk: the fills travel as a JSON array and are joined on (txSeq, inputIndex).
|
|
109
|
+
* COALESCE keeps any value that is already there. Postgres and SQLite; other databases get one
|
|
110
|
+
* UPDATE per row.
|
|
111
|
+
*/
|
|
112
|
+
function inputFillStatement(kind) {
|
|
113
|
+
const set = FILL_COLUMNS
|
|
114
|
+
.map(([c]) => c.startsWith('has')
|
|
115
|
+
? `${c} = CASE WHEN v.address_address IS NOT NULL AND t.address_address IS NULL THEN v.${c} ELSE t.${c} END`
|
|
116
|
+
: `${c} = COALESCE(t.${c}, v.${c})`)
|
|
117
|
+
.join(', ');
|
|
118
|
+
if (kind === 'postgres') {
|
|
119
|
+
const cols = [['txSeq', 'bigint'], ['inputIndex', 'integer'], ...FILL_COLUMNS].map(([c, ty]) => `${c.toLowerCase()} ${ty}`).join(', ');
|
|
120
|
+
return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM json_to_recordset($1::json) AS v(${cols}) ` +
|
|
121
|
+
'WHERE t.txSeq = v.txseq AND t.inputIndex = v.inputindex';
|
|
122
|
+
}
|
|
123
|
+
if (kind === 'sqlite' || kind === 'better-sqlite') {
|
|
124
|
+
const cols = ['txSeq', 'inputIndex', ...FILL_COLUMNS.map(([c]) => c)]
|
|
125
|
+
.map((c) => `json_extract(value, '$.${c.toLowerCase()}') AS ${c}`).join(', ');
|
|
126
|
+
return `UPDATE ${INPUTS_TABLE} AS t SET ${set} FROM (SELECT ${cols} FROM json_each(?)) AS v ` +
|
|
127
|
+
'WHERE t.txSeq = v.txSeq AND t.inputIndex = v.inputIndex';
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
/** Writes the fills of a batch: bulk statement where the database has one, else row by row. */
|
|
132
|
+
async function writeInputFills(tx, fills) {
|
|
133
|
+
if (!fills.length)
|
|
134
|
+
return;
|
|
135
|
+
const sql = inputFillStatement(cds_1.default.db?.kind ?? '');
|
|
136
|
+
if (!sql) {
|
|
137
|
+
for (const f of fills)
|
|
138
|
+
await tx.run(UPDATE.entity(cardano_1.TransactionInputs).set(f.set).where({ txSeq: f.txSeq, inputIndex: f.inputIndex }));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
for (const part of (0, collections_1.chunk)(fills, FILL_CHUNK)) {
|
|
142
|
+
const records = part.map((f) => {
|
|
143
|
+
const r = { txseq: f.txSeq, inputindex: f.inputIndex };
|
|
144
|
+
for (const [c] of FILL_COLUMNS)
|
|
145
|
+
r[c.toLowerCase()] = f.set[c] ?? null;
|
|
146
|
+
return r;
|
|
147
|
+
});
|
|
148
|
+
await tx.run(sql, [JSON.stringify(records)]);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Rewrites the input rows of one transaction as the ledger view: the kept rows (and their assets)
|
|
153
|
+
* move to their position, rows left out are dropped, empty fields are filled on the way.
|
|
154
|
+
*/
|
|
155
|
+
async function rewriteInOrder(tx, seq, ordered, fresh) {
|
|
156
|
+
const assets = (await tx.run(SELECT.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }))) ?? [];
|
|
157
|
+
const newIndex = new Map(ordered.map((r, i) => [Number(r.inputIndex), i]));
|
|
158
|
+
const rows = ordered.map((r, i) => ({ ...r, ...missingFields(r, fresh[i]), txSeq: seq, inputIndex: i }));
|
|
159
|
+
// assets of rows the ledger view drops go with them
|
|
160
|
+
const movedAssets = assets
|
|
161
|
+
.filter((a) => newIndex.has(Number(a.input_inputIndex)))
|
|
162
|
+
.map((a) => ({ ...a, input_txSeq: seq, input_inputIndex: newIndex.get(Number(a.input_inputIndex)) }));
|
|
163
|
+
await tx.run(DELETE.from(cardano_1.TransactionInputAssets).where({ input_txSeq: seq }));
|
|
164
|
+
await tx.run(DELETE.from(cardano_1.TransactionInputs).where({ txSeq: seq }));
|
|
165
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputs).entries(rows));
|
|
166
|
+
if (movedAssets.length)
|
|
167
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(movedAssets));
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Deletes stored outputs the ledger never produced: a provider lists the collateral return of a
|
|
171
|
+
* valid transaction, and the declared outputs of a phase-2 failure. Only when every output of the
|
|
172
|
+
* stream is stored, so a gap is never mistaken for an extra. Returns the transactions touched.
|
|
173
|
+
*/
|
|
174
|
+
async function dropUnappliedOutputs(tx, txs) {
|
|
175
|
+
const wanted = new Map(txs.map((t) => [(0, mappers_1.txSeqOf)(t.slot, t.index), new Set((t.outputs ?? []).map((o) => o.outputIndex))]));
|
|
176
|
+
const stored = new Map();
|
|
177
|
+
for (const seqChunk of (0, collections_1.chunk)([...wanted.keys()], collections_1.IN_CHUNK)) {
|
|
178
|
+
const rows = (await tx.run(SELECT.from(cardano_1.TransactionOutputs).columns('txSeq', 'outputIndex').where({ txSeq: { in: seqChunk } })));
|
|
179
|
+
for (const r of rows ?? [])
|
|
180
|
+
stored.set(Number(r.txSeq), [...(stored.get(Number(r.txSeq)) ?? []), Number(r.outputIndex)]);
|
|
181
|
+
}
|
|
182
|
+
const touched = [];
|
|
183
|
+
for (const [seq, indices] of stored) {
|
|
184
|
+
const keep = wanted.get(seq);
|
|
185
|
+
const extra = indices.filter((i) => !keep.has(i));
|
|
186
|
+
if (!extra.length || [...keep].some((i) => !indices.includes(i)))
|
|
187
|
+
continue;
|
|
188
|
+
await tx.run(DELETE.from(cardano_1.TransactionOutputAssets).where({ output_txSeq: seq, output_outputIndex: { in: extra } }));
|
|
189
|
+
await tx.run(DELETE.from(cardano_1.TransactionOutputs).where({ txSeq: seq, outputIndex: { in: extra } }));
|
|
190
|
+
touched.push(seq);
|
|
191
|
+
}
|
|
192
|
+
return touched;
|
|
193
|
+
}
|
|
194
|
+
async function backfillTransactions(opts) {
|
|
195
|
+
const { fromSlot, toSlot, indexer } = opts;
|
|
196
|
+
const progress = { atSlot: 0, blocks: 0, transactions: 0, inputs: 0, redeemers: 0, rewritten: 0, skipped: 0 };
|
|
197
|
+
let started = false;
|
|
198
|
+
const intersection = await (0, certificate_backfill_1.streamCrawledBlocks)({ ...opts, errorType: TransactionBackfillError }, (_block, txs) => txs, async (tx, blocks) => {
|
|
199
|
+
const txs = blocks.flatMap((b) => b.payload);
|
|
200
|
+
progress.blocks += blocks.length;
|
|
201
|
+
progress.transactions += txs.length;
|
|
202
|
+
if (!txs.length)
|
|
203
|
+
return;
|
|
204
|
+
// the UTxO set rows answer too: they keep spent outputs, also those from before the crawl
|
|
205
|
+
await indexer.resolveInputs(tx, txs, { hashes: new Set(), rows: new Map(), assets: new Map() });
|
|
206
|
+
const seqs = txs.map((t) => (0, mappers_1.txSeqOf)(t.slot, t.index));
|
|
207
|
+
const stored = new Map();
|
|
208
|
+
const storedLovelace = new Map();
|
|
209
|
+
const storedCount = new Map();
|
|
210
|
+
const storedBySeq = new Map();
|
|
211
|
+
for (const seqChunk of (0, collections_1.chunk)(seqs, collections_1.IN_CHUNK)) {
|
|
212
|
+
const [rows, lovelace] = await Promise.all([
|
|
213
|
+
tx.run(SELECT.from(cardano_1.TransactionInputs).where({ txSeq: { in: seqChunk } })),
|
|
214
|
+
tx.run(SELECT.from(cardano_1.TransactionInputAssets).columns('input_txSeq', 'input_inputIndex', 'asset_quantity')
|
|
215
|
+
.where({ input_txSeq: { in: seqChunk }, unit: 'lovelace' })),
|
|
216
|
+
]);
|
|
217
|
+
for (const r of rows ?? []) {
|
|
218
|
+
stored.set(key(r.txSeq, r.inputIndex), r);
|
|
219
|
+
storedCount.set(String(Number(r.txSeq)), (storedCount.get(String(Number(r.txSeq))) ?? 0) + 1);
|
|
220
|
+
storedBySeq.set(String(Number(r.txSeq)), [...(storedBySeq.get(String(Number(r.txSeq))) ?? []), r]);
|
|
221
|
+
}
|
|
222
|
+
for (const a of lovelace ?? [])
|
|
223
|
+
storedLovelace.set(key(a.input_txSeq, a.input_inputIndex), String(a.asset_quantity));
|
|
224
|
+
}
|
|
225
|
+
const fills = [];
|
|
226
|
+
const assetRows = [];
|
|
227
|
+
const reorders = [];
|
|
228
|
+
const rewritten = new Set();
|
|
229
|
+
for (const t of txs) {
|
|
230
|
+
const seq = (0, mappers_1.txSeqOf)(t.slot, t.index);
|
|
231
|
+
const inputs = t.inputs ?? [];
|
|
232
|
+
const rows = inputs.map((_, i) => stored.get(key(seq, i)));
|
|
233
|
+
const lines = (storedCount.get(String(seq)) ?? 0) === inputs.length && rows.every((r, i) => r && sameInput(r, inputs[i], storedLovelace.get(key(seq, i)) ?? null));
|
|
234
|
+
if (!lines) {
|
|
235
|
+
// after a phase-2 failure the ledger applied no regular input: rows a provider stored for them go
|
|
236
|
+
const all = [...(storedBySeq.get(String(seq)) ?? [])].sort((a, b) => Number(a.inputIndex) - Number(b.inputIndex));
|
|
237
|
+
const kept = t.spendsCollaterals ? all.filter((r) => r.isCollateral || r.isReference) : all;
|
|
238
|
+
const inPlace = kept.length === inputs.length &&
|
|
239
|
+
kept.every((r, i) => sameInput(r, inputs[i], storedLovelace.get(key(seq, Number(r.inputIndex))) ?? null));
|
|
240
|
+
const ordered = inPlace ? kept : reorderByOutpoint(kept, inputs);
|
|
241
|
+
if (ordered) {
|
|
242
|
+
reorders.push({ seq, rows: ordered, inputs });
|
|
243
|
+
rewritten.add(seq);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
progress.skipped++;
|
|
247
|
+
logger.debug(`Transaction ${t.hash}: stored inputs differ from the stream — left as it is`);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
for (let i = 0; i < inputs.length; i++) {
|
|
251
|
+
const set = missingFields(rows[i], inputs[i]);
|
|
252
|
+
if (!Object.keys(set).length)
|
|
253
|
+
continue;
|
|
254
|
+
fills.push({ txSeq: seq, inputIndex: i, set });
|
|
255
|
+
if (set.address_address)
|
|
256
|
+
assetRows.push(...(0, mappers_1.mapTransactionInputAssets)(seq, inputs).filter((a) => a.input_inputIndex === i));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
await writeInputFills(tx, fills);
|
|
260
|
+
progress.inputs += fills.length;
|
|
261
|
+
if (assetRows.length)
|
|
262
|
+
await tx.run(UPSERT.into(cardano_1.TransactionInputAssets).entries(assetRows));
|
|
263
|
+
for (const r of reorders)
|
|
264
|
+
await rewriteInOrder(tx, r.seq, r.rows, r.inputs);
|
|
265
|
+
for (const seq of await dropUnappliedOutputs(tx, txs))
|
|
266
|
+
rewritten.add(seq);
|
|
267
|
+
progress.rewritten += rewritten.size;
|
|
268
|
+
const redeemerRows = txs.flatMap((t) => (0, mappers_1.mapTransactionRedeemers)(t.hash, t.redeemers ?? []));
|
|
269
|
+
progress.redeemers += redeemerRows.length;
|
|
270
|
+
if (redeemerRows.length)
|
|
271
|
+
await tx.run(UPSERT.into(cardano_1.TransactionRedeemers).entries(redeemerRows));
|
|
272
|
+
}, (atSlot) => {
|
|
273
|
+
started = true;
|
|
274
|
+
progress.atSlot = atSlot;
|
|
275
|
+
opts.onProgress?.({ ...progress });
|
|
276
|
+
});
|
|
277
|
+
if (!started)
|
|
278
|
+
progress.atSlot = intersection === 'origin' ? 0 : intersection.slot;
|
|
279
|
+
logger.info(`Transaction backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.inputs} inputs, ` +
|
|
280
|
+
`${progress.redeemers} redeemers, ${progress.rewritten} transactions rewritten, ${progress.skipped} skipped`);
|
|
281
|
+
return { ...progress, fromSlot, toSlot, intersection };
|
|
282
|
+
}
|
|
283
|
+
//# sourceMappingURL=transaction-backfill.js.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { CardanoClient } from '../cardano-client';
|
|
2
|
+
import type { CardanoIndexer } from '../cardano-indexer';
|
|
3
|
+
import type { Amount } from '../../utils/types';
|
|
4
|
+
import { type LedgerAnchor } from '../ledger-state';
|
|
5
|
+
/**
|
|
6
|
+
* One-off import of the UTxO set at the anchor `crawler.utxoSet` builds on: from Ogmios
|
|
7
|
+
* (`queryLedgerState/utxo` at the cursor point) or a `cardano-cli query utxo --whole-utxo`
|
|
8
|
+
* dump (`.json` parsed whole; `.ndjson`/`.jsonl` streamed, one entry or `{key,value}` per line).
|
|
9
|
+
*/
|
|
10
|
+
export declare class UtxoSetImportError extends Error {
|
|
11
|
+
constructor(message: string);
|
|
12
|
+
}
|
|
13
|
+
/** The cursor lease went to someone else: nothing more may be written, not even `invalid`. */
|
|
14
|
+
export declare class UtxoSetLeaseLostError extends UtxoSetImportError {
|
|
15
|
+
constructor(message?: string);
|
|
16
|
+
}
|
|
17
|
+
export interface UtxoSetEntry {
|
|
18
|
+
txHash: string;
|
|
19
|
+
outputIndex: number;
|
|
20
|
+
address: string;
|
|
21
|
+
amount: Amount[];
|
|
22
|
+
dataHash?: string | null;
|
|
23
|
+
inlineDatum?: string | null;
|
|
24
|
+
referenceScriptHash?: string | null;
|
|
25
|
+
}
|
|
26
|
+
export interface UtxoSetImportOptions {
|
|
27
|
+
source: 'ogmios' | 'file';
|
|
28
|
+
filePath?: string;
|
|
29
|
+
anchor: LedgerAnchor;
|
|
30
|
+
client: CardanoClient;
|
|
31
|
+
indexer: CardanoIndexer;
|
|
32
|
+
/** Rows per write transaction. */
|
|
33
|
+
batchSize?: number;
|
|
34
|
+
onProgress?: (imported: number) => void;
|
|
35
|
+
}
|
|
36
|
+
export interface UtxoSetImportResult {
|
|
37
|
+
utxos: number;
|
|
38
|
+
anchor: LedgerAnchor;
|
|
39
|
+
}
|
|
40
|
+
/** `cardano-cli query utxo` value: `{ lovelace: n, [policyId]: { [assetNameHex]: qty } }`. */
|
|
41
|
+
export interface CliUtxoValue {
|
|
42
|
+
address: string;
|
|
43
|
+
value: Record<string, number | string | Record<string, number | string>>;
|
|
44
|
+
datumhash?: string | null;
|
|
45
|
+
datumHash?: string | null;
|
|
46
|
+
inlineDatumRaw?: string | null;
|
|
47
|
+
referenceScript?: unknown;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* `JSON.parse` for a cardano-cli dump that keeps every integer exact: integer literals outside
|
|
51
|
+
* strings are quoted before parsing, so a quantity above 2^53 is never rounded.
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseJsonLossless<T = unknown>(text: string): T;
|
|
54
|
+
/** Parse one `"txHash#index": {…}` entry of a cardano-cli dump; null when malformed. */
|
|
55
|
+
export declare function parseCliUtxoEntry(key: string, value: CliUtxoValue | null | undefined): UtxoSetEntry | null;
|
|
56
|
+
/** Stream a cardano-cli dump. See the module doc for the accepted layouts. */
|
|
57
|
+
export declare function readUtxoSetFile(filePath: string): AsyncGenerator<UtxoSetEntry>;
|
|
58
|
+
/**
|
|
59
|
+
* The three aggregate statements that derive the running sums from the imported rows.
|
|
60
|
+
* Plain SQL because millions of addresses do not fit an in-memory map and a per-row
|
|
61
|
+
* UPSERT would take hours; the syntax is the portable subset (sqlite, PostgreSQL, HANA).
|
|
62
|
+
*/
|
|
63
|
+
export declare function aggregateStatements(): string[];
|
|
64
|
+
/**
|
|
65
|
+
* Run the import. Throws `UtxoSetImportError` on a precondition failure before anything is
|
|
66
|
+
* written; a failure mid-way leaves the set marked `invalid` (never half-`active`).
|
|
67
|
+
*/
|
|
68
|
+
export declare function importUtxoSet(opts: UtxoSetImportOptions): Promise<UtxoSetImportResult>;
|
|
69
|
+
/**
|
|
70
|
+
* Rebuild only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an
|
|
71
|
+
* earlier import left at the stored anchor, e.g. after the aggregate phase failed. Nothing may have
|
|
72
|
+
* been applied since the anchor; a cursor past it is set back to the anchor, and the blocks after
|
|
73
|
+
* it are crawled again (idempotent writes) so the set follows them.
|
|
74
|
+
*/
|
|
75
|
+
export declare function rebuildUtxoSetAggregates(opts: {
|
|
76
|
+
indexer: CardanoIndexer;
|
|
77
|
+
}): Promise<UtxoSetImportResult>;
|
|
78
|
+
//# sourceMappingURL=utxo-set-import.d.ts.map
|