@totemsdk/omnia-router 0.2.0 → 0.2.1

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.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Durable settled-segment ledger (RFC-007 G9).
3
+ *
4
+ * Payment execution is multi-channel: a route spans several HTLC hops, each
5
+ * fulfilled in reverse order by revealing the preimage. If the host dies
6
+ * mid-route (after some hops settled, before others), the already-settled
7
+ * segments — channel + HTLC + revealed preimage + settled-at — must survive a
8
+ * restart so the node can (a) never re-lock or re-settle an already-committed
9
+ * segment, and (b) reconcile still-pending locks. This ledger records exactly
10
+ * those settled segments, keyed `channelId:htlcId`, idempotently.
11
+ *
12
+ * Backed by the shared revision-CAS snapshot store: corruption is surfaced
13
+ * (never treated as absence), no silent downgrade, and concurrent hop
14
+ * settlement is never lost.
15
+ */
16
+ import type { StorageAdapterWithCapabilities, CasStore, WriteAckMode } from '@totemsdk/storage/types';
17
+ /** A payment segment that has been irrevocably settled by preimage reveal. */
18
+ export interface SettledSegment {
19
+ channelId: string;
20
+ htlcId: string;
21
+ /** Preimage revealed during settlement — must survive a mid-route restart. */
22
+ preimage: string;
23
+ /** Monotonic settlement timestamp. */
24
+ settledAt: number;
25
+ /** Optional hop-level detail for reconciliation (amount, counterpart, digest). */
26
+ tokenId?: string;
27
+ senderPublicKeyDigest?: string;
28
+ recipientPublicKeyDigest?: string;
29
+ /** Set once a segment is fully reconciled against the node's route state. */
30
+ reconciled?: boolean;
31
+ }
32
+ export interface RouterLedgerState {
33
+ /** `channelId:htlcId` → settled segment. */
34
+ segments: Record<string, SettledSegment>;
35
+ }
36
+ export interface DurableRouterLedgerOptions {
37
+ /** Key namespace prefix; default `totem_omnia_router:v1:`. */
38
+ readonly namespace?: string;
39
+ /**
40
+ * Required write acknowledgment; default `durably-acknowledged`. Pass
41
+ * `volatile` only for tests/scratch adapters (e.g. `MemoryStore`).
42
+ */
43
+ readonly requireAckMode?: WriteAckMode;
44
+ }
45
+ export interface DurableRouterLedger {
46
+ /** Idempotently record a settled segment. Re-recording the same segment is a no-op. */
47
+ recordSettled(segment: SettledSegment): Promise<void>;
48
+ /** True when the given channel+HTLC already settled. */
49
+ isSettled(channelId: string, htlcId: string): Promise<boolean>;
50
+ /** Retrieve a previously settled segment. */
51
+ getSettled(channelId: string, htlcId: string): Promise<SettledSegment | undefined>;
52
+ /** All settled segments, optionally filtered by channel. */
53
+ listSettled(channelId?: string): Promise<SettledSegment[]>;
54
+ /** Mark a settled segment as reconciled with the route state. */
55
+ markReconciled(channelId: string, htlcId: string): Promise<void>;
56
+ getRevision(): Promise<number>;
57
+ hasState(): Promise<boolean>;
58
+ getSnapshot(): Promise<RouterLedgerState>;
59
+ }
60
+ export declare function createDurableRouterLedger(adapter: StorageAdapterWithCapabilities & CasStore, options?: DurableRouterLedgerOptions): DurableRouterLedger;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /**
3
+ * Durable settled-segment ledger (RFC-007 G9).
4
+ *
5
+ * Payment execution is multi-channel: a route spans several HTLC hops, each
6
+ * fulfilled in reverse order by revealing the preimage. If the host dies
7
+ * mid-route (after some hops settled, before others), the already-settled
8
+ * segments — channel + HTLC + revealed preimage + settled-at — must survive a
9
+ * restart so the node can (a) never re-lock or re-settle an already-committed
10
+ * segment, and (b) reconcile still-pending locks. This ledger records exactly
11
+ * those settled segments, keyed `channelId:htlcId`, idempotently.
12
+ *
13
+ * Backed by the shared revision-CAS snapshot store: corruption is surfaced
14
+ * (never treated as absence), no silent downgrade, and concurrent hop
15
+ * settlement is never lost.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.createDurableRouterLedger = createDurableRouterLedger;
19
+ const snapshot_1 = require("@totemsdk/storage/snapshot");
20
+ const errors_1 = require("@totemsdk/storage/errors");
21
+ const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
22
+ function segmentKey(channelId, htlcId) {
23
+ return `${channelId}:${htlcId}`;
24
+ }
25
+ function assertLedgerState(state) {
26
+ if (typeof state !== 'object' || state === null || Array.isArray(state)) {
27
+ throw new errors_1.StorageError('omnia-router ledger state is not an object', 'corrupt');
28
+ }
29
+ const value = state.segments;
30
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
31
+ throw new errors_1.StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
32
+ }
33
+ }
34
+ function createDurableRouterLedger(adapter, options = {}) {
35
+ const snapshots = (0, snapshot_1.createRevisionedSnapshotStore)(adapter, {
36
+ namespace: options.namespace ?? DEFAULT_NAMESPACE,
37
+ requireAckMode: options.requireAckMode,
38
+ empty: () => ({ segments: {} }),
39
+ validate: assertLedgerState,
40
+ });
41
+ async function mutate(fn) {
42
+ await snapshots.mutate(fn);
43
+ }
44
+ async function loadSegment(channelId, htlcId) {
45
+ const state = await snapshots.load();
46
+ return state.segments[segmentKey(channelId, htlcId)];
47
+ }
48
+ return {
49
+ async recordSettled(segment) {
50
+ // Short-circuit already-recorded segments: re-recording is a no-op and
51
+ // must not advance the revision or rewrite an immutable record.
52
+ if (await loadSegment(segment.channelId, segment.htlcId))
53
+ return;
54
+ await mutate((state) => {
55
+ const key = segmentKey(segment.channelId, segment.htlcId);
56
+ return { ...state, segments: { ...state.segments, [key]: segment } };
57
+ });
58
+ },
59
+ isSettled(channelId, htlcId) {
60
+ return loadSegment(channelId, htlcId).then((seg) => seg !== undefined);
61
+ },
62
+ getSettled: loadSegment,
63
+ async listSettled(channelId) {
64
+ const state = await snapshots.load();
65
+ const all = Object.values(state.segments);
66
+ if (channelId === undefined)
67
+ return all;
68
+ return all.filter((s) => s.channelId === channelId);
69
+ },
70
+ async markReconciled(channelId, htlcId) {
71
+ await mutate((state) => {
72
+ const key = segmentKey(channelId, htlcId);
73
+ const existing = state.segments[key];
74
+ if (!existing)
75
+ return state;
76
+ return {
77
+ ...state,
78
+ segments: { ...state.segments, [key]: { ...existing, reconciled: true } },
79
+ };
80
+ });
81
+ },
82
+ getRevision: () => snapshots.getRevision(),
83
+ hasState: () => snapshots.hasState(),
84
+ async getSnapshot() {
85
+ return snapshots.load();
86
+ },
87
+ };
88
+ }
package/dist/execute.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, LeaseProvider } from './types.js';
1
+ import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest, PaymentResult, LeaseProvider, ChannelHTLC, RouterFeeProof } from './types.js';
2
2
  /**
3
3
  * Execute a single-token multi-hop payment atomically:
4
4
  *
@@ -14,6 +14,14 @@ import type { ChannelOps, RouterChannel, Route, CrossTokenRoute, PaymentRequest,
14
14
  * The `channels` map is updated in-place after each HTLC operation.
15
15
  */
