@totemsdk/omnia-router 0.4.3 → 0.6.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.
@@ -1,4 +1,6 @@
1
- import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, PendingRefund, LeaseProvider, ChannelHTLC, RouterFeeProof } from './types.js';
1
+ import { type RouteBinding } from './route-validation.js';
2
+ import { type ExpiryPolicy } from './expiry.js';
3
+ import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, PendingRefund, LeaseProvider, ChannelHTLC, RouterFeeProof, RouterSignedState, RouterStateTransition } from './types.js';
2
4
  /**
3
5
  * Best-effort timeout of a set of locked HTLCs.
4
6
  * Errors from individual timeoutHTLC calls are silently ignored so rollback
@@ -23,15 +25,40 @@ export declare class PendingRefundError extends Error {
23
25
  *
24
26
  * The `channels` map is updated in-place after each HTLC operation.
25
27
  */
26
- export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
27
- export declare const ROUTER_FEE_PROOF_DOMAIN = "totemsdk/omnia-router/fee-proof/v1";
28
+ export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>, binding?: RouteBinding, expiry?: ExpiryPolicy): Promise<PaymentResult>;
29
+ export declare const ROUTER_FEE_PROOF_DOMAIN = "totemsdk/omnia-router/fee-proof/v2";
28
30
  /**
29
- * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
30
- * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
31
- * real fulfilled payment, never a declared string.
31
+ * OMN-083: build a fee proof bound to the authenticated transition that settled
32
+ * the HTLC.
33
+ *
34
+ * The proof carries both state commitments, the exact balance delta the
35
+ * recipient received, and the fee the intermediary retained. A hash over
36
+ * descriptive fields proves only that the caller's numbers are self-consistent;
37
+ * this proves the payment happened on this channel.
38
+ */
39
+ export declare function buildAuthenticatedRouterFeeProof(channel: RouterChannel, htlc: ChannelHTLC, transition: RouterStateTransition, options?: {
40
+ feeAmount?: bigint;
41
+ settledAt?: number;
42
+ }): RouterFeeProof;
43
+ /**
44
+ * Legacy descriptive proof. Kept for callers that only need a provenance
45
+ * record; it is explicitly **not** settlement evidence (OMN-083).
32
46
  */
33
47
  export declare function buildRouterFeeProof(channel: RouterChannel, htlc: ChannelHTLC, settledAt?: number): RouterFeeProof;
34
48
  export declare function computeRouterFeeProofHash(proof: RouterFeeProof): string;
49
+ export interface VerifyRouterFeeProofOptions {
50
+ /**
51
+ * Optional signature check over the successor state. The router is runtime
52
+ * neutral, so bilateral authorization is verified by the caller that holds
53
+ * the channel keys.
54
+ */
55
+ verifySignature?: (state: RouterSignedState, party: {
56
+ partyId: string;
57
+ publicKeyDigest: string;
58
+ }) => boolean;
59
+ }
60
+ /** Re-derive an authenticated fee proof from the states it claims. */
61
+ export declare function verifyRouterFeeProof(channel: RouterChannel, transition: RouterStateTransition, proof: RouterFeeProof, options?: VerifyRouterFeeProofOptions): boolean;
35
62
  /**
36
63
  * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
37
64
  * Call this explicitly to roll back before or without attempting execution.
@@ -52,4 +79,4 @@ export declare function cancelPayment(ops: ChannelOps, channels: Map<string, Rou
52
79
  * Rollback fires on ANY failure (forward OR backward phase) by timing out
53
80
  * all still-pending locked HTLCs.
54
81
  */
55
- export declare function executeCrossTokenPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: CrossTokenRoute, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
82
+ export declare function executeCrossTokenPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: CrossTokenRoute, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>, expiry?: ExpiryPolicy): Promise<PaymentResult>;
@@ -2,12 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ROUTER_FEE_PROOF_DOMAIN = exports.PendingRefundError = void 0;
4
4
  exports.executeMultiHopPayment = executeMultiHopPayment;
5
+ exports.buildAuthenticatedRouterFeeProof = buildAuthenticatedRouterFeeProof;
5
6
  exports.buildRouterFeeProof = buildRouterFeeProof;
6
7
  exports.computeRouterFeeProofHash = computeRouterFeeProofHash;
8
+ exports.verifyRouterFeeProof = verifyRouterFeeProof;
7
9
  exports.cancelPayment = cancelPayment;
8
10
  exports.executeCrossTokenPayment = executeCrossTokenPayment;
9
11
  const core_1 = require("@totemsdk/core");
