@totemsdk/omnia-router 0.2.1 → 0.4.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/bounded-search.d.ts +36 -0
- package/dist/bounded-search.js +164 -0
- package/dist/cjs/bounded-search.d.ts +36 -0
- package/dist/cjs/bounded-search.js +174 -0
- 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 +359 -0
- package/dist/cjs/forward.d.ts +50 -0
- package/dist/cjs/forward.js +56 -0
- package/dist/cjs/graph.d.ts +40 -0
- package/dist/cjs/graph.js +141 -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 +24 -0
- package/dist/cjs/pathfind.js +151 -0
- package/dist/cjs/rates.d.ts +9 -0
- package/dist/cjs/rates.js +27 -0
- package/dist/cjs/request.d.ts +19 -0
- package/dist/cjs/request.js +38 -0
- package/dist/cjs/route-validation.d.ts +24 -0
- package/dist/cjs/route-validation.js +91 -0
- package/dist/cjs/routing-engine.d.ts +86 -0
- package/dist/cjs/routing-engine.js +154 -0
- package/dist/cjs/types.d.ts +207 -0
- package/dist/cjs/types.js +10 -0
- package/dist/durable-router-ledger.js +6 -9
- package/dist/execute.js +72 -24
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +53 -0
- package/dist/graph.d.ts +8 -0
- package/dist/graph.js +46 -15
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -26
- package/dist/pathfind.d.ts +11 -12
- package/dist/pathfind.js +88 -196
- package/dist/rates.d.ts +9 -0
- package/dist/rates.js +22 -0
- package/dist/request.js +5 -9
- package/dist/route-validation.d.ts +24 -0
- package/dist/route-validation.js +84 -0
- package/dist/routing-engine.d.ts +86 -0
- package/dist/routing-engine.js +147 -0
- package/dist/types.d.ts +8 -1
- package/dist/types.js +1 -2
- package/package.json +17 -10
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @totemsdk/omnia-router — public types
|
|
3
|
+
*
|
|
4
|
+
* All monetary values are scaled bigints (SCALE = 10^8).
|
|
5
|
+
* The router uses local mirrors of OmniaChannel/HTLCRecord so the package
|
|
6
|
+
* has no hard runtime dependency on @totemsdk/omnia — callers pass the
|
|
7
|
+
* real objects (structural typing ensures compatibility).
|
|
8
|
+
*/
|
|
9
|
+
export interface ChannelParty {
|
|
10
|
+
partyId: string;
|
|
11
|
+
publicKeyDigest: string;
|
|
12
|
+
addressIndex: number;
|
|
13
|
+
}
|
|
14
|
+
export type HTLCStatus = 'pending' | 'fulfilled' | 'timed_out';
|
|
15
|
+
export interface ChannelHTLC {
|
|
16
|
+
htlcId: string;
|
|
17
|
+
amount: bigint;
|
|
18
|
+
hashlock: string;
|
|
19
|
+
timeoutBlock: bigint;
|
|
20
|
+
direction: 'offered' | 'received';
|
|
21
|
+
status: HTLCStatus;
|
|
22
|
+
htlcAddress: string;
|
|
23
|
+
senderPublicKeyDigest: string;
|
|
24
|
+
recipientPublicKeyDigest: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ChannelSigner {
|
|
27
|
+
publicKeyDigest: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Minimal mirror of OmniaChannel — the fields the router actually reads.
|
|
31
|
+
* Structurally compatible with @totemsdk/omnia's OmniaChannel so callers
|
|
32
|
+
* can pass real channel objects without an adapter.
|
|
33
|
+
*/
|
|
34
|
+
export interface RouterChannel {
|
|
35
|
+
channelId: string;
|
|
36
|
+
tokenId: string;
|
|
37
|
+
parties: ChannelParty[];
|
|
38
|
+
balances: Record<string, bigint>;
|
|
39
|
+
pendingHTLCs: ChannelHTLC[];
|
|
40
|
+
totalValue: bigint;
|
|
41
|
+
currentSequence: number;
|
|
42
|
+
status: string;
|
|
43
|
+
localSigner?: ChannelSigner;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Parameters for adding an HTLC — mirrors @totemsdk/omnia's AddHTLCParams.
|
|
47
|
+
*/
|
|
48
|
+
export interface HTLCParams {
|
|
49
|
+
amount: bigint;
|
|
50
|
+
hashlock: string;
|
|
51
|
+
timeoutBlock: bigint;
|
|
52
|
+
direction: 'offered' | 'received';
|
|
53
|
+
counterpartPublicKeyDigest: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Opaque lease-provider handle — the router passes it through to the
|
|
57
|
+
* underlying HTLC operations but never inspects it.
|
|
58
|
+
*/
|
|
59
|
+
export type LeaseProvider = unknown;
|
|
60
|
+
/**
|
|
61
|
+
* Dependency-injected HTLC operations.
|
|
62
|
+
*
|
|
63
|
+
* In production, wire in the real functions from @totemsdk/omnia:
|
|
64
|
+
* import { addHTLC, fulfillHTLC, timeoutHTLC } from '@totemsdk/omnia';
|
|
65
|
+
* const ops: ChannelOps = { addHTLC, fulfillHTLC, timeoutHTLC };
|
|
66
|
+
*
|
|
67
|
+
* In tests, pass mocks directly — no jest.mock() needed.
|
|
68
|
+
*/
|
|
69
|
+
export interface ChannelOps {
|
|
70
|
+
addHTLC(channel: RouterChannel, params: HTLCParams, leaseProvider: LeaseProvider): Promise<{
|
|
71
|
+
channel: RouterChannel;
|
|
72
|
+
htlcId: string;
|
|
73
|
+
error?: string;
|
|
74
|
+
}>;
|
|
75
|
+
fulfillHTLC(channel: RouterChannel, htlcId: string, preimage: string, leaseProvider: LeaseProvider): Promise<{
|
|
76
|
+
channel: RouterChannel;
|
|
77
|
+
error?: string;
|
|
78
|
+
}>;
|
|
79
|
+
timeoutHTLC(channel: RouterChannel, htlcId: string, leaseProvider: LeaseProvider): Promise<{
|
|
80
|
+
channel: RouterChannel;
|
|
81
|
+
error?: string;
|
|
82
|
+
}>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A directed edge in the channel graph.
|
|
86
|
+
* For a bidirectional channel, add two edges (one per direction).
|
|
87
|
+
*/
|
|
88
|
+
export interface ChannelGraphEdge {
|
|
89
|
+
channelId: string;
|
|
90
|
+
/** Sender's public key digest */
|
|
91
|
+
from: string;
|
|
92
|
+
/** Recipient's public key digest */
|
|
93
|
+
to: string;
|
|
94
|
+
tokenId: string;
|
|
95
|
+
/** Sender's available balance in scaled units */
|
|
96
|
+
availableBalance: bigint;
|
|
97
|
+
/** Maximum additional HTLC capacity in scaled units */
|
|
98
|
+
htlcCapacity: bigint;
|
|
99
|
+
/** Fee per SCALE units of amount (e.g. 100_000n = 0.1%) */
|
|
100
|
+
feeRate: bigint;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* In-memory channel graph with a swap announcement index.
|
|
104
|
+
*
|
|
105
|
+
* A single logical channel may have up to two directed edges (one per
|
|
106
|
+
* direction of flow, e.g. Alice→Bob and Bob→Alice). Both edges share the
|
|
107
|
+
* same `channelId` and are stored together in `edgesByChannel`.
|
|
108
|
+
*/
|
|
109
|
+
export interface ChannelGraph {
|
|
110
|
+
/** Directed edges keyed by sender pubkey */
|
|
111
|
+
nodeEdges: Map<string, ChannelGraphEdge[]>;
|
|
112
|
+
/**
|
|
113
|
+
* All directed edges for a channel, keyed by channelId.
|
|
114
|
+
* Value is an array because a bidirectional channel has two directed edges.
|
|
115
|
+
*/
|
|
116
|
+
edgesByChannel: Map<string, ChannelGraphEdge[]>;
|
|
117
|
+
/** Swap announcements keyed by `${tokenIn}:${tokenOut}` */
|
|
118
|
+
swapIndex: Map<string, SwapAnnouncement[]>;
|
|
119
|
+
}
|
|
120
|
+
export interface RoutingHop {
|
|
121
|
+
channelId: string;
|
|
122
|
+
from: string;
|
|
123
|
+
to: string;
|
|
124
|
+
amount: bigint;
|
|
125
|
+
tokenId: string;
|
|
126
|
+
/** Edge fee rate (per SCALE); populated by the routing engine. */
|
|
127
|
+
feeRate?: bigint;
|
|
128
|
+
/** Populated during payment execution */
|
|
129
|
+
htlcId?: string;
|
|
130
|
+
}
|
|
131
|
+
export interface SwapHop extends RoutingHop {
|
|
132
|
+
isSwap: true;
|
|
133
|
+
tokenIn: string;
|
|
134
|
+
tokenOut: string;
|
|
135
|
+
amountIn: bigint;
|
|
136
|
+
amountOut: bigint;
|
|
137
|
+
/** "amountOut per amountIn" expressed as decimal string, e.g. "0.95" */
|
|
138
|
+
rate: string;
|
|
139
|
+
inboundChannelId: string;
|
|
140
|
+
outboundChannelId: string;
|
|
141
|
+
}
|
|
142
|
+
export interface Route {
|
|
143
|
+
hops: (RoutingHop | SwapHop)[];
|
|
144
|
+
totalFees: bigint;
|
|
145
|
+
tokenIn: string;
|
|
146
|
+
tokenOut: string;
|
|
147
|
+
estimatedBlocks: number;
|
|
148
|
+
}
|
|
149
|
+
export interface CrossTokenRoute extends Route {
|
|
150
|
+
swapHops: SwapHop[];
|
|
151
|
+
}
|
|
152
|
+
export interface SwapAnnouncement {
|
|
153
|
+
intermediaryPubKey: string;
|
|
154
|
+
tokenIn: string;
|
|
155
|
+
tokenOut: string;
|
|
156
|
+
/** How many tokenOut scaled units per tokenIn scaled unit */
|
|
157
|
+
rate: string;
|
|
158
|
+
inboundChannelId: string;
|
|
159
|
+
outboundChannelId: string;
|
|
160
|
+
maxAmountIn: bigint;
|
|
161
|
+
}
|
|
162
|
+
export interface PaymentRequest {
|
|
163
|
+
/** SHA3-256 hex of preimage */
|
|
164
|
+
hashlock: string;
|
|
165
|
+
/**
|
|
166
|
+
* Known to the payer (returned by buildPaymentRequest).
|
|
167
|
+
* Strip this before sharing the request with intermediaries.
|
|
168
|
+
*/
|
|
169
|
+
preimage?: string;
|
|
170
|
+
amount: bigint;
|
|
171
|
+
tokenId: string;
|
|
172
|
+
expiryBlock: bigint;
|
|
173
|
+
description?: string;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* A verifiable fee-provenance record for a settled hop (#29): the artifact a
|
|
177
|
+
* pool's `recordPoolFee` earn-proof consumes. Binds channel + HTLC + recipient
|
|
178
|
+
* + amount so a fee record traces to a real fulfilled payment.
|
|
179
|
+
*/
|
|
180
|
+
export interface RouterFeeProof {
|
|
181
|
+
channelId: string;
|
|
182
|
+
htlcId: string;
|
|
183
|
+
recipientPublicKeyDigest: string;
|
|
184
|
+
amount: bigint;
|
|
185
|
+
tokenId: string;
|
|
186
|
+
settledAt: number;
|
|
187
|
+
proofHash: string;
|
|
188
|
+
}
|
|
189
|
+
export interface PaymentResult {
|
|
190
|
+
success: boolean;
|
|
191
|
+
/** Hex preimage revealed during settlement (present on success) */
|
|
192
|
+
preimage?: string;
|
|
193
|
+
error?: string;
|
|
194
|
+
/** Machine-readable failure code (e.g. ROUTE_REVALIDATION_FAILED). */
|
|
195
|
+
errorCode?: string;
|
|
196
|
+
/** htlcIds that were successfully settled */
|
|
197
|
+
settledHops: string[];
|
|
198
|
+
/** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
|
|
199
|
+
feeProofs?: RouterFeeProof[];
|
|
200
|
+
}
|
|
201
|
+
export interface RouteOptions {
|
|
202
|
+
/**
|
|
203
|
+
* Maximum number of hops for the whole route (default: 8). For cross-token
|
|
204
|
+
* routes this is a global end-to-end budget.
|
|
205
|
+
*/
|
|
206
|
+
maxHops?: number;
|
|
207
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @totemsdk/omnia-router — public types
|
|
4
|
+
*
|
|
5
|
+
* All monetary values are scaled bigints (SCALE = 10^8).
|
|
6
|
+
* The router uses local mirrors of OmniaChannel/HTLCRecord so the package
|
|
7
|
+
* has no hard runtime dependency on @totemsdk/omnia — callers pass the
|
|
8
|
+
* real objects (structural typing ensures compatibility).
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
"use strict";
|
|
2
1
|
/**
|
|
3
2
|
* Durable settled-segment ledger (RFC-007 G9).
|
|
4
3
|
*
|
|
@@ -14,25 +13,23 @@
|
|
|
14
13
|
* (never treated as absence), no silent downgrade, and concurrent hop
|
|
15
14
|
* settlement is never lost.
|
|
16
15
|
*/
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const snapshot_1 = require("@totemsdk/storage/snapshot");
|
|
20
|
-
const errors_1 = require("@totemsdk/storage/errors");
|
|
16
|
+
import { createRevisionedSnapshotStore, } from '@totemsdk/storage/snapshot';
|
|
17
|
+
import { StorageError } from '@totemsdk/storage/errors';
|
|
21
18
|
const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
|
|
22
19
|
function segmentKey(channelId, htlcId) {
|
|
23
20
|
return `${channelId}:${htlcId}`;
|
|
24
21
|
}
|
|
25
22
|
function assertLedgerState(state) {
|
|
26
23
|
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
27
|
-
throw new
|
|
24
|
+
throw new StorageError('omnia-router ledger state is not an object', 'corrupt');
|
|
28
25
|
}
|
|
29
26
|
const value = state.segments;
|
|
30
27
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
31
|
-
throw new
|
|
28
|
+
throw new StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
|
|
32
29
|
}
|
|
33
30
|
}
|
|
34
|
-
function createDurableRouterLedger(adapter, options = {}) {
|
|
35
|
-
const snapshots =
|
|
31
|
+
export function createDurableRouterLedger(adapter, options = {}) {
|
|
32
|
+
const snapshots = createRevisionedSnapshotStore(adapter, {
|
|
36
33
|
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
37
34
|
requireAckMode: options.requireAckMode,
|
|
38
35
|
empty: () => ({ segments: {} }),
|
package/dist/execute.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
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");
|
|
1
|
+
import { bytesToHex, sha3_256 } from '@totemsdk/core';
|
|
2
|
+
import { validateChannelSpend, validateRoute, validateRoutingHop, swapIntermediary } from './route-validation.js';
|
|
3
|
+
import { SCALE } from './rates.js';
|
|
10
4
|
// ─── Type guard ───────────────────────────────────────────────────────────────
|
|
11
5
|
function isSwapHop(hop) {
|
|
12
6
|
return hop.isSwap === true;
|
|
13
7
|
}
|
|
8
|
+
function revalidationErrorCode(message) {
|
|
9
|
+
return message.includes('ROUTE_REVALIDATION_FAILED') ? 'ROUTE_REVALIDATION_FAILED' : undefined;
|
|
10
|
+
}
|
|
14
11
|
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
15
12
|
/** Determine the counterparty public key digest relative to the local signer. */
|
|
16
13
|
function counterpartPkd(channel) {
|
|
@@ -53,12 +50,31 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders) {
|
|
|
53
50
|
*
|
|
54
51
|
* The `channels` map is updated in-place after each HTLC operation.
|
|
55
52
|
*/
|
|
56
|
-
async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
53
|
+
export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
57
54
|
const preimage = paymentRequest.preimage;
|
|
58
55
|
if (!preimage) {
|
|
59
56
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
60
57
|
}
|
|
61
58
|
const plainHops = route.hops.filter(h => !isSwapHop(h));
|
|
59
|
+
// Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
|
|
60
|
+
// downstream intermediaries; the fee for the final edge belongs to the
|
|
61
|
+
// recipient and is not charged. Intermediary i retains
|
|
62
|
+
// hopAmount[i] - hopAmount[i+1]. With no fee rates this is the legacy
|
|
63
|
+
// same-amount behaviour.
|
|
64
|
+
const fees = plainHops.map((hop) => hop.feeRate && hop.feeRate > 0n ? (paymentRequest.amount * hop.feeRate) / SCALE : 0n);
|
|
65
|
+
for (let i = 0; i < plainHops.length; i++) {
|
|
66
|
+
const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
|
|
67
|
+
plainHops[i].amount = paymentRequest.amount + downstream;
|
|
68
|
+
}
|
|
69
|
+
const routeValidation = validateRoute(channels, route);
|
|
70
|
+
if (!routeValidation.ok) {
|
|
71
|
+
return {
|
|
72
|
+
success: false,
|
|
73
|
+
error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
|
|
74
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
75
|
+
settledHops: [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
62
78
|
const locked = [];
|
|
63
79
|
// ── Forward: lock HTLCs ───────────────────────────────────────────────────
|
|
64
80
|
for (let i = 0; i < plainHops.length; i++) {
|
|
@@ -73,6 +89,16 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
|
|
|
73
89
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
74
90
|
return { success: false, error: `No lease provider for channel ${hop.channelId}`, settledHops: [] };
|
|
75
91
|
}
|
|
92
|
+
const hopValidation = validateRoutingHop(channels, hop);
|
|
93
|
+
if (!hopValidation.ok) {
|
|
94
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
95
|
+
return {
|
|
96
|
+
success: false,
|
|
97
|
+
error: `ROUTE_REVALIDATION_FAILED: ${hopValidation.error}`,
|
|
98
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
99
|
+
settledHops: [],
|
|
100
|
+
};
|
|
101
|
+
}
|
|
76
102
|
// Timeouts decrease toward the recipient so each hop has time to claim.
|
|
77
103
|
const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
|
|
78
104
|
let addResult;
|
|
@@ -132,13 +158,13 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
|
|
|
132
158
|
}
|
|
133
159
|
return { success: true, preimage, settledHops: settled, feeProofs };
|
|
134
160
|
}
|
|
135
|
-
|
|
161
|
+
export const ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
|
|
136
162
|
/**
|
|
137
163
|
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
138
164
|
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
139
165
|
* real fulfilled payment, never a declared string.
|
|
140
166
|
*/
|
|
141
|
-
function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
167
|
+
export function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
142
168
|
const ts = settledAt ?? Date.now();
|
|
143
169
|
const proof = {
|
|
144
170
|
channelId: channel.channelId,
|
|
@@ -152,10 +178,10 @@ function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
|
152
178
|
proof.proofHash = computeRouterFeeProofHash(proof);
|
|
153
179
|
return proof;
|
|
154
180
|
}
|
|
155
|
-
function computeRouterFeeProofHash(proof) {
|
|
181
|
+
export function computeRouterFeeProofHash(proof) {
|
|
156
182
|
const { proofHash, ...rest } = proof;
|
|
157
|
-
const input = `${
|
|
158
|
-
return
|
|
183
|
+
const input = `${ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
|
|
184
|
+
return bytesToHex(sha3_256(new TextEncoder().encode(input)));
|
|
159
185
|
}
|
|
160
186
|
function canonicalJson(value) {
|
|
161
187
|
if (typeof value === 'bigint')
|
|
@@ -175,7 +201,7 @@ function canonicalJson(value) {
|
|
|
175
201
|
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
176
202
|
* Call this explicitly to roll back before or without attempting execution.
|
|
177
203
|
*/
|
|
178
|
-
async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
204
|
+
export async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
179
205
|
const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
|
|
180
206
|
await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
|
|
181
207
|
}
|
|
@@ -195,23 +221,35 @@ async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
|
195
221
|
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
196
222
|
* all still-pending locked HTLCs.
|
|
197
223
|
*/
|
|
198
|
-
async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
224
|
+
export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
199
225
|
const preimage = paymentRequest.preimage;
|
|
200
226
|
if (!preimage) {
|
|
201
227
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
202
228
|
}
|
|
229
|
+
const routeValidation = validateRoute(channels, route);
|
|
230
|
+
if (!routeValidation.ok) {
|
|
231
|
+
return {
|
|
232
|
+
success: false,
|
|
233
|
+
error: `ROUTE_REVALIDATION_FAILED: ${routeValidation.error}`,
|
|
234
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
235
|
+
settledHops: [],
|
|
236
|
+
};
|
|
237
|
+
}
|
|
203
238
|
const locked = [];
|
|
204
239
|
/**
|
|
205
240
|
* Lock a single HTLC, add it to `locked`, and return the htlcId.
|
|
206
241
|
* Throws on any error so callers can handle rollback uniformly.
|
|
207
242
|
*/
|
|
208
|
-
async function lockHTLC(channelId, amount, hashlock, timeoutBlock) {
|
|
243
|
+
async function lockHTLC(channelId, amount, hashlock, timeoutBlock, tokenId, sender) {
|
|
209
244
|
const channel = channels.get(channelId);
|
|
210
245
|
const lp = leaseProviders.get(channelId);
|
|
211
246
|
if (!channel)
|
|
212
247
|
throw new Error(`Channel ${channelId} not found`);
|
|
213
248
|
if (!lp)
|
|
214
249
|
throw new Error(`No lease provider for channel ${channelId}`);
|
|
250
|
+
const spend = validateChannelSpend(channel, sender, amount, tokenId);
|
|
251
|
+
if (!spend.ok)
|
|
252
|
+
throw new Error(`ROUTE_REVALIDATION_FAILED: ${spend.error}`);
|
|
215
253
|
// Let addHTLC exceptions propagate — they carry the original error message.
|
|
216
254
|
const result = await ops.addHTLC(channel, {
|
|
217
255
|
amount,
|
|
@@ -248,30 +286,40 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
|
|
|
248
286
|
// Inbound channel (sender → intermediary, tokenIn side)
|
|
249
287
|
const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
250
288
|
try {
|
|
251
|
-
hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout);
|
|
289
|
+
hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
|
|
252
290
|
}
|
|
253
291
|
catch (err) {
|
|
254
292
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
255
|
-
return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
293
|
+
return { success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
256
294
|
}
|
|
257
295
|
// Outbound channel (intermediary → recipient, tokenOut side)
|
|
258
296
|
const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
297
|
+
const intermediary = swapIntermediary(channels, hop);
|
|
298
|
+
if (!intermediary) {
|
|
299
|
+
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
300
|
+
return {
|
|
301
|
+
success: false,
|
|
302
|
+
error: `ROUTE_REVALIDATION_FAILED: no intermediary for ${hop.inboundChannelId}`,
|
|
303
|
+
errorCode: 'ROUTE_REVALIDATION_FAILED',
|
|
304
|
+
settledHops: [],
|
|
305
|
+
};
|
|
306
|
+
}
|
|
259
307
|
try {
|
|
260
|
-
await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout);
|
|
308
|
+
await lockHTLC(hop.outboundChannelId, hop.amountOut, paymentRequest.hashlock, outTimeout, hop.tokenOut, intermediary);
|
|
261
309
|
}
|
|
262
310
|
catch (err) {
|
|
263
311
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
264
|
-
return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
312
|
+
return { success: false, error: `Outbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
265
313
|
}
|
|
266
314
|
}
|
|
267
315
|
else {
|
|
268
316
|
const timeout = paymentRequest.expiryBlock - BigInt(pos++);
|
|
269
317
|
try {
|
|
270
|
-
hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout);
|
|
318
|
+
hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
|
|
271
319
|
}
|
|
272
320
|
catch (err) {
|
|
273
321
|
await cancelHtlcs(ops, channels, locked, leaseProviders);
|
|
274
|
-
return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, settledHops: [] };
|
|
322
|
+
return { success: false, error: `Hop HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] };
|
|
275
323
|
}
|
|
276
324
|
}
|
|
277
325
|
}
|
|
@@ -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;
|
package/dist/forward.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
/**
|
|
14
|
+
* Cleartext routing codec: the envelope is the JSON of the remaining hops.
|
|
15
|
+
* No confidentiality — a forwarder sees the path. Suitable for the RFC-035
|
|
16
|
+
* "known counterparties" scope; swap for an onion codec when path privacy is
|
|
17
|
+
* required.
|
|
18
|
+
*/
|
|
19
|
+
export function createCleartextRoutingCodec() {
|
|
20
|
+
return {
|
|
21
|
+
build(hops) {
|
|
22
|
+
const wire = hops.map((h) => ({
|
|
23
|
+
channelId: h.channelId,
|
|
24
|
+
to: h.to,
|
|
25
|
+
amount: h.amount.toString(),
|
|
26
|
+
tokenId: h.tokenId,
|
|
27
|
+
}));
|
|
28
|
+
return JSON.stringify(wire);
|
|
29
|
+
},
|
|
30
|
+
peel(envelope) {
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(envelope);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { kind: 'final' };
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
39
|
+
return { kind: 'final' };
|
|
40
|
+
const [head, ...rest] = parsed;
|
|
41
|
+
const next = {
|
|
42
|
+
via: head.to,
|
|
43
|
+
amount: BigInt(head.amount),
|
|
44
|
+
tokenId: head.tokenId,
|
|
45
|
+
...(head.channelId ? { channelId: head.channelId } : {}),
|
|
46
|
+
...(head.timeoutBlock ? { timeoutBlock: BigInt(head.timeoutBlock) } : {}),
|
|
47
|
+
};
|
|
48
|
+
return rest.length > 0
|
|
49
|
+
? { kind: 'forward', next, onward: JSON.stringify(rest) }
|
|
50
|
+
: { kind: 'forward', next };
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
package/dist/graph.d.ts
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { ChannelGraph, ChannelGraphEdge, SwapAnnouncement } from './types.js';
|
|
2
|
+
/** Internal graph revisions (topology / economics / live state). */
|
|
3
|
+
export interface GraphRevisions {
|
|
4
|
+
topology: number;
|
|
5
|
+
economics: number;
|
|
6
|
+
live: number;
|
|
7
|
+
}
|
|
8
|
+
/** Snapshot-consistent revision marker for routing caches and trees. */
|
|
9
|
+
export declare function getGraphRevisions(graph: ChannelGraph): GraphRevisions;
|
|
2
10
|
/** Create an empty ChannelGraph. */
|
|
3
11
|
export declare function createChannelGraph(): ChannelGraph;
|
|
4
12
|
/**
|