@odatano/core 2.0.0-rc.20 → 2.0.0-rc.21
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/CardanoODataService/index.d.ts +7 -6
- package/@cds-models/odatano/cardano/index.d.ts +7 -6
- package/db/schema.cds +19 -7
- package/package.json +4 -2
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +7 -2
- package/srv/blockchain/backends/koios-backend.js +1 -1
- package/srv/blockchain/backends/ogmios-backend.d.ts +15 -3
- package/srv/blockchain/backends/ogmios-backend.js +102 -56
- package/srv/blockchain/cardano-client.d.ts +8 -0
- package/srv/blockchain/cardano-client.js +14 -2
- package/srv/blockchain/cardano-indexer.d.ts +35 -1
- package/srv/blockchain/cardano-indexer.js +177 -57
- package/srv/blockchain/cardano-tx-builder.d.ts +15 -3
- package/srv/blockchain/cardano-tx-builder.js +70 -24
- package/srv/blockchain/crawler/crawler.js +3 -9
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +42 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +6 -1
- package/srv/cardano-tx-service.js +3 -1
- package/srv/utils/db-indexes.js +4 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +25 -0
- package/srv/utils/errors.d.ts +2 -1
- package/srv/utils/errors.js +7 -3
- package/srv/utils/mappers.d.ts +7 -4
- package/srv/utils/mappers.js +18 -9
- package/srv/utils/types.d.ts +2 -0
|
@@ -297,6 +297,7 @@ export class AssetHistory_ extends Array<AssetHistory> {
|
|
|
297
297
|
export declare function _TransactionAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
298
298
|
new (...args: any[]): {
|
|
299
299
|
hash?: __.Key<_.Blake2b256>
|
|
300
|
+
txSeq?: number | null
|
|
300
301
|
blockHash?: _.Blake2b256 | null
|
|
301
302
|
blockHeight?: number | null
|
|
302
303
|
blockTime?: number | null
|
|
@@ -328,8 +329,8 @@ export class Transactions extends Array<Transaction> {
|
|
|
328
329
|
// entity 'TransactionInput'
|
|
329
330
|
export declare function _TransactionInputAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
330
331
|
new (...args: any[]): {
|
|
331
|
-
|
|
332
|
-
|
|
332
|
+
txSeq?: __.Key<number>
|
|
333
|
+
tx?: __.Association.to<Transaction> | null
|
|
333
334
|
inputIndex?: __.Key<number>
|
|
334
335
|
address?: __.Association.to<Address> | null
|
|
335
336
|
address_address?: _.Bech32 | null
|
|
@@ -358,8 +359,8 @@ export class TransactionInputs extends Array<TransactionInput> {
|
|
|
358
359
|
// entity 'TransactionOutput'
|
|
359
360
|
export declare function _TransactionOutputAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
360
361
|
new (...args: any[]): {
|
|
361
|
-
|
|
362
|
-
|
|
362
|
+
txSeq?: __.Key<number>
|
|
363
|
+
tx?: __.Association.to<Transaction> | null
|
|
363
364
|
outputIndex?: __.Key<number>
|
|
364
365
|
address?: __.Association.to<Address> | null
|
|
365
366
|
address_address?: _.Bech32 | null
|
|
@@ -385,8 +386,8 @@ export class TransactionOutputs extends Array<TransactionOutput> {
|
|
|
385
386
|
export declare function _TransactionInputAssetAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
386
387
|
new (...args: any[]): {
|
|
387
388
|
input?: __.Key<__.Association.to<TransactionInput>>
|
|
389
|
+
input_txSeq?: __.Key<number>
|
|
388
390
|
input_inputIndex?: __.Key<number>
|
|
389
|
-
input_tx_hash?: __.Key<_.Blake2b256>
|
|
390
391
|
unit?: __.Key<_.AssetUnit>
|
|
391
392
|
asset_quantity?: _.Lovelace | null
|
|
392
393
|
asset_policyId?: _.Blake2b224 | null
|
|
@@ -409,8 +410,8 @@ export class TransactionInputAssets extends Array<TransactionInputAsset> {
|
|
|
409
410
|
export declare function _TransactionOutputAssetAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
410
411
|
new (...args: any[]): {
|
|
411
412
|
output?: __.Key<__.Association.to<TransactionOutput>>
|
|
413
|
+
output_txSeq?: __.Key<number>
|
|
412
414
|
output_outputIndex?: __.Key<number>
|
|
413
|
-
output_tx_hash?: __.Key<_.Blake2b256>
|
|
414
415
|
unit?: __.Key<_.AssetUnit>
|
|
415
416
|
asset_quantity?: _.Lovelace | null
|
|
416
417
|
asset_policyId?: _.Blake2b224 | null
|
|
@@ -387,6 +387,7 @@ export class Accounts extends Array<Account> {
|
|
|
387
387
|
export declare function _TransactionAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
388
388
|
new (...args: any[]): {
|
|
389
389
|
hash?: __.Key<_.Blake2b256>
|
|
390
|
+
txSeq?: number | null
|
|
390
391
|
blockHash?: _.Blake2b256 | null
|
|
391
392
|
blockHeight?: number | null
|
|
392
393
|
blockTime?: number | null
|
|
@@ -418,8 +419,8 @@ export class Transactions extends Array<Transaction> {
|
|
|
418
419
|
// entity 'TransactionInput'
|
|
419
420
|
export declare function _TransactionInputAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
420
421
|
new (...args: any[]): {
|
|
421
|
-
|
|
422
|
-
|
|
422
|
+
txSeq?: __.Key<number>
|
|
423
|
+
tx?: __.Association.to<Transaction> | null
|
|
423
424
|
inputIndex?: __.Key<number>
|
|
424
425
|
address?: __.Association.to<Address> | null
|
|
425
426
|
address_address?: _.Bech32 | null
|
|
@@ -449,8 +450,8 @@ export class TransactionInputs extends Array<TransactionInput> {
|
|
|
449
450
|
export declare function _TransactionInputAssetAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
450
451
|
new (...args: any[]): {
|
|
451
452
|
input?: __.Key<__.Association.to<TransactionInput>>
|
|
453
|
+
input_txSeq?: __.Key<number>
|
|
452
454
|
input_inputIndex?: __.Key<number>
|
|
453
|
-
input_tx_hash?: __.Key<_.Blake2b256>
|
|
454
455
|
unit?: __.Key<_.AssetUnit>
|
|
455
456
|
asset_quantity?: _.Lovelace | null
|
|
456
457
|
asset_policyId?: _.Blake2b224 | null
|
|
@@ -638,8 +639,8 @@ export class TransactionWithdrawals extends Array<TransactionWithdrawal> {
|
|
|
638
639
|
// entity 'TransactionOutput'
|
|
639
640
|
export declare function _TransactionOutputAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
640
641
|
new (...args: any[]): {
|
|
641
|
-
|
|
642
|
-
|
|
642
|
+
txSeq?: __.Key<number>
|
|
643
|
+
tx?: __.Association.to<Transaction> | null
|
|
643
644
|
outputIndex?: __.Key<number>
|
|
644
645
|
address?: __.Association.to<Address> | null
|
|
645
646
|
address_address?: _.Bech32 | null
|
|
@@ -665,8 +666,8 @@ export class TransactionOutputs extends Array<TransactionOutput> {
|
|
|
665
666
|
export declare function _TransactionOutputAssetAspect<TBase extends new (...args: any[]) => object>(Base: TBase): {
|
|
666
667
|
new (...args: any[]): {
|
|
667
668
|
output?: __.Key<__.Association.to<TransactionOutput>>
|
|
669
|
+
output_txSeq?: __.Key<number>
|
|
668
670
|
output_outputIndex?: __.Key<number>
|
|
669
|
-
output_tx_hash?: __.Key<_.Blake2b256>
|
|
670
671
|
unit?: __.Key<_.AssetUnit>
|
|
671
672
|
asset_quantity?: _.Lovelace | null
|
|
672
673
|
asset_policyId?: _.Blake2b224 | null
|
package/db/schema.cds
CHANGED
|
@@ -62,7 +62,7 @@ entity Blocks {
|
|
|
62
62
|
height : Integer;
|
|
63
63
|
|
|
64
64
|
@title : 'Block SlotLeader'
|
|
65
|
-
@description: '
|
|
65
|
+
@description: 'Bech32 id of the pool that produced the block'
|
|
66
66
|
slotLeader : String;
|
|
67
67
|
|
|
68
68
|
@title : 'Block Epoch Number'
|
|
@@ -636,6 +636,10 @@ entity Transactions {
|
|
|
636
636
|
@description: 'The unique transaction identifier as hex string'
|
|
637
637
|
key hash : Blake2b256;
|
|
638
638
|
|
|
639
|
+
@title : 'Transaction Sequence Number'
|
|
640
|
+
@description: 'Chain position slot * 65536 + txIndex; key of the input and output rows, ascending along the chain'
|
|
641
|
+
txSeq : Integer64;
|
|
642
|
+
|
|
639
643
|
@title : 'Transaction Block Hash'
|
|
640
644
|
@description: 'The block hash containing the transaction'
|
|
641
645
|
blockHash : Blake2b256;
|
|
@@ -676,12 +680,12 @@ entity Transactions {
|
|
|
676
680
|
@title : 'Transaction Inputs'
|
|
677
681
|
@description: 'The transaction inputs composition'
|
|
678
682
|
inputs : Composition of many TransactionInputs
|
|
679
|
-
on inputs.
|
|
683
|
+
on inputs.txSeq = txSeq;
|
|
680
684
|
|
|
681
685
|
@title : 'Transaction Outputs'
|
|
682
686
|
@description: 'The transaction outputs composition'
|
|
683
687
|
outputs : Composition of many TransactionOutputs
|
|
684
|
-
on outputs.
|
|
688
|
+
on outputs.txSeq = txSeq;
|
|
685
689
|
|
|
686
690
|
@title : 'Transaction Certificates'
|
|
687
691
|
@description: 'Certificates carried by the transaction (stake/pool/DRep). Filled by the chain crawler only (crawler.certificates); the lazy path leaves it empty.'
|
|
@@ -711,9 +715,13 @@ entity Transactions {
|
|
|
711
715
|
@readonly
|
|
712
716
|
entity TransactionInputs {
|
|
713
717
|
|
|
714
|
-
@title : 'Transaction (key)'
|
|
718
|
+
@title : 'Transaction Sequence Number (key)'
|
|
719
|
+
@description: 'Transactions.txSeq of the spending transaction'
|
|
720
|
+
key txSeq : Integer64;
|
|
721
|
+
|
|
722
|
+
@title : 'Transaction'
|
|
715
723
|
@description: 'The associated transaction'
|
|
716
|
-
|
|
724
|
+
tx : Association to one Transactions on tx.txSeq = txSeq;
|
|
717
725
|
|
|
718
726
|
@title : 'Input Index (key)'
|
|
719
727
|
@description: 'The input index of the input utxo'
|
|
@@ -1015,9 +1023,13 @@ entity TransactionWithdrawals {
|
|
|
1015
1023
|
@readonly
|
|
1016
1024
|
entity TransactionOutputs {
|
|
1017
1025
|
|
|
1018
|
-
@title : 'Transaction (key)'
|
|
1026
|
+
@title : 'Transaction Sequence Number (key)'
|
|
1027
|
+
@description: 'Transactions.txSeq of the creating transaction'
|
|
1028
|
+
key txSeq : Integer64;
|
|
1029
|
+
|
|
1030
|
+
@title : 'Transaction'
|
|
1019
1031
|
@description: 'The associated transaction'
|
|
1020
|
-
|
|
1032
|
+
tx : Association to one Transactions on tx.txSeq = txSeq;
|
|
1021
1033
|
|
|
1022
1034
|
@title : 'Output Index (key)'
|
|
1023
1035
|
@description: 'The output index of the output utxo'
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@odatano/core",
|
|
3
|
-
"version": "2.0.0-rc.
|
|
3
|
+
"version": "2.0.0-rc.21",
|
|
4
4
|
"description": "SAP CAP plugin for Cardano blockchain OData V4 integration",
|
|
5
5
|
"imports": {
|
|
6
6
|
"#cds-models/*": "./@cds-models/*/index.js"
|
|
@@ -15,7 +15,9 @@
|
|
|
15
15
|
"srv/**/*.d.ts",
|
|
16
16
|
"srv/**/*.cds",
|
|
17
17
|
"db/**/*.cds",
|
|
18
|
-
"@cds-models/"
|
|
18
|
+
"@cds-models/",
|
|
19
|
+
"scripts/migrate-txseq.mjs",
|
|
20
|
+
"scripts/migrate-slot-leader.mjs"
|
|
19
21
|
],
|
|
20
22
|
"engines": {
|
|
21
23
|
"node": ">=22.5"
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Rewrite Blocks.slotLeader values written before it became the bech32 pool id: an Ogmios
|
|
3
|
+
// issuer key (64 hex chars) becomes bech32('pool', blake2b-224(key)); a Koios VRF key
|
|
4
|
+
// (vrf_vk1…) is matched on blake2b-256 against the pools' registered VRF key hashes, taken
|
|
5
|
+
// from an Ogmios `queryLedgerState/stakePools` response. Prints SQL; the database is not touched.
|
|
6
|
+
//
|
|
7
|
+
// psql -Atc "SELECT DISTINCT slotLeader FROM odatano_cardano_Blocks WHERE slotLeader NOT LIKE 'pool1%'" \
|
|
8
|
+
// | node scripts/migrate-slot-leader.mjs [--stake-pools stake-pools.json] [--extra-map extra.txt] > slot-leader.sql
|
|
9
|
+
//
|
|
10
|
+
// The SQL fills a mapping table and runs one UPDATE (PostgreSQL and SQLite). Values that cannot
|
|
11
|
+
// be mapped (a VRF key of a pool no longer registered, unknown formats) are listed on stderr
|
|
12
|
+
// and left unchanged; `--extra-map` supplies them as "<old value> <pool id>" lines.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import { pathToFileURL } from 'node:url';
|
|
15
|
+
import { bech32 } from 'bech32';
|
|
16
|
+
import { blake2b_224, blake2b_256 } from '@harmoniclabs/crypto';
|
|
17
|
+
|
|
18
|
+
const toHex = (bytes) => Buffer.from(bytes).toString('hex');
|
|
19
|
+
const lines = (text) => text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
|
|
20
|
+
|
|
21
|
+
/** VRF key hash (hex) -> pool id, from an Ogmios stakePools response (whole JSON-RPC reply or its result). */
|
|
22
|
+
export function vrfMapFromStakePools(response) {
|
|
23
|
+
const pools = response?.result ?? response ?? {};
|
|
24
|
+
const map = new Map();
|
|
25
|
+
for (const [id, pool] of Object.entries(pools)) {
|
|
26
|
+
const vrf = pool?.vrfVerificationKeyHash;
|
|
27
|
+
if (typeof vrf === 'string') map.set(vrf.toLowerCase(), pool.id ?? id);
|
|
28
|
+
}
|
|
29
|
+
return map;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** "<old value> <pool id>" lines to a Map; lines starting with # are skipped. */
|
|
33
|
+
export function parseExtraMap(text) {
|
|
34
|
+
const map = new Map();
|
|
35
|
+
for (const line of lines(text)) {
|
|
36
|
+
if (line.startsWith('#')) continue;
|
|
37
|
+
const [from, to] = line.split(/\s+/);
|
|
38
|
+
if (!to?.startsWith('pool1')) throw new Error(`extra map: no pool id for ${from}`);
|
|
39
|
+
map.set(from, to);
|
|
40
|
+
}
|
|
41
|
+
return map;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Bech32 pool id for an old slotLeader value, or null when it cannot be derived. */
|
|
45
|
+
export function slotLeaderToPoolId(value, vrfMap = new Map()) {
|
|
46
|
+
if (typeof value !== 'string') return null;
|
|
47
|
+
const v = value.trim();
|
|
48
|
+
if (/^[0-9a-f]{64}$/i.test(v)) {
|
|
49
|
+
return bech32.encode('pool', bech32.toWords(blake2b_224(Uint8Array.from(Buffer.from(v, 'hex')))));
|
|
50
|
+
}
|
|
51
|
+
if (v.startsWith('vrf_vk1')) {
|
|
52
|
+
const { words } = bech32.decode(v, 120);
|
|
53
|
+
const vrfHash = toHex(blake2b_256(Uint8Array.from(bech32.fromWords(words))));
|
|
54
|
+
return vrfMap.get(vrfHash) ?? null;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const sqlString = (s) => `'${s.replace(/'/g, "''")}'`;
|
|
60
|
+
|
|
61
|
+
/** SQL that rewrites every mapped value in one UPDATE; empty string when nothing maps. */
|
|
62
|
+
export function migrationSql(mapping) {
|
|
63
|
+
if (mapping.size === 0) return '';
|
|
64
|
+
const rows = [...mapping].map(([from, to]) => ` (${sqlString(from)}, ${sqlString(to)})`);
|
|
65
|
+
return [
|
|
66
|
+
'BEGIN;',
|
|
67
|
+
'CREATE TEMPORARY TABLE slot_leader_map (old_value VARCHAR(200) PRIMARY KEY, new_value VARCHAR(120) NOT NULL);',
|
|
68
|
+
`INSERT INTO slot_leader_map (old_value, new_value) VALUES\n${rows.join(',\n')};`,
|
|
69
|
+
'UPDATE odatano_cardano_Blocks',
|
|
70
|
+
' SET slotLeader = (SELECT m.new_value FROM slot_leader_map m WHERE m.old_value = odatano_cardano_Blocks.slotLeader)',
|
|
71
|
+
' WHERE slotLeader IN (SELECT old_value FROM slot_leader_map);',
|
|
72
|
+
'DROP TABLE slot_leader_map;',
|
|
73
|
+
'COMMIT;',
|
|
74
|
+
'',
|
|
75
|
+
].join('\n');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function argValue(name) {
|
|
79
|
+
const i = process.argv.indexOf(name);
|
|
80
|
+
return i >= 0 ? process.argv[i + 1] : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function main() {
|
|
84
|
+
const stakePoolsFile = argValue('--stake-pools');
|
|
85
|
+
const extraMapFile = argValue('--extra-map');
|
|
86
|
+
const vrfMap = stakePoolsFile ? vrfMapFromStakePools(JSON.parse(fs.readFileSync(stakePoolsFile, 'utf8'))) : new Map();
|
|
87
|
+
const extraMap = extraMapFile ? parseExtraMap(fs.readFileSync(extraMapFile, 'utf8')) : new Map();
|
|
88
|
+
|
|
89
|
+
const values = [...new Set(lines(fs.readFileSync(0, 'utf8')))];
|
|
90
|
+
const mapping = new Map();
|
|
91
|
+
const unmapped = [];
|
|
92
|
+
for (const v of values) {
|
|
93
|
+
if (v.startsWith('pool1')) continue;
|
|
94
|
+
const poolId = extraMap.get(v) ?? slotLeaderToPoolId(v, vrfMap);
|
|
95
|
+
if (poolId) mapping.set(v, poolId);
|
|
96
|
+
else unmapped.push(v);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
process.stdout.write(migrationSql(mapping));
|
|
100
|
+
console.error(`slotLeader values: ${values.length} read, ${mapping.size} mapped, ${unmapped.length} left unchanged`);
|
|
101
|
+
for (const v of unmapped) console.error(` unmapped: ${v}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Move a database written before the txSeq schema onto it: TransactionInputs / TransactionOutputs
|
|
3
|
+
// and their asset tables are keyed by Transactions.txSeq (slot * 65536 + txIndex) instead of the
|
|
4
|
+
// transaction hash. Runs against the configured `db` (PostgreSQL or SQLite) with ODATANO stopped:
|
|
5
|
+
//
|
|
6
|
+
// node scripts/migrate-txseq.mjs # image: docker compose run --rm --no-deps odatano migrate-txseq
|
|
7
|
+
// node scripts/migrate-txseq.mjs --dry-run # report what would change, touch nothing
|
|
8
|
+
//
|
|
9
|
+
// One transaction: fill Transactions.txSeq, rebuild the four tables in the new layout (rows copied
|
|
10
|
+
// in key order, row counts checked), recreate the service views, refresh the planner statistics
|
|
11
|
+
// and store the new model in `cds_model` so the next schema deployment sees no difference. A
|
|
12
|
+
// database already on the new layout is left alone. The table indexes are recreated by the server
|
|
13
|
+
// on its next start.
|
|
14
|
+
import cds from '@sap/cds';
|
|
15
|
+
|
|
16
|
+
const DRY = process.argv.includes('--dry-run');
|
|
17
|
+
const T = (name) => `odatano_cardano_${name}`;
|
|
18
|
+
const TX_SEQ_SLOT_FACTOR = 65536;
|
|
19
|
+
|
|
20
|
+
/** Old key column -> new key column, and the column the copy is ordered by after the key. */
|
|
21
|
+
const TABLES = [
|
|
22
|
+
{ name: 'TransactionInputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'inputIndex' },
|
|
23
|
+
{ name: 'TransactionOutputs', hashKey: 'tx_hash', seqKey: 'txSeq', order: 'outputIndex' },
|
|
24
|
+
{ name: 'TransactionInputAssets', hashKey: 'input_tx_hash', seqKey: 'input_txSeq', order: 'input_inputIndex, unit' },
|
|
25
|
+
{ name: 'TransactionOutputAssets', hashKey: 'output_tx_hash', seqKey: 'output_txSeq', order: 'output_outputIndex, unit' },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
/** Column names of a table, lower-cased (PostgreSQL folds unquoted identifiers). */
|
|
29
|
+
export async function tableColumns(db, table) {
|
|
30
|
+
const rows = db.kind === 'postgres'
|
|
31
|
+
? await db.run(`SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = '${table.toLowerCase()}'`)
|
|
32
|
+
: await db.run(`SELECT name FROM pragma_table_info('${table}')`);
|
|
33
|
+
return rows.map(r => String(r.name).toLowerCase());
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** CREATE statements of the compiled model for one table (renamed) and for every view. */
|
|
37
|
+
export function modelStatements(model, options) {
|
|
38
|
+
const sql = cds.compile.to.sql(model, options);
|
|
39
|
+
const views = sql.filter(s => /^CREATE VIEW/i.test(s.trim()));
|
|
40
|
+
const tableDdl = (name) => {
|
|
41
|
+
const stmt = sql.find(s => new RegExp(`^CREATE TABLE ${T(name)} \\(`, 'i').test(s.trim()));
|
|
42
|
+
if (!stmt) throw new Error(`model has no table ${T(name)}`);
|
|
43
|
+
return stmt;
|
|
44
|
+
};
|
|
45
|
+
return { views, tableDdl };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const viewName = (stmt) => stmt.trim().match(/^CREATE VIEW\s+("?[\w.]+"?)/i)[1];
|
|
49
|
+
|
|
50
|
+
/** Copy statement: every column of the old table except the hash key, the new key from Transactions. */
|
|
51
|
+
export function copySql(spec, oldColumns) {
|
|
52
|
+
const others = oldColumns.filter(c => c !== spec.hashKey.toLowerCase());
|
|
53
|
+
const target = [spec.seqKey, ...others].join(', ');
|
|
54
|
+
const source = ['t.txSeq', ...others.map(c => `x.${c}`)].join(', ');
|
|
55
|
+
const order = ['t.txSeq', ...spec.order.split(',').map(c => `x.${c.trim()}`)].join(', ');
|
|
56
|
+
return `INSERT INTO ${T(spec.name)}_txseq_new (${target}) SELECT ${source} FROM ${T(spec.name)} x `
|
|
57
|
+
+ `JOIN ${T('Transactions')} t ON t.hash = x.${spec.hashKey} ORDER BY ${order}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function count(tx, table) {
|
|
61
|
+
const [row] = await tx.run(`SELECT count(*) AS n FROM ${table}`);
|
|
62
|
+
return Number(row.n);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function main() {
|
|
66
|
+
const db = await cds.connect.to('db');
|
|
67
|
+
if (db.kind !== 'postgres' && db.kind !== 'sqlite') throw new Error(`unsupported database kind ${db.kind}: re-crawl instead`);
|
|
68
|
+
|
|
69
|
+
const inputColumns = await tableColumns(db, T('TransactionInputs'));
|
|
70
|
+
if (!inputColumns.includes('tx_hash')) {
|
|
71
|
+
console.log('Already on the txSeq layout; nothing to do.');
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const [lease] = await db.run(`SELECT leaseUntil FROM ${T('CardanoSyncState')}`).catch(() => []);
|
|
76
|
+
const leaseUntil = lease?.leaseUntil ?? lease?.leaseuntil;
|
|
77
|
+
if (leaseUntil && Date.parse(leaseUntil) > Date.now()) {
|
|
78
|
+
throw new Error(`the crawler lease is held until ${leaseUntil}: stop ODATANO first`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// the model exactly as `cds deploy` compiles it
|
|
82
|
+
const model = await cds.load('*').then(cds.minify);
|
|
83
|
+
cds.deploy.exclude_external_entities_in(model);
|
|
84
|
+
const options = { ...db.options };
|
|
85
|
+
const { views, tableDdl } = modelStatements(model, options);
|
|
86
|
+
const [hasModelTable] = await db.run(db.kind === 'postgres'
|
|
87
|
+
? `SELECT 1 AS x FROM pg_tables WHERE tablename = 'cds_model' AND schemaname = current_schema()`
|
|
88
|
+
: `SELECT 1 AS x FROM sqlite_schema WHERE name = 'cds_model'`);
|
|
89
|
+
|
|
90
|
+
const txNull = Number((await db.run(`SELECT count(*) AS n FROM ${T('Transactions')} WHERE slot IS NULL OR txIndex IS NULL`))[0].n);
|
|
91
|
+
if (txNull > 0) throw new Error(`${txNull} transactions have no slot or txIndex; their txSeq cannot be derived`);
|
|
92
|
+
|
|
93
|
+
const plan = [];
|
|
94
|
+
for (const spec of TABLES) plan.push({ spec, columns: await tableColumns(db, T(spec.name)), rows: await count(db, T(spec.name)) });
|
|
95
|
+
for (const p of plan) console.log(`${T(p.spec.name)}: ${p.rows} rows, key ${p.spec.hashKey} -> ${p.spec.seqKey}`);
|
|
96
|
+
console.log(`${views.length} views recreated${hasModelTable ? ', cds_model updated' : ''}`);
|
|
97
|
+
if (DRY) { console.log('dry run: nothing changed'); return; }
|
|
98
|
+
|
|
99
|
+
await db.tx(async (tx) => {
|
|
100
|
+
const started = Date.now();
|
|
101
|
+
const step = (msg) => console.log(`[${Math.round((Date.now() - started) / 1000)}s] ${msg}`);
|
|
102
|
+
|
|
103
|
+
for (const stmt of [...views].reverse()) {
|
|
104
|
+
await tx.run(`DROP VIEW IF EXISTS ${viewName(stmt)}${db.kind === 'postgres' ? ' CASCADE' : ''}`);
|
|
105
|
+
}
|
|
106
|
+
step('views dropped');
|
|
107
|
+
|
|
108
|
+
const txColumns = await tableColumns(tx, T('Transactions'));
|
|
109
|
+
if (!txColumns.includes('txseq')) await tx.run(`ALTER TABLE ${T('Transactions')} ADD COLUMN txSeq BIGINT`);
|
|
110
|
+
await tx.run(`UPDATE ${T('Transactions')} SET txSeq = slot * ${TX_SEQ_SLOT_FACTOR} + txIndex`);
|
|
111
|
+
await tx.run(`CREATE INDEX IF NOT EXISTS odatano_cardano_transactions_txseq ON ${T('Transactions')} (txSeq)`);
|
|
112
|
+
step('Transactions.txSeq filled');
|
|
113
|
+
|
|
114
|
+
for (const { spec, columns, rows } of plan) {
|
|
115
|
+
const table = T(spec.name);
|
|
116
|
+
const newTable = `${table}_txseq_new`;
|
|
117
|
+
await tx.run(tableDdl(spec.name).replace(new RegExp(`^(\\s*CREATE TABLE )${table}\\b`, 'i'), `$1${newTable}`));
|
|
118
|
+
await tx.run(copySql(spec, columns));
|
|
119
|
+
const copied = await count(tx, newTable);
|
|
120
|
+
if (copied !== rows) throw new Error(`${table}: ${rows} rows, ${copied} copied (rows without a Transactions row?)`);
|
|
121
|
+
await tx.run(`DROP TABLE ${table}`);
|
|
122
|
+
await tx.run(`ALTER TABLE ${newTable} RENAME TO ${table}`);
|
|
123
|
+
if (db.kind === 'postgres') {
|
|
124
|
+
await tx.run(`ALTER TABLE ${table} RENAME CONSTRAINT ${newTable.toLowerCase()}_pkey TO ${table.toLowerCase()}_pkey`);
|
|
125
|
+
}
|
|
126
|
+
step(`${table}: ${copied} rows`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
for (const stmt of views) await tx.run(stmt);
|
|
130
|
+
step('views recreated');
|
|
131
|
+
|
|
132
|
+
// fresh planner statistics: without them the rebuilt tables are read by sequential scans
|
|
133
|
+
for (const name of ['Transactions', ...TABLES.map(t => t.name)]) await tx.run(`ANALYZE ${T(name)}`);
|
|
134
|
+
step('statistics updated');
|
|
135
|
+
|
|
136
|
+
if (hasModelTable) {
|
|
137
|
+
const { afterImage } = cds.compile.to.sql.delta(model, options);
|
|
138
|
+
await tx.run(db.kind === 'postgres' ? 'UPDATE cds_model SET csn = $1' : 'UPDATE cds_model SET csn = ?', [JSON.stringify(afterImage)]);
|
|
139
|
+
step('cds_model updated');
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
console.log('Migration to the txSeq layout done. Start ODATANO; it recreates the table indexes.');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (process.argv[1] && import.meta.url === (await import('node:url')).pathToFileURL(process.argv[1]).href) {
|
|
146
|
+
main().then(() => process.exit(0), (err) => { console.error(`FAILED: ${err.message}`); process.exit(1); });
|
|
147
|
+
}
|
|
@@ -120,11 +120,16 @@ export interface ChainSyncBackend extends CardanoBackend {
|
|
|
120
120
|
/** Type guard: does this backend support streamed chain-sync? */
|
|
121
121
|
export declare function isChainSyncBackend(backend: CardanoBackend): backend is ChainSyncBackend;
|
|
122
122
|
/**
|
|
123
|
-
* Backend that
|
|
124
|
-
*
|
|
123
|
+
* Backend that reads UTxOs straight from the node's ledger (Ogmios `queryLedgerState/utxo`):
|
|
124
|
+
* the whole set as of a chain point inside the volatile window, or selected outputs at the tip.
|
|
125
125
|
*/
|
|
126
126
|
export interface LedgerStateBackend extends CardanoBackend {
|
|
127
127
|
queryUtxoSetAt(point: ChainPoint): Promise<UTxO[]>;
|
|
128
|
+
/** Outputs among `refs` that are unspent at the tip; spent or unknown references are absent. */
|
|
129
|
+
getUnspentOutputs(refs: Array<{
|
|
130
|
+
txHash: string;
|
|
131
|
+
outputIndex: number;
|
|
132
|
+
}>): Promise<UTxO[]>;
|
|
128
133
|
}
|
|
129
134
|
export declare function isLedgerStateBackend(backend: CardanoBackend): backend is LedgerStateBackend;
|
|
130
135
|
/**
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, LedgerProtocolParameters, ScriptEvaluationResult } from '../../utils/types';
|
|
2
2
|
import { EvaluatingBackend, ChainSyncBackend, ChainSyncCallbacks, ChainSyncHandle, ChainPoint, LedgerStateBackend } from './cardano-backend';
|
|
3
3
|
import { Network } from '../cardano-client';
|
|
4
|
+
/** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
|
|
5
|
+
export declare function ogmiosScriptHash(script: unknown): string | null;
|
|
6
|
+
/** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
|
|
7
|
+
export declare function issuerKeyToPoolId(verificationKeyHex: string): string;
|
|
4
8
|
/**
|
|
5
9
|
* Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
|
|
6
10
|
* high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
|
|
@@ -24,8 +28,8 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
|
|
|
24
28
|
readonly name = "ogmios";
|
|
25
29
|
/**
|
|
26
30
|
* Capability declaration — the orchestrator skips Ogmios for these without counting
|
|
27
|
-
* circuit failures. Historic queries are out of protocol scope, and address
|
|
28
|
-
*
|
|
31
|
+
* circuit failures. Historic queries are out of protocol scope, and address aggregates
|
|
32
|
+
* cannot be derived from state queries.
|
|
29
33
|
*/
|
|
30
34
|
readonly unsupportedMethods: ReadonlySet<string>;
|
|
31
35
|
private stateQueryClient;
|
|
@@ -101,7 +105,10 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
|
|
|
101
105
|
* @returns {Promise<AssetInfo>} asset info
|
|
102
106
|
*/
|
|
103
107
|
getAssetInfo(_unit: string): Promise<AssetInfo>;
|
|
104
|
-
/**
|
|
108
|
+
/**
|
|
109
|
+
* Supply figures from `queryLedgerState/treasuryAndReserves`: total = max − reserves.
|
|
110
|
+
* Circulating, locked and stake totals are not in the ledger state and stay '0'.
|
|
111
|
+
*/
|
|
105
112
|
getNetworkInformation(): Promise<NetworkInformation>;
|
|
106
113
|
/**
|
|
107
114
|
* Not supported — address type, script flag and stake address are not derivable from
|
|
@@ -173,6 +180,11 @@ export declare class OgmiosBackend implements EvaluatingBackend, ChainSyncBacken
|
|
|
173
180
|
* @param outputIndex non-negative integer
|
|
174
181
|
*/
|
|
175
182
|
isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
|
|
183
|
+
/** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
|
|
184
|
+
getUnspentOutputs(refs: Array<{
|
|
185
|
+
txHash: string;
|
|
186
|
+
outputIndex: number;
|
|
187
|
+
}>): Promise<UTxO[]>;
|
|
176
188
|
/** Close the WebSocket and mark the backend as shut down. */
|
|
177
189
|
shutdown(): Promise<void>;
|
|
178
190
|
isConnected(): boolean;
|