@totemsdk/omnia-router 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/durable-router-ledger.d.ts +60 -0
- package/dist/cjs/durable-router-ledger.js +88 -0
- package/dist/cjs/execute.d.ts +45 -0
- package/dist/cjs/execute.js +303 -0
- package/dist/cjs/forward.d.ts +50 -0
- package/dist/cjs/forward.js +56 -0
- package/dist/cjs/graph.d.ts +32 -0
- package/dist/cjs/graph.js +102 -0
- package/dist/cjs/index.d.ts +10 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pathfind.d.ts +25 -0
- package/dist/cjs/pathfind.js +253 -0
- package/dist/cjs/request.d.ts +19 -0
- package/dist/cjs/request.js +38 -0
- package/dist/cjs/types.d.ts +200 -0
- package/dist/cjs/types.js +10 -0
- package/dist/durable-router-ledger.d.ts +60 -0
- package/dist/durable-router-ledger.js +85 -0
- package/dist/execute.d.ts +9 -1
- package/dist/execute.js +50 -9
- package/dist/forward.d.ts +50 -0
- package/dist/forward.js +53 -0
- package/dist/graph.js +7 -14
- package/dist/index.d.ts +6 -1
- package/dist/index.js +7 -21
- package/dist/pathfind.js +6 -12
- package/dist/request.js +5 -9
- package/dist/types.d.ts +16 -0
- package/dist/types.js +1 -2
- package/package.json +16 -9
|
@@ -0,0 +1,200 @@
|
|
|
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
|
+
/** Populated during payment execution */
|
|
127
|
+
htlcId?: string;
|
|
128
|
+
}
|
|
129
|
+
export interface SwapHop extends RoutingHop {
|
|
130
|
+
isSwap: true;
|
|
131
|
+
tokenIn: string;
|
|
132
|
+
tokenOut: string;
|
|
133
|
+
amountIn: bigint;
|
|
134
|
+
amountOut: bigint;
|
|
135
|
+
/** "amountOut per amountIn" expressed as decimal string, e.g. "0.95" */
|
|
136
|
+
rate: string;
|
|
137
|
+
inboundChannelId: string;
|
|
138
|
+
outboundChannelId: string;
|
|
139
|
+
}
|
|
140
|
+
export interface Route {
|
|
141
|
+
hops: (RoutingHop | SwapHop)[];
|
|
142
|
+
totalFees: bigint;
|
|
143
|
+
tokenIn: string;
|
|
144
|
+
tokenOut: string;
|
|
145
|
+
estimatedBlocks: number;
|
|
146
|
+
}
|
|
147
|
+
export interface CrossTokenRoute extends Route {
|
|
148
|
+
swapHops: SwapHop[];
|
|
149
|
+
}
|
|
150
|
+
export interface SwapAnnouncement {
|
|
151
|
+
intermediaryPubKey: string;
|
|
152
|
+
tokenIn: string;
|
|
153
|
+
tokenOut: string;
|
|
154
|
+
/** How many tokenOut scaled units per tokenIn scaled unit */
|
|
155
|
+
rate: string;
|
|
156
|
+
inboundChannelId: string;
|
|
157
|
+
outboundChannelId: string;
|
|
158
|
+
maxAmountIn: bigint;
|
|
159
|
+
}
|
|
160
|
+
export interface PaymentRequest {
|
|
161
|
+
/** SHA3-256 hex of preimage */
|
|
162
|
+
hashlock: string;
|
|
163
|
+
/**
|
|
164
|
+
* Known to the payer (returned by buildPaymentRequest).
|
|
165
|
+
* Strip this before sharing the request with intermediaries.
|
|
166
|
+
*/
|
|
167
|
+
preimage?: string;
|
|
168
|
+
amount: bigint;
|
|
169
|
+
tokenId: string;
|
|
170
|
+
expiryBlock: bigint;
|
|
171
|
+
description?: string;
|
|
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
|
+
}
|
|
187
|
+
export interface PaymentResult {
|
|
188
|
+
success: boolean;
|
|
189
|
+
/** Hex preimage revealed during settlement (present on success) */
|
|
190
|
+
preimage?: string;
|
|
191
|
+
error?: string;
|
|
192
|
+
/** htlcIds that were successfully settled */
|
|
193
|
+
settledHops: string[];
|
|
194
|
+
/** Verifiable fee proofs for each settled hop — feeds recordPoolFee earn-proofs. */
|
|
195
|
+
feeProofs?: RouterFeeProof[];
|
|
196
|
+
}
|
|
197
|
+
export interface RouteOptions {
|
|
198
|
+
/** Maximum number of hops (default: 8) */
|
|
199
|
+
maxHops?: number;
|
|
200
|
+
}
|
|
@@ -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 });
|
|
@@ -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,85 @@
|
|
|
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 { createRevisionedSnapshotStore, } from '@totemsdk/storage/snapshot';
|
|
17
|
+
import { StorageError } from '@totemsdk/storage/errors';
|
|
18
|
+
const DEFAULT_NAMESPACE = 'totem_omnia_router:v1:';
|
|
19
|
+
function segmentKey(channelId, htlcId) {
|
|
20
|
+
return `${channelId}:${htlcId}`;
|
|
21
|
+
}
|
|
22
|
+
function assertLedgerState(state) {
|
|
23
|
+
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
24
|
+
throw new StorageError('omnia-router ledger state is not an object', 'corrupt');
|
|
25
|
+
}
|
|
26
|
+
const value = state.segments;
|
|
27
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
28
|
+
throw new StorageError('omnia-router ledger state is missing section "segments"', 'corrupt');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export function createDurableRouterLedger(adapter, options = {}) {
|
|
32
|
+
const snapshots = createRevisionedSnapshotStore(adapter, {
|
|
33
|
+
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
34
|
+
requireAckMode: options.requireAckMode,
|
|
35
|
+
empty: () => ({ segments: {} }),
|
|
36
|
+
validate: assertLedgerState,
|
|
37
|
+
});
|
|
38
|
+
async function mutate(fn) {
|
|
39
|
+
await snapshots.mutate(fn);
|
|
40
|
+
}
|
|
41
|
+
async function loadSegment(channelId, htlcId) {
|
|
42
|
+
const state = await snapshots.load();
|
|
43
|
+
return state.segments[segmentKey(channelId, htlcId)];
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
async recordSettled(segment) {
|
|
47
|
+
// Short-circuit already-recorded segments: re-recording is a no-op and
|
|
48
|
+
// must not advance the revision or rewrite an immutable record.
|
|
49
|
+
if (await loadSegment(segment.channelId, segment.htlcId))
|
|
50
|
+
return;
|
|
51
|
+
await mutate((state) => {
|
|
52
|
+
const key = segmentKey(segment.channelId, segment.htlcId);
|
|
53
|
+
return { ...state, segments: { ...state.segments, [key]: segment } };
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
isSettled(channelId, htlcId) {
|
|
57
|
+
return loadSegment(channelId, htlcId).then((seg) => seg !== undefined);
|
|
58
|
+
},
|
|
59
|
+
getSettled: loadSegment,
|
|
60
|
+
async listSettled(channelId) {
|
|
61
|
+
const state = await snapshots.load();
|
|
62
|
+
const all = Object.values(state.segments);
|
|
63
|
+
if (channelId === undefined)
|
|
64
|
+
return all;
|
|
65
|
+
return all.filter((s) => s.channelId === channelId);
|
|
66
|
+
},
|
|
67
|
+
async markReconciled(channelId, htlcId) {
|
|
68
|
+
await mutate((state) => {
|
|
69
|
+
const key = segmentKey(channelId, htlcId);
|
|
70
|
+
const existing = state.segments[key];
|
|
71
|
+
if (!existing)
|
|
72
|
+
return state;
|
|
73
|
+
return {
|
|
74
|
+
...state,
|
|
75
|
+
segments: { ...state.segments, [key]: { ...existing, reconciled: true } },
|
|
76
|
+
};
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
getRevision: () => snapshots.getRevision(),
|
|
80
|
+
hasState: () => snapshots.hasState(),
|
|
81
|
+
async getSnapshot() {
|
|
82
|
+
return snapshots.load();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
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,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.executeMultiHopPayment = executeMultiHopPayment;
|
|
4
|
-
exports.cancelPayment = cancelPayment;
|
|
5
|
-
exports.executeCrossTokenPayment = executeCrossTokenPayment;
|
|
1
|
+
import { bytesToHex, sha3_256 } from '@totemsdk/core';
|
|
6
2
|
// ─── Type guard ───────────────────────────────────────────────────────────────
|
|
7
3
|
function isSwapHop(hop) {
|
|
8
4
|
return hop.isSwap === true;
|
|
@@ -49,7 +45,7 @@ async function cancelHtlcs(ops, channels, locked, leaseProviders) {
|
|
|
49
45
|
*
|
|
50
46
|
* The `channels` map is updated in-place after each HTLC operation.
|
|
51
47
|
*/
|
|
52
|
-
async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
48
|
+
export async function executeMultiHopPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
53
49
|
const preimage = paymentRequest.preimage;
|
|
54
50
|
if (!preimage) {
|
|
55
51
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
@@ -98,6 +94,7 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
|
|
|
98
94
|
// ones (already-fulfilled HTLCs are irreversible and must not be retouched).
|
|
99
95
|
const settled = [];
|
|
100
96
|
const fulfilledSet = new Set();
|
|
97
|
+
const feeProofs = [];
|
|
101
98
|
for (const { channelId, htlcId } of [...locked].reverse()) {
|
|
102
99
|
const channel = channels.get(channelId);
|
|
103
100
|
const lp = leaseProviders.get(channelId);
|
|
@@ -119,14 +116,58 @@ async function executeMultiHopPayment(ops, channels, route, paymentRequest, leas
|
|
|
119
116
|
channels.set(channelId, fulfillResult.channel);
|
|
120
117
|
settled.push(htlcId);
|
|
121
118
|
fulfilledSet.add(htlcId);
|
|
119
|
+
// Build the verifiable fee proof for this settled hop (#29).
|
|
120
|
+
const htlc = fulfillResult.channel.pendingHTLCs.find(h => h.htlcId === htlcId);
|
|
121
|
+
if (htlc) {
|
|
122
|
+
feeProofs.push(buildRouterFeeProof(fulfillResult.channel, htlc, Date.now()));
|
|
123
|
+
}
|
|
122
124
|
}
|
|
123
|
-
return { success: true, preimage, settledHops: settled };
|
|
125
|
+
return { success: true, preimage, settledHops: settled, feeProofs };
|
|
126
|
+
}
|
|
127
|
+
export const ROUTER_FEE_PROOF_DOMAIN = 'totemsdk/omnia-router/fee-proof/v1';
|
|
128
|
+
/**
|
|
129
|
+
* Build a verifiable fee-provenance record for a settled hop (#29). The pool's
|
|
130
|
+
* `recordPoolFee` earn-proof consumes this — a fee record can be traced to a
|
|
131
|
+
* real fulfilled payment, never a declared string.
|
|
132
|
+
*/
|
|
133
|
+
export function buildRouterFeeProof(channel, htlc, settledAt) {
|
|
134
|
+
const ts = settledAt ?? Date.now();
|
|
135
|
+
const proof = {
|
|
136
|
+
channelId: channel.channelId,
|
|
137
|
+
htlcId: htlc.htlcId,
|
|
138
|
+
recipientPublicKeyDigest: htlc.recipientPublicKeyDigest,
|
|
139
|
+
amount: htlc.amount,
|
|
140
|
+
tokenId: channel.tokenId,
|
|
141
|
+
settledAt: ts,
|
|
142
|
+
proofHash: '',
|
|
143
|
+
};
|
|
144
|
+
proof.proofHash = computeRouterFeeProofHash(proof);
|
|
145
|
+
return proof;
|
|
146
|
+
}
|
|
147
|
+
export function computeRouterFeeProofHash(proof) {
|
|
148
|
+
const { proofHash, ...rest } = proof;
|
|
149
|
+
const input = `${ROUTER_FEE_PROOF_DOMAIN}|${canonicalJson(rest)}`;
|
|
150
|
+
return bytesToHex(sha3_256(new TextEncoder().encode(input)));
|
|
151
|
+
}
|
|
152
|
+
function canonicalJson(value) {
|
|
153
|
+
if (typeof value === 'bigint')
|
|
154
|
+
return JSON.stringify({ __bigint: value.toString() });
|
|
155
|
+
if (Array.isArray(value))
|
|
156
|
+
return `[${value.map(canonicalJson).join(',')}]`;
|
|
157
|
+
if (value && typeof value === 'object') {
|
|
158
|
+
const keys = Object.keys(value).sort();
|
|
159
|
+
const pairs = keys
|
|
160
|
+
.map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
|
|
161
|
+
.filter((p) => p !== `${JSON.stringify('')}:null`);
|
|
162
|
+
return `{${pairs.join(',')}}`;
|
|
163
|
+
}
|
|
164
|
+
return JSON.stringify(value);
|
|
124
165
|
}
|
|
125
166
|
/**
|
|
126
167
|
* Cancel all pending HTLCs on a route by calling timeoutHTLC on each hop.
|
|
127
168
|
* Call this explicitly to roll back before or without attempting execution.
|
|
128
169
|
*/
|
|
129
|
-
async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
170
|
+
export async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
130
171
|
const hopsWithHtlc = route.hops.filter(h => h.htlcId && !isSwapHop(h));
|
|
131
172
|
await cancelHtlcs(ops, channels, hopsWithHtlc.map(h => ({ channelId: h.channelId, htlcId: h.htlcId })), leaseProviders);
|
|
132
173
|
}
|
|
@@ -146,7 +187,7 @@ async function cancelPayment(ops, channels, route, leaseProviders) {
|
|
|
146
187
|
* Rollback fires on ANY failure (forward OR backward phase) by timing out
|
|
147
188
|
* all still-pending locked HTLCs.
|
|
148
189
|
*/
|
|
149
|
-
async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
190
|
+
export async function executeCrossTokenPayment(ops, channels, route, paymentRequest, leaseProviders) {
|
|
150
191
|
const preimage = paymentRequest.preimage;
|
|
151
192
|
if (!preimage) {
|
|
152
193
|
return { success: false, error: 'paymentRequest.preimage is required for execution', settledHops: [] };
|
|
@@ -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.js
CHANGED
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createChannelGraph = createChannelGraph;
|
|
4
|
-
exports.addChannel = addChannel;
|
|
5
|
-
exports.removeChannel = removeChannel;
|
|
6
|
-
exports.announceSwap = announceSwap;
|
|
7
|
-
exports.getSwapAnnouncements = getSwapAnnouncements;
|
|
8
|
-
const pathfind_js_1 = require("./pathfind.js");
|
|
1
|
+
import { parseRateToScaled } from './pathfind.js';
|
|
9
2
|
/** Create an empty ChannelGraph. */
|
|
10
|
-
function createChannelGraph() {
|
|
3
|
+
export function createChannelGraph() {
|
|
11
4
|
return {
|
|
12
5
|
nodeEdges: new Map(),
|
|
13
6
|
edgesByChannel: new Map(),
|
|
@@ -23,7 +16,7 @@ function createChannelGraph() {
|
|
|
23
16
|
* `addChannel` twice with the same `(channelId, from)` replaces the first
|
|
24
17
|
* entry (balance update semantics).
|
|
25
18
|
*/
|
|
26
|
-
function addChannel(graph, edge) {
|
|
19
|
+
export function addChannel(graph, edge) {
|
|
27
20
|
const existing = graph.edgesByChannel.get(edge.channelId) ?? [];
|
|
28
21
|
// Replace any edge for the same (channelId, from) direction.
|
|
29
22
|
const idx = existing.findIndex(e => e.from === edge.from);
|
|
@@ -44,7 +37,7 @@ function addChannel(graph, edge) {
|
|
|
44
37
|
* Remove ALL directed edges for `channelId` (i.e. both directions).
|
|
45
38
|
* No-op if the channelId is not present.
|
|
46
39
|
*/
|
|
47
|
-
function removeChannel(graph, channelId) {
|
|
40
|
+
export function removeChannel(graph, channelId) {
|
|
48
41
|
const edges = graph.edgesByChannel.get(channelId);
|
|
49
42
|
if (!edges)
|
|
50
43
|
return;
|
|
@@ -74,8 +67,8 @@ function _removeFromNodeEdges(graph, edge) {
|
|
|
74
67
|
* Duplicate announcements (same `intermediaryPubKey` + `inboundChannelId`)
|
|
75
68
|
* are replaced to prevent stale rate data.
|
|
76
69
|
*/
|
|
77
|
-
function announceSwap(graph, announcement) {
|
|
78
|
-
const rateScaled =
|
|
70
|
+
export function announceSwap(graph, announcement) {
|
|
71
|
+
const rateScaled = parseRateToScaled(announcement.rate);
|
|
79
72
|
if (rateScaled <= 0n) {
|
|
80
73
|
throw new Error(`Invalid swap rate "${announcement.rate}" from intermediary ${announcement.intermediaryPubKey}: rate must be positive`);
|
|
81
74
|
}
|
|
@@ -94,7 +87,7 @@ function announceSwap(graph, announcement) {
|
|
|
94
87
|
/**
|
|
95
88
|
* Return all swap announcements for a given token pair, or an empty array.
|
|
96
89
|
*/
|
|
97
|
-
function getSwapAnnouncements(graph, tokenIn, tokenOut) {
|
|
90
|
+
export function getSwapAnnouncements(graph, tokenIn, tokenOut) {
|
|
98
91
|
return graph.swapIndex.get(_swapKey(tokenIn, tokenOut)) ?? [];
|
|
99
92
|
}
|
|
100
93
|
function _swapKey(tokenIn, tokenOut) {
|
package/dist/index.d.ts
CHANGED
|
@@ -2,4 +2,9 @@ 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 { createCleartextRoutingCodec } from './forward.js';
|
|
8
|
+
export type { RoutingEnvelopeCodec, ForwardHop, PeelResult } from './forward.js';
|
|
9
|
+
export { createDurableRouterLedger, } from './durable-router-ledger.js';
|
|
10
|
+
export type { SettledSegment, RouterLedgerState, DurableRouterLedger, DurableRouterLedgerOptions, } from './durable-router-ledger.js';
|