@totemsdk/omnia-router 0.5.0 → 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.
@@ -5,6 +5,9 @@ exports.validateRoutingHop = validateRoutingHop;
5
5
  exports.swapIntermediary = swapIntermediary;
6
6
  exports.validateSwapHop = validateSwapHop;
7
7
  exports.validateRoute = validateRoute;
8
+ function sameToken(a, b) {
9
+ return a.toLowerCase() === b.toLowerCase();
10
+ }
8
11
  function fail(error) {
9
12
  return { ok: false, error };
10
13
  }
@@ -78,14 +81,59 @@ function validateSwapHop(channels, hop) {
78
81
  }
79
82
  return validateChannelSpend(outbound, intermediary, hop.amountOut, hop.tokenOut);
80
83
  }
81
- /** Validate every hop of a route against live channel state. */
82
- function validateRoute(channels, route) {
83
- for (const hop of route.hops) {
84
+ /**
85
+ * Validate a route against live channel state **and** against what the payment
86
+ * is supposed to do (OMN-080).
87
+ *
88
+ * Per-hop checks answer "can this channel spend?". They do not answer "does
89
+ * this route pay the right party the right amount?" — an empty route, a route
90
+ * whose hops do not connect, or a route that delivers a different amount all
91
+ * used to pass. `binding` supplies the intent; when it is omitted the route is
92
+ * still required to be non-empty and internally consistent.
93
+ */
94
+ function validateRoute(channels, route, binding = {}) {
95
+ if (!Array.isArray(route.hops) || route.hops.length === 0) {
96
+ return fail('route has no hops');
97
+ }
98
+ for (const [index, hop] of route.hops.entries()) {
84
99
  const result = hop.isSwap
85
100
  ? validateSwapHop(channels, hop)
86
101
  : validateRoutingHop(channels, hop);
87
102
  if (!result.ok)
88
103
  return result;
104
+ const next = route.hops[index + 1];
105
+ if (next && hop.to !== next.from) {
106
+ return fail(`route is disconnected between hops ${index} and ${index + 1}: `
107
+ + `${hop.to} != ${next.from}`);
108
+ }
109
+ if (next && sameToken(hop.tokenId, next.tokenId) === false) {
110
+ // A token transition is only legitimate through an explicit swap hop.
111
+ const swap = hop.isSwap ? hop : next.isSwap ? next : undefined;
112
+ if (!swap) {
113
+ return fail(`route changes asset between hops ${index} and ${index + 1} `
114
+ + `(${hop.tokenId} -> ${next.tokenId}) without a swap`);
115
+ }
116
+ }
117
+ }
118
+ const first = route.hops[0];
119
+ const last = route.hops[route.hops.length - 1];
120
+ if (binding.payer !== undefined && first.from !== binding.payer) {
121
+ return fail(`route starts at ${first.from}, not at the payer ${binding.payer}`);
122
+ }
123
+ if (binding.recipient !== undefined && last.to !== binding.recipient) {
124
+ return fail(`route ends at ${last.to}, not at the recipient ${binding.recipient}`);
125
+ }
126
+ if (binding.amount !== undefined) {
127
+ const delivered = last.isSwap ? last.amountOut : last.amount;
128
+ if (delivered !== binding.amount) {
129
+ return fail(`route delivers ${delivered.toString()}, not the requested ${binding.amount.toString()}`);
130
+ }
131
+ }
132
+ if (binding.tokenId !== undefined) {
133
+ const deliveredToken = last.isSwap ? last.tokenOut : last.tokenId;
134
+ if (!sameToken(deliveredToken, binding.tokenId)) {
135
+ return fail(`route delivers ${deliveredToken}, not the requested ${binding.tokenId}`);
136
+ }
89
137
  }
90
138
  return { ok: true };
91
139
  }
@@ -41,6 +41,13 @@ export interface RouterChannel {
41
41
  currentSequence: number;
42
42
  status: string;
43
43
  localSigner?: ChannelSigner;
44
+ /**
45
+ * Eltoo contest window embedded in the funding script (OMN-081). The router
46
+ * derives the per-hop HTLC expiry spread from this: an intermediary needs the
47
+ * full contest period plus a recovery margin between its incoming and
48
+ * outgoing deadlines. Defaults to 256 for channels opened by this SDK.
49
+ */
50
+ contestDelayBlocks?: number;
44
51
  }
45
52
  /**
46
53
  * Parameters for adding an HTLC — mirrors @totemsdk/omnia's AddHTLCParams.
@@ -75,6 +82,13 @@ export interface ChannelOps {
75
82
  fulfillHTLC(channel: RouterChannel, htlcId: string, preimage: string, leaseProvider: LeaseProvider): Promise<{
76
83
  channel: RouterChannel;
77
84
  error?: string;
85
+ /**
86
+ * OMN-083: the authenticated state pair the fulfilment produced. When an
87
+ * implementation can supply it, the router emits an authenticated fee proof;
88
+ * otherwise the proof is marked unauthenticated.
89
+ */
90
+ previousState?: RouterSignedState;
91
+ nextState?: RouterSignedState;
78
92
  }>;
79
93
  timeoutHTLC(channel: RouterChannel, htlcId: string, leaseProvider: LeaseProvider): Promise<{
80
94
  channel: RouterChannel;
@@ -183,6 +197,29 @@ export interface PaymentRequest {
183
197
  * pool's `recordPoolFee` earn-proof consumes. Binds channel + HTLC + recipient
184
198
  * + amount so a fee record traces to a real fulfilled payment.
185
199
  */
200
+ /**
201
+ * A channel state the router can reason about without depending on `omnia`
202
+ * (OMN-083). Only the fields the fee proof binds are modelled.
203
+ */
204
+ export interface RouterSignedState {
205
+ sequence: number;
206
+ balances: Record<string, bigint>;
207
+ pendingHTLCs?: Array<{
208
+ htlcId: string;
209
+ amount: bigint;
210
+ recipientPublicKeyDigest?: string;
211
+ status?: string;
212
+ }>;
213
+ stateVariables?: Array<{
214
+ port: number;
215
+ value: unknown;
216
+ }>;
217
+ signatures?: Record<string, unknown>;
218
+ }
219
+ export interface RouterStateTransition {
220
+ previous: RouterSignedState;
221
+ next: RouterSignedState;
222
+ }
186
223
  export interface RouterFeeProof {
187
224
  channelId: string;
188
225
  htlcId: string;
@@ -190,6 +227,19 @@ export interface RouterFeeProof {
190
227
  amount: bigint;
191
228
  tokenId: string;
192
229
  settledAt: number;
230
+ /**
231
+ * OMN-083: true only when the proof was derived from an authenticated
232
+ * predecessor→successor transition. A hash over descriptive fields is not
233
+ * settlement evidence, so `false` proofs must not be treated as income.
234
+ */
235
+ authenticated: boolean;
236
+ /** Fee the intermediary retained on this hop, when both legs are known. */
237
+ feeAmount?: bigint;
238
+ previousSequence?: number;
239
+ sequence?: number;
240
+ previousStateCommitmentV2?: string;
241
+ stateCommitmentV2?: string;
242
+ balanceDelta?: bigint;
193
243
  proofHash: string;
194
244
  }
195
245
  /** An HTLC that failed to release during rollback and is still locked. */
package/dist/execute.d.ts CHANGED
@@ -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>;
package/dist/execute.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { bytesToHex, sha3_256 } from '@totemsdk/core';
2
2
  import { validateChannelSpend, validateRoute, validateRoutingHop, swapIntermediary } from './route-validation.js';
3
+ import { hopTimeout, planRouteExpiry } from './expiry.js';
3
4
  import { SCALE } from './rates.js';
4
5
  // ─── Type guard ───────────────────────────────────────────────────────────────
5
6
  function isSwapHop(hop) {
@@ -35,8 +36,18 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders, pending) {
35
36
  for (const { channelId, htlcId } of [...locked].reverse()) {
36
37
  const ch = channels.get(channelId);
37
38
  const lp = leaseProviders.get(channelId);
38
- if (!ch || !lp)
39
+ if (!ch || !lp) {
40
+ // OMN-082 (CAN-015): a missing dependency is not a released lock. Record
41
+ // the obligation so the caller is never told rollback was clean.
42
+ pending.push({
43
+ channelId,
44
+ htlcId,
45
+ reason: !ch
46
+ ? `channel ${channelId} is no longer in the routing view`
47
+ : `no lease provider for channel ${channelId}`,
48
+ });
39
49
  continue;
50
+ }
40
51
  try {
41
52
  const res = await ops.timeoutHTLC(ch, htlcId, lp);
42
53
  channels.set(channelId, res.channel);
@@ -70,7 +81,7 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders, pending) {
70
81
  *
71
82
  * The `channels` map is updated in-place after each HTLC operation.
72
83
  */
73
- export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
84
+ export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders, binding, expiry) {
74
85
  /** Locks rollback could not release (CAN-015). */
75
86
  const pendingRefunds = [];
76
87
  const failed = (result) => pendingRefunds.length > 0 ? { ...result, pendingRefunds: [...pendingRefunds] } : result;
@@ -79,6 +90,27 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
79
90
  return failed({ success: false, state: 'failed', terminal: true, error: 'paymentRequest.preimage is required for execution', settledHops: [] });
80
91
  }
81
92
  const plainHops = route.hops.filter(h => !isSwapHop(h));
93
+ // OMN-080: this entry point settles a single asset. A swap hop belongs to
94
+ // executeCrossTokenPayment; silently dropping them used to let a swap-only
95
+ // route report success with nothing settled.
96
+ if (plainHops.length !== route.hops.length) {
97
+ return failed({
98
+ success: false,
99
+ state: 'failed',
100
+ terminal: true,
101
+ error: 'executeMultiHopPayment received a route with swap hops; use executeCrossTokenPayment',
102
+ settledHops: [],
103
+ });
104
+ }
105
+ if (plainHops.length === 0) {
106
+ return failed({
107
+ success: false,
108
+ state: 'failed',
109
+ terminal: true,
110
+ error: 'route has no executable hops',
111
+ settledHops: [],
112
+ });
113
+ }
82
114
  // Fee-aware per-hop amounts. Each hop locks the payment plus the fees of the
83
115
  // downstream intermediaries; the fee for the final edge belongs to the
84
116
  // recipient and is not charged. Intermediary i retains
@@ -89,7 +121,12 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
89
121
  const downstream = fees.slice(i, Math.max(i, fees.length - 1)).reduce((a, b) => a + b, 0n);
90
122
  plainHops[i].amount = paymentRequest.amount + downstream;
91
123
  }
92
- const routeValidation = validateRoute(channels, route);
124
+ const routeValidation = validateRoute(channels, route, {
125
+ payer: binding?.payer ?? plainHops[0].from,
126
+ recipient: binding?.recipient ?? plainHops[plainHops.length - 1].to,
127
+ amount: paymentRequest.amount,
128
+ tokenId: paymentRequest.tokenId,
129
+ });
93
130
  if (!routeValidation.ok) {
94
131
  return failed({
95
132
  success: false,
@@ -98,6 +135,19 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
98
135
  settledHops: [],
99
136
  });
100
137
  }
138
+ // OMN-081: derive the deadline spread from the channels' contest windows and
139
+ // refuse the route if the requested expiry cannot fit every hop.
140
+ const expiryPlan = planRouteExpiry(channels, route, paymentRequest.expiryBlock, plainHops.length, expiry ?? {});
141
+ if (!expiryPlan.ok) {
142
+ return failed({
143
+ success: false,
144
+ state: 'failed',
145
+ terminal: true,
146
+ error: `EXPIRY_PLAN_FAILED: ${expiryPlan.error}`,
147
+ errorCode: 'EXPIRY_PLAN_FAILED',
148
+ settledHops: [],
149
+ });
150
+ }
101
151
  const locked = [];
102
152
  // ── Forward: lock HTLCs ───────────────────────────────────────────────────
103
153
  for (let i = 0; i < plainHops.length; i++) {
@@ -123,7 +173,7 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
123
173
  });
124
174
  }
125
175
  // Timeouts decrease toward the recipient so each hop has time to claim.
126
- const timeoutBlock = paymentRequest.expiryBlock - BigInt(i);
176
+ const timeoutBlock = hopTimeout(paymentRequest.expiryBlock, expiryPlan.plan.delta, i);
127
177
  let addResult;
128
178
  try {
129
179
  addResult = await ops.addHTLC(channel, {
@@ -173,10 +223,23 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
173
223
  channels.set(channelId, fulfillResult.channel);
174
224
  settled.push(htlcId);
175
225
  fulfilledSet.add(htlcId);
176
- // Build the verifiable fee proof for this settled hop (#29).
226
+ // Build the verifiable fee proof for this settled hop (#29 / OMN-083).
177
227
  const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
178
228
  if (htlc) {
179
- feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
229
+ const hopIndex = plainHops.findIndex(h => h.htlcId === htlcId);
230
+ const hopAmount = hopIndex >= 0 ? plainHops[hopIndex].amount : htlc.amount;
231
+ const downstream = hopIndex >= 0
232
+ ? (plainHops[hopIndex + 1]?.amount ?? paymentRequest.amount)
233
+ : paymentRequest.amount;
234
+ const feeAmount = hopAmount > downstream ? hopAmount - downstream : 0n;
235
+ if (fulfillResult.previousState && fulfillResult.nextState) {
236
+ feeProofs.push(buildAuthenticatedRouterFeeProof(fulfillResult.channel, htlc, { previous: fulfillResult.previousState, next: fulfillResult.nextState }, { feeAmount, settledAt: Date.now() }));
237
+ }
238
+ else {
239
+ // No authenticated state pair: emit a proof that says so, rather than a
240
+ // descriptive hash masquerading as settlement evidence.
241
+ feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
242
+ }
180
243
  }
181
244
  }
182
245
  return {
@@ -188,21 +251,78 @@ export async function executeMultiHopPayment(ops, channels, route, paymentReques
188
251
  feeProofs,
189
252
  };
190
253
  }
191
- export const ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
254
+ export const ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v2';
255
+ /** Port carrying the state commitment the proof binds (OMN-083). */
256
+ const STATE_COMMITMENT_V2_PORT = 102;
257
+ function commitmentOf(state, label) {
258
+ const value = state.stateVariables?.find((sv) => sv.port === STATE_COMMITMENT_V2_PORT);
259
+ if (!value)
260
+ throw new Error(`${label} is missing the port-102 commitment`);
261
+ return String(value.value).replace(/^0x/i, '').toLowerCase();
262
+ }
263
+ function recipientOf(channel, htlc) {
264
+ const party = channel.parties.find((p) => p.publicKeyDigest === htlc.recipientPublicKeyDigest);
265
+ if (!party)
266
+ throw new Error('HTLC recipient is not a channel party');
267
+ return { partyId: party.partyId, publicKeyDigest: party.publicKeyDigest };
268
+ }
269
+ /**
270
+ * OMN-083: build a fee proof bound to the authenticated transition that settled
271
+ * the HTLC.
272
+ *
273
+ * The proof carries both state commitments, the exact balance delta the
274
+ * recipient received, and the fee the intermediary retained. A hash over
275
+ * descriptive fields proves only that the caller's numbers are self-consistent;
276
+ * this proves the payment happened on this channel.
277
+ */
278
+ export function buildAuthenticatedRouterFeeProof(channel, htlc, transition, options = {}) {
279
+ const { previous, next } = transition;
280
+ if (next.sequence <= previous.sequence) {
281
+ throw new Error('successor state does not follow the predecessor');
282
+ }
283
+ const pending = previous.pendingHTLCs?.find((h) => h.htlcId === htlc.htlcId);
284
+ if (!pending)
285
+ throw new Error(`HTLC ${htlc.htlcId} is not pending in the predecessor state`);
286
+ if (next.pendingHTLCs?.some((h) => h.htlcId === htlc.htlcId)) {
287
+ throw new Error(`successor state still carries HTLC ${htlc.htlcId}`);
288
+ }
289
+ const recipient = recipientOf(channel, htlc);
290
+ const balanceDelta = (next.balances[recipient.partyId] ?? 0n) - (previous.balances[recipient.partyId] ?? 0n);
291
+ if (balanceDelta !== pending.amount) {
292
+ throw new Error(`transition moves ${balanceDelta.toString()} to the recipient, not the HTLC amount ${pending.amount.toString()}`);
293
+ }
294
+ const proof = {
295
+ channelId: channel.channelId,
296
+ htlcId: htlc.htlcId,
297
+ recipientPublicKeyDigest: recipient.publicKeyDigest,
298
+ amount: pending.amount,
299
+ tokenId: channel.tokenId,
300
+ settledAt: options.settledAt ?? Date.now(),
301
+ authenticated: true,
302
+ ...(options.feeAmount !== undefined ? { feeAmount: options.feeAmount } : {}),
303
+ previousSequence: previous.sequence,
304
+ sequence: next.sequence,
305
+ previousStateCommitmentV2: commitmentOf(previous, 'predecessor state'),
306
+ stateCommitmentV2: commitmentOf(next, 'successor state'),
307
+ balanceDelta,
308
+ proofHash: '',
309
+ };
310
+ proof.proofHash = computeRouterFeeProofHash(proof);
311
+ return proof;
312
+ }
192
313
  /**
193
- * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
194
- * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
195
- * real fulfilled payment, never a declared string.
314
+ * Legacy descriptive proof. Kept for callers that only need a provenance
315
+ * record; it is explicitly **not** settlement evidence (OMN-083).
196
316
  */
197
317
  export function buildRouterFeeProof(channel, htlc, settledAt) {
198
- const ts = settledAt ?? Date.now();
199
318
  const proof = {
200
319
  channelId: channel.channelId,
201
320
  htlcId: htlc.htlcId,
202
321
  recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
203
322
  amount: htlc.amount,
204
323
  tokenId: channel.tokenId,
205
- settledAt: ts,
324
+ settledAt: settledAt ?? Date.now(),
325
+ authenticated: false,
206
326
  proofHash: '',
207
327
  };
208
328
  proof.proofHash = computeRouterFeeProofHash(proof);
@@ -213,6 +333,49 @@ export function computeRouterFeeProofHash(proof) {
213
333
  const input = `${ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
214
334
  return bytesToHex(sha3_256(new TextEncoder().encode(input)));
215
335
  }
336
+ /** Re-derive an authenticated fee proof from the states it claims. */
337
+ export function verifyRouterFeeProof(channel, transition, proof, options = {}) {
338
+ try {
339
+ if (proof.authenticated !== true)
340
+ return false;
341
+ if (proof.channelId !== channel.channelId)
342
+ return false;
343
+ if (proof.previousSequence !== transition.previous.sequence)
344
+ return false;
345
+ if (proof.sequence !== transition.next.sequence)
346
+ return false;
347
+ const pending = transition.previous.pendingHTLCs?.find((h) => h.htlcId === proof.htlcId);
348
+ if (!pending)
349
+ return false;
350
+ if (transition.next.pendingHTLCs?.some((h) => h.htlcId === proof.htlcId))
351
+ return false;
352
+ const recipient = recipientOf(channel, { recipientPublicKeyDigest: proof.recipientPublicKeyDigest });
353
+ const delta = (transition.next.balances[recipient.partyId] ?? 0n)
354
+ - (transition.previous.balances[recipient.partyId] ?? 0n);
355
+ if (delta !== proof.balanceDelta)
356
+ return false;
357
+ if (delta !== proof.amount || pending.amount !== proof.amount)
358
+ return false;
359
+ if (commitmentOf(transition.previous, 'predecessor state') !== proof.previousStateCommitmentV2)
360
+ return false;
361
+ if (commitmentOf(transition.next, 'successor state') !== proof.stateCommitmentV2)
362
+ return false;
363
+ const { proofHash, ...rest } = proof;
364
+ if (computeRouterFeeProofHash({ ...rest, proofHash: '' }) !== proofHash)
365
+ return false;
366
+ if (options.verifySignature) {
367
+ for (const party of channel.parties) {
368
+ if (!options.verifySignature(transition.next, { partyId: party.partyId, publicKeyDigest: party.publicKeyDigest })) {
369
+ return false;
370
+ }
371
+ }
372
+ }
373
+ return true;
374
+ }
375
+ catch {
376
+ return false;
377
+ }
378
+ }
216
379
  function canonicalJson(value) {
217
380
  if (typeof value === 'bigint')
218
381
  return JSON.stringify({ __bigint: value.toString() });
@@ -257,7 +420,7 @@ export async function cancelPayment(ops, channels, route, leaseProviders) {
257
420
  * Rollback fires on ANY failure (forward OR backward phase) by timing out
258
421
  * all still-pending locked HTLCs.
259
422
  */
260
- export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
423
+ export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders, expiry) {
261
424
  /** Locks rollback could not release (CAN-015). */
262
425
  const pendingRefunds = [];
263
426
  const failed = (result) => pendingRefunds.length > 0 ? { ...result, pendingRefunds: [...pendingRefunds] } : result;
@@ -274,6 +437,20 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
274
437
  settledHops: [],
275
438
  });
276
439
  }
440
+ // OMN-081: one lock per routing hop, two per swap hop. Derive the spread from
441
+ // the channels' contest windows before anything is locked.
442
+ const lockCount = route.hops.reduce((count, hop) => count + (isSwapHop(hop) ? 2 : 1), 0);
443
+ const expiryPlan = planRouteExpiry(channels, route, paymentRequest.expiryBlock, lockCount, expiry ?? {});
444
+ if (!expiryPlan.ok) {
445
+ return failed({
446
+ success: false,
447
+ state: 'failed',
448
+ terminal: true,
449
+ error: `EXPIRY_PLAN_FAILED: ${expiryPlan.error}`,
450
+ errorCode: 'EXPIRY_PLAN_FAILED',
451
+ settledHops: [],
452
+ });
453
+ }
277
454
  const locked = [];
278
455
  /**
279
456
  * Lock a single HTLC, add it to `locked`, and return the htlcId.
@@ -323,7 +500,7 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
323
500
  for (const hop of route.hops) {
324
501
  if (isSwapHop(hop)) {
325
502
  // Inbound channel (sender → intermediary, tokenIn side)
326
- const inTimeout = paymentRequest.expiryBlock - BigInt(pos++);
503
+ const inTimeout = hopTimeout(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
327
504
  try {
328
505
  hop.htlcId = await lockHTLC(hop.inboundChannelId, hop.amountIn, paymentRequest.hashlock, inTimeout, hop.tokenIn, hop.from);
329
506
  }
@@ -332,7 +509,7 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
332
509
  return failed({ success: false, error: `Inbound HTLC lock failed: ${String(err)}`, ...(revalidationErrorCode(String(err)) ? { errorCode: 'ROUTE_REVALIDATION_FAILED' } : {}), settledHops: [] });
333
510
  }
334
511
  // Outbound channel (intermediary → recipient, tokenOut side)
335
- const outTimeout = paymentRequest.expiryBlock - BigInt(pos++);
512
+ const outTimeout = hopTimeout(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
336
513
  const intermediary = swapIntermediary(channels, hop);
337
514
  if (!intermediary) {
338
515
  await cancelHtlcs(ops, channels, locked, leaseProviders, pendingRefunds);
@@ -352,7 +529,7 @@ export async function executeCrossTokenPayment(ops, channels, route, paymentRequ
352
529
  }
353
530
  }
354
531
  else {
355
- const timeout = paymentRequest.expiryBlock - BigInt(pos++);
532
+ const timeout = hopTimeout(paymentRequest.expiryBlock, expiryPlan.plan.delta, pos++);
356
533
  try {
357
534
  hop.htlcId = await lockHTLC(hop.channelId, hop.amount, paymentRequest.hashlock, timeout, hop.tokenId, hop.from);
358
535
  }
@@ -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;
package/dist/expiry.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Deadline of the `index`-th HTLC lock, counting from the payer.
3
+ *
4
+ * Timeouts decrease toward the recipient: the downstream HTLC expires first so
5
+ * the intermediary can claim it before its own incoming HTLC becomes
6
+ * refundable.
7
+ */
8
+ export function hopTimeout(expiryBlock, delta, index) {
9
+ return expiryBlock - BigInt(index) * delta;
10
+ }
11
+ /**
12
+ * Derive the expiry delta for a route and check it fits the requested window.
13
+ *
14
+ * `lockCount` is the number of HTLC locks the execution will place — one per
15
+ * routing hop, two per swap hop — not the number of route hops.
16
+ */
17
+ export function planRouteExpiry(channels, route, expiryBlock, lockCount, policy = {}) {
18
+ const errors = [];
19
+ let contestDelayBlocks = 0n;
20
+ for (const hop of route.hops) {
21
+ const channel = channels.get(hop.channelId);
22
+ const declared = channel?.contestDelayBlocks;
23
+ if (declared === undefined) {
24
+ if (policy.requireContestDelay) {
25
+ errors.push(`channel ${hop.channelId} does not declare contestDelayBlocks`);
26
+ continue;
27
+ }
28
+ const fallback = BigInt(Math.max(0, Math.trunc(policy.defaultContestDelayBlocks ?? 0)));
29
+ if (fallback > contestDelayBlocks)
30
+ contestDelayBlocks = fallback;
31
+ continue;
32
+ }
33
+ const value = BigInt(Math.max(0, Math.trunc(declared)));
34
+ if (value > contestDelayBlocks)
35
+ contestDelayBlocks = value;
36
+ }
37
+ const recoveryMarginBlocks = BigInt(Math.max(0, Math.trunc(policy.recoveryMarginBlocks ?? 1)));
38
+ const derived = contestDelayBlocks + recoveryMarginBlocks;
39
+ const floor = derived > 0n ? derived : 1n;
40
+ const override = policy.minHopExpiryDelta ?? 0n;
41
+ const delta = override > floor ? override : floor;
42
+ const locks = Math.max(1, lockCount);
43
+ const earliest = expiryBlock - BigInt(locks - 1) * delta;
44
+ if (earliest < 1n) {
45
+ errors.push(`expiry window ${expiryBlock.toString()} cannot fit ${locks} locks `
46
+ + `at ${delta.toString()} blocks apart`);
47
+ }
48
+ if (policy.tipBlock !== undefined) {
49
+ const lead = policy.minLeadBlocks ?? 0n;
50
+ if (earliest <= policy.tipBlock + lead) {
51
+ errors.push(`earliest HTLC deadline ${earliest.toString()} does not clear the tip `
52
+ + `${policy.tipBlock.toString()} by ${lead.toString()} blocks`);
53
+ }
54
+ }
55
+ if (errors.length > 0)
56
+ return { ok: false, error: errors.join('; ') };
57
+ return {
58
+ ok: true,
59
+ plan: { delta, contestDelayBlocks, recoveryMarginBlocks, earliest },
60
+ };
61
+ }