10
12
  const route_validation_js_1 = require("./route-validation.js");
13
+ const expiry_js_1 = require("./expiry.js");
11
14
  const rates_js_1 = require("./rates.js");
12
15
  // ─── Type guard ───────────────────────────────────────────────────────────────
13
16
  function isSwapHop(hop) {
@@ -44,8 +47,18 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders, pending) {
44
47
  for (const { channelId, htlcId } of [...locked].reverse()) {
45
48
  const ch = channels.get(channelId);
46
49
  const lp = leaseProviders.get(channelId);
47
- if (!ch || !lp)
50
+ if (!ch || !lp) {
51
+ // OMN-082 (CAN-015): a missing dependency is not a released lock. Record
52
+ // the obligation so the caller is never told rollback was clean.
53
+ pending.push({
54
+ channelId,
55
+ htlcId,
56
+ reason: !ch
57
+ ? `channel ${channelId} is no longer in the routing view`
58
+ : `no lease provider for channel ${channelId}`,
59
+ });
48
60
  continue;
61
+ }
49
62
  try {
50
63
  const res = await ops.timeoutHTLC(ch, htlcId, lp);
51
64
  channels.set(channelId, res.channel);
@@ -79,7 +92,7 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders, pending) {
79
92
  *
80
93
  * The `channels` map is updated in-place after each HTLC operation.
81
94
  */
82
- async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
95
+ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders, binding, expiry) {
83
96
  /** Locks rollback could not release (CAN-015). */
84
97
  const pendingRefunds = [];
85
98
  const failed = (result) => pendingRefunds.length > 0 ? { ...result, pendingRefunds: [...pendingRefunds] } : result;
@@ -88,6 +101,27 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
88
101
  return failed({ success: false, state: 'failed', terminal: true, error: 'paymentRequest.preimage is required for execution', settledHops: [] });
89
102
  }
90
103
  const plainHops = route.hops.filter(h => !isSwapHop(h));
104
+ // OMN-080: this entry point settles a single asset. A swap hop belongs to
105
+ // executeCrossTokenPayment; silently dropping them used to let a swap-only
106
+ // route report success with nothing settled.
107
+ if (plainHops.length !== route.hops.length) {
108
+ return failed({
109
+ success: false,
110
+ state: 'failed',
111
+ terminal: true,
112
+ error: 'executeMultiHopPayment received a route with swap hops; use executeCrossTokenPayment',
113
+ settledHops: [],
114
+ });
115
+ }
116
+ if (plainHops.length === 0) {
117
+ return failed({
118
+ success: false,
119
+ state: 'failed',
120
+ terminal: true,
121
+ error: 'route has no executable hops',
122
+ settledHops: [],
123
+ });
124
+ }
91
125
  // Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
92
126
  // downstream intermediaries; the fee for the final edge belongs to the
93
127
  // recipient and is not charged. Intermediary i retains
@@ -98,7 +132,12 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
98
132
  const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
99
133
  plainHops[i].amount = paymentRequest.amount + downstream;
100
134
  }
101
- const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route);
135
+ const routeValidation = (0, route_validation_js_1.validateRoute)(channels, route, {
136
+ payer: binding?.payer ?? plainHops[0].from,
137
+ recipient: binding?.recipient ?? plainHops[plainHops.length - 1].to,
138
+ amount: paymentRequest.amount,
139
+ tokenId: paymentRequest.tokenId,
140
+ });
102
141
  if (!routeValidation.ok) {
103
142
  return failed({
104
143
  success: false,
@@ -107,6 +146,19 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
107
146
  settledHops: [],
108
147
  });
109
148
  }
149
+ // OMN-081: derive the deadline spread from the channels' contest windows and
150
+ // refuse the route if the requested expiry cannot fit every hop.
151
+ const expiryPlan = (0, expiry_js_1.planRouteExpiry)(channels, route, paymentRequest.expiryBlock, plainHops.length, expiry ?? {});
152
+ if (!expiryPlan.ok) {
153
+ return failed({
154
+ success: false,
155
+ state: 'failed',
156
+ terminal: true,
157
+ error: `EXPIRY_PLAN_FAILED: ${expiryPlan.error}`,
158
+ errorCode: 'EXPIRY_PLAN_FAILED',
159
+ settledHops: [],
160
+ });
161
+ }
110
162
  const locked = [];
111
163
  // ── Forward: lock HTLCs ───────────────────────────────────────────────────
112
164
  for (let i = 0; i < plainHops.length; i++) {
@@ -132,7 +184,7 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
132
184
  });
