@totemsdk/omnia-router 0.2.0 → 0.3.0
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/dist/cjs/durable-router-ledger.d.ts +60 -0
- package/dist/cjs/durable-router-ledger.js +88 -0
- package/dist/cjs/execute.d.ts +45 -0
- package/dist/cjs/execute.js +303 -0
- package/dist/cjs/forward.d.ts +50 -0
- package/dist/cjs/forward.js +56 -0
- package/dist/cjs/graph.d.ts +32 -0
- package/dist/cjs/graph.js +102 -0
- package/dist/cjs/index.d.ts +10 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pathfind.d.ts +25 -0
- package/dist/cjs/pathfind.js +253 -0
- package/dist/cjs/request.d.ts +19 -0
- package/dist/cjs/request.js +38 -0
- package/dist/cjs/types.d.ts +200 -0
- package/dist/cjs/types.js +10 -0
- package/dist/durable-router-ledger.d.ts +60 -0
- package/dist/durable-router-ledger.js +85 -0
- package/dist/execute.d.ts +9 -1
- package/dist/execute.js +50 -9
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +53 -0
- package/dist/graph.js +7 -14
- package/dist/index.d.ts +6 -1
- package/dist/index.js +7 -21
- package/dist/pathfind.js +6 -12
- package/dist/request.js +5 -9
- package/dist/types.d.ts +16 -0
- package/dist/types.js +1 -2
- package/package.json +16 -9
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable settled-segment ledger (RFC-007 G9).
|
|
3
|
+
*
|
|
4
|
+
* Payment execution is multi-channel: a route spans several HTLC hops, each
|
|
5
|
+
* fulfilled in reverse order by revealing the preimage. If the host dies
|
|
6
|
+
* mid-route (after some hops settled, before others), the already-settled
|
|
7
|
+
* segments — channel + HTLC + revealed preimage + settled-at — must survive a
|
|
8
|
+
* restart so the node can (a) never re-lock or re-settle an already-committed
|
|
9
|
+
* segment, and (b) reconcile still-pending locks. This ledger records exactly
|
|
10
|
+
* those settled segments, keyed `channelId:htlcId`, idempotently.
|
|
11
|
+
*
|
|
12
|
+
* Backed by the shared revision-CAS snapshot store: corruption is surfaced
|
|
13
|
+
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
14
|
+
* settlement is never lost.
|
|
15
|
+
*/
|
|
16
|
+
import type { StorageAdapterWithCapabilities, CasStore, WriteAckMode } from '@totemsdk/storage/types';
|
|
17
|
+
/** A payment segment that has been irrevocably settled by preimage reveal. */
|
|
18
|
+
export interface SettledSegment {
|
|
19
|
+
channelId: string;
|
|
20
|
+
htlcId: string;
|
|
21
|
+
/** Preimage revealed during settlement — must survive a mid-route restart. */
|
|
22
|
+
preimage: string;
|
|
23
|
+
/** Monotonic settlement timestamp. */
|
|
24
|
+
settledAt: number;
|
|
25
|
+
/** Optional hop-level detail for reconciliation (amount, counterpart, digest). */
|
|
26
|
+
tokenId?: string;
|
|
27
|
+
senderPublicKeyDigest?: string;
|
|
28
|
+
recipientPublicKeyDigest?: string;
|
|
29
|
+
/** Set once a segment is fully reconciled against the node's route state. */
|
|
30
|
+
reconciled?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface RouterLedgerState {
|
|
33
|
+
/** `channelId:htlcId` → settled segment. */
|
|
34
|
+
segments: Record<string, SettledSegment>;
|
|
35
|
+
}
|
|
36
|
+
export interface DurableRouterLedgerOptions {
|
|
37
|
+
/** Key namespace prefix; default `totem_omnia_router:v1:`. */
|
|
38
|
+
readonly namespace?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Required write acknowledgment; default `durably-acknowledged`. Pass
|
|
41
|
+
* `volatile` only for tests/scratch adapters (e.g. `MemoryStore`).
|
|
42
|
+
*/
|
|
43
|
+
readonly requireAckMode?: WriteAckMode;
|
|
44
|
+
}
|
|
45
|
+
export interface DurableRouterLedger {
|
|
46
|
+
/** Idempotently record a settled segment. Re-recording the same segment is a no-op. */
|
|
47
|
+
recordSettled(segment: SettledSegment): Promise<void>;
|
|
48
|
+
/** True when the given channel+HTLC already settled. */
|
|
49
|
+
isSettled(channelId: string, htlcId: string): Promise<boolean>;
|
|
50
|
+
/** Retrieve a previously settled segment. */
|
|
51
|
+
getSettled(channelId: string, htlcId: string): Promise<SettledSegment | undefined>;
|
|
52
|
+
/** All settled segments, optionally filtered by channel. */
|
|
53
|
+
listSettled(channelId?: string): Promise<SettledSegment[]>;
|
|
54
|
+
/** Mark a settled segment as reconciled with the route state. */
|
|
55
|
+
markReconciled(channelId: string, htlcId: string): Promise<void>;
|
|
56
|
+
getRevision(): Promise<number>;
|
|
57
|
+
hasState(): Promise<boolean>;
|
|
58
|
+
getSnapshot(): Promise<RouterLedgerState>;
|
|
59
|
+
}
|
|
60
|
+
export declare function createDurableRouterLedger(adapter: StorageAdapterWithCapabilities & CasStore, options?: DurableRouterLedgerOptions): DurableRouterLedger;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Durable settled-segment ledger (RFC-007 G9).
|
|
4
|
+
*
|
|
5
|
+
* Payment execution is multi-channel: a route spans several HTLC hops, each
|
|
6
|
+
* fulfilled in reverse order by revealing the preimage. If the host dies
|
|
7
|
+
* mid-route (after some hops settled, before others), the already-settled
|
|
8
|
+
* segments — channel + HTLC + revealed preimage + settled-at — must survive a
|
|
9
|
+
* restart so the node can (a) never re-lock or re-settle an already-committed
|
|
10
|
+
* segment, and (b) reconcile still-pending locks. This ledger records exactly
|
|
11
|
+
* those settled segments, keyed `channelId:htlcId`, idempotently.
|
|
12
|
+
*
|
|
13
|
+
* Backed by the shared revision-CAS snapshot store: corruption is surfaced
|
|
14
|
+
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
15
|
+
* settlement is never lost.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.createDurableRouterLedger = createDurableRouterLedger;
|
|
19
|
+
const snapshot_1 = require("@totemsdk/storage/snapshot");
|
|
20
|
+
const errors_1 = require("@totemsdk/storage/errors");
|
|
21
|
+
const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
|
|
22
|
+
function segmentKey(channelId, htlcId) {
|
|
23
|
+
return `${channelId}:${htlcId}`;
|
|
24
|
+
}
|
|
25
|
+
function assertLedgerState(state) {
|
|
26
|
+
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
27
|
+
throw new errors_1.StorageError('omnia-router ledger state is not an object', 'corrupt');
|
|
28
|
+
}
|
|
29
|
+
const value = state.segments;
|
|
30
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
31
|
+
throw new errors_1.StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function createDurableRouterLedger(adapter, options = {}) {
|
|
35
|
+
const snapshots = (0, snapshot_1.createRevisionedSnapshotStore)(adapter, {
|
|
36
|
+
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
37
|
+
requireAckMode: options.requireAckMode,
|
|
38
|
+
empty: () => ({ segments: {} }),
|
|
39
|
+
validate: assertLedgerState,
|
|
40
|
+
});
|
|
41
|
+
async function mutate(fn) {
|
|
42
|
+
await snapshots.mutate(fn);
|
|
43
|
+
}
|
|
44
|
+
async function loadSegment(channelId, htlcId) {
|
|
45
|
+
const state = await snapshots.load();
|
|
46
|
+
return state.segments[segmentKey(channelId, htlcId)];
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
async recordSettled(segment) {
|
|
50
|
+
// Short-circuit already-recorded segments: re-recording is a no-op and
|
|
51
|
+
// must not advance the revision or rewrite an immutable record.
|
|
52
|
+
if (await loadSegment(segment.channelId, segment.htlcId))
|
|
53
|
+
return;
|
|
54
|
+
await mutate((state) => {
|
|
55
|
+
const key = segmentKey(segment.channelId, segment.htlcId);
|
|
56
|
+
return { ...state, segments: { ...state.segments, [key]: segment } };
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
isSettled(channelId, htlcId) {
|
|
60
|
+
return loadSegment(channelId, htlcId).then((seg) => seg !== undefined);
|
|
61
|
+
},
|
|
62
|
+
getSettled: loadSegment,
|
|
63
|
+
async listSettled(channelId) {
|
|
64
|
+
const state = await snapshots.load();
|
|
65
|
+
const all = Object.values(state.segments);
|
|
66
|
+
if (channelId === undefined)
|
|
67
|
+
return all;
|
|
68
|
+
return all.filter((s) => s.channelId === channelId);
|
|
69
|
+
},
|
|
70
|
+
async markReconciled(channelId, htlcId) {
|
|
71
|
+
await mutate((state) => {
|
|
72
|
+
const key = segmentKey(channelId, htlcId);
|
|
73
|
+
const existing = state.segments[key];
|
|
74
|
+
if (!existing)
|
|
75
|
+
return state;
|
|
76
|
+
return {
|
|
77
|
+
...state,
|
|
78
|
+
segments: { ...state.segments, [key]: { ...existing, reconciled: true } },
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
getRevision: () => snapshots.getRevision(),
|
|
83
|
+
hasState: () => snapshots.hasState(),
|
|
84
|
+
async getSnapshot() {
|
|
85
|
+
return snapshots.load();
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, LeaseProvider, ChannelHTLC, RouterFeeProof } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Execute a single-token multi-hop payment atomically:
|
|
4
|
+
*
|
|
5
|
+
* 1. Forward phase — lock HTLCs across each hop in route.hops.
|
|
6
|
+
* 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
|
|
7
|
+
*
|
|
8
|
+
* Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
|
|
9
|
+
* failure, including failures that occur during the reveal phase — so stranded
|
|
10
|
+
* HTLCs are never left behind silently.
|
|
11
|
+
*
|
|
12
|
+
* `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
|
|
13
|
+
*
|
|
14
|
+
* The `channels` map is updated in-place after each HTLC operation.
|
|
15
|
+
*/
|
|
16
|
+
export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
|
|
17
|
+
export declare const ROUTER_FEE_PROOF_DOMAIN = "totemsdk/omnia-router/fee-proof/v1";
|
|
18
|
+
/**
|
|
19
|
+
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
20
|
+
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
21
|
+
* real fulfilled payment, never a declared string.
|
|
22
|
+
*/
|
|
23
|
+
export declare function buildRouterFeeProof(channel: RouterChannel, htlc: ChannelHTLC, settledAt?: number): RouterFeeProof;
|
|
24
|
+
export declare function computeRouterFeeProofHash(proof: RouterFeeProof): string;
|
|
25
|
+
/**
|
|
26
|
+
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
27
|
+
* Call this explicitly to roll back before or without attempting execution.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cancelPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, leaseProviders: Map<string, LeaseProvider>): Promise<void>;
|
|
30
|
+
/**
|
|
31
|
+
* Execute a cross-token payment atomically.
|
|
32
|
+
*
|
|
33
|
+
* For each SwapHop:
|
|
34
|
+
* 1. Lock the inbound HTLC (tokenIn side).
|
|
35
|
+
* 2. Lock the outbound HTLC (tokenOut side).
|
|
36
|
+
* Both use the same hashlock — the intermediary can only claim by revealing
|
|
37
|
+
* the preimage on both sides simultaneously.
|
|
38
|
+
*
|
|
39
|
+
* Then forward-locks all remaining non-swap hops, and reveals the preimage
|
|
40
|
+
* backwards across all locked channels.
|
|
41
|
+
*
|
|
42
|
+
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
43
|
+
* all still-pending locked HTLCs.
|
|
44
|
+
*/
|
|
45
|
+
export declare function executeCrossTokenPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: CrossTokenRoute, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ROUTER_FEE_PROOF_DOMAIN = void 0;
|
|
4
|
+
exports.executeMultiHopPayment = executeMultiHopPayment;
|
|
5
|
+
exports.buildRouterFeeProof = buildRouterFeeProof;
|
|
6
|
+
exports.computeRouterFeeProofHash = computeRouterFeeProofHash;
|
|
7
|
+
exports.cancelPayment = cancelPayment;
|
|
8
|
+
exports.executeCrossTokenPayment = executeCrossTokenPayment;
|
|
9
|
+
const core_1 = require("@totemsdk/core");
|
|
10
|
+
// ─── Type guard ───────────────────────────────────────────────────────────────
|
|
11
|
+
function isSwapHop(hop) {
|
|
12
|
+
return hop.isSwap === true;
|
|
13
|
+
}
|
|
14
|
+
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
15
|
+
/** Determine the counterparty public key digest relative to the local signer. */
|
|
16
|
+
function counterpartPkd(channel) {
|
|
17
|
+
const localPkd = channel.localSigner?.publicKeyDigest;
|
|
18
|
+
const other = channel.parties.find(p => p.publicKeyDigest !== localPkd);
|
|
19
|
+
if (!other)
|
|
20
|
+
throw new Error(`Channel ${channel.channelId}: cannot determine counterpart`);
|
|
21
|
+
return other.publicKeyDigest;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Best-effort timeout of a set of locked HTLCs.
|
|
25
|
+
* Errors from individual timeoutHTLC calls are silently ignored so rollback
|
|
26
|
+
* always completes as many cancellations as possible.
|
|
27
|
+
*/
|
|
28
|
+
async function cancelHtlcs(ops, channels, locked, leaseProviders) {
|
|
29
|
+
for (const { channelId, htlcId } of [...locked].reverse()) {
|
|
30
|
+
const ch = channels.get(channelId);
|
|
31
|
+
const lp = leaseProviders.get(channelId);
|
|
32
|
+
if (!ch || !lp)
|
|
33
|
+
continue;
|
|
34
|
+
try {
|
|
35
|
+
const res = await ops.timeoutHTLC(ch, htlcId, lp);
|
|
36
|
+
channels.set(channelId, res.channel);
|
|
37
|
+
}
|
|
38
|
+
catch { /* best-effort: continue rolling back other hops */ }
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// ─── Single-token multi-hop payment ──────────────────────────────────────────
|
|
42
|
+
/**
|
|
43
|
+
* Execute a single-token multi-hop payment atomically:
|
|
44
|
+
*
|
|
45
|
+
* 1. Forward phase — lock HTLCs across each hop in route.hops.
|
|
46
|
+
* 2. Reveal phase — reveal preimage via fulfillHTLC in reverse order.
|
|
47
|
+
*
|
|
48
|
+
* Rollback (best-effort timeoutHTLC on all still-pending locks) fires on ANY
|
|
49
|
+
* failure, including failures that occur during the reveal phase — so stranded
|
|
50
|
+
* HTLCs are never left behind silently.
|
|
51
|
+
*
|
|
52
|
+
* `paymentRequest.preimage` MUST be set (buildPaymentRequest sets it).
|
|
53
|
+
*
|
|
54
|
+
* The `channels` map is updated in-place after each HTLC operation.
|
|
55
|
+
*/
|
|
56
|
+
async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
57
|
+
const preimage = paymentRequest.preimage;
|
|
58
|
+
if (!preimage) {
|
|
59
|
+
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
60
|
+
}
|
|
61
|
+
const plainHops = route.hops.filter(h => !isSwapHop(h));
|
|
62
|
+
const locked = [];
|
|
63
|
+
// ── Forward: lock HTLCs ───────────────────────────────────────────────────
|
|
64
|
+
for (let i = 0; i < plainHops.length; i++) {
|
|
65
|
+
const hop = plainHops[i];
|
|
66
|
+
const channel = channels.get(hop.channelId);
|
|
67
|
+
if (!channel) {
|
|
68
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
69
|
+
return { success: false, error: `Channel ${hop.channelId} not found`, settledHops: [] };
|
|
70
|
+
}
|
|
71
|
+
const lp = leaseProviders.get(hop.channelId);
|
|
72
|
+
if (!lp) {
|
|
73
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
74
|
+
return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
|
|
75
|
+
}
|
|
76
|
+
// Timeouts decrease toward the recipient so each hop has time to claim.
|
|
77
|
+
const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
|
|
78
|
+
let addResult;
|
|
79
|
+
try {
|
|
80
|
+
addResult = await ops.addHTLC(channel, {
|
|
81
|
+
amount: hop.amount,
|
|
82
|
+
hashlock: paymentRequest.hashlock,
|
|
83
|
+
timeoutBlock,
|
|
84
|
+
direction: 'offered',
|
|
85
|
+
counterpartPublicKeyDigest: counterpartPkd(channel),
|
|
86
|
+
}, lp);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
90
|
+
return { success: false, error: String(err), settledHops: [] };
|
|
91
|
+
}
|
|
92
|
+
if (addResult.error) {
|
|
93
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
94
|
+
return { success: false, error: addResult.error, settledHops: [] };
|
|
95
|
+
}
|
|
96
|
+
channels.set(hop.channelId, addResult.channel);
|
|
97
|
+
hop.htlcId = addResult.htlcId;
|
|
98
|
+
locked.push({ channelId: hop.channelId, htlcId: addResult.htlcId });
|
|
99
|
+
}
|
|
100
|
+
// ── Backward: reveal preimage ─────────────────────────────────────────────
|
|
101
|
+
// Track fulfilled IDs so that on failure we can timeout only the still-pending
|
|
102
|
+
// ones (already-fulfilled HTLCs are irreversible and must not be retouched).
|
|
103
|
+
const settled = [];
|
|
104
|
+
const fulfilledSet = new Set();
|
|
105
|
+
const feeProofs = [];
|
|
106
|
+
for (const { channelId, htlcId } of [...locked].reverse()) {
|
|
107
|
+
const channel = channels.get(channelId);
|
|
108
|
+
const lp = leaseProviders.get(channelId);
|
|
109
|
+
let fulfillResult;
|
|
110
|
+
try {
|
|
111
|
+
fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
// Timeout every still-pending lock (not yet fulfilled)
|
|
115
|
+
const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
|
|
116
|
+
await cancelHtlcs(ops, channels, stillPending, leaseProviders);
|
|
117
|
+
return { success: false, error: String(err), settledHops: settled };
|
|
118
|
+
}
|
|
119
|
+
if (fulfillResult.error) {
|
|
120
|
+
const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
|
|
121
|
+
await cancelHtlcs(ops, channels, stillPending, leaseProviders);
|
|
122
|
+
return { success: false, error: fulfillResult.error, settledHops: settled };
|
|
123
|
+
}
|
|
124
|
+
channels.set(channelId, fulfillResult.channel);
|
|
125
|
+
settled.push(htlcId);
|
|
126
|
+
fulfilledSet.add(htlcId);
|
|
127
|
+
// Build the verifiable fee proof for this settled hop (#29).
|
|
128
|
+
const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
|
|
129
|
+
if (htlc) {
|
|
130
|
+
feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { success: true, preimage, settledHops: settled, feeProofs };
|
|
134
|
+
}
|
|
135
|
+
exports.ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
|
|
136
|
+
/**
|
|
137
|
+
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
138
|
+
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
139
|
+
* real fulfilled payment, never a declared string.
|
|
140
|
+
*/
|
|
141
|
+
function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
142
|
+
const ts = settledAt ?? Date.now();
|
|
143
|
+
const proof = {
|
|
144
|
+
channelId: channel.channelId,
|
|
145
|
+
htlcId: htlc.htlcId,
|
|
146
|
+
recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
|
|
147
|
+
amount: htlc.amount,
|
|
148
|
+
tokenId: channel.tokenId,
|
|
149
|
+
settledAt: ts,
|
|
150
|
+
proofHash: '',
|
|
151
|
+
};
|
|
152
|
+
proof.proofHash = computeRouterFeeProofHash(proof);
|
|
153
|
+
return proof;
|
|
154
|
+
}
|
|
155
|
+
function computeRouterFeeProofHash(proof) {
|
|
156
|
+
const { proofHash, ...rest } = proof;
|
|
157
|
+
const input = `${exports.ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
|
|
158
|
+
return (0, core_1.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode(input)));
|
|
159
|
+
}
|
|
160
|
+
function canonicalJson(value) {
|
|
161
|
+
if (typeof value === 'bigint')
|
|
162
|
+
return JSON.stringify({ __bigint: value.toString() });
|
|
163
|
+
if (Array.isArray(value))
|
|
164
|
+
return `[${value.map(canonicalJson).join(',')}]`;
|
|
165
|
+
if (value && typeof value === 'object') {
|
|
166
|
+
const keys = Object.keys(value).sort();
|
|
167
|
+
const pairs = keys
|
|
168
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
|
|
169
|
+
.filter((p) => p !== `${JSON.stringify('')}:null`);
|
|
170
|
+
return `{${pairs.join(',')}}`;
|
|
171
|
+
}
|
|
172
|
+
return JSON.stringify(value);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
176
|
+
* Call this explicitly to roll back before or without attempting execution.
|
|
177
|
+
*/
|
|
178
|
+
async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
179
|
+
const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
|
|
180
|
+
await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
|
|
181
|
+
}
|
|
182
|
+
// ─── Cross-token multi-hop payment ───────────────────────────────────────────
|
|
183
|
+
/**
|
|
184
|
+
* Execute a cross-token payment atomically.
|
|
185
|
+
*
|
|
186
|
+
* For each SwapHop:
|
|
187
|
+
* 1. Lock the inbound HTLC (tokenIn side).
|
|
188
|
+
* 2. Lock the outbound HTLC (tokenOut side).
|
|
189
|
+
* Both use the same hashlock — the intermediary can only claim by revealing
|
|
190
|
+
* the preimage on both sides simultaneously.
|
|
191
|
+
*
|
|
192
|
+
* Then forward-locks all remaining non-swap hops, and reveals the preimage
|
|
193
|
+
* backwards across all locked channels.
|
|
194
|
+
*
|
|
195
|
+
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
196
|
+
* all still-pending locked HTLCs.
|
|
197
|
+
*/
|
|
198
|
+
async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
199
|
+
const preimage = paymentRequest.preimage;
|
|
200
|
+
if (!preimage) {
|
|
201
|
+
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
202
|
+
}
|
|
203
|
+
const locked = [];
|
|
204
|
+
/**
|
|
205
|
+
* Lock a single HTLC, add it to `locked`, and return the htlcId.
|
|
206
|
+
* Throws on any error so callers can handle rollback uniformly.
|
|
207
|
+
*/
|
|
208
|
+
async function lockHTLC(channelId, amount, hashlock, timeoutBlock) {
|
|
209
|
+
const channel = channels.get(channelId);
|
|
210
|
+
const lp = leaseProviders.get(channelId);
|
|
211
|
+
if (!channel)
|
|
212
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
213
|
+
if (!lp)
|
|
214
|
+
throw new Error(`No lease provider for channel ${channelId}`);
|
|
215
|
+
// Let addHTLC exceptions propagate — they carry the original error message.
|
|
216
|
+
const result = await ops.addHTLC(channel, {
|
|
217
|
+
amount,
|
|
218
|
+
hashlock,
|
|
219
|
+
timeoutBlock,
|
|
220
|
+
direction: 'offered',
|
|
221
|
+
counterpartPublicKeyDigest: counterpartPkd(channel),
|
|
222
|
+
}, lp);
|
|
223
|
+
if (result.error)
|
|
224
|
+
throw new Error(result.error);
|
|
225
|
+
channels.set(channelId, result.channel);
|
|
226
|
+
locked.push({ channelId, htlcId: result.htlcId });
|
|
227
|
+
return result.htlcId;
|
|
228
|
+
}
|
|
229
|
+
// ── Lock HTLCs in full route order with monotonically decreasing timeouts ──
|
|
230
|
+
//
|
|
231
|
+
// Correct HTLC safety requires timeouts to DECREASE toward the recipient:
|
|
232
|
+
// sender (highest timeout) → ... → recipient (lowest timeout)
|
|
233
|
+
//
|
|
234
|
+
// We iterate route.hops in their declared order. For each RoutingHop we
|
|
235
|
+
// consume one position. For each SwapHop we consume two consecutive
|
|
236
|
+
// positions: inbound channel first (higher timeout), outbound second (lower).
|
|
237
|
+
//
|
|
238
|
+
// position 0: preHops[0] ← highest timeout
|
|
239
|
+
// position 1: preHops[1]
|
|
240
|
+
// ...
|
|
241
|
+
// position k: swapInbound
|
|
242
|
+
// position k+1: swapOutbound
|
|
243
|
+
// ...
|
|
244
|
+
// position n: postHops[last] ← lowest timeout
|
|
245
|
+
let pos = 0;
|
|
246
|
+
for (const hop of route.hops) {
|
|
247
|
+
if (isSwapHop(hop)) {
|
|
248
|
+
// Inbound channel (sender → intermediary, tokenIn side)
|
|
249
|
+
const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
250
|
+
try {
|
|
251
|
+
hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout);
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
255
|
+
return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
256
|
+
}
|
|
257
|
+
// Outbound channel (intermediary → recipient, tokenOut side)
|
|
258
|
+
const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
259
|
+
try {
|
|
260
|
+
await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout);
|
|
261
|
+
}
|
|
262
|
+
catch (err) {
|
|
263
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
264
|
+
return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
const timeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
269
|
+
try {
|
|
270
|
+
hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout);
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
274
|
+
return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// ── Reveal preimage backward ──────────────────────────────────────────────
|
|
279
|
+
const settled = [];
|
|
280
|
+
const fulfilledSet = new Set();
|
|
281
|
+
for (const { channelId, htlcId } of [...locked].reverse()) {
|
|
282
|
+
const channel = channels.get(channelId);
|
|
283
|
+
const lp = leaseProviders.get(channelId);
|
|
284
|
+
let fulfillResult;
|
|
285
|
+
try {
|
|
286
|
+
fulfillResult = await ops.fulfillHTLC(channel, htlcId, preimage, lp);
|
|
287
|
+
}
|
|
288
|
+
catch (err) {
|
|
289
|
+
const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
|
|
290
|
+
await cancelHtlcs(ops, channels, stillPending, leaseProviders);
|
|
291
|
+
return { success: false, error: String(err), settledHops: settled };
|
|
292
|
+
}
|
|
293
|
+
if (fulfillResult.error) {
|
|
294
|
+
const stillPending = locked.filter(h => !fulfilledSet.has(h.htlcId));
|
|
295
|
+
await cancelHtlcs(ops, channels, stillPending, leaseProviders);
|
|
296
|
+
return { success: false, error: fulfillResult.error, settledHops: settled };
|
|
297
|
+
}
|
|
298
|
+
channels.set(channelId, fulfillResult.channel);
|
|
299
|
+
settled.push(htlcId);
|
|
300
|
+
fulfilledSet.add(htlcId);
|
|
301
|
+
}
|
|
302
|
+
return { success: true, preimage, settledHops: settled };
|
|
303
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-hop forwarding envelopes (RFC-035 B4).
|
|
3
|
+
*
|
|
4
|
+
* A forwarder is handed an opaque `routingEnvelope` alongside an incoming HTLC
|
|
5
|
+
* and peels one hop from it: it learns the next hop, locks an HTLC onward, and
|
|
6
|
+
* passes the remaining (smaller) envelope to that hop.
|
|
7
|
+
*
|
|
8
|
+
* The envelope is deliberately **opaque** so the representation is pluggable: the
|
|
9
|
+
* cleartext codec (below) is the first implementation; an onion (X25519 + AEAD,
|
|
10
|
+
* per-hop encryption keys advertised on graph edges) can be added behind the same
|
|
11
|
+
* `RoutingEnvelopeCodec` seam without changing the message types.
|
|
12
|
+
*/
|
|
13
|
+
import type { RoutingHop, SwapHop } from './types.js';
|
|
14
|
+
/** Onward instruction the forwarder peels from an envelope. */
|
|
15
|
+
export interface ForwardHop {
|
|
16
|
+
/** Next-hop party public-key digest (the immediate recipient of the outgoing HTLC). */
|
|
17
|
+
via: string;
|
|
18
|
+
/** Optional explicit outgoing channel id (else the forwarder finds its channel to `via`). */
|
|
19
|
+
channelId?: string;
|
|
20
|
+
amount: bigint;
|
|
21
|
+
tokenId: string;
|
|
22
|
+
/** Absolute timeout (block) for the outgoing HTLC, when the envelope carries one. */
|
|
23
|
+
timeoutBlock?: bigint;
|
|
24
|
+
}
|
|
25
|
+
export type PeelResult =
|
|
26
|
+
/** This node is the recipient — no onward hop. */
|
|
27
|
+
{
|
|
28
|
+
kind: 'final';
|
|
29
|
+
}
|
|
30
|
+
/** Forward to `next`; `onward` is the remaining envelope for that hop (absent at the last hop). */
|
|
31
|
+
| {
|
|
32
|
+
kind: 'forward';
|
|
33
|
+
next: ForwardHop;
|
|
34
|
+
onward?: string;
|
|
35
|
+
};
|
|
36
|
+
export interface RoutingEnvelopeCodec {
|
|
37
|
+
/** Sender: build the envelope from the onward hops (already excludes the first hop). */
|
|
38
|
+
build(hops: (RoutingHop | SwapHop)[]): string;
|
|
39
|
+
/** Forwarder: peel one hop for `self`. */
|
|
40
|
+
peel(envelope: string, self: {
|
|
41
|
+
publicKeyDigest: string;
|
|
42
|
+
}): PeelResult;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Cleartext routing codec: the envelope is the JSON of the remaining hops.
|
|
46
|
+
* No confidentiality — a forwarder sees the path. Suitable for the RFC-035
|
|
47
|
+
* "known counterparties" scope; swap for an onion codec when path privacy is
|
|
48
|
+
* required.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createCleartextRoutingCodec(): RoutingEnvelopeCodec;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Multi-hop forwarding envelopes (RFC-035 B4).
|
|
4
|
+
*
|
|
5
|
+
* A forwarder is handed an opaque `routingEnvelope` alongside an incoming HTLC
|
|
6
|
+
* and peels one hop from it: it learns the next hop, locks an HTLC onward, and
|
|
7
|
+
* passes the remaining (smaller) envelope to that hop.
|
|
8
|
+
*
|
|
9
|
+
* The envelope is deliberately **opaque** so the representation is pluggable: the
|
|
10
|
+
* cleartext codec (below) is the first implementation; an onion (X25519 + AEAD,
|
|
11
|
+
* per-hop encryption keys advertised on graph edges) can be added behind the same
|
|
12
|
+
* `RoutingEnvelopeCodec` seam without changing the message types.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.createCleartextRoutingCodec = createCleartextRoutingCodec;
|
|
16
|
+
/**
|
|
17
|
+
* Cleartext routing codec: the envelope is the JSON of the remaining hops.
|
|
18
|
+
* No confidentiality — a forwarder sees the path. Suitable for the RFC-035
|
|
19
|
+
* "known counterparties" scope; swap for an onion codec when path privacy is
|
|
20
|
+
* required.
|
|
21
|
+
*/
|
|
22
|
+
function createCleartextRoutingCodec() {
|
|
23
|
+
return {
|
|
24
|
+
build(hops) {
|
|
25
|
+
const wire = hops.map((h) => ({
|
|
26
|
+
channelId: h.channelId,
|
|
27
|
+
to: h.to,
|
|
28
|
+
amount: h.amount.toString(),
|
|
29
|
+
tokenId: h.tokenId,
|
|
30
|
+
}));
|
|
31
|
+
return JSON.stringify(wire);
|
|
32
|
+
},
|
|
33
|
+
peel(envelope) {
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(envelope);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return { kind: 'final' };
|
|
40
|
+
}
|
|
41
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
42
|
+
return { kind: 'final' };
|
|
43
|
+
const [head, ...rest] = parsed;
|
|
44
|
+
const next = {
|
|
45
|
+
via: head.to,
|
|
46
|
+
amount: BigInt(head.amount),
|
|
47
|
+
tokenId: head.tokenId,
|
|
48
|
+
...(head.channelId ? { channelId: head.channelId } : {}),
|
|
49
|
+
...(head.timeoutBlock ? { timeoutBlock: BigInt(head.timeoutBlock) } : {}),
|
|
50
|
+
};
|
|
51
|
+
return rest.length > 0
|
|
52
|
+
? { kind: 'forward', next, onward: JSON.stringify(rest) }
|
|
53
|
+
: { kind: 'forward', next };
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ChannelGraph, ChannelGraphEdge, SwapAnnouncement } from './types.js';
|
|
2
|
+
/** Create an empty ChannelGraph. */
|
|
3
|
+
export declare function createChannelGraph(): ChannelGraph;
|
|
4
|
+
/**
|
|
5
|
+
* Add a directed channel edge to the graph.
|
|
6
|
+
*
|
|
7
|
+
* A single logical channel between two parties has two directed edges — one
|
|
8
|
+
* per direction of flow. Both may be added independently using the same
|
|
9
|
+
* `channelId` because they are keyed by `(channelId, from)`. Calling
|
|
10
|
+
* `addChannel` twice with the same `(channelId, from)` replaces the first
|
|
11
|
+
* entry (balance update semantics).
|
|
12
|
+
*/
|
|
13
|
+
export declare function addChannel(graph: ChannelGraph, edge: ChannelGraphEdge): void;
|
|
14
|
+
/**
|
|
15
|
+
* Remove ALL directed edges for `channelId` (i.e. both directions).
|
|
16
|
+
* No-op if the channelId is not present.
|
|
17
|
+
*/
|
|
18
|
+
export declare function removeChannel(graph: ChannelGraph, channelId: string): void;
|
|
19
|
+
/**
|
|
20
|
+
* Register a swap announcement from a bridging intermediary.
|
|
21
|
+
*
|
|
22
|
+
* Validates that the rate is a positive finite decimal before storing.
|
|
23
|
+
* Throws `Error` if the rate is zero or negative.
|
|
24
|
+
*
|
|
25
|
+
* Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
|
|
26
|
+
* are replaced to prevent stale rate data.
|
|
27
|
+
*/
|
|
28
|
+
export declare function announceSwap(graph: ChannelGraph, announcement: SwapAnnouncement): void;
|
|
29
|
+
/**
|
|
30
|
+
* Return all swap announcements for a given token pair, or an empty array.
|
|
31
|
+
*/
|
|
32
|
+
export declare function getSwapAnnouncements(graph: ChannelGraph, tokenIn: string, tokenOut: string): SwapAnnouncement[];
|