16
16
  export declare function executeMultiHopPayment(ops: ChannelOps, channels: Map<string, RouterChannel>, route: Route, paymentRequest: PaymentRequest, leaseProviders: Map<string, LeaseProvider>): Promise<PaymentResult>;
17
+ export declare const ROUTER_FEE_PROOF_DOMAIN = "totemsdk/omnia-router/fee-proof/v1";
18
+ /**
19
+ * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
20
+ * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
21
+ * real fulfilled payment, never a declared string.
22
+ */
23
+ export declare function buildRouterFeeProof(channel: RouterChannel, htlc: ChannelHTLC, settledAt?: number): RouterFeeProof;
24
+ export declare function computeRouterFeeProofHash(proof: RouterFeeProof): string;
17
25
  /**
18
26
  * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
19
27
  * Call this explicitly to roll back before or without attempting execution.
package/dist/execute.js CHANGED
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROUTER_FEE_PROOF_DOMAIN = void 0;
3
4
  exports.executeMultiHopPayment = executeMultiHopPayment;
5
+ exports.buildRouterFeeProof = buildRouterFeeProof;
6
+ exports.computeRouterFeeProofHash = computeRouterFeeProofHash;
4
7
  exports.cancelPayment = cancelPayment;
5
8
  exports.executeCrossTokenPayment = executeCrossTokenPayment;
9
+ const core_1 = require("@totemsdk/core");
6
10
  // ─── Type guard ───────────────────────────────────────────────────────────────
7
11
  function isSwapHop(hop) {
8
12
  return hop.isSwap === true;
@@ -98,6 +102,7 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
98
102
  // ones (already-fulfilled HTLCs are irreversible and must not be retouched).
99
103
  const settled = [];
100
104
  const fulfilledSet = new Set();
105
+ const feeProofs = [];
101
106
  for (const { channelId, htlcId } of [...locked].reverse()) {
102
107
  const channel = channels.get(channelId);
103
108
  const lp = leaseProviders.get(channelId);
@@ -119,8 +124,52 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
119
124
  channels.set(channelId, fulfillResult.channel);
120
125
  settled.push(htlcId);
121
126
  fulfilledSet.add(htlcId);
127
+ // Build the verifiable fee proof for this settled hop (#29).
128
+ const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
129
+ if (htlc) {
130
+ feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
131
+ }
122
132
  }
123
- return { success: true, preimage, settledHops: settled };
133
+ return { success: true, preimage, settledHops: settled, feeProofs };
134
+ }
135
+ exports.ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
136
+ /**
137
+ * Build a verifiable fee-provenance record for a settled hop (#29). The pool's
138
+ * `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
139
+ * real fulfilled payment, never a declared string.
140
+ */
141
+ function buildRouterFeeProof(channel, htlc, settledAt) {
142
+ const ts = settledAt ?? Date.now();
143
+ const proof = {
144
+ channelId: channel.channelId,
145
+ htlcId: htlc.htlcId,
146
+ recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
147
+ amount: htlc.amount,
148
+ tokenId: channel.tokenId,
149
+ settledAt: ts,
150
+ proofHash: '',
151
+ };
152
+ proof.proofHash = computeRouterFeeProofHash(proof);
153
+ return proof;
154
+ }
155
+ function computeRouterFeeProofHash(proof) {
156
+ const { proofHash, ...rest } = proof;
157
+ const input = `${exports.ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
158
+ return (0, core_1.bytesToHex)((0, core_1.sha3_256)(new TextEncoder().encode(input)));
159
+ }
160
+ function canonicalJson(value) {
161
+ if (typeof value === 'bigint')
162
+ return JSON.stringify({ __bigint: value.toString() });
163
+ if (Array.isArray(value))
164
+ return `[${value.map(canonicalJson).join(',')}]`;
165
+ if (value && typeof value === 'object') {
166
+ const keys = Object.keys(value).sort();
167
+ const pairs = keys
168
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
169
+ .filter((p) => p !== `${JSON.stringify('')}:null`);
170
+ return `{${pairs.join(',')}}`;
171
+ }
172
+ return JSON.stringify(value);
124
173
  }
125
174
  /**
126
175
  * Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
package/dist/index.d.ts CHANGED
@@ -2,4 +2,7 @@ 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, } from './execute.js';
5
+ export { executeMultiHopPayment, executeCrossTokenPayment, cancelPayment, buildRouterFeeProof, computeRouterFeeProofHash, ROUTER_FEE_PROOF_DOMAIN, } from './execute.js';
6
+ export type { RouterFeeProof } from './types.js';
7
+ export { createDurableRouterLedger, } from './durable-router-ledger.js';
8
+ export type { SettledSegment, RouterLedgerState, DurableRouterLedger, DurableRouterLedgerOptions, } from './durable-router-ledger.js';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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.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;
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; } });
@@ -19,3 +19,8 @@ var execute_js_1 = require("./execute.js");
19
19
  Object.defineProperty(exports, "executeMultiHopPayment", { enumerable: true, get: function () { return execute_js_1.executeMultiHopPayment; } });
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
+ Object.defineProperty(exports, "buildRouterFeeProof", { enumerable: true, get: function () { return execute_js_1.buildRouterFeeProof; } });
23
+ Object.defineProperty(exports, "computeRouterFeeProofHash", { enumerable: true, get: function () { return execute_js_1.computeRouterFeeProofHash; } });
24
+ Object.defineProperty(exports, "ROUTER_FEE_PROOF_DOMAIN", { enumerable: true, get: function () { return execute_js_1.ROUTER_FEE_PROOF_DOMAIN; } });
25
+ var durable_router_ledger_js_1 = require("./durable-router-ledger.js");
26
+ Object.defineProperty(exports, "createDurableRouterLedger", { enumerable: true, get: function () { return durable_router_ledger_js_1.createDurableRouterLedger; } });
package/dist/types.d.ts CHANGED
@@ -170,6 +170,20 @@ export interface PaymentRequest {
170
170
  expiryBlock: bigint;
171
171
  description?: string;
172
172
  }
173
+ /**
174
+ * A verifiable fee-provenance record for a settled hop (#29): the artifact a
175
+ * pool's `recordPoolFee` earn-proof consumes. Binds channel + HTLC + recipient
176
+ * + amount so a fee record traces to a real fulfilled payment.
177
+ */
178
+ export interface RouterFeeProof {
179
+ channelId: string;
180
+ htlcId: string;
181
+ recipientPublicKeyDigest: string;
182
+ amount: bigint;
183
+ tokenId: string;
184
+ settledAt: number;
185
+ proofHash: string;
186
+ }
173
187
  export interface PaymentResult {
174
188
  success: boolean;
175
189
  /** Hex preimage revealed during settlement (present on success) */
@@ -177,6 +191,8 @@ export interface PaymentResult {
177
191
  error?: string;
178
192
  /** htlcIds that were successfully settled */
179
193
  settledHops: string[];
194
+ /** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
195
+ feeProofs?: RouterFeeProof[];
180
196
  }
181
197
  export interface RouteOptions {
182
198
  /** Maximum number of hops (default: 8) */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-router",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Multi-hop payment routing over Omnia channels — single-token and cross-token paths",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -17,10 +17,11 @@
17
17
  "LICENSE"
18
18
  ],
19
19
  "dependencies": {
20
- "@totemsdk/core": "^1.2.9"
20
+ "@totemsdk/core": "^1.2.11",
21
+ "@totemsdk/storage": "^0.1.0"
21
22
  },
22
23
  "peerDependencies": {
23
- "@totemsdk/omnia": "^1.0.0"
24
+ "@totemsdk/omnia": "^1.0.2"
24
25
  },
25
26
  "peerDependenciesMeta": {
26
27
  "@totemsdk/omnia": {