133
185
  }
134
186
  // Timeouts decrease toward the recipient so each hop has time to claim.
135
- const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
187
+ const timeoutBlock = (0, expiry_js_1.hopTimeout)(paymentRequest.expiryBlock, expiryPlan.plan.delta, i);
136
188
  let addResult;
137
189
  try {
138
190
  addResult = await ops.addHTLC(channel, {
@@ -182,10 +234,23 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
182
234
  channels.set(channelId, fulfillResult.channel);
183
235
  settled.push(htlcId);
184
236
  fulfilledSet.add(htlcId);
185
- // Build the verifiable fee proof for this settled hop (#29).
237
+ // Build the verifiable fee proof for this settled hop (#29 / OMN-083).
186
238
  const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
187
239
  if (htlc) {
188
- feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
240
+ const hopIndex = plainHops.findIndex(h => h.htlcId === htlcId);
241
+ const hopAmount = hopIndex >= 0 ? plainHops[hopIndex].amount : htlc.amount;
242
+ const downstream = hopIndex >= 0
243
+ ? (plainHops[hopIndex + 1]?.amount ?? paymentRequest.amount)
244
+ : paymentRequest.amount;
245
+ const feeAmount = hopAmount > downstream ? hopAmount - downstream : 0n;
246
+ if (fulfillResult.previousState && fulfillResult.nextState) {
247
+ feeProofs.push(buildAuthenticatedRouterFeeProof(fulfillResult.channel, htlc, { previous: fulfillResult.previousState, next: fulfillResult.nextState }, { feeAmount, settledAt: Date.now() }));
248
+ }
249
+ else {
250
+ // No authenticated state pair: emit a proof that says so, rather than a
251
+ // descriptive hash masquerading as settlement evidence.
252
+ feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
253
+ }
189
254
  }
190
255
  }
191
256
  return {
@@ -197,21 +262,78 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
197
262
  feeProofs,
198
263
  };
199
264
  }
200
- exports.ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
265
+ exports.ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v2';
266
+ /** Port carrying the state commitment the proof binds (OMN-083). */
267
+ const STATE_COMMITMENT_V2_PORT = 102;
268
+ function commitmentOf(state, label) {
269
+ const value = state.stateVariables?.find((sv) => sv.port === STATE_COMMITMENT_V2_PORT);
270
+ if (!value)
271
+ throw new Error(`${label} is missing the port-102 commitment`);
272
+ return String(value.value).replace(/^0x/i, '').toLowerCase();
273
+ }
274
+ function recipientOf(channel, htlc) {
275
+ const party = channel.parties.find((p) => p.publicKeyDigest === htlc.recipientPublicKeyDigest);
276
+ if (!party)
277
+ throw new Error('HTLC recipient is not a channel party');
278
+ return { partyId: party.partyId, publicKeyDigest: party.publicKeyDigest };
279
+ }
280
+ /**
281
+ * OMN-083: build a fee proof bound to the authenticated transition that settled
282
+ * the HTLC.
283
+ *
284
+ * The proof carries both state commitments, the exact balance delta the
285
+ * recipient received, and the fee the intermediary retained. A hash over
286
+ * descriptive fields proves only that the caller's numbers are self-consistent;
287
+ * this proves the payment happened on this channel.
288
+ */
289
+ function buildAuthenticatedRouterFeeProof(channel, htlc, transition, options = {}) {
290
+ const { previous, next } = transition;
291
+ if (next.sequence <= previous.sequence) {
292
+ throw new Error('successor state does not follow the predecessor');
293
+ }
294
+ const pending = previous.pendingHTLCs?.find((h) => h.htlcId === htlc.htlcId);
295
+ if (!pending)
296
+ throw new Error(`HTLC ${htlc.htlcId} is not pending in the predecessor state`);
297
+ if (next.pendingHTLCs?.some((h) => h.htlcId === htlc.htlcId)) {
298
+ throw new Error(`successor state still carries HTLC ${htlc.htlcId}`);
299
+ }
300
+ const recipient = recipientOf(channel, htlc);
301
+ const balanceDelta = (next.balances[recipient.partyId] ?? 0n) - (previous.balances[recipient.partyId] ?? 0n);
302
+ if (balanceDelta !== pending.amount) {
303
+ throw new Error(`transition moves ${balanceDelta.toString()} to the recipient, not the HTLC amount ${pending.amount.toString()}`);
304
+ }
305
+ const proof = {
306
+ channelId: channel.channelId,
307
+ htlcId: htlc.htlcId,
308
+ recipientPublicKeyDigest: recipient.publicKeyDigest,
309
+ amount: pending.amount,
310
+ tokenId: channel.tokenId,
311
+ settledAt: options.settledAt ?? Date.now(),
312
+ authenticated: true,
313
+ ...(options.feeAmount !== undefined ? { feeAmount: options.feeAmount } : {}),
314
+ previousSequence: previous.sequence,
315
+ sequence: next.sequence,
316
+ previousStateCommitmentV2: commitmentOf(previous, 'predecessor state'),
317
+ stateCommitmentV2: commitmentOf(next, 'successor state'),
318
+ balanceDelta,
319
+ proofHash: '',
320
+ };
321
+ proof.proofHash = computeRouterFeeProofHash(proof);
322
+ return proof;
323
+ }
201
324
  /**
202
- * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
203
- * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
204
- * real fulfilled payment, never a declared string.
325
+ * Legacy descriptive proof. Kept for callers that only need a provenance
326
+ * record; it is explicitly **not** settlement evidence (OMN-083).
205
327
  */
206
328
  function buildRouterFeeProof(channel, htlc, settledAt) {
207
- const ts = settledAt ?? Date.now();
208
329
  const proof = {
209
330
  channelId: channel.channelId,
210
331
  htlcId: htlc.htlcId,
211
332
  recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
212
333
  amount: htlc.amount,
213
334
  tokenId: channel.tokenId,
214
- settledAt: ts,
335
+ settledAt: settledAt ?? Date.now(),
336
+ authenticated: false,
215
337
  proofHash: '',
216
338
  };
217
339
  proof.proofHash = computeRouterFeeProofHash(proof);
@@ -222,6 +344,49 @@ function computeRouterFeeProofHash(proof) {
222
344
  const input = `${exports.ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
223
345
  return (0, core_1.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode(input)));
224
346
  }
347
+ /** Re-derive an authenticated fee proof from the states it claims. */
348
+ function verifyRouterFeeProof(channel, transition, proof, options = {}) {
349
+ try {
350
+ if (proof.authenticated !== true)
351
+ return false;
352
+ if (proof.channelId !== channel.channelId)
353
+ return false;
354
+ if (proof.previousSequence !== transition.previous.sequence)
355
+ return false;
356
+ if (proof.sequence !== transition.next.sequence)
357
+ return false;
358
+ const pending = transition.previous.pendingHTLCs?.find((h) => h.htlcId === proof.htlcId);
359
+ if (!pending)
360
+ return false;
361
+ if (transition.next.pendingHTLCs?.some((h) => h.htlcId === proof.htlcId))
362
+ return false;
363
+ const recipient = recipientOf(channel, { recipientPublicKeyDigest: proof.recipientPublicKeyDigest });
364
+ const delta = (transition.next.balances[recipient.partyId] ?? 0n)
365
+ - (transition.previous.balances[recipient.partyId] ?? 0n);
366
+ if (delta !== proof.balanceDelta)
367
+ return false;
368
+ if (delta !== proof.amount || pending.amount !== proof.amount)
369
+ return false;
370
+ if (commitmentOf(transition.previous, 'predecessor state') !== proof.previousStateCommitmentV2)
371
+ return false;
372
+ if (commitmentOf(transition.next, 'successor state') !== proof.stateCommitmentV2)
373
+ return false;
374
+ const { proofHash, ...rest } = proof;
375
+ if (computeRouterFeeProofHash({ ...rest, proofHash: '' }) !== proofHash)
376
+ return false;
377
+ if (options.verifySignature) {
378
+ for (const party of channel.parties) {
379
+ if (!options.verifySignature(transition.next, { partyId: party.partyId, publicKeyDigest: party.publicKeyDigest })) {
380
+ return false;
381
+ }
382
+ }
383
+ }
384
+ return true;
385
+ }
386
+ catch {
387
+ return false;
388
+ }
389
+ }
225
390
  function canonicalJson(value) {
226
391
  if (typeof value === 'bigint')
227
392
  return JSON.stringify({ __bigint: value.toString() });
@@ -266,7 +431,7 @@ async function cancelPayment(ops, channels, route, leaseProviders) {
266
431
  * Rollback fires on ANY failure (forward OR backward phase) by timing out
267
432
  * all still-pending locked HTLCs.
268
433
  */
269
- async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
434
+ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders, expiry) {
270
435
  /** Locks rollback could not release (CAN-015). */
271
436
  const pendingRefunds = [];
272
437
  const failed = (result) => pendingRefunds.length > 0 ? { ...result, pendingRefunds: [...pendingRefunds] } : result;
@@ -283,6 +448,20 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
283
448
  settledHops: [],
284
449
  });
285
450
  }
451
+ // OMN-081: one lock per routing hop, two per swap hop. Derive the spread from
452
+ // the channels' contest windows before anything is locked.
453
+ const lockCount = route.hops.reduce((count, hop) => count + (isSwapHop(hop) ? 2 : 1), 0);
454
+ const expiryPlan = (0, expiry_js_1.planRouteExpiry)(channels, route, paymentRequest.expiryBlock, lockCount, expiry ?? {});
455
+ if (!expiryPlan.ok) {
456
+ return failed({
457
+ success: false,
458
+ state: 'failed',
459
+ terminal: true,
460
+ error: `EXPIRY_PLAN_FAILED: ${expiryPlan.error}`,
461
+ errorCode: 'EXPIRY_PLAN_FAILED',
462
+ settledHops: [],
463
+ });
464
+ }
286
465
  const locked = [];
287
466
  /**
288
467
  * Lock a single HTLC, add it to `locked`, and return the htlcId.
@@ -332,7 +511,7 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
332
511
  for (const hop of route.hops) {
333
512
  if (isSwapHop(hop)) {
334
513
  // Inbound channel (sender → intermediary, tokenIn side)
335
- const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
514
+ const inTimeout = (0, expiry_js_1.hopTimeout)(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
336
515
  try {
337
516
  hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
338
517
  }
@@ -341,7 +520,7 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
341
520
  return failed({ success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] });
342
521
  }
343
522
  // Outbound channel (intermediary → recipient, tokenOut side)
344
- const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
523
+ const outTimeout = (0, expiry_js_1.hopTimeout)(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
345
524
  const intermediary = (0, route_validation_js_1.swapIntermediary)(channels, hop);
346
525
  if (!intermediary) {
347
526
  await cancelHtlcs(ops, channels, locked, leaseProviders, pendingRefunds);
@@ -361,7 +540,7 @@ async function executeCrossTokenPayment(ops, channels, route, paymentRequest, le
361
540
  }
362
541
  }
363
542
  else {
364
- const timeout = paymentRequest.expiryBlock - BigInt(pos++);
543
+ const timeout = (0, expiry_js_1.hopTimeout)(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
365
544
  try {
366
545
  hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
367
546
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Per-hop HTLC expiry planning (OMN-081).
3
+ *
4
+ * The executor used to space consecutive deadlines one block apart
5
+ * (`expiryBlock - i`), regardless of the channel's contest period. An
6
+ * intermediary that needs to claim downstream and refund upstream therefore had
7
+ * one block of slack to do it in.
8
+ *
9
+ * The spread is now derived from the channel's own script: each hop needs the
10
+ * eltoo contest window (`contestDelayBlocks`, embedded in the funding script)
11
+ * plus a recovery margin for confirmation, reorg and retry. Policy may *raise*
12
+ * the delta but never lower it below the contest period, so a stale config
13
+ * cannot reintroduce the defect.
14
+ */
15
+ import type { Route, RouterChannel } from './types.js';
16
+ export interface ExpiryPolicy {
17
+ /**
18
+ * Blocks added on top of the contest delay for confirmation/recovery.
19
+ * Default 1.
20
+ */
21
+ recoveryMarginBlocks?: number;
22
+ /**
23
+ * Operator floor, in blocks per hop. Used only when it exceeds the derived
24
+ * value — it cannot shrink the spread below a channel's contest period.
25
+ */
26
+ minHopExpiryDelta?: bigint;
27
+ /**
28
+ * Contest delay assumed for a channel that does not declare one. Default 0,
29
+ * which reproduces the legacy one-block spread. Production hosts pass the
30
+ * documented eltoo default (256) instead.
31
+ */
32
+ defaultContestDelayBlocks?: number;
33
+ /**
34
+ * Refuse to route through a channel with no declared contest delay rather
35
+ * than assuming one. Default false.
36
+ */
37
+ requireContestDelay?: boolean;
38
+ /** Current chain tip, when known, so the window can be checked. */
39
+ tipBlock?: bigint;
40
+ /** Blocks of headroom the earliest HTLC must keep above the tip. Default 0. */
41
+ minLeadBlocks?: bigint;
42
+ }
43
+ export interface ExpiryPlan {
44
+ /** Blocks between consecutive HTLC deadlines. */
45
+ delta: bigint;
46
+ /** Largest contest delay across the route's channels. */
47
+ contestDelayBlocks: bigint;
48
+ recoveryMarginBlocks: bigint;
49
+ /** Deadline of the last lock (closest to the recipient). */
50
+ earliest: bigint;
51
+ }
52
+ export type ExpiryPlanResult = {
53
+ ok: true;
54
+ plan: ExpiryPlan;
55
+ } | {
56
+ ok: false;
57
+ error: string;
58
+ };
59
+ /**
60
+ * Deadline of the `index`-th HTLC lock, counting from the payer.
61
+ *
62
+ * Timeouts decrease toward the recipient: the downstream HTLC expires first so
63
+ * the intermediary can claim it before its own incoming HTLC becomes
64
+ * refundable.
65
+ */
66
+ export declare function hopTimeout(expiryBlock: bigint, delta: bigint, index: number | bigint): bigint;
67
+ /**
68
+ * Derive the expiry delta for a route and check it fits the requested window.
69
+ *
70
+ * `lockCount` is the number of HTLC locks the execution will place — one per
71
+ * routing hop, two per swap hop — not the number of route hops.
72
+ */
73
+ export declare function planRouteExpiry(channels: Map<string, RouterChannel>, route: Route, expiryBlock: bigint, lockCount: number, policy?: ExpiryPolicy): ExpiryPlanResult;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hopTimeout = hopTimeout;
4
+ exports.planRouteExpiry = planRouteExpiry;
5
+ /**
6
+ * Deadline of the `index`-th HTLC lock, counting from the payer.
7
+ *
8
+ * Timeouts decrease toward the recipient: the downstream HTLC expires first so
9
+ * the intermediary can claim it before its own incoming HTLC becomes
10
+ * refundable.
11
+ */
12
+ function hopTimeout(expiryBlock, delta, index) {
13
+ return expiryBlock - BigInt(index) * delta;
14
+ }
15
+ /**
16
+ * Derive the expiry delta for a route and check it fits the requested window.
17
+ *
18
+ * `lockCount` is the number of HTLC locks the execution will place — one per
19
+ * routing hop, two per swap hop — not the number of route hops.
20
+ */
21
+ function planRouteExpiry(channels, route, expiryBlock, lockCount, policy = {}) {
22
+ const errors = [];
23
+ let contestDelayBlocks = 0n;
24
+ for (const hop of route.hops) {
25
+ const channel = channels.get(hop.channelId);
26
+ const declared = channel?.contestDelayBlocks;
27
+ if (declared === undefined) {
28
+ if (policy.requireContestDelay) {
29
+ errors.push(`channel ${hop.channelId} does not declare contestDelayBlocks`);
30
+ continue;
31
+ }
32
+ const fallback = BigInt(Math.max(0, Math.trunc(policy.defaultContestDelayBlocks ?? 0)));
33
+ if (fallback > contestDelayBlocks)
34
+ contestDelayBlocks = fallback;
35
+ continue;
36
+ }
37
+ const value = BigInt(Math.max(0, Math.trunc(declared)));
38
+ if (value > contestDelayBlocks)
39
+ contestDelayBlocks = value;
40
+ }
41
+ const recoveryMarginBlocks = BigInt(Math.max(0, Math.trunc(policy.recoveryMarginBlocks ?? 1)));
42
+ const derived = contestDelayBlocks + recoveryMarginBlocks;
43
+ const floor = derived > 0n ? derived : 1n;
44
+ const override = policy.minHopExpiryDelta ?? 0n;
45
+ const delta = override > floor ? override : floor;
46
+ const locks = Math.max(1, lockCount);
47
+ const earliest = expiryBlock - BigInt(locks - 1) * delta;
48
+ if (earliest < 1n) {
49
+ errors.push(`expiry window ${expiryBlock.toString()} cannot fit ${locks} locks `
50
+ + `at ${delta.toString()} blocks apart`);
51
+ }
52
+ if (policy.tipBlock !== undefined) {
53
+ const lead = policy.minLeadBlocks ?? 0n;
54
+ if (earliest <= policy.tipBlock + lead) {
55
+ errors.push(`earliest HTLC deadline ${earliest.toString()} does not clear the tip `
56
+ + `${policy.tipBlock.toString()} by ${lead.toString()} blocks`);
57
+ }
58
+ }
59
+ if (errors.length > 0)
60
+ return { ok: false, error: errors.join('; ') };
61
+ return {
62
+ ok: true,
63
+ plan: { delta, contestDelayBlocks, recoveryMarginBlocks, earliest },
64
+ };
65
+ }
@@ -34,6 +34,12 @@ export type PeelResult =
34
34
  onward?: string;
35
35
  };
36
36
  export interface RoutingEnvelopeCodec {
37
+ /**
38
+ * What a forwarder can learn from the envelope. `cleartext` means the path is
39
+ * visible to every hop it passes through, so a capability manifest must not
40
+ * claim path privacy while this codec is in use (RFC-035 §6.7).
41
+ */
42
+ readonly pathPrivacy: 'cleartext' | 'onion';
37
43
  /** Sender: build the envelope from the onward hops (already excludes the first hop). */
38
44
  build(hops: (RoutingHop | SwapHop)[]): string;
39
45
  /** Forwarder: peel one hop for `self`. */
@@ -21,12 +21,16 @@ exports.createCleartextRoutingCodec = createCleartextRoutingCodec;
21
21
  */
22
22
  function createCleartextRoutingCodec() {
23
23
  return {
24
+ pathPrivacy: 'cleartext',
24
25
  build(hops) {
25
26
  const wire = hops.map((h) => ({
26
27
  channelId: h.channelId,
27
28
  to: h.to,
28
29
  amount: h.amount.toString(),
29
30
  tokenId: h.tokenId,
31
+ // Without this the forwarder has no bound to apply and would have to
32
+ // reuse the incoming timeout, which can never be strictly earlier.
33
+ ...(h.timeoutBlock !== undefined ? { timeoutBlock: h.timeoutBlock.toString() } : {}),
30
34
  }));
31
35
  return JSON.stringify(wire);
32
36
  },
@@ -2,8 +2,13 @@ export type { RouterChannel, ChannelParty, ChannelHTLC, HTLCStatus, ChannelSigne
2
2
  export { createChannelGraph, addChannel, removeChannel, announceSwap, getSwapAnnouncements, } from './graph.js';
3
3
  export { findRoute, findCrossTokenRoute, applyRate, parseRateToScaled, } from './pathfind.js';
4
4
  export { buildPaymentRequest, buildCrossTokenRequest, } from './request.js';
5
- export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
6
- export type { RouterFeeProof } from './types.js';
5
+ export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, buildAuthenticatedRouterFeeProof, verifyRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, PendingRefundError, } from './execute.js';
6
+ export { planRouteExpiry, hopTimeout } from './expiry.js';
7
+ export type { ExpiryPlan, ExpiryPlanResult, ExpiryPolicy } from './expiry.js';
8
+ export { validateRoute } from './route-validation.js';
9
+ export type { RouteBinding, RouteValidationResult } from './route-validation.js';
10
+ export type { RouterFeeProof, RouterSignedState, RouterStateTransition, } from './types.js';
11
+ export type { VerifyRouterFeeProofOptions } from './execute.js';
7
12
  export { createCleartextRoutingCodec } from './forward.js';
8
13
  export type { RoutingEnvelopeCodec, ForwardHop, PeelResult } from './forward.js';
9
14
  export { createDurableRouterLedger, } from './durable-router-ledger.js';
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDurableRouterLedger = exports.createCleartextRoutingCodec = exports.ROUTER_FEE_PROOF_DOMAIN = exports.computeRouterFeeProofHash = exports.buildRouterFeeProof = exports.cancelPayment = exports.executeCrossTokenPayment = exports.executeMultiHopPayment = exports.buildCrossTokenRequest = exports.buildPaymentRequest = exports.parseRateToScaled = exports.applyRate = exports.findCrossTokenRoute = exports.findRoute = exports.getSwapAnnouncements = exports.announceSwap = exports.removeChannel = exports.addChannel = exports.createChannelGraph = void 0;
3
+ exports.createDurableRouterLedger = exports.createCleartextRoutingCodec = exports.validateRoute = exports.hopTimeout = exports.planRouteExpiry = exports.PendingRefundError = exports.ROUTER_FEE_PROOF_DOMAIN = exports.computeRouterFeeProofHash = exports.verifyRouterFeeProof = exports.buildAuthenticatedRouterFeeProof = exports.buildRouterFeeProof = exports.cancelPayment = exports.executeCrossTokenPayment = exports.executeMultiHopPayment = exports.buildCrossTokenRequest = exports.buildPaymentRequest = exports.parseRateToScaled = exports.applyRate = exports.findCrossTokenRoute = exports.findRoute = exports.getSwapAnnouncements = exports.announceSwap = exports.removeChannel = exports.addChannel = exports.createChannelGraph = void 0;
4
4
  var graph_js_1 = require("./graph.js");
5
5
  Object.defineProperty(exports, "createChannelGraph", { enumerable: true, get: function () { return graph_js_1.createChannelGraph; } });
6
6
  Object.defineProperty(exports, "addChannel", { enumerable: true, get: function () { return graph_js_1.addChannel; } });
@@ -20,8 +20,16 @@ Object.defineProperty(exports, "executeMultiHopPayment", { enumerable: true, get
20
20
  Object.defineProperty(exports, "executeCrossTokenPayment", { enumerable: true, get: function () { return execute_js_1.executeCrossTokenPayment; } });
21
21
  Object.defineProperty(exports, "cancelPayment", { enumerable: true, get: function () { return execute_js_1.cancelPayment; } });
22
22
  Object.defineProperty(exports, "buildRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.buildRouterFeeProof; } });
23
+ Object.defineProperty(exports, "buildAuthenticatedRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.buildAuthenticatedRouterFeeProof; } });
24
+ Object.defineProperty(exports, "verifyRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.verifyRouterFeeProof; } });
23
25
  Object.defineProperty(exports, "computeRouterFeeProofHash", { enumerable: true, get: function () { return execute_js_1.computeRouterFeeProofHash; } });
24
26
  Object.defineProperty(exports, "ROUTER_FEE_PROOF_DOMAIN", { enumerable: true, get: function () { return execute_js_1.ROUTER_FEE_PROOF_DOMAIN; } });
27
+ Object.defineProperty(exports, "PendingRefundError", { enumerable: true, get: function () { return execute_js_1.PendingRefundError; } });
28
+ var expiry_js_1 = require("./expiry.js");
29
+ Object.defineProperty(exports, "planRouteExpiry", { enumerable: true, get: function () { return expiry_js_1.planRouteExpiry; } });
30
+ Object.defineProperty(exports, "hopTimeout", { enumerable: true, get: function () { return expiry_js_1.hopTimeout; } });
31
+ var route_validation_js_1 = require("./route-validation.js");
32
+ Object.defineProperty(exports, "validateRoute", { enumerable: true, get: function () { return route_validation_js_1.validateRoute; } });
25
33
  // RFC-035 B4 — pluggable forwarding envelopes (cleartext now; onion behind the same seam).
26
34
  var forward_js_1 = require("./forward.js");
27
35
  Object.defineProperty(exports, "createCleartextRoutingCodec", { enumerable: true, get: function () { return forward_js_1.createCleartextRoutingCodec; } });
@@ -6,6 +6,21 @@
6
6
  * have the expected direction and have enough sender balance.
7
7
  */
8
8
  import type { RouterChannel, RoutingHop, Route, SwapHop } from './types.js';
9
+ /**
10
+ * What the route is supposed to do, expressed independently of the route object
11
+ * (OMN-080). Without this a structurally valid route that pays nobody still
12
+ * "passes" validation.
13
+ */
14
+ export interface RouteBinding {
15
+ /** Party the payment starts from. */
16
+ payer?: string;
17
+ /** Party the payment must reach. */
18
+ recipient?: string;
19
+ /** Amount the recipient must receive. */
20
+ amount?: bigint;
21
+ /** Asset the recipient must receive. */
22
+ tokenId?: string;
23
+ }
9
24
  export type RouteValidationResult = {
10
25
  ok: true;
11
26
  } | {
@@ -20,5 +35,14 @@ export declare function validateRoutingHop(channels: Map<string, RouterChannel>,
20
35
  export declare function swapIntermediary(channels: Map<string, RouterChannel>, hop: SwapHop): string | undefined;
21
36
  /** Validate both legs of a swap hop. */
22
37
  export declare function validateSwapHop(channels: Map<string, RouterChannel>, hop: SwapHop): RouteValidationResult;
23
- /** Validate every hop of a route against live channel state. */
24
- export declare function validateRoute(channels: Map<string, RouterChannel>, route: Route): RouteValidationResult;
38
+ /**
39
+ * Validate a route against live channel state **and** against what the payment
40
+ * is supposed to do (OMN-080).
41
+ *
42
+ * Per-hop checks answer "can this channel spend?". They do not answer "does
43
+ * this route pay the right party the right amount?" — an empty route, a route
44
+ * whose hops do not connect, or a route that delivers a different amount all
45
+ * used to pass. `binding` supplies the intent; when it is omitted the route is
46
+ * still required to be non-empty and internally consistent.
47
+ */
48
+ export declare function validateRoute(channels: Map<string, RouterChannel>, route: Route, binding?: RouteBinding): RouteValidationResult;