@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
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 +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.buildLedgerUtxoRows = buildLedgerUtxoRows;
|
|
7
|
+
exports.readLedgerOutputs = readLedgerOutputs;
|
|
8
|
+
exports.ledgerRowAmount = ledgerRowAmount;
|
|
9
|
+
exports.applyBlockToLedger = applyBlockToLedger;
|
|
10
|
+
exports.undoLedgerForTransactions = undoLedgerForTransactions;
|
|
11
|
+
exports.recountLedgerAddresses = recountLedgerAddresses;
|
|
12
|
+
exports.recountLedgerAccounts = recountLedgerAccounts;
|
|
13
|
+
exports.backfillPaymentCredentials = backfillPaymentCredentials;
|
|
14
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
15
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
16
|
+
const mappers_1 = require("../utils/mappers");
|
|
17
|
+
const collections_1 = require("../utils/collections");
|
|
18
|
+
const { SELECT, UPSERT, UPDATE, DELETE } = cds_1.default.ql;
|
|
19
|
+
const logger = cds_1.default.log('LedgerState');
|
|
20
|
+
const outpoint = (txHash, outputIndex) => `${txHash}#${outputIndex}`;
|
|
21
|
+
const lovelaceOf = (amount) => BigInt(amount?.find(a => a.unit === 'lovelace')?.quantity ?? '0');
|
|
22
|
+
const nativeAssets = (amount) => (amount ?? []).filter(a => a.unit !== 'lovelace' && a.quantity !== '0');
|
|
23
|
+
const big = (v) => (v == null || v === '' ? 0n : BigInt(String(v)));
|
|
24
|
+
const num = (v) => Number(v ?? 0);
|
|
25
|
+
function decodeAssetName(hex) {
|
|
26
|
+
if (!hex)
|
|
27
|
+
return null;
|
|
28
|
+
try {
|
|
29
|
+
const text = Buffer.from(hex, 'hex').toString('utf8');
|
|
30
|
+
// printable only, a binary asset name has no useful decoded form
|
|
31
|
+
return /^[\x20-\x7e]*$/.test(text) ? text : null;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Build the `LedgerUTxOs` row (+ asset rows) for one output. */
|
|
38
|
+
function buildLedgerUtxoRows(o, createdSlot) {
|
|
39
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(o.address);
|
|
40
|
+
const assets = nativeAssets(o.amount).map((a) => ({
|
|
41
|
+
utxo_txHash: o.txHash,
|
|
42
|
+
utxo_outputIndex: o.outputIndex,
|
|
43
|
+
unit: a.unit,
|
|
44
|
+
asset_quantity: String(a.quantity),
|
|
45
|
+
asset_policyId: a.unit.length >= 56 ? a.unit.slice(0, 56) : null,
|
|
46
|
+
asset_assetNameHex: a.unit.length > 56 ? a.unit.slice(56) : '',
|
|
47
|
+
asset_assetName: a.unit.length > 56 ? decodeAssetName(a.unit.slice(56)) : null,
|
|
48
|
+
}));
|
|
49
|
+
return {
|
|
50
|
+
row: {
|
|
51
|
+
txHash: o.txHash,
|
|
52
|
+
outputIndex: o.outputIndex,
|
|
53
|
+
address: o.address,
|
|
54
|
+
stakeAddress: decoded.stakeAddress,
|
|
55
|
+
addressType: decoded.type,
|
|
56
|
+
isScript: decoded.isScript,
|
|
57
|
+
lovelace: lovelaceOf(o.amount).toString(),
|
|
58
|
+
createdSlot,
|
|
59
|
+
spentTxHash: null,
|
|
60
|
+
spentSlot: null,
|
|
61
|
+
utxo_dataHash: o.dataHash || null,
|
|
62
|
+
utxo_inlineDatum: o.inlineDatum || null,
|
|
63
|
+
utxo_referenceScriptHash: o.referenceScriptHash || null,
|
|
64
|
+
utxo_referenceScriptSize: o.referenceScriptSize ?? null,
|
|
65
|
+
utxo_referenceScriptType: o.referenceScriptType ?? null,
|
|
66
|
+
utxo_paymentCredential: decoded.paymentCredential,
|
|
67
|
+
hasAssets: assets.length > 0,
|
|
68
|
+
},
|
|
69
|
+
assets,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** Outputs the ledger actually produced: collateral return on a phase-2 failure, else the regular ones. */
|
|
73
|
+
function producedOutputs(t) {
|
|
74
|
+
return (t.outputs ?? []).filter(o => (t.spendsCollaterals ? o.isCollateral : !o.isCollateral));
|
|
75
|
+
}
|
|
76
|
+
/** Inputs the ledger actually consumed: collateral on a phase-2 failure, else the regular (non-reference) ones. */
|
|
77
|
+
function consumedInputs(t) {
|
|
78
|
+
return (t.inputs ?? [])
|
|
79
|
+
.filter(i => (t.spendsCollaterals ? i.isCollateral : !i.isReference && !i.isCollateral))
|
|
80
|
+
.map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex }));
|
|
81
|
+
}
|
|
82
|
+
function deltaFor(map, row) {
|
|
83
|
+
let d = map.get(row.address);
|
|
84
|
+
if (!d) {
|
|
85
|
+
d = { lovelace: 0n, utxos: 0, assets: new Map(), stakeAddress: row.stakeAddress, addressType: row.addressType, isScript: row.isScript };
|
|
86
|
+
map.set(row.address, d);
|
|
87
|
+
}
|
|
88
|
+
return d;
|
|
89
|
+
}
|
|
90
|
+
function applyDelta(d, row, assets, sign) {
|
|
91
|
+
d.lovelace += sign * BigInt(row.lovelace);
|
|
92
|
+
d.utxos += Number(sign);
|
|
93
|
+
for (const a of assets ?? []) {
|
|
94
|
+
const unit = 'unit' in a ? a.unit : '';
|
|
95
|
+
const qty = 'asset_quantity' in a ? a.asset_quantity : a.quantity;
|
|
96
|
+
if (!unit)
|
|
97
|
+
continue;
|
|
98
|
+
d.assets.set(unit, (d.assets.get(unit) ?? 0n) + sign * BigInt(qty));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Read the ledger rows of the given source transactions. Asset rows are read only where a row
|
|
102
|
+
// has assets, so an ada-only block costs one SELECT.
|
|
103
|
+
async function readLedgerOutputs(tx, txHashes, into) {
|
|
104
|
+
const lookup = into ?? { hashes: new Set(), rows: new Map(), assets: new Map() };
|
|
105
|
+
const todo = [...new Set(txHashes)].filter(h => !lookup.hashes.has(h));
|
|
106
|
+
for (const hashChunk of (0, collections_1.chunk)(todo, collections_1.IN_CHUNK)) {
|
|
107
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
|
|
108
|
+
for (const r of rows ?? [])
|
|
109
|
+
lookup.rows.set(outpoint(r.txHash, num(r.outputIndex)), r);
|
|
110
|
+
const withAssets = [...new Set((rows ?? []).filter(r => r.hasAssets).map(r => r.txHash))];
|
|
111
|
+
if (withAssets.length) {
|
|
112
|
+
const assets = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: withAssets } }));
|
|
113
|
+
for (const a of assets ?? []) {
|
|
114
|
+
const k = outpoint(a.utxo_txHash, num(a.utxo_outputIndex));
|
|
115
|
+
const list = lookup.assets.get(k) ?? [];
|
|
116
|
+
list.push(a);
|
|
117
|
+
lookup.assets.set(k, list);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const h of hashChunk)
|
|
121
|
+
lookup.hashes.add(h);
|
|
122
|
+
}
|
|
123
|
+
return lookup;
|
|
124
|
+
}
|
|
125
|
+
/** Amount list (lovelace + native assets) of a ledger row, the shape a resolved input carries. */
|
|
126
|
+
function ledgerRowAmount(row, assets) {
|
|
127
|
+
return [
|
|
128
|
+
{ unit: 'lovelace', quantity: String(row.lovelace ?? '0') },
|
|
129
|
+
...(assets ?? []).map(a => ({ unit: a.unit, quantity: String(a.asset_quantity) })),
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
// Apply one block after the anchor. `lookup` may carry rows the caller already read.
|
|
133
|
+
// A missing output is counted, not thrown. DB errors propagate so the block transaction rolls back.
|
|
134
|
+
async function applyBlockToLedger(tx, block, txs, lookup) {
|
|
135
|
+
const slot = block.slot ?? 0;
|
|
136
|
+
// 1) everything this block produces
|
|
137
|
+
const created = new Map();
|
|
138
|
+
for (const t of txs) {
|
|
139
|
+
for (const o of producedOutputs(t)) {
|
|
140
|
+
const built = buildLedgerUtxoRows({ ...o, txHash: t.hash }, slot);
|
|
141
|
+
created.set(outpoint(t.hash, o.outputIndex), built);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// 2) everything this block consumes, same-block outputs first, the rest from the DB
|
|
145
|
+
const lookups = [];
|
|
146
|
+
const spentInBlock = new Set();
|
|
147
|
+
for (const t of txs) {
|
|
148
|
+
for (const i of consumedInputs(t)) {
|
|
149
|
+
const key = outpoint(i.txHash, i.outputIndex);
|
|
150
|
+
const own = created.get(key);
|
|
151
|
+
if (own) {
|
|
152
|
+
own.row.spentTxHash = t.hash;
|
|
153
|
+
own.row.spentSlot = slot;
|
|
154
|
+
spentInBlock.add(key);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
lookups.push({ key, txHash: i.txHash, outputIndex: i.outputIndex, spender: t.hash });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const { rows: dbRows, assets: dbAssets } = await readLedgerOutputs(tx, lookups.map(l => l.txHash), lookup);
|
|
162
|
+
const spentRows = [];
|
|
163
|
+
let missing = 0;
|
|
164
|
+
for (const l of lookups) {
|
|
165
|
+
const row = dbRows.get(l.key);
|
|
166
|
+
if (!row || row.spentTxHash) {
|
|
167
|
+
missing++;
|
|
168
|
+
if (missing <= 3) {
|
|
169
|
+
logger.warn(`ledger: ${l.spender} consumes ${l.key} which has no open row (${row ? 'already spent' : 'unknown'}), snapshot gap?`);
|
|
170
|
+
}
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
spentRows.push({
|
|
174
|
+
...row,
|
|
175
|
+
outputIndex: num(row.outputIndex),
|
|
176
|
+
lovelace: String(row.lovelace),
|
|
177
|
+
createdSlot: row.createdSlot == null ? null : num(row.createdSlot),
|
|
178
|
+
isScript: Boolean(row.isScript),
|
|
179
|
+
hasAssets: Boolean(row.hasAssets),
|
|
180
|
+
spentTxHash: l.spender,
|
|
181
|
+
spentSlot: slot,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
// 3) per-address deltas
|
|
185
|
+
const deltas = new Map();
|
|
186
|
+
for (const [key, { row, assets }] of created) {
|
|
187
|
+
const d = deltaFor(deltas, row);
|
|
188
|
+
applyDelta(d, row, assets, 1n);
|
|
189
|
+
if (spentInBlock.has(key))
|
|
190
|
+
applyDelta(d, row, assets, -1n);
|
|
191
|
+
}
|
|
192
|
+
for (const row of spentRows) {
|
|
193
|
+
applyDelta(deltaFor(deltas, row), row, dbAssets.get(outpoint(row.txHash, row.outputIndex)), -1n);
|
|
194
|
+
}
|
|
195
|
+
// 4) UTxO rows
|
|
196
|
+
const createdRows = [...created.values()];
|
|
197
|
+
for (const rows of (0, collections_1.chunk)(createdRows.map(c => c.row), collections_1.IN_CHUNK)) {
|
|
198
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
199
|
+
}
|
|
200
|
+
for (const rows of (0, collections_1.chunk)(createdRows.flatMap(c => c.assets), collections_1.IN_CHUNK)) {
|
|
201
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOAssets).entries(rows));
|
|
202
|
+
}
|
|
203
|
+
for (const rows of (0, collections_1.chunk)(spentRows, collections_1.IN_CHUNK)) {
|
|
204
|
+
await tx.run(UPSERT.into(cardano_1.LedgerUTxOs).entries(rows));
|
|
205
|
+
}
|
|
206
|
+
// 5) addresses, address assets, accounts
|
|
207
|
+
const touched = [...deltas.keys()];
|
|
208
|
+
const stakeDeltas = new Map();
|
|
209
|
+
for (const addrChunk of (0, collections_1.chunk)(touched, collections_1.IN_CHUNK)) {
|
|
210
|
+
const [existing, existingAssets] = await Promise.all([
|
|
211
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).where({ address: { in: addrChunk } })),
|
|
212
|
+
tx.run(SELECT.from(cardano_1.LedgerAddressAssets).where({ address_address: { in: addrChunk } })),
|
|
213
|
+
]);
|
|
214
|
+
const byAddress = new Map((existing ?? []).map(e => [String(e.address), e]));
|
|
215
|
+
const assetQty = new Map();
|
|
216
|
+
for (const a of existingAssets ?? [])
|
|
217
|
+
assetQty.set(`${a.address_address}|${a.unit}`, big(a.asset_quantity));
|
|
218
|
+
const addressRows = [];
|
|
219
|
+
const assetRows = [];
|
|
220
|
+
const assetDeletes = [];
|
|
221
|
+
for (const address of addrChunk) {
|
|
222
|
+
const d = deltas.get(address);
|
|
223
|
+
const prev = byAddress.get(address);
|
|
224
|
+
const total = big(prev?.totalLovelace) + d.lovelace;
|
|
225
|
+
const count = num(prev?.utxoCount) + d.utxos;
|
|
226
|
+
addressRows.push({
|
|
227
|
+
address,
|
|
228
|
+
stakeAddress: prev?.stakeAddress ?? d.stakeAddress,
|
|
229
|
+
paymentCredential: (0, mappers_1.decodeShelleyAddress)(address).paymentCredential,
|
|
230
|
+
addressType: prev?.addressType ?? d.addressType,
|
|
231
|
+
isScript: prev ? Boolean(prev.isScript) : d.isScript,
|
|
232
|
+
totalLovelace: total.toString(),
|
|
233
|
+
utxoCount: count,
|
|
234
|
+
// null stays null: an address that came with the snapshot has no known first slot
|
|
235
|
+
firstSeenSlot: prev ? (prev.firstSeenSlot == null ? null : num(prev.firstSeenSlot)) : slot,
|
|
236
|
+
lastActiveSlot: slot,
|
|
237
|
+
});
|
|
238
|
+
for (const [unit, delta] of d.assets) {
|
|
239
|
+
if (delta === 0n)
|
|
240
|
+
continue;
|
|
241
|
+
const k = `${address}|${unit}`;
|
|
242
|
+
const next = (assetQty.get(k) ?? 0n) + delta;
|
|
243
|
+
if (next === 0n) {
|
|
244
|
+
if (assetQty.has(k))
|
|
245
|
+
assetDeletes.push({ address_address: address, unit });
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
assetRows.push({
|
|
249
|
+
address_address: address,
|
|
250
|
+
unit,
|
|
251
|
+
asset_quantity: next.toString(),
|
|
252
|
+
asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
|
|
253
|
+
asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
|
|
254
|
+
asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const stake = prev?.stakeAddress ?? d.stakeAddress;
|
|
259
|
+
if (stake) {
|
|
260
|
+
const s = stakeDeltas.get(stake) ?? { lovelace: 0n, utxos: 0, newAddresses: 0 };
|
|
261
|
+
s.lovelace += d.lovelace;
|
|
262
|
+
s.utxos += d.utxos;
|
|
263
|
+
if (!prev)
|
|
264
|
+
s.newAddresses++;
|
|
265
|
+
stakeDeltas.set(stake, s);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
for (const rows of (0, collections_1.chunk)(addressRows, collections_1.IN_CHUNK))
|
|
269
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries(rows));
|
|
270
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
271
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
272
|
+
for (const del of assetDeletes)
|
|
273
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where(del));
|
|
274
|
+
}
|
|
275
|
+
const stakes = [...stakeDeltas.keys()];
|
|
276
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakes, collections_1.IN_CHUNK)) {
|
|
277
|
+
const existing = await tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } }));
|
|
278
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
279
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
280
|
+
const d = stakeDeltas.get(stakeAddress);
|
|
281
|
+
const prev = byStake.get(stakeAddress);
|
|
282
|
+
return {
|
|
283
|
+
stakeAddress,
|
|
284
|
+
controlledAmount: (big(prev?.controlledAmount) + d.lovelace).toString(),
|
|
285
|
+
addressCount: num(prev?.addressCount) + d.newAddresses,
|
|
286
|
+
utxoCount: num(prev?.utxoCount) + d.utxos,
|
|
287
|
+
lastActiveSlot: slot,
|
|
288
|
+
};
|
|
289
|
+
});
|
|
290
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
291
|
+
}
|
|
292
|
+
return { created: created.size, spent: spentInBlock.size + spentRows.length, missing, addresses: touched.length };
|
|
293
|
+
}
|
|
294
|
+
// Undo rolled-back transactions: drop what they created, reopen what they spent,
|
|
295
|
+
// then recount every touched address. Returns the recounted addresses.
|
|
296
|
+
async function undoLedgerForTransactions(tx, txHashes) {
|
|
297
|
+
if (!txHashes.length)
|
|
298
|
+
return [];
|
|
299
|
+
const touched = new Set();
|
|
300
|
+
for (const hashChunk of (0, collections_1.chunk)(txHashes, collections_1.IN_CHUNK)) {
|
|
301
|
+
const [createdRows, spentRows] = await Promise.all([
|
|
302
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ txHash: { in: hashChunk } })),
|
|
303
|
+
tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('address').where({ spentTxHash: { in: hashChunk } })),
|
|
304
|
+
]);
|
|
305
|
+
for (const r of [...(createdRows ?? []), ...(spentRows ?? [])])
|
|
306
|
+
touched.add(r.address);
|
|
307
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
308
|
+
await tx.run(DELETE.from(cardano_1.LedgerUTxOs).where({ txHash: { in: hashChunk } }));
|
|
309
|
+
await tx.run(UPDATE.entity(cardano_1.LedgerUTxOs).set({ spentTxHash: null, spentSlot: null }).where({ spentTxHash: { in: hashChunk } }));
|
|
310
|
+
}
|
|
311
|
+
const addresses = [...touched];
|
|
312
|
+
await recountLedgerAddresses(tx, addresses);
|
|
313
|
+
return addresses;
|
|
314
|
+
}
|
|
315
|
+
// Recount the sums of these addresses and their stake keys from open rows. Also repairs a drifted sum.
|
|
316
|
+
async function recountLedgerAddresses(tx, addresses) {
|
|
317
|
+
const stakes = new Set();
|
|
318
|
+
for (const address of addresses) {
|
|
319
|
+
const open = await tx.run(SELECT.from(cardano_1.LedgerUTxOs).columns('txHash', 'outputIndex', 'lovelace', 'hasAssets', 'stakeAddress')
|
|
320
|
+
.where({ address, spentTxHash: null }));
|
|
321
|
+
const openKeys = new Set((open ?? []).map(r => outpoint(r.txHash, num(r.outputIndex))));
|
|
322
|
+
let total = 0n;
|
|
323
|
+
for (const r of open ?? [])
|
|
324
|
+
total += big(r.lovelace);
|
|
325
|
+
const assetSums = new Map();
|
|
326
|
+
const withAssets = [...new Set((open ?? []).filter(r => Boolean(r.hasAssets)).map(r => r.txHash))];
|
|
327
|
+
for (const hashChunk of (0, collections_1.chunk)(withAssets, collections_1.IN_CHUNK)) {
|
|
328
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerUTxOAssets).where({ utxo_txHash: { in: hashChunk } }));
|
|
329
|
+
for (const a of rows ?? []) {
|
|
330
|
+
if (!openKeys.has(outpoint(a.utxo_txHash, num(a.utxo_outputIndex))))
|
|
331
|
+
continue;
|
|
332
|
+
assetSums.set(a.unit, (assetSums.get(a.unit) ?? 0n) + big(a.asset_quantity));
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const prev = await tx.run(SELECT.one.from(cardano_1.LedgerAddresses).where({ address }));
|
|
336
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
337
|
+
const stakeAddress = prev?.stakeAddress ?? open?.[0]?.stakeAddress ?? decoded.stakeAddress;
|
|
338
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddresses).entries({
|
|
339
|
+
address,
|
|
340
|
+
stakeAddress,
|
|
341
|
+
paymentCredential: decoded.paymentCredential,
|
|
342
|
+
addressType: prev?.addressType ?? decoded.type,
|
|
343
|
+
isScript: prev ? Boolean(prev.isScript) : decoded.isScript,
|
|
344
|
+
totalLovelace: total.toString(),
|
|
345
|
+
utxoCount: (open ?? []).length,
|
|
346
|
+
firstSeenSlot: prev?.firstSeenSlot == null ? null : num(prev.firstSeenSlot),
|
|
347
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
348
|
+
}));
|
|
349
|
+
await tx.run(DELETE.from(cardano_1.LedgerAddressAssets).where({ address_address: address }));
|
|
350
|
+
const assetRows = [...assetSums].filter(([, q]) => q !== 0n).map(([unit, q]) => ({
|
|
351
|
+
address_address: address,
|
|
352
|
+
unit,
|
|
353
|
+
asset_quantity: q.toString(),
|
|
354
|
+
asset_policyId: unit.length >= 56 ? unit.slice(0, 56) : null,
|
|
355
|
+
asset_assetNameHex: unit.length > 56 ? unit.slice(56) : '',
|
|
356
|
+
asset_assetName: unit.length > 56 ? decodeAssetName(unit.slice(56)) : null,
|
|
357
|
+
}));
|
|
358
|
+
for (const rows of (0, collections_1.chunk)(assetRows, collections_1.IN_CHUNK))
|
|
359
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAddressAssets).entries(rows));
|
|
360
|
+
if (stakeAddress)
|
|
361
|
+
stakes.add(stakeAddress);
|
|
362
|
+
}
|
|
363
|
+
await recountLedgerAccounts(tx, [...stakes]);
|
|
364
|
+
}
|
|
365
|
+
/** Recount `LedgerAccounts` for the given stake keys from `LedgerAddresses`. */
|
|
366
|
+
async function recountLedgerAccounts(tx, stakeAddresses) {
|
|
367
|
+
for (const stakeChunk of (0, collections_1.chunk)(stakeAddresses, collections_1.IN_CHUNK)) {
|
|
368
|
+
const [addrRows, existing] = await Promise.all([
|
|
369
|
+
tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('stakeAddress', 'totalLovelace', 'utxoCount')
|
|
370
|
+
.where({ stakeAddress: { in: stakeChunk } })),
|
|
371
|
+
tx.run(SELECT.from(cardano_1.LedgerAccounts).where({ stakeAddress: { in: stakeChunk } })),
|
|
372
|
+
]);
|
|
373
|
+
const sums = new Map();
|
|
374
|
+
for (const r of addrRows ?? []) {
|
|
375
|
+
const k = String(r.stakeAddress);
|
|
376
|
+
const s = sums.get(k) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
377
|
+
s.lovelace += big(r.totalLovelace);
|
|
378
|
+
s.addresses += 1;
|
|
379
|
+
s.utxos += num(r.utxoCount);
|
|
380
|
+
sums.set(k, s);
|
|
381
|
+
}
|
|
382
|
+
const byStake = new Map((existing ?? []).map(e => [String(e.stakeAddress), e]));
|
|
383
|
+
const rows = stakeChunk.map((stakeAddress) => {
|
|
384
|
+
const s = sums.get(stakeAddress) ?? { lovelace: 0n, addresses: 0, utxos: 0 };
|
|
385
|
+
const prev = byStake.get(stakeAddress);
|
|
386
|
+
return {
|
|
387
|
+
stakeAddress,
|
|
388
|
+
controlledAmount: s.lovelace.toString(),
|
|
389
|
+
addressCount: s.addresses,
|
|
390
|
+
utxoCount: s.utxos,
|
|
391
|
+
lastActiveSlot: prev?.lastActiveSlot == null ? null : num(prev.lastActiveSlot),
|
|
392
|
+
};
|
|
393
|
+
});
|
|
394
|
+
await tx.run(UPSERT.into(cardano_1.LedgerAccounts).entries(rows));
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/** Address types that carry a payment credential. */
|
|
398
|
+
const CREDENTIAL_ADDRESS_TYPES = ['base', 'pointer', 'enterprise'];
|
|
399
|
+
// Fill a missing `LedgerAddresses.paymentCredential`, one transaction per chunk. Returns rows updated.
|
|
400
|
+
async function backfillPaymentCredentials(chunkSize = 1000) {
|
|
401
|
+
let updated = 0;
|
|
402
|
+
for (;;) {
|
|
403
|
+
const n = await cds_1.default.tx(async (tx) => {
|
|
404
|
+
const rows = await tx.run(SELECT.from(cardano_1.LedgerAddresses).columns('address')
|
|
405
|
+
.where({ paymentCredential: null, addressType: { in: CREDENTIAL_ADDRESS_TYPES } })
|
|
406
|
+
.limit(chunkSize));
|
|
407
|
+
for (const { address } of rows ?? []) {
|
|
408
|
+
// '' marks an address that decodes without a credential, so it is not picked again
|
|
409
|
+
const credential = (0, mappers_1.decodeShelleyAddress)(address).paymentCredential ?? '';
|
|
410
|
+
await tx.run(UPDATE.entity(cardano_1.LedgerAddresses).set({ paymentCredential: credential }).where({ address }));
|
|
411
|
+
}
|
|
412
|
+
return (rows ?? []).length;
|
|
413
|
+
});
|
|
414
|
+
updated += n;
|
|
415
|
+
if (n < chunkSize)
|
|
416
|
+
return updated;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
//# sourceMappingURL=ledger-state.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { UTxO } from '../utils/types';
|
|
2
|
+
/** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
|
|
3
|
+
export declare const PENDING_TX_TTL_MS: number;
|
|
4
|
+
export declare class PendingSpends {
|
|
5
|
+
private readonly now;
|
|
6
|
+
private readonly txs;
|
|
7
|
+
constructor(now?: () => number);
|
|
8
|
+
/** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
|
|
9
|
+
record(signedTxCbor: string): void;
|
|
10
|
+
/** The pending transaction that spends this output, if any. */
|
|
11
|
+
spentBy(txHash: string, outputIndex: number): string | undefined;
|
|
12
|
+
apply(address: string, utxos: UTxO[]): UTxO[];
|
|
13
|
+
get size(): number;
|
|
14
|
+
private prune;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=pending-spends.d.ts.map
|
|
@@ -0,0 +1,81 @@
|
|
|
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.PendingSpends = exports.PENDING_TX_TTL_MS = void 0;
|
|
7
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
const parse_1 = require("../cbor/parse");
|
|
9
|
+
const logger = cds_1.default.log('PendingSpends');
|
|
10
|
+
/** How long a submitted transaction counts as pending when no crawled block confirms it earlier. */
|
|
11
|
+
exports.PENDING_TX_TTL_MS = 10 * 60_000;
|
|
12
|
+
const refKey = (txHash, outputIndex) => `${txHash.toLowerCase()}#${outputIndex}`;
|
|
13
|
+
// Submitted transactions still in the mempool, whose inputs still look unspent. Builders skip
|
|
14
|
+
// those inputs and may spend the pending change. Entries end when crawled or after PENDING_TX_TTL_MS.
|
|
15
|
+
class PendingSpends {
|
|
16
|
+
now;
|
|
17
|
+
txs = new Map();
|
|
18
|
+
constructor(now = Date.now) {
|
|
19
|
+
this.now = now;
|
|
20
|
+
}
|
|
21
|
+
/** Remember a submitted transaction; unparseable CBOR is ignored (the submit already succeeded). */
|
|
22
|
+
record(signedTxCbor) {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = (0, parse_1.parseTransaction)(signedTxCbor);
|
|
25
|
+
this.txs.set(parsed.txHash, {
|
|
26
|
+
inputs: parsed.inputs.map((i) => refKey(i.txHash, i.outputIndex)),
|
|
27
|
+
outputs: parsed.outputs.map((o, outputIndex) => ({
|
|
28
|
+
txHash: parsed.txHash,
|
|
29
|
+
outputIndex,
|
|
30
|
+
address: o.address,
|
|
31
|
+
amount: [{ unit: 'lovelace', quantity: o.lovelace }, ...o.assets],
|
|
32
|
+
datumHash: o.datumHash,
|
|
33
|
+
inlineDatum: o.inlineDatumHex,
|
|
34
|
+
scriptRefCbor: o.referenceScriptHex,
|
|
35
|
+
})),
|
|
36
|
+
expiresAt: this.now() + exports.PENDING_TX_TTL_MS,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
logger.warn(`submitted transaction not tracked as pending: ${err instanceof Error ? err.message : String(err)}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The pending transaction that spends this output, if any. */
|
|
44
|
+
spentBy(txHash, outputIndex) {
|
|
45
|
+
this.prune();
|
|
46
|
+
const key = refKey(txHash, outputIndex);
|
|
47
|
+
for (const [hash, tx] of this.txs)
|
|
48
|
+
if (tx.inputs.includes(key))
|
|
49
|
+
return hash;
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
// The address's UTxOs after the pending transactions. One whose outputs already appear in `utxos`
|
|
53
|
+
// has been crawled and is forgotten.
|
|
54
|
+
apply(address, utxos) {
|
|
55
|
+
this.prune();
|
|
56
|
+
if (this.txs.size === 0)
|
|
57
|
+
return utxos;
|
|
58
|
+
const listed = new Set(utxos.map((u) => u.txHash.toLowerCase()));
|
|
59
|
+
for (const hash of [...this.txs.keys()])
|
|
60
|
+
if (listed.has(hash))
|
|
61
|
+
this.txs.delete(hash);
|
|
62
|
+
const spent = new Set([...this.txs.values()].flatMap((t) => t.inputs));
|
|
63
|
+
const keep = utxos.filter((u) => !spent.has(refKey(u.txHash, u.outputIndex)));
|
|
64
|
+
const pendingOut = [...this.txs.values()]
|
|
65
|
+
.flatMap((t) => t.outputs)
|
|
66
|
+
.filter((o) => o.address === address && !spent.has(refKey(o.txHash, o.outputIndex)));
|
|
67
|
+
return [...keep, ...pendingOut];
|
|
68
|
+
}
|
|
69
|
+
get size() {
|
|
70
|
+
this.prune();
|
|
71
|
+
return this.txs.size;
|
|
72
|
+
}
|
|
73
|
+
prune() {
|
|
74
|
+
const now = this.now();
|
|
75
|
+
for (const [hash, tx] of this.txs)
|
|
76
|
+
if (tx.expiresAt <= now)
|
|
77
|
+
this.txs.delete(hash);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
exports.PendingSpends = PendingSpends;
|
|
81
|
+
//# sourceMappingURL=pending-spends.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import net from 'node:net';
|
|
2
|
+
/** A stake pool's metadata file is at most this many bytes. */
|
|
3
|
+
export declare const POOL_METADATA_MAX_BYTES = 512;
|
|
4
|
+
/** The four fields of a stake pool's metadata file. */
|
|
5
|
+
export interface PoolMetadata {
|
|
6
|
+
name: string;
|
|
7
|
+
ticker: string;
|
|
8
|
+
homepage: string;
|
|
9
|
+
description: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function validPoolMetadata(value: unknown): PoolMetadata | null;
|
|
12
|
+
export declare function isPublicAddress(address: string): boolean;
|
|
13
|
+
export declare const publicLookup: net.LookupFunction;
|
|
14
|
+
export declare function fetchPoolMetadata(url: string, hash: string): Promise<PoolMetadata | null>;
|
|
15
|
+
//# sourceMappingURL=pool-metadata.d.ts.map
|
|
@@ -0,0 +1,132 @@
|
|
|
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.publicLookup = exports.POOL_METADATA_MAX_BYTES = void 0;
|
|
7
|
+
exports.validPoolMetadata = validPoolMetadata;
|
|
8
|
+
exports.isPublicAddress = isPublicAddress;
|
|
9
|
+
exports.fetchPoolMetadata = fetchPoolMetadata;
|
|
10
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
11
|
+
const node_dns_1 = __importDefault(require("node:dns"));
|
|
12
|
+
const node_http_1 = __importDefault(require("node:http"));
|
|
13
|
+
const node_https_1 = __importDefault(require("node:https"));
|
|
14
|
+
const node_net_1 = __importDefault(require("node:net"));
|
|
15
|
+
const node_util_1 = require("node:util");
|
|
16
|
+
const crypto_1 = require("@harmoniclabs/crypto");
|
|
17
|
+
const logger = cds_1.default.log('PoolMetadata');
|
|
18
|
+
/** A stake pool's metadata file is at most this many bytes. */
|
|
19
|
+
exports.POOL_METADATA_MAX_BYTES = 512;
|
|
20
|
+
const MAX_REDIRECTS = 5;
|
|
21
|
+
/** For the whole fetch, redirects included. */
|
|
22
|
+
const FETCH_TIMEOUT_MS = 3_000;
|
|
23
|
+
const chars = (s) => [...s].length;
|
|
24
|
+
// The limits cardano-db-sync applies: name up to 50 characters, description up to 255, ticker 3 to 5.
|
|
25
|
+
// Null when a field is missing, not a string or out of range.
|
|
26
|
+
function validPoolMetadata(value) {
|
|
27
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
28
|
+
return null;
|
|
29
|
+
const { name, ticker, homepage, description } = value;
|
|
30
|
+
if (typeof name !== 'string' || typeof ticker !== 'string' || typeof homepage !== 'string' || typeof description !== 'string')
|
|
31
|
+
return null;
|
|
32
|
+
if (chars(name) > 50 || chars(description) > 255 || chars(ticker) < 3 || chars(ticker) > 5)
|
|
33
|
+
return null;
|
|
34
|
+
if (Buffer.byteLength(homepage, 'utf8') > exports.POOL_METADATA_MAX_BYTES)
|
|
35
|
+
return null;
|
|
36
|
+
return { name, ticker, homepage, description };
|
|
37
|
+
}
|
|
38
|
+
// Loopback, private, link-local, carrier-grade NAT, multicast and reserved ranges.
|
|
39
|
+
// A pool registers any URL it likes, so the fetch must not reach hosts behind this server.
|
|
40
|
+
const NON_PUBLIC = new node_net_1.default.BlockList();
|
|
41
|
+
for (const [prefix, bits] of [
|
|
42
|
+
['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12],
|
|
43
|
+
['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 3],
|
|
44
|
+
])
|
|
45
|
+
NON_PUBLIC.addSubnet(prefix, bits, 'ipv4');
|
|
46
|
+
for (const [prefix, bits] of [['::', 127], ['64:ff9b::', 96], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) {
|
|
47
|
+
NON_PUBLIC.addSubnet(prefix, bits, 'ipv6');
|
|
48
|
+
}
|
|
49
|
+
function isPublicAddress(address) {
|
|
50
|
+
const family = node_net_1.default.isIP(address);
|
|
51
|
+
return family !== 0 && !NON_PUBLIC.check(address, family === 6 ? 'ipv6' : 'ipv4');
|
|
52
|
+
}
|
|
53
|
+
// DNS lookup that refuses a name with any non-public address. The connection uses the checked
|
|
54
|
+
// addresses, so a second, different DNS answer cannot redirect it.
|
|
55
|
+
const publicLookup = (hostname, options, callback) => {
|
|
56
|
+
node_dns_1.default.lookup(hostname, { ...options, all: true }, (err, addresses) => {
|
|
57
|
+
if (err)
|
|
58
|
+
return callback(err, '', 4);
|
|
59
|
+
if (addresses.length === 0 || addresses.some(a => !isPublicAddress(a.address))) {
|
|
60
|
+
return callback(new Error(`${hostname} resolves to a non-public address`), '', 4);
|
|
61
|
+
}
|
|
62
|
+
if (options.all)
|
|
63
|
+
return callback(null, addresses);
|
|
64
|
+
return callback(null, addresses[0].address, addresses[0].family);
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
exports.publicLookup = publicLookup;
|
|
68
|
+
function get(url, signal) {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
const transport = url.protocol === 'https:' ? node_https_1.default : node_http_1.default;
|
|
71
|
+
const req = transport.get(url, { lookup: exports.publicLookup, signal, headers: { accept: 'application/json' } }, (res) => {
|
|
72
|
+
const chunks = [];
|
|
73
|
+
let size = 0;
|
|
74
|
+
const done = (body) => resolve({ status: res.statusCode ?? 0, location: res.headers.location, body });
|
|
75
|
+
res.on('data', (chunk) => {
|
|
76
|
+
size += chunk.length;
|
|
77
|
+
if (size > exports.POOL_METADATA_MAX_BYTES) {
|
|
78
|
+
res.destroy();
|
|
79
|
+
done(null);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
chunks.push(chunk);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
res.on('end', () => done(Buffer.concat(chunks)));
|
|
86
|
+
res.on('error', reject);
|
|
87
|
+
});
|
|
88
|
+
req.on('error', reject);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** The file behind `url`, following redirects; every hop must be http(s) on a public host. */
|
|
92
|
+
async function download(url) {
|
|
93
|
+
const signal = AbortSignal.timeout(FETCH_TIMEOUT_MS);
|
|
94
|
+
let next = new URL(url);
|
|
95
|
+
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
96
|
+
if (next.protocol !== 'http:' && next.protocol !== 'https:')
|
|
97
|
+
throw new Error(`unsupported protocol ${next.protocol}`);
|
|
98
|
+
// an address literal never reaches the DNS lookup
|
|
99
|
+
const host = next.hostname.replace(/^\[|\]$/g, '');
|
|
100
|
+
if (node_net_1.default.isIP(host) && !isPublicAddress(host))
|
|
101
|
+
throw new Error(`${host} is not a public address`);
|
|
102
|
+
const reply = await get(next, signal);
|
|
103
|
+
if ([301, 302, 303, 307, 308].includes(reply.status) && reply.location) {
|
|
104
|
+
next = new URL(reply.location, next);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (reply.status !== 200)
|
|
108
|
+
throw new Error(`HTTP ${reply.status}`);
|
|
109
|
+
if (!reply.body)
|
|
110
|
+
throw new Error(`more than ${exports.POOL_METADATA_MAX_BYTES} bytes`);
|
|
111
|
+
return reply.body;
|
|
112
|
+
}
|
|
113
|
+
throw new Error(`more than ${MAX_REDIRECTS} redirects`);
|
|
114
|
+
}
|
|
115
|
+
// Loads a pool's metadata file and returns its fields when the bytes hash to `hash` (blake2b-256,
|
|
116
|
+
// as registered on chain). Null for any failure; never throws.
|
|
117
|
+
async function fetchPoolMetadata(url, hash) {
|
|
118
|
+
try {
|
|
119
|
+
const bytes = await download(url);
|
|
120
|
+
if (Buffer.from((0, crypto_1.blake2b_256)(bytes)).toString('hex') !== hash.toLowerCase())
|
|
121
|
+
throw new Error('hash mismatch');
|
|
122
|
+
const metadata = validPoolMetadata(JSON.parse(new node_util_1.TextDecoder('utf-8', { fatal: true }).decode(bytes)));
|
|
123
|
+
if (!metadata)
|
|
124
|
+
throw new Error('not a valid pool metadata file');
|
|
125
|
+
return metadata;
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
logger.debug(`Pool metadata ${url} not used: ${err instanceof Error ? err.message : String(err)}`);
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=pool-metadata.js.map
|