@odatano/core 2.0.0-rc.44 → 2.0.0-rc.45
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 +0 -46
- package/@cds-models/CardanoBackendService/index.d.ts +0 -10
- package/@cds-models/CardanoIndexerService/index.d.ts +5 -20
- package/@cds-models/CardanoODataService/index.d.ts +18 -47
- package/@cds-models/CardanoSignService/index.d.ts +3 -18
- package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
- package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
- package/@cds-models/index.d.ts +17 -0
- package/@cds-models/index.js +2 -0
- package/@cds-models/odatano/cardano/index.d.ts +0 -34
- package/README.md +6 -6
- package/db/schema.cds +25 -44
- package/db/types.cds +22 -5
- package/package.json +3 -1
- package/scripts/migrate-slot-leader.mjs +3 -11
- package/scripts/migrate-txseq.mjs +3 -12
- package/src/index.d.ts +0 -4
- package/src/index.js +3 -5
- package/src/plugin.js +4 -8
- package/srv/blockchain/asset-decimals.d.ts +0 -9
- package/srv/blockchain/asset-decimals.js +21 -16
- package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
- package/srv/blockchain/backends/blockfrost-backend.js +15 -21
- package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
- package/srv/blockchain/backends/koios-backend.d.ts +14 -147
- package/srv/blockchain/backends/koios-backend.js +40 -164
- package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
- package/srv/blockchain/backends/odatano-backend.js +11 -12
- package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
- package/srv/blockchain/backends/ogmios-backend.js +48 -175
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
- package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
- package/srv/blockchain/cardano-client.d.ts +12 -80
- package/srv/blockchain/cardano-client.js +36 -88
- package/srv/blockchain/cardano-indexer.d.ts +12 -192
- package/srv/blockchain/cardano-indexer.js +126 -222
- package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
- package/srv/blockchain/cardano-tx-builder.js +17 -34
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +0 -5
- package/srv/blockchain/crawler/asset-decimals-backfill.js +2 -5
- package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
- package/srv/blockchain/crawler/certificate-backfill.js +8 -22
- package/srv/blockchain/crawler/crawler.d.ts +16 -93
- package/srv/blockchain/crawler/crawler.js +85 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +0 -10
- package/srv/blockchain/crawler/credential-backfill.js +2 -4
- package/srv/blockchain/crawler/hooks.d.ts +1 -5
- package/srv/blockchain/crawler/index.d.ts +0 -12
- package/srv/blockchain/crawler/index.js +6 -20
- package/srv/blockchain/crawler/sync-state.d.ts +6 -44
- package/srv/blockchain/crawler/sync-state.js +18 -53
- package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
- package/srv/blockchain/crawler/transaction-backfill.js +11 -30
- package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
- package/srv/blockchain/crawler/utxo-set-import.js +27 -53
- package/srv/blockchain/ledger-state.d.ts +10 -54
- package/srv/blockchain/ledger-state.js +11 -27
- package/srv/blockchain/pending-spends.d.ts +0 -12
- package/srv/blockchain/pending-spends.js +4 -12
- 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 +0 -9
- package/srv/blockchain/signing/cose-verifier.js +4 -10
- package/srv/blockchain/signing/external-signer.d.ts +1 -4
- package/srv/blockchain/signing/external-signer.js +2 -8
- package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
- package/srv/blockchain/signing/hsm-signer.js +16 -28
- package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
- package/srv/blockchain/signing/signature-verifier.js +9 -19
- package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
- package/srv/blockchain/signing/submission-finalizer.js +48 -19
- package/srv/blockchain/stored-chain.d.ts +1 -14
- package/srv/blockchain/stored-chain.js +3 -8
- package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
- package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
- package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
- package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
- package/srv/blockchain/transaction-building/caller-datums.js +3 -9
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
- package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
- package/srv/blockchain/wallet-worker/build-request.js +6 -9
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -5
- package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
- package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
- package/srv/blockchain/wallet-worker/signers.js +3 -6
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
- package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
- package/srv/cardano-agent-service.cds +123 -146
- package/srv/cardano-agent-service.js +2 -5
- package/srv/cardano-backend-service.cds +10 -17
- package/srv/cardano-backend-service.js +7 -12
- package/srv/cardano-indexer-service.cds +16 -37
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +44 -35
- package/srv/cardano-service.cds +56 -40
- package/srv/cardano-service.js +42 -69
- package/srv/cardano-sign-service.cds +14 -23
- package/srv/cardano-sign-service.js +18 -24
- package/srv/cardano-tx-service.cds +27 -29
- package/srv/cardano-tx-service.js +60 -122
- package/srv/cardano-worker-service.cds +109 -125
- package/srv/cardano-worker-service.js +21 -31
- package/srv/cbor/cip68.d.ts +0 -4
- package/srv/cbor/cip68.js +2 -4
- package/srv/cbor/parse.d.ts +3 -18
- package/srv/cbor/parse.js +2 -7
- package/srv/cbor/plutus-data-json.d.ts +0 -4
- package/srv/server.d.ts +5 -36
- package/srv/server.js +30 -51
- package/srv/utils/agent-grants-config.d.ts +0 -18
- package/srv/utils/agent-grants-config.js +6 -13
- package/srv/utils/agent-grants.d.ts +14 -68
- package/srv/utils/agent-grants.js +42 -60
- package/srv/utils/agent-token-auth.d.ts +0 -5
- package/srv/utils/agent-token-auth.js +2 -5
- package/srv/utils/backend-request-handler.d.ts +1 -1
- package/srv/utils/collections.d.ts +1 -4
- package/srv/utils/collections.js +1 -4
- package/srv/utils/const.d.ts +0 -18
- package/srv/utils/const.js +7 -18
- package/srv/utils/crypto.js +3 -5
- package/srv/utils/db-indexes.d.ts +2 -0
- package/srv/utils/db-indexes.js +22 -9
- package/srv/utils/db-sanitize.d.ts +1 -8
- package/srv/utils/db-sanitize.js +3 -8
- package/srv/utils/epoch-slots.d.ts +1 -8
- package/srv/utils/epoch-slots.js +3 -8
- package/srv/utils/error-codes.d.ts +0 -4
- package/srv/utils/error-codes.js +2 -4
- package/srv/utils/errors.d.ts +2 -22
- package/srv/utils/errors.js +13 -27
- package/srv/utils/liveness.d.ts +0 -4
- package/srv/utils/liveness.js +2 -4
- package/srv/utils/mappers.d.ts +0 -37
- package/srv/utils/mappers.js +19 -39
- package/srv/utils/network-context.js +2 -4
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.js +3 -7
- package/srv/utils/pg-order-nulls.js +2 -5
- package/srv/utils/plutus-placeholders.d.ts +0 -13
- package/srv/utils/plutus-placeholders.js +6 -13
- package/srv/utils/rate-limiter.d.ts +0 -8
- package/srv/utils/rate-limiter.js +2 -4
- package/srv/utils/reference-script.d.ts +0 -18
- package/srv/utils/reference-script.js +8 -19
- package/srv/utils/service-events.d.ts +0 -4
- package/srv/utils/service-events.js +2 -4
- package/srv/utils/signing-helper.d.ts +1 -8
- package/srv/utils/signing-helper.js +3 -8
- package/srv/utils/tx-build-helper.d.ts +2 -32
- package/srv/utils/tx-build-helper.js +26 -40
- package/srv/utils/tx-request-parsers.d.ts +1 -25
- package/srv/utils/tx-request-parsers.js +10 -25
- package/srv/utils/tx-utils.d.ts +0 -8
- package/srv/utils/tx-utils.js +10 -13
- package/srv/utils/types.d.ts +2 -37
- package/srv/utils/validators.d.ts +0 -4
- package/srv/utils/validators.js +2 -4
|
@@ -1,28 +1,14 @@
|
|
|
1
1
|
import { Tx } from "@harmoniclabs/cardano-ledger-ts";
|
|
2
|
-
/**
|
|
3
|
-
* Inline datums given as CBOR, keyed by output index. Buildooor writes every datum in its
|
|
4
|
-
* own encoding, so definite lists and maps change bytes and hash. These helpers put the
|
|
5
|
-
* caller's bytes back into the built transaction.
|
|
6
|
-
*/
|
|
7
2
|
export type CallerDatums = Map<number, Uint8Array>;
|
|
8
3
|
/** Bytes one output gains when its datum is written as given; negative when it shrinks. */
|
|
9
4
|
export declare function callerDatumGrowth(datum: Uint8Array): number;
|
|
10
5
|
/** Bytes the whole transaction gains from the caller's datums, never below zero. */
|
|
11
6
|
export declare function callerDatumsGrowth(datums: CallerDatums): number;
|
|
12
|
-
/**
|
|
13
|
-
* Replace Buildooor's datum encoding in the listed outputs with the caller's bytes.
|
|
14
|
-
* Only the datum bytes change. Containers in CBOR count items, not bytes, so the rest stays valid.
|
|
15
|
-
*/
|
|
16
7
|
export declare function writeCallerDatums(tx: Tx, datums: CallerDatums): Tx;
|
|
17
8
|
/** Datum hash as the ledger computes it: blake2b-256 of the datum bytes. */
|
|
18
9
|
export declare function datumHashOf(datum: Uint8Array): string;
|
|
19
10
|
/** Bytes the witness set gains from the caller's datums, never below zero. */
|
|
20
11
|
export declare function witnessDatumsGrowth(datums: Uint8Array[]): number;
|
|
21
|
-
/**
|
|
22
|
-
* Replace Buildooor's encoding of the witness datums with the caller's bytes, then recompute
|
|
23
|
-
* scriptDataHash over redeemers, datums and language views as they now stand in the transaction.
|
|
24
|
-
* The ledger finds a witness datum by the hash of its bytes, so a re-encoded datum is missing to it.
|
|
25
|
-
*/
|
|
26
12
|
export declare function writeWitnessDatums(tx: Tx, datums: Uint8Array[], languageViews: Uint8Array): Tx;
|
|
27
13
|
/** scriptDataHash of a transaction over its redeemer and datum bytes as they stand, laid out like Buildooor's getScriptDataHash. */
|
|
28
14
|
export declare function scriptDataHashOf(txBytes: Uint8Array, languageViews: Uint8Array): Uint8Array;
|
|
@@ -27,10 +27,7 @@ function callerDatumsGrowth(datums) {
|
|
|
27
27
|
growth += callerDatumGrowth(datum);
|
|
28
28
|
return Math.max(0, growth);
|
|
29
29
|
}
|
|
30
|
-
|
|
31
|
-
* Replace Buildooor's datum encoding in the listed outputs with the caller's bytes.
|
|
32
|
-
* Only the datum bytes change. Containers in CBOR count items, not bytes, so the rest stays valid.
|
|
33
|
-
*/
|
|
30
|
+
// Only the datum bytes change. CBOR containers count items, not bytes, so the rest stays valid.
|
|
34
31
|
function writeCallerDatums(tx, datums) {
|
|
35
32
|
if (datums.size === 0)
|
|
36
33
|
return tx;
|
|
@@ -82,11 +79,8 @@ function entryOf(map, key) {
|
|
|
82
79
|
function valueBytes(bytes, entry) {
|
|
83
80
|
return bytes.subarray(entry.k.subCborRef.end, endOf(entry.v));
|
|
84
81
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
* scriptDataHash over redeemers, datums and language views as they now stand in the transaction.
|
|
88
|
-
* The ledger finds a witness datum by the hash of its bytes, so a re-encoded datum is missing to it.
|
|
89
|
-
*/
|
|
82
|
+
// The ledger finds a witness datum by the hash of its bytes, so the caller's bytes go back in.
|
|
83
|
+
// Then scriptDataHash is recomputed over redeemers, datums and language views.
|
|
90
84
|
function writeWitnessDatums(tx, datums, languageViews) {
|
|
91
85
|
const wanted = new Map();
|
|
92
86
|
for (const datum of datums) {
|
|
@@ -4,10 +4,7 @@ import { CardanoClient } from "../cardano-client";
|
|
|
4
4
|
export interface CardanoTxBuilder {
|
|
5
5
|
/** Builder name */
|
|
6
6
|
name: string;
|
|
7
|
-
/**
|
|
8
|
-
* Initialize the builder.
|
|
9
|
-
* @param protocolParams - optional; fetched from the backend when omitted
|
|
10
|
-
*/
|
|
7
|
+
/** Initialize the builder. Protocol parameters are fetched when omitted. */
|
|
11
8
|
init(client: CardanoClient, protocolParams?: LedgerProtocolParameters): Promise<void>;
|
|
12
9
|
/** Build an unsigned transfer transaction (ADA-only or with native assets). */
|
|
13
10
|
buildUnsignedTransfer(req: TxBuildRequest, ctx: TxBuildContext): Promise<TxBuildResult>;
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
import type { TxBuildRequest } from '../../utils/types';
|
|
2
2
|
import type { Network } from '../cardano-client';
|
|
3
3
|
import type { WalletJobKindValue } from './job-store';
|
|
4
|
-
/**
|
|
5
|
-
* Transforms a stored wallet-job request (Build*-action payload shape) into the
|
|
6
|
-
* TxBuildRequest the CardanoIndexer build methods expect, mirroring the synchronous handlers.
|
|
7
|
-
* Validation failures throw BackendError 400 INVALID_INPUT so the job fails terminally, not via retries.
|
|
8
|
-
*/
|
|
9
4
|
type RawRequest = Record<string, unknown>;
|
|
10
5
|
/** Raw job request → TxBuildRequest for the matching build method; malformed payloads throw 400 INVALID_INPUT. */
|
|
11
6
|
export declare function prepareWorkerBuildRequest(kind: WalletJobKindValue, raw: RawRequest, network: Network): TxBuildRequest;
|
|
@@ -48,7 +48,7 @@ function parseMintActions(raw, allowBareNames) {
|
|
|
48
48
|
}
|
|
49
49
|
const action = rawAction;
|
|
50
50
|
if (typeof action.quantity !== 'string' || !/^-?\d+$/.test(action.quantity)) {
|
|
51
|
-
fail(`Invalid quantity: "${String(action.quantity)}"
|
|
51
|
+
fail(`Invalid quantity: "${String(action.quantity)}": must be an integer string`);
|
|
52
52
|
}
|
|
53
53
|
if (typeof action.assetUnit !== 'string')
|
|
54
54
|
fail('Each mint action must have an assetUnit string');
|
|
@@ -65,7 +65,7 @@ function parseMintActions(raw, allowBareNames) {
|
|
|
65
65
|
action.assetUnit.length % 2 === 0 &&
|
|
66
66
|
/^[0-9a-fA-F]*$/.test(action.assetUnit);
|
|
67
67
|
if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
|
|
68
|
-
fail(`Invalid assetUnit: "${action.assetUnit}"
|
|
68
|
+
fail(`Invalid assetUnit: "${action.assetUnit}": must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson or a per-action mintingPolicyScript is set)`);
|
|
69
69
|
}
|
|
70
70
|
let assetUnit = action.assetUnit;
|
|
71
71
|
if (actionPolicyId) {
|
|
@@ -93,15 +93,12 @@ function scriptHashOf(scriptHex, context) {
|
|
|
93
93
|
return fail(`${context}: ${err instanceof Error ? err.message : String(err)}`);
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
|
-
/**
|
|
97
|
-
* Every mint action must carry the effective policy id: parseAssetUnit drops the first
|
|
98
|
-
* 56 hex chars, so a mismatched prefix would mint a truncated asset name.
|
|
99
|
-
*/
|
|
96
|
+
/** parseAssetUnit drops the first 56 hex chars, so a wrong policy prefix would mint a truncated name. */
|
|
100
97
|
function assertPolicyPrefix(actions, policyId) {
|
|
101
98
|
// Actions with their own script were already checked against that script's policy id.
|
|
102
99
|
const mismatch = actions.find((a) => !a.mintingPolicyScript && !a.assetUnit.toLowerCase().startsWith(policyId));
|
|
103
100
|
if (mismatch) {
|
|
104
|
-
fail(`assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId}
|
|
101
|
+
fail(`assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId}. Pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`);
|
|
105
102
|
}
|
|
106
103
|
}
|
|
107
104
|
function takeParsed(result) {
|
|
@@ -228,7 +225,7 @@ function prepareMint(raw, network) {
|
|
|
228
225
|
effectivePolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(raw.mintingPolicyScript, 'hex')).hash.toString();
|
|
229
226
|
}
|
|
230
227
|
catch {
|
|
231
|
-
//
|
|
228
|
+
// Invalid script CBOR. The builder rejects it with its own message.
|
|
232
229
|
}
|
|
233
230
|
}
|
|
234
231
|
if (effectivePolicyId)
|
|
@@ -303,7 +300,7 @@ function preparePlutusSpend(raw, network) {
|
|
|
303
300
|
mintPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalMintingPolicyScript, 'hex')).hash.toString();
|
|
304
301
|
}
|
|
305
302
|
catch {
|
|
306
|
-
//
|
|
303
|
+
// Invalid script CBOR. The builder rejects it with its own message.
|
|
307
304
|
}
|
|
308
305
|
if (mintPolicyId)
|
|
309
306
|
assertPolicyPrefix(mintActions, mintPolicyId);
|
|
@@ -1,10 +1,4 @@
|
|
|
1
1
|
import type { CardanoClient } from '../cardano-client';
|
|
2
|
-
/**
|
|
3
|
-
* Watches `submitted` jobs until their tx sits at depth >= `confirmationDepth`, via crawler
|
|
4
|
-
* `blockIndexed`/`reorg` hooks plus an always-on polling fallback. A reorg re-submits the SAME
|
|
5
|
-
* signed CBOR (never a rebuild); a tx unseen past `confirmationTimeoutMs` fails as TX_DROPPED.
|
|
6
|
-
* Depth = `tipHeight - foundHeight + 1`, so depth 1 means "included in a block".
|
|
7
|
-
*/
|
|
8
2
|
export interface TrackedJob {
|
|
9
3
|
jobId: string;
|
|
10
4
|
walletId: string;
|
|
@@ -16,10 +10,7 @@ export interface TrackedJob {
|
|
|
16
10
|
submittedAt: string;
|
|
17
11
|
foundSlot: number | null;
|
|
18
12
|
foundHeight: number | null;
|
|
19
|
-
/**
|
|
20
|
-
* Polling round in which the tx was last seen on-chain. An inclusion from an earlier
|
|
21
|
-
* round is re-checked before confirming, so a rollback the crawler did not report cannot slip through.
|
|
22
|
-
*/
|
|
13
|
+
/** Polling round that last saw the tx. Older inclusions are re-checked to catch unreported rollbacks. */
|
|
23
14
|
seenRound?: number;
|
|
24
15
|
}
|
|
25
16
|
export interface ConfirmationTrackerOptions {
|
|
@@ -37,7 +28,7 @@ export interface ConfirmationTrackerDeps {
|
|
|
37
28
|
walletId: string;
|
|
38
29
|
outcome: 'confirmed' | 'failed';
|
|
39
30
|
kind: string | null;
|
|
40
|
-
/**
|
|
31
|
+
/** Set even on failure, since the tx was submitted. */
|
|
41
32
|
txHash: string;
|
|
42
33
|
errorCode?: string;
|
|
43
34
|
errorMessage?: string;
|
|
@@ -72,22 +63,13 @@ export declare class ConfirmationTracker {
|
|
|
72
63
|
}): void;
|
|
73
64
|
private onBlockIndexed;
|
|
74
65
|
private onReorg;
|
|
75
|
-
/**
|
|
76
|
-
* Inclusion rolled back: back to watching, optionally re-submitting the SAME signed CBOR
|
|
77
|
-
* (never a rebuild — the double-spend guard). "Already known" means the tx survived; success.
|
|
78
|
-
*/
|
|
66
|
+
/** Back to watching after a rollback. Re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
|
|
79
67
|
private forgetInclusion;
|
|
80
68
|
/** One polling round. Public for tests; guarded against overlapping rounds. */
|
|
81
69
|
pollOnce(): Promise<void>;
|
|
82
|
-
/**
|
|
83
|
-
* Confirm every found job whose depth is met by the known tip. With `revalidate`
|
|
84
|
-
* (polling path) an inclusion not seen in this round is looked up again first.
|
|
85
|
-
*/
|
|
70
|
+
/** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
|
|
86
71
|
private confirmMature;
|
|
87
|
-
/**
|
|
88
|
-
* Is the tx still on-chain and deep enough? A tx that moved blocks is re-anchored at its
|
|
89
|
-
* new height; one that is gone goes back to watching and the tip is re-learned next round.
|
|
90
|
-
*/
|
|
72
|
+
/** True if the tx is still on-chain and deep enough. A moved tx takes its new height, a vanished one is watched again. */
|
|
91
73
|
private stillIncluded;
|
|
92
74
|
private finalize;
|
|
93
75
|
}
|
|
@@ -5,9 +5,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.ConfirmationTracker = void 0;
|
|
7
7
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
8
9
|
const errors_1 = require("../../utils/errors");
|
|
9
10
|
const hooks_1 = require("../crawler/hooks");
|
|
10
11
|
const job_store_1 = require("./job-store");
|
|
12
|
+
const { UPDATE } = cds_1.default.ql;
|
|
11
13
|
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
12
14
|
class ConfirmationTracker {
|
|
13
15
|
deps;
|
|
@@ -102,15 +104,12 @@ class ConfirmationTracker {
|
|
|
102
104
|
}
|
|
103
105
|
for (const job of this.pending.values()) {
|
|
104
106
|
if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
|
|
105
|
-
logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot}
|
|
107
|
+
logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot}, re-watching`);
|
|
106
108
|
await this.forgetInclusion(job);
|
|
107
109
|
}
|
|
108
110
|
}
|
|
109
111
|
}
|
|
110
|
-
/**
|
|
111
|
-
* Inclusion rolled back: back to watching, optionally re-submitting the SAME signed CBOR
|
|
112
|
-
* (never a rebuild — the double-spend guard). "Already known" means the tx survived; success.
|
|
113
|
-
*/
|
|
112
|
+
/** Back to watching after a rollback. Re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
|
|
114
113
|
async forgetInclusion(job) {
|
|
115
114
|
job.foundSlot = null;
|
|
116
115
|
job.foundHeight = null;
|
|
@@ -128,7 +127,7 @@ class ConfirmationTracker {
|
|
|
128
127
|
}
|
|
129
128
|
catch (err) {
|
|
130
129
|
if (err instanceof errors_1.TransactionAlreadySubmittedError) {
|
|
131
|
-
logger.debug(`Job ${job.jobId}: tx already known after rollback
|
|
130
|
+
logger.debug(`Job ${job.jobId}: tx already known after rollback, nothing to do`);
|
|
132
131
|
}
|
|
133
132
|
else {
|
|
134
133
|
logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
|
|
@@ -144,7 +143,7 @@ class ConfirmationTracker {
|
|
|
144
143
|
this.polling = true;
|
|
145
144
|
this.round++;
|
|
146
145
|
try {
|
|
147
|
-
// Tip first
|
|
146
|
+
// Tip first. It is also the depth check for hook-found entries when the crawler is off.
|
|
148
147
|
try {
|
|
149
148
|
const tip = await this.deps.client.getLatestBlock();
|
|
150
149
|
if (tip.height != null) {
|
|
@@ -170,7 +169,7 @@ class ConfirmationTracker {
|
|
|
170
169
|
// Failover wraps per-backend 404s into AllBackendsFailedError; the helper
|
|
171
170
|
// treats "every backend said 404" as proof of absence.
|
|
172
171
|
if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
|
|
173
|
-
// Not on-chain yet
|
|
172
|
+
// Not on-chain yet. Check the submission timeout.
|
|
174
173
|
const age = Date.now() - Date.parse(job.submittedAt);
|
|
175
174
|
if (age > this.deps.options.confirmationTimeoutMs) {
|
|
176
175
|
await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(`Transaction ${job.txHash} not seen on-chain within ${this.deps.options.confirmationTimeoutMs}ms of submission`));
|
|
@@ -189,10 +188,7 @@ class ConfirmationTracker {
|
|
|
189
188
|
}
|
|
190
189
|
}
|
|
191
190
|
// ---- Shared -----------------------------------------------------------------
|
|
192
|
-
/**
|
|
193
|
-
* Confirm every found job whose depth is met by the known tip. With `revalidate`
|
|
194
|
-
* (polling path) an inclusion not seen in this round is looked up again first.
|
|
195
|
-
*/
|
|
191
|
+
/** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
|
|
196
192
|
async confirmMature(revalidate = false) {
|
|
197
193
|
const tip = this.lastKnownTipHeight;
|
|
198
194
|
if (tip == null)
|
|
@@ -207,17 +203,14 @@ class ConfirmationTracker {
|
|
|
207
203
|
await this.finalize(job, 'confirmed');
|
|
208
204
|
}
|
|
209
205
|
}
|
|
210
|
-
/**
|
|
211
|
-
* Is the tx still on-chain and deep enough? A tx that moved blocks is re-anchored at its
|
|
212
|
-
* new height; one that is gone goes back to watching and the tip is re-learned next round.
|
|
213
|
-
*/
|
|
206
|
+
/** True if the tx is still on-chain and deep enough. A moved tx takes its new height, a vanished one is watched again. */
|
|
214
207
|
async stillIncluded(job, tip) {
|
|
215
208
|
try {
|
|
216
209
|
const tx = await this.deps.client.getTransaction(job.txHash);
|
|
217
210
|
const height = tx.blockHeight ?? null;
|
|
218
211
|
job.seenRound = this.round;
|
|
219
212
|
if (height != null && height !== job.foundHeight) {
|
|
220
|
-
logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height}
|
|
213
|
+
logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height}, re-anchoring`);
|
|
221
214
|
job.foundHeight = height;
|
|
222
215
|
job.foundSlot = tx.slot ?? null;
|
|
223
216
|
await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
|
|
@@ -227,7 +220,7 @@ class ConfirmationTracker {
|
|
|
227
220
|
}
|
|
228
221
|
catch (err) {
|
|
229
222
|
if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
|
|
230
|
-
logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight})
|
|
223
|
+
logger.warn(`Job ${job.jobId}: tx ${job.txHash} no longer on-chain (was at height ${job.foundHeight}). Rollback without a crawler signal, re-watching`);
|
|
231
224
|
this.lastKnownTipHeight = null;
|
|
232
225
|
await this.forgetInclusion(job);
|
|
233
226
|
return false;
|
|
@@ -245,17 +238,20 @@ class ConfirmationTracker {
|
|
|
245
238
|
: await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
|
|
246
239
|
if (transitioned) {
|
|
247
240
|
await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
|
|
241
|
+
if (outcome === 'confirmed') {
|
|
242
|
+
await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'confirmed' }).where({ txHash: job.txHash, status: 'submitted' }));
|
|
243
|
+
}
|
|
248
244
|
}
|
|
249
245
|
});
|
|
250
246
|
}
|
|
251
247
|
catch (persistErr) {
|
|
252
248
|
logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
|
|
253
|
-
return; // keep tracking
|
|
249
|
+
return; // keep tracking, the next round retries
|
|
254
250
|
}
|
|
255
251
|
this.pending.delete(job.jobId);
|
|
256
252
|
if (!transitioned) {
|
|
257
253
|
// Another actor reached the terminal state first; stats bump and event belong to it.
|
|
258
|
-
logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere
|
|
254
|
+
logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere, no event from this tracker`);
|
|
259
255
|
return;
|
|
260
256
|
}
|
|
261
257
|
logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
|
|
@@ -3,7 +3,7 @@ export type StartWalletWorkerDeps = Omit<WalletWorkerDeps, 'instanceId'> & {
|
|
|
3
3
|
instanceId?: string;
|
|
4
4
|
};
|
|
5
5
|
export type { WalletWorkerConfig };
|
|
6
|
-
/**
|
|
6
|
+
/** Starts the worker. A no-op when one is already running. */
|
|
7
7
|
export declare function startWalletWorker(deps: StartWalletWorkerDeps): Promise<void>;
|
|
8
8
|
/** Stop the local worker (in-flight execution steps are awaited). */
|
|
9
9
|
export declare function stopWalletWorker(): Promise<void>;
|
|
@@ -11,13 +11,11 @@ const cds_1 = __importDefault(require("@sap/cds"));
|
|
|
11
11
|
const node_crypto_1 = require("node:crypto");
|
|
12
12
|
const wallet_worker_1 = require("./wallet-worker");
|
|
13
13
|
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
* worker service. No standby: every instance may dispatch, the per-wallet DB leases decide who executes.
|
|
17
|
-
*/
|
|
14
|
+
// Process-wide wallet-worker singleton, started from the served hook.
|
|
15
|
+
// Every instance may dispatch. Per-wallet DB leases decide who executes.
|
|
18
16
|
let active = null;
|
|
19
17
|
let lifecycleQueue = Promise.resolve();
|
|
20
|
-
/**
|
|
18
|
+
/** Starts the worker. A no-op when one is already running. */
|
|
21
19
|
async function startWalletWorker(deps) {
|
|
22
20
|
return serializeLifecycle(async () => {
|
|
23
21
|
if (active?.isRunning()) {
|
|
@@ -1,19 +1,4 @@
|
|
|
1
1
|
import type { Transaction as CapTransaction } from '@sap/cds';
|
|
2
|
-
/**
|
|
3
|
-
* Persistence for `CardanoWalletJobs` + `CardanoWorkerWallets`. `insertJob` runs on the caller's
|
|
4
|
-
* ambient tx (a detached insert would deadlock on the SQLite write lock); transition helpers run in
|
|
5
|
-
* short fresh txs so the pooled connection is never held across a job execution.
|
|
6
|
-
*
|
|
7
|
-
* State machine:
|
|
8
|
-
* pending → building → submitting → submitted → confirmed
|
|
9
|
-
* │ │ │ └────→ failed
|
|
10
|
-
* │ │ └→ submitted (reconciled) | failed (proven absent)
|
|
11
|
-
* │ └→ pending (transient retry) | failed
|
|
12
|
-
* └→ cancelled
|
|
13
|
-
*
|
|
14
|
-
* `submitting` commits the signed CBOR, hash and fee BEFORE the network call and keeps the idempotency
|
|
15
|
-
* key held; transitions are conditional UPDATEs on the expected source status.
|
|
16
|
-
*/
|
|
17
2
|
/** Per-wallet DB lease TTL. */
|
|
18
3
|
export declare const WORKER_LEASE_TTL_MS = 15000;
|
|
19
4
|
export declare const JOB_ERROR_CODES: {
|
|
@@ -85,44 +70,26 @@ export interface InsertJobResult {
|
|
|
85
70
|
/** True when an idempotent retry matched an existing non-failed job. */
|
|
86
71
|
deduplicated: boolean;
|
|
87
72
|
}
|
|
88
|
-
/**
|
|
89
|
-
* Stored dedup claim for an idempotency key, scoped to the submitting principal: an owned key
|
|
90
|
-
* becomes `o:` + hash(owner, key) (fits String(100), never collides with a plain key); an
|
|
91
|
-
* owner-less key stays as-is. The `idempotencyKey` column keeps the raw key.
|
|
92
|
-
*/
|
|
73
|
+
/** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
|
|
93
74
|
export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
|
|
94
|
-
/**
|
|
95
|
-
* Insert a job row on the caller's transaction; an active-or-confirmed row with the same
|
|
96
|
-
* (walletId, kind, dedupKey) is returned instead, `failed`/`cancelled` rows never block a retry.
|
|
97
|
-
* The UNIQUE constraint decides concurrent inserts (the loser returns the winner's job).
|
|
98
|
-
*/
|
|
75
|
+
/** Inserts a job, or returns the active or confirmed job with the same dedup key. The UNIQUE constraint settles races. */
|
|
99
76
|
export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
|
|
100
77
|
export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
|
|
101
|
-
/**
|
|
102
|
-
* Pending jobs ordered by (priority, createdAt). `notBefore` is filtered in JS to avoid
|
|
103
|
-
* adapter-specific NULL/OR predicate quirks.
|
|
104
|
-
*/
|
|
78
|
+
/** Pending jobs by priority and age. notBefore is filtered in JS, since NULL predicates differ per database. */
|
|
105
79
|
export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
|
|
80
|
+
/** Number of pending jobs, due or not. */
|
|
81
|
+
export declare function countPendingJobs(db: CapTransaction): Promise<number>;
|
|
106
82
|
/** All jobs awaiting confirmation (used by the tracker on start/recovery). */
|
|
107
83
|
export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
|
|
108
84
|
/** Whether the wallet has a job currently in flight (building, submitting or submitted). */
|
|
109
85
|
export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
|
|
110
|
-
/**
|
|
111
|
-
* Oldest `submitting` row of a wallet whose lease is expired/unowned: its submit outcome is
|
|
112
|
-
* unknown and needs chain reconciliation. Rows under a held lease are being worked on.
|
|
113
|
-
*/
|
|
86
|
+
/** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
|
|
114
87
|
export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
|
|
115
|
-
/**
|
|
116
|
-
* Free a job's idempotency key by pointing `dedupKey` at its own ID; `idempotencyKey` stays for
|
|
117
|
-
* the audit trail. Not called for `confirmed`: a completed job keeps its key.
|
|
118
|
-
*/
|
|
88
|
+
/** Frees the idempotency key by pointing dedupKey at the job ID. Confirmed jobs keep their key. */
|
|
119
89
|
export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
|
|
120
90
|
/** pending → building. Increments the attempt counter. Returns false when lost. */
|
|
121
91
|
export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
|
|
122
|
-
/**
|
|
123
|
-
* building → submitting. Commits the signed tx, hash, unsigned CBOR and fee BEFORE the network
|
|
124
|
-
* call, so the exact bytes survive a crash. `submittedAt` is the attempt time, not proof of acceptance.
|
|
125
|
-
*/
|
|
92
|
+
/** Stores the signed tx before the network call, so the exact bytes survive a crash. submittedAt is the attempt time. */
|
|
126
93
|
export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
|
|
127
94
|
txHash: string;
|
|
128
95
|
unsignedTxCbor: string | null;
|
|
@@ -131,45 +98,31 @@ export declare function markSubmitting(db: CapTransaction, jobId: string, artifa
|
|
|
131
98
|
}): Promise<boolean>;
|
|
132
99
|
/** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
|
|
133
100
|
export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
|
|
134
|
-
/**
|
|
135
|
-
* building → pending (transient failure), deferring via `notBefore`. Guarded on `building` only:
|
|
136
|
-
* a `submitting` tx may be in a mempool and a rebuild would double-pay; those rows are reconciled.
|
|
137
|
-
*/
|
|
101
|
+
/** Requeues a building job after a transient error. Never a submitting job, since a rebuild could pay twice. */
|
|
138
102
|
export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
|
|
139
103
|
/** Record where the submitted tx was seen on-chain (not yet at depth). */
|
|
140
104
|
export declare function recordConfirmationPoint(db: CapTransaction, jobId: string, point: {
|
|
141
105
|
slot: number | null;
|
|
142
106
|
height: number | null;
|
|
143
107
|
}): Promise<void>;
|
|
144
|
-
/** A rollback invalidated the recorded confirmation point
|
|
108
|
+
/** A rollback invalidated the recorded confirmation point. */
|
|
145
109
|
export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
|
|
146
110
|
/** submitted → confirmed (depth reached). */
|
|
147
111
|
export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
|
|
148
|
-
/**
|
|
149
|
-
* Any active state → failed. Releases the idempotency key, so a `submitting`/`submitted` row
|
|
150
|
-
* may only be failed once the chain has been consulted.
|
|
151
|
-
*/
|
|
112
|
+
/** Fails an active job and frees its key. Fail a submitted job only after checking the chain. */
|
|
152
113
|
export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
|
|
153
114
|
/** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
|
|
154
115
|
export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
|
|
155
116
|
export interface RecoveryResult {
|
|
156
117
|
/** `building` rows flipped to failed (never signed+stored, so never submitted). */
|
|
157
118
|
failedBuilding: number;
|
|
158
|
-
/** `submitted` rows
|
|
119
|
+
/** `submitted` rows for the confirmation tracker. The chain decides. */
|
|
159
120
|
submittedToReconcile: WalletJobRow[];
|
|
160
|
-
/** `submitting` rows with an unknown
|
|
121
|
+
/** `submitting` rows with an unknown outcome. The dispatch loop reconciles them. */
|
|
161
122
|
submittingToReconcile: WalletJobRow[];
|
|
162
123
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Fail a wallet's orphaned `building` rows, only when its lease is expired/unowned. A `building`
|
|
165
|
-
* row is pre-submit by definition (the signed CBOR is committed as `submitting` first), so nothing sent is failed.
|
|
166
|
-
*/
|
|
124
|
+
/** Fails orphaned building rows of a wallet without a live lease. Such rows were never sent. */
|
|
167
125
|
export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
|
|
168
|
-
/**
|
|
169
|
-
* Boot-time recovery: `building` → failed PROCESS_RESTART (never sent; only when the wallet lease
|
|
170
|
-
* is expired/unowned, a held lease means another live instance owns it); `submitting` → returned
|
|
171
|
-
* for chain reconciliation, never rebuilt; `submitted` → handed to the confirmation tracker.
|
|
172
|
-
*/
|
|
173
126
|
export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
|
|
174
127
|
/** Idempotently register/refresh a configured wallet row (no key material). */
|
|
175
128
|
export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
|
|
@@ -180,10 +133,7 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
|
|
|
180
133
|
}): Promise<void>;
|
|
181
134
|
export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
|
|
182
135
|
export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
|
|
183
|
-
/**
|
|
184
|
-
* Acquire an expired/unowned per-wallet lease (compare-and-swap + read-back verification).
|
|
185
|
-
* At most one worker instance may execute jobs for a wallet at any time.
|
|
186
|
-
*/
|
|
136
|
+
/** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
|
|
187
137
|
export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
188
138
|
/** Renew/fence the caller's lease. Call before every job-advancing write. */
|
|
189
139
|
export declare function renewWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
Binary file
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Keeps a per-wallet lease alive while a job executes (build+sign can outlast the TTL).
|
|
3
|
-
* Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
|
|
4
|
-
* (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
|
|
5
|
-
*/
|
|
6
1
|
export declare const LEASE_HEARTBEAT_INTERVAL_MS: number;
|
|
7
2
|
export declare class LeaseHeartbeat {
|
|
8
3
|
private readonly renew;
|
|
@@ -10,14 +5,11 @@ export declare class LeaseHeartbeat {
|
|
|
10
5
|
private readonly intervalMs;
|
|
11
6
|
private timer;
|
|
12
7
|
private lost;
|
|
13
|
-
/**
|
|
14
|
-
* @param renew renews the lease and reports whether it is (still) ours
|
|
15
|
-
* @param label what the lease covers, for log messages
|
|
16
|
-
*/
|
|
8
|
+
/** renew reports whether the lease is still ours. label names the lease in logs. */
|
|
17
9
|
constructor(renew: () => Promise<boolean>, label: string, intervalMs?: number);
|
|
18
10
|
start(): void;
|
|
19
11
|
stop(): void;
|
|
20
|
-
/** True once a renewal proved the lease is not ours
|
|
12
|
+
/** True once a renewal proved the lease is not ours. The execution must abort. */
|
|
21
13
|
isLost(): boolean;
|
|
22
14
|
/** Renew now; false means "do not touch this wallet any further". */
|
|
23
15
|
fence(): Promise<boolean>;
|
|
@@ -7,11 +7,8 @@ exports.LeaseHeartbeat = exports.LEASE_HEARTBEAT_INTERVAL_MS = void 0;
|
|
|
7
7
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
8
|
const job_store_1 = require("./job-store");
|
|
9
9
|
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
* Renews at a third of the TTL, so two consecutive misses are tolerated. `beat` is lenient
|
|
13
|
-
* (DB error → retry next tick); `fence()` is strict (unprovable ownership = lost, before irreversible steps).
|
|
14
|
-
*/
|
|
10
|
+
// Keeps a wallet lease alive while a job runs. Renewing at a third of the TTL tolerates two misses.
|
|
11
|
+
// beat retries on DB errors. fence treats an unprovable lease as lost, before irreversible steps.
|
|
15
12
|
exports.LEASE_HEARTBEAT_INTERVAL_MS = Math.floor(job_store_1.WORKER_LEASE_TTL_MS / 3);
|
|
16
13
|
class LeaseHeartbeat {
|
|
17
14
|
renew;
|
|
@@ -19,10 +16,7 @@ class LeaseHeartbeat {
|
|
|
19
16
|
intervalMs;
|
|
20
17
|
timer = null;
|
|
21
18
|
lost = false;
|
|
22
|
-
/**
|
|
23
|
-
* @param renew renews the lease and reports whether it is (still) ours
|
|
24
|
-
* @param label what the lease covers, for log messages
|
|
25
|
-
*/
|
|
19
|
+
/** renew reports whether the lease is still ours. label names the lease in logs. */
|
|
26
20
|
constructor(renew, label, intervalMs = exports.LEASE_HEARTBEAT_INTERVAL_MS) {
|
|
27
21
|
this.renew = renew;
|
|
28
22
|
this.label = label;
|
|
@@ -40,7 +34,7 @@ class LeaseHeartbeat {
|
|
|
40
34
|
this.timer = null;
|
|
41
35
|
}
|
|
42
36
|
}
|
|
43
|
-
/** True once a renewal proved the lease is not ours
|
|
37
|
+
/** True once a renewal proved the lease is not ours. The execution must abort. */
|
|
44
38
|
isLost() {
|
|
45
39
|
return this.lost;
|
|
46
40
|
}
|
|
@@ -55,7 +49,7 @@ class LeaseHeartbeat {
|
|
|
55
49
|
return held;
|
|
56
50
|
}
|
|
57
51
|
catch (err) {
|
|
58
|
-
logger.warn(`Lease fence for ${this.label} could not be verified
|
|
52
|
+
logger.warn(`Lease fence for ${this.label} could not be verified, treating the lease as lost:`, err);
|
|
59
53
|
this.lost = true;
|
|
60
54
|
return false;
|
|
61
55
|
}
|
|
@@ -76,7 +70,7 @@ class LeaseHeartbeat {
|
|
|
76
70
|
return;
|
|
77
71
|
this.lost = true;
|
|
78
72
|
this.stop();
|
|
79
|
-
logger.warn(`Lease for ${this.label} was taken over by another instance
|
|
73
|
+
logger.warn(`Lease for ${this.label} was taken over by another instance, this executor must stand down`);
|
|
80
74
|
}
|
|
81
75
|
}
|
|
82
76
|
exports.LeaseHeartbeat = LeaseHeartbeat;
|
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
import type { WorkerSignerTypeValue } from './job-store';
|
|
2
|
-
/**
|
|
3
|
-
* Wallet-worker signers: `hsm` wraps the process-wide HsmSigner (PKCS#11), `software` holds an
|
|
4
|
-
* Ed25519 key from an env var (plain hex or AES-256-GCM `iv:authTag:ciphertext`, keyed by ENCRYPTION_KEY).
|
|
5
|
-
* Keys are never accepted via OData and never persisted.
|
|
6
|
-
*/
|
|
7
2
|
export interface WorkerSigner {
|
|
8
3
|
readonly type: WorkerSignerTypeValue;
|
|
9
4
|
/** Bech32 enterprise address the wallet spends from. */
|
|
@@ -17,17 +12,14 @@ export interface WorkerSigner {
|
|
|
17
12
|
export interface WorkerWalletConfig {
|
|
18
13
|
walletId: string;
|
|
19
14
|
signerType: WorkerSignerTypeValue;
|
|
20
|
-
/** software only
|
|
15
|
+
/** software only. Env var with the Ed25519 key as 64 hex chars or AES-256-GCM `iv:authTag:ciphertext` in base64. */
|
|
21
16
|
keyEnv?: string;
|
|
22
17
|
}
|
|
23
|
-
/**
|
|
24
|
-
* Merge a single VKey witness into the witness set at the raw CBOR level, preserving
|
|
25
|
-
* non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
|
|
26
|
-
*/
|
|
18
|
+
/** Replaces the vkey witnesses in the raw CBOR witness set with this one. Other entries and encoding stay. */
|
|
27
19
|
export declare function mergeVkeyWitness(unsignedTxCbor: string, publicKeyHex: string, signatureHex: string): string;
|
|
28
20
|
/** Derive the bech32 enterprise key-hash address for a 28-byte key hash. */
|
|
29
21
|
export declare function deriveEnterpriseAddress(publicKeyHash: Uint8Array, network: string): string;
|
|
30
|
-
/**
|
|
22
|
+
/** In-memory Ed25519 key for development and tests. */
|
|
31
23
|
export declare class SoftwareWorkerSigner implements WorkerSigner {
|
|
32
24
|
readonly type: "software";
|
|
33
25
|
private readonly privateKey;
|
|
@@ -16,10 +16,7 @@ const hsm_signer_1 = require("../signing/hsm-signer");
|
|
|
16
16
|
const errors_1 = require("../../utils/errors");
|
|
17
17
|
const crypto_2 = require("../../utils/crypto");
|
|
18
18
|
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
19
|
-
/**
|
|
20
|
-
* Merge a single VKey witness into the witness set at the raw CBOR level, preserving
|
|
21
|
-
* non-vkey entries and encoding metadata. Single-signer semantics as HsmSigner.signTransaction.
|
|
22
|
-
*/
|
|
19
|
+
/** Replaces the vkey witnesses in the raw CBOR witness set with this one. Other entries and encoding stay. */
|
|
23
20
|
function mergeVkeyWitness(unsignedTxCbor, publicKeyHex, signatureHex) {
|
|
24
21
|
const txObj = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(unsignedTxCbor));
|
|
25
22
|
if (!(txObj instanceof cbor_1.CborArray) || txObj.array.length < 2) {
|
|
@@ -47,7 +44,7 @@ function deriveEnterpriseAddress(publicKeyHash, network) {
|
|
|
47
44
|
const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
|
|
48
45
|
return bech32_1.bech32.encode(hrp, bech32_1.bech32.toWords(payload), 120);
|
|
49
46
|
}
|
|
50
|
-
/**
|
|
47
|
+
/** Delegates to the process-wide HsmSigner set up at bootstrap. */
|
|
51
48
|
class HsmWorkerSigner {
|
|
52
49
|
type = 'hsm';
|
|
53
50
|
get signer() {
|
|
@@ -67,7 +64,7 @@ class HsmWorkerSigner {
|
|
|
67
64
|
return this.signer.signTransaction(unsignedTxCbor, txBodyHash);
|
|
68
65
|
}
|
|
69
66
|
}
|
|
70
|
-
/**
|
|
67
|
+
/** In-memory Ed25519 key for development and tests. */
|
|
71
68
|
class SoftwareWorkerSigner {
|
|
72
69
|
type = 'software';
|
|
73
70
|
privateKey;
|