@totemsdk/omnia-factory 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/commitment.d.ts +16 -0
- package/dist/cjs/commitment.js +30 -0
- package/dist/cjs/coordination.d.ts +52 -0
- package/dist/cjs/coordination.js +319 -0
- package/dist/cjs/durable-factory-store.d.ts +42 -0
- package/dist/cjs/durable-factory-store.js +59 -0
- package/dist/cjs/factory.d.ts +91 -0
- package/dist/cjs/factory.js +382 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +39 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/script.d.ts +56 -0
- package/dist/cjs/script.js +113 -0
- package/dist/cjs/settlement.d.ts +55 -0
- package/dist/cjs/settlement.js +193 -0
- package/dist/cjs/types.d.ts +131 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/virtual.d.ts +75 -0
- package/dist/cjs/virtual.js +277 -0
- package/dist/commitment.js +3 -6
- package/dist/coordination.d.ts +52 -0
- package/dist/coordination.js +316 -0
- package/dist/durable-factory-store.js +6 -9
- package/dist/factory.d.ts +21 -0
- package/dist/factory.js +103 -30
- package/dist/index.d.ts +8 -4
- package/dist/index.js +8 -23
- package/dist/script.d.ts +40 -13
- package/dist/script.js +75 -34
- package/dist/settlement.d.ts +36 -12
- package/dist/settlement.js +108 -70
- package/dist/types.js +1 -2
- package/dist/virtual.d.ts +31 -0
- package/dist/virtual.js +110 -59
- package/package.json +15 -9
- package/rust/pkg/omnia_factory_wasm_bg.wasm +0 -0
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/omnia_factory_wasm_bg.wasm +0 -0
- package/rust/pkg-node/package.json +1 -1
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildVirtualChannelOpen = buildVirtualChannelOpen;
|
|
4
|
+
exports.signVirtualChannelOpen = signVirtualChannelOpen;
|
|
5
|
+
exports.verifyVirtualChannelOpenSignature = verifyVirtualChannelOpenSignature;
|
|
6
|
+
exports.assembleVirtualChannelOpen = assembleVirtualChannelOpen;
|
|
7
|
+
exports.openVirtualChannel = openVirtualChannel;
|
|
8
|
+
exports.closeVirtualChannel = closeVirtualChannel;
|
|
9
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
10
|
+
const factory_js_1 = require("./factory.js");
|
|
11
|
+
const commitment_js_1 = require("./commitment.js");
|
|
12
|
+
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
13
|
+
function generateChannelId(factoryId, partyAId, partyBId) {
|
|
14
|
+
const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
15
|
+
return `vc-${factoryId.slice(0, 8)}-${partyAId}-${partyBId}-${nonce}`;
|
|
16
|
+
}
|
|
17
|
+
/** Run the WOTS lease cycle for one party and verify the produced signature. */
|
|
18
|
+
async function leaseSign(factoryId, commitment, purpose, partyId, publicKeyDigest, bundle) {
|
|
19
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
20
|
+
treeId: `omnia-factory-${factoryId}`,
|
|
21
|
+
purpose,
|
|
22
|
+
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
23
|
+
});
|
|
24
|
+
let sig;
|
|
25
|
+
try {
|
|
26
|
+
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
33
|
+
if (!verifyFn(sig, commitment, publicKeyDigest)) {
|
|
34
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
35
|
+
throw new Error(`Signature verification failed for party '${partyId}' — aborting virtual channel operation`);
|
|
36
|
+
}
|
|
37
|
+
await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-vc-${factoryId}`);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Collect N-of-N signatures from all factory participants for a state commitment.
|
|
41
|
+
* Commitment is bound to `newSequence` (the post-commit sequence) for replay resistance.
|
|
42
|
+
*/
|
|
43
|
+
async function collectNofN(factoryId, commitment, purpose, participants, leaseProviders) {
|
|
44
|
+
for (const p of participants) {
|
|
45
|
+
if (!leaseProviders[p.partyId]) {
|
|
46
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for (const p of participants) {
|
|
50
|
+
await leaseSign(factoryId, commitment, purpose, p.partyId, p.publicKeyDigest, leaseProviders[p.partyId]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Validate + build the VC-open plan (no signing). Exported so peers can bind. */
|
|
54
|
+
function buildVirtualChannelOpen(factory, parties, amounts, channelId) {
|
|
55
|
+
if (factory.status !== 'active') {
|
|
56
|
+
throw new Error(`openVirtualChannel requires factory status 'active', got '${factory.status}'`);
|
|
57
|
+
}
|
|
58
|
+
const [partyAId, partyBId] = parties;
|
|
59
|
+
const amountA = amounts[partyAId] ?? 0n;
|
|
60
|
+
const amountB = amounts[partyBId] ?? 0n;
|
|
61
|
+
if (amountA < 0n || amountB < 0n)
|
|
62
|
+
throw new Error('Virtual channel amounts must be non-negative');
|
|
63
|
+
if (amountA + amountB === 0n)
|
|
64
|
+
throw new Error('Virtual channel must have positive total value');
|
|
65
|
+
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
66
|
+
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
67
|
+
if (!partyAMeta)
|
|
68
|
+
throw new Error(`Party '${partyAId}' not found in factory`);
|
|
69
|
+
if (!partyBMeta)
|
|
70
|
+
throw new Error(`Party '${partyBId}' not found in factory`);
|
|
71
|
+
const allocA = factory.allocations[partyAId] ?? 0n;
|
|
72
|
+
const allocB = factory.allocations[partyBId] ?? 0n;
|
|
73
|
+
if (allocA < amountA)
|
|
74
|
+
throw new Error(`Party '${partyAId}' has insufficient allocation: ${allocA} < ${amountA}`);
|
|
75
|
+
if (allocB < amountB)
|
|
76
|
+
throw new Error(`Party '${partyBId}' has insufficient allocation: ${allocB} < ${amountB}`);
|
|
77
|
+
const vcId = channelId ?? generateChannelId(factory.factoryId, partyAId, partyBId);
|
|
78
|
+
const newSequence = factory.currentSequence + 1;
|
|
79
|
+
const newAllocations = {
|
|
80
|
+
...factory.allocations,
|
|
81
|
+
[partyAId]: allocA - amountA,
|
|
82
|
+
[partyBId]: allocB - amountB,
|
|
83
|
+
};
|
|
84
|
+
const newVcIds = [...factory.virtualChannels.map(vc => vc.channelId), vcId];
|
|
85
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
86
|
+
return {
|
|
87
|
+
vcId,
|
|
88
|
+
parties,
|
|
89
|
+
amounts: { [partyAId]: amountA, [partyBId]: amountB },
|
|
90
|
+
newSequence,
|
|
91
|
+
newAllocations,
|
|
92
|
+
newVcIds,
|
|
93
|
+
commitment,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Produce this party's VC-open signature WITHOUT committing the lease
|
|
98
|
+
* (RFC-035 B3). The caller commits on `VC_FINALIZED` or burns on expiry.
|
|
99
|
+
*/
|
|
100
|
+
async function signVirtualChannelOpen(factory, plan, bundle) {
|
|
101
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
102
|
+
if (!participant) {
|
|
103
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
104
|
+
}
|
|
105
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
106
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
107
|
+
purpose: 'factory-vc-open',
|
|
108
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
109
|
+
});
|
|
110
|
+
let sig;
|
|
111
|
+
try {
|
|
112
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
119
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
120
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
121
|
+
throw new Error(`Virtual-channel signature verification failed for party '${participant.partyId}'`);
|
|
122
|
+
}
|
|
123
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
124
|
+
}
|
|
125
|
+
function verifyVirtualChannelOpenSignature(factory, commitment, partyId, signature, verify) {
|
|
126
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
127
|
+
if (!participant)
|
|
128
|
+
return false;
|
|
129
|
+
const verifyFn = verify ?? omnia_1.verifyChannelSignature;
|
|
130
|
+
try {
|
|
131
|
+
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Assemble N-of-N VC-open signatures into the updated factory + virtual channel.
|
|
139
|
+
*/
|
|
140
|
+
function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
141
|
+
for (const p of factory.participants) {
|
|
142
|
+
const s = signatures[p.partyId];
|
|
143
|
+
if (!s)
|
|
144
|
+
throw new Error(`Missing virtual-channel signature for party '${p.partyId}' — open requires all N`);
|
|
145
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
146
|
+
throw new Error(`Virtual-channel signature verification failed for party '${p.partyId}'`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const [partyAId, partyBId] = plan.parties;
|
|
150
|
+
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
151
|
+
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
152
|
+
const now = Date.now();
|
|
153
|
+
const partyA = {
|
|
154
|
+
partyId: partyAId,
|
|
155
|
+
publicKeyDigest: partyAMeta.publicKeyDigest,
|
|
156
|
+
addressIndex: partyAMeta.addressIndex,
|
|
157
|
+
settlementAddress: partyAMeta.settlementAddress,
|
|
158
|
+
};
|
|
159
|
+
const partyB = {
|
|
160
|
+
partyId: partyBId,
|
|
161
|
+
publicKeyDigest: partyBMeta.publicKeyDigest,
|
|
162
|
+
addressIndex: partyBMeta.addressIndex,
|
|
163
|
+
settlementAddress: partyBMeta.settlementAddress,
|
|
164
|
+
};
|
|
165
|
+
const channel = {
|
|
166
|
+
channelId: plan.vcId,
|
|
167
|
+
fundingTxId: factory.fundingTxId ?? '',
|
|
168
|
+
fundingCoinId: factory.fundingCoinId ?? '',
|
|
169
|
+
fundingScript: factory.fundingScript,
|
|
170
|
+
programId: omnia_1.DefaultEltooPaymentProgram.id,
|
|
171
|
+
programVersion: omnia_1.DefaultEltooPaymentProgram.version,
|
|
172
|
+
fundingAddress: factory.fundingAddress,
|
|
173
|
+
tokenId: factory.tokenId,
|
|
174
|
+
tokenScale: factory.tokenScale,
|
|
175
|
+
totalValue: plan.amounts[partyAId] + plan.amounts[partyBId],
|
|
176
|
+
parties: [partyA, partyB],
|
|
177
|
+
balances: { [partyAId]: plan.amounts[partyAId], [partyBId]: plan.amounts[partyBId] },
|
|
178
|
+
pendingHTLCs: [],
|
|
179
|
+
currentSequence: 0,
|
|
180
|
+
latestState: null,
|
|
181
|
+
stateLog: [],
|
|
182
|
+
status: 'active',
|
|
183
|
+
channelType: 'virtual',
|
|
184
|
+
factoryRef: factory.factoryId,
|
|
185
|
+
createdAt: now,
|
|
186
|
+
updatedAt: now,
|
|
187
|
+
};
|
|
188
|
+
const logEntry = {
|
|
189
|
+
sequence: plan.newSequence,
|
|
190
|
+
timestamp: now,
|
|
191
|
+
event: 'virtual_open',
|
|
192
|
+
allocations: plan.newAllocations,
|
|
193
|
+
virtualChannelIds: plan.newVcIds,
|
|
194
|
+
};
|
|
195
|
+
const updated = {
|
|
196
|
+
...factory,
|
|
197
|
+
allocations: plan.newAllocations,
|
|
198
|
+
virtualChannels: [...factory.virtualChannels, channel],
|
|
199
|
+
currentSequence: plan.newSequence,
|
|
200
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
201
|
+
};
|
|
202
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
203
|
+
return { factory: updated, channel };
|
|
204
|
+
}
|
|
205
|
+
async function openVirtualChannel(factory, parties, amounts, leaseProviders, channelId) {
|
|
206
|
+
for (const p of factory.participants) {
|
|
207
|
+
if (!leaseProviders[p.partyId]) {
|
|
208
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — openVirtualChannel requires all N`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const plan = buildVirtualChannelOpen(factory, parties, amounts, channelId);
|
|
212
|
+
const signatures = {};
|
|
213
|
+
for (const p of factory.participants) {
|
|
214
|
+
const sig = await signVirtualChannelOpen(factory, plan, leaseProviders[p.partyId]);
|
|
215
|
+
await leaseProviders[p.partyId].leaseProvider.commitKeyUse(sig.reservationId, `factory-vc-open-${factory.factoryId}`);
|
|
216
|
+
signatures[p.partyId] = sig;
|
|
217
|
+
}
|
|
218
|
+
return assembleVirtualChannelOpen(factory, plan, signatures, (sig, digest, pkd) => {
|
|
219
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === pkd);
|
|
220
|
+
const bundle = participant ? leaseProviders[participant.partyId] : undefined;
|
|
221
|
+
return (bundle?.verify ?? omnia_1.verifyChannelSignature)(sig, digest, pkd);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
// ─── closeVirtualChannel ─────────────────────────────────────────────────────
|
|
225
|
+
/**
|
|
226
|
+
* Close a virtual channel and return its final balances to factory allocations.
|
|
227
|
+
*
|
|
228
|
+
* ALL N factory participants must agree (N-of-N WOTS signature collection).
|
|
229
|
+
* The commitment is bound to `currentSequence + 1`.
|
|
230
|
+
*
|
|
231
|
+
* Final balances are taken from `channel.latestState.balances` (the last agreed
|
|
232
|
+
* off-chain state from `@totemsdk/omnia`'s state machine) or fall back to
|
|
233
|
+
* `channel.balances` (the initial opening split) if no state updates have occurred.
|
|
234
|
+
*
|
|
235
|
+
* No on-chain TX is needed: the factory's shared UTXO remains intact.
|
|
236
|
+
*
|
|
237
|
+
* @param factory - Active factory.
|
|
238
|
+
* @param channel - The virtual `OmniaChannel` to close (with `latestState` set if updated).
|
|
239
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
240
|
+
*/
|
|
241
|
+
async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
242
|
+
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
243
|
+
if (!existing)
|
|
244
|
+
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
245
|
+
// Use latest agreed state's balances; fall back to initial balances.
|
|
246
|
+
const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
|
|
247
|
+
const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
|
|
248
|
+
if (finalSum !== channel.totalValue) {
|
|
249
|
+
throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
|
|
250
|
+
}
|
|
251
|
+
const newSequence = factory.currentSequence + 1;
|
|
252
|
+
const newAllocations = { ...factory.allocations };
|
|
253
|
+
for (const [partyId, amount] of Object.entries(finalAllocations)) {
|
|
254
|
+
newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
|
|
255
|
+
}
|
|
256
|
+
const remainingVcIds = factory.virtualChannels
|
|
257
|
+
.filter(c => c.channelId !== channel.channelId)
|
|
258
|
+
.map(c => c.channelId);
|
|
259
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, remainingVcIds);
|
|
260
|
+
await collectNofN(factory.factoryId, commitment, 'factory-vc-close', factory.participants, leaseProviders);
|
|
261
|
+
const logEntry = {
|
|
262
|
+
sequence: newSequence,
|
|
263
|
+
timestamp: Date.now(),
|
|
264
|
+
event: 'virtual_close',
|
|
265
|
+
allocations: newAllocations,
|
|
266
|
+
virtualChannelIds: remainingVcIds,
|
|
267
|
+
};
|
|
268
|
+
const updated = {
|
|
269
|
+
...factory,
|
|
270
|
+
allocations: newAllocations,
|
|
271
|
+
virtualChannels: factory.virtualChannels.filter(c => c.channelId !== channel.channelId),
|
|
272
|
+
currentSequence: newSequence,
|
|
273
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
274
|
+
};
|
|
275
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
276
|
+
return updated;
|
|
277
|
+
}
|
package/dist/commitment.js
CHANGED
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.computeFactoryStateCommitment = computeFactoryStateCommitment;
|
|
4
|
-
const core_1 = require("@totemsdk/core");
|
|
1
|
+
import { sha3_256 } from '@totemsdk/core/wasm';
|
|
5
2
|
/**
|
|
6
3
|
* Compute the canonical 32-byte state commitment for N-of-N factory signing.
|
|
7
4
|
*
|
|
@@ -17,7 +14,7 @@ const core_1 = require("@totemsdk/core");
|
|
|
17
14
|
* This commitment is what every party signs via `FactorySignerOps.sign`, and
|
|
18
15
|
* what `FactorySignerOps.verify` checks against each stored signature.
|
|
19
16
|
*/
|
|
20
|
-
function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
|
|
17
|
+
export function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
|
|
21
18
|
const canonical = {
|
|
22
19
|
factoryId,
|
|
23
20
|
sequence,
|
|
@@ -26,5 +23,5 @@ function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations,
|
|
|
26
23
|
.map(([k, v]) => [k, v.toString()])),
|
|
27
24
|
virtualChannelIds: [...virtualChannelIds].sort(),
|
|
28
25
|
};
|
|
29
|
-
return
|
|
26
|
+
return sha3_256(new TextEncoder().encode(JSON.stringify(canonical)));
|
|
30
27
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory peer round-trips (RFC-035 B2 open, B3 close).
|
|
3
|
+
*
|
|
4
|
+
* Opening:
|
|
5
|
+
* initiator ── FACTORY_PROPOSAL (opening factory) ─▶ co-signer ×(N-1)
|
|
6
|
+
* initiator ◀─ FACTORY_ACCEPT (own opening signature) ── co-signer
|
|
7
|
+
* initiator ── FACTORY_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
8
|
+
*
|
|
9
|
+
* Closing (cooperative N-of-N settlement):
|
|
10
|
+
* initiator ── FACTORY_CLOSE_PROPOSAL (settlement draft) ─▶ co-signer ×(N-1)
|
|
11
|
+
* initiator ◀─ FACTORY_CLOSE_ACCEPT (own settlement signature) ── co-signer
|
|
12
|
+
* initiator assembles + (optional) mines/broadcasts, then
|
|
13
|
+
* ── FACTORY_CLOSE_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
14
|
+
*
|
|
15
|
+
* Each party commits/burns its **own** lease: the initiator on assemble, the
|
|
16
|
+
* co-signers on the `*_FINALIZED` confirmation (burns on TTL).
|
|
17
|
+
*/
|
|
18
|
+
import type { OmniaPeer, OmniaCoordination, CoordinationHandlers } from '@totemsdk/omnia';
|
|
19
|
+
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
20
|
+
import type { ChannelFactory, FactorySettlementPayload, OmniaChannel, WotsLeaseBundle } from './types.js';
|
|
21
|
+
export type VerifySignature = (signature: Uint8Array, commitment: Uint8Array, publicKeyDigest: string) => boolean;
|
|
22
|
+
export type FactoryStore = Map<string, ChannelFactory>;
|
|
23
|
+
export interface FactoryApprovalRequest {
|
|
24
|
+
factoryId: string;
|
|
25
|
+
proposer: string;
|
|
26
|
+
participants: number;
|
|
27
|
+
}
|
|
28
|
+
export type FactoryApproval = (request: FactoryApprovalRequest) => Promise<boolean>;
|
|
29
|
+
export interface FactoryCoordinationDeps {
|
|
30
|
+
/** This peer's factories (its own copies). */
|
|
31
|
+
factories: FactoryStore;
|
|
32
|
+
/** This peer's signing bundle. */
|
|
33
|
+
bundle: WotsLeaseBundle;
|
|
34
|
+
verifySignature?: VerifySignature;
|
|
35
|
+
approval?: FactoryApproval;
|
|
36
|
+
onOpened?: (factory: ChannelFactory, peer: OmniaPeer) => void;
|
|
37
|
+
onClosed?: (payload: FactorySettlementPayload, peer: OmniaPeer) => void;
|
|
38
|
+
onVcOpened?: (factory: ChannelFactory, channel: OmniaChannel, peer: OmniaPeer) => void;
|
|
39
|
+
/** Initiator-only: mine + broadcast the settlement TxPoW. */
|
|
40
|
+
chainProvider?: ChainStateProvider;
|
|
41
|
+
ttlMs?: number;
|
|
42
|
+
}
|
|
43
|
+
export interface FactoryCoordination {
|
|
44
|
+
handlers: CoordinationHandlers;
|
|
45
|
+
/** Send a FACTORY_PROPOSAL for an 'opening' factory. */
|
|
46
|
+
openFactory(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory): Promise<void>;
|
|
47
|
+
/** Send a FACTORY_CLOSE_PROPOSAL and gather N-of-N settlement signatures. */
|
|
48
|
+
closeFactory(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory): Promise<void>;
|
|
49
|
+
/** Send a VC_PROPOSAL and gather N-of-N virtual-channel-open signatures. */
|
|
50
|
+
openVirtualChannel(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory, parties: [string, string], amounts: Record<string, bigint>): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
export declare function createFactoryCoordination(deps: FactoryCoordinationDeps): FactoryCoordination;
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory peer round-trips (RFC-035 B2 open, B3 close).
|
|
3
|
+
*
|
|
4
|
+
* Opening:
|
|
5
|
+
* initiator ── FACTORY_PROPOSAL (opening factory) ─▶ co-signer ×(N-1)
|
|
6
|
+
* initiator ◀─ FACTORY_ACCEPT (own opening signature) ── co-signer
|
|
7
|
+
* initiator ── FACTORY_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
8
|
+
*
|
|
9
|
+
* Closing (cooperative N-of-N settlement):
|
|
10
|
+
* initiator ── FACTORY_CLOSE_PROPOSAL (settlement draft) ─▶ co-signer ×(N-1)
|
|
11
|
+
* initiator ◀─ FACTORY_CLOSE_ACCEPT (own settlement signature) ── co-signer
|
|
12
|
+
* initiator assembles + (optional) mines/broadcasts, then
|
|
13
|
+
* ── FACTORY_CLOSE_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
14
|
+
*
|
|
15
|
+
* Each party commits/burns its **own** lease: the initiator on assemble, the
|
|
16
|
+
* co-signers on the `*_FINALIZED` confirmation (burns on TTL).
|
|
17
|
+
*/
|
|
18
|
+
import { verifyChannelSignature } from '@totemsdk/omnia';
|
|
19
|
+
import { signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
20
|
+
import { buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
21
|
+
import { buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
22
|
+
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
23
|
+
function toHex(bytes) {
|
|
24
|
+
return Buffer.from(bytes).toString('hex');
|
|
25
|
+
}
|
|
26
|
+
export function createFactoryCoordination(deps) {
|
|
27
|
+
const { factories, bundle, approval, onOpened, onClosed, onVcOpened, chainProvider } = deps;
|
|
28
|
+
const verify = deps.verifySignature ?? ((sig, commitment, pkd) => verifyChannelSignature(sig, commitment, pkd));
|
|
29
|
+
const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;
|
|
30
|
+
const pendingOpenings = new Map();
|
|
31
|
+
const pendingSettlements = new Map();
|
|
32
|
+
const pendingVcOpenings = new Map();
|
|
33
|
+
const burnTimers = new Map();
|
|
34
|
+
const factoryPeers = new Map();
|
|
35
|
+
// Initiator-side close state.
|
|
36
|
+
const closeDrafts = new Map();
|
|
37
|
+
const closeSignatures = new Map();
|
|
38
|
+
// Initiator-side VC-open state.
|
|
39
|
+
const vcPlans = new Map();
|
|
40
|
+
const vcSignatures = new Map();
|
|
41
|
+
const scheduleBurn = (factoryId, reservationId, reason) => {
|
|
42
|
+
burnTimers.set(factoryId, setTimeout(() => {
|
|
43
|
+
const had = pendingOpenings.has(factoryId) ||
|
|
44
|
+
pendingSettlements.has(factoryId) ||
|
|
45
|
+
pendingVcOpenings.has(factoryId);
|
|
46
|
+
if (!had)
|
|
47
|
+
return;
|
|
48
|
+
pendingOpenings.delete(factoryId);
|
|
49
|
+
pendingSettlements.delete(factoryId);
|
|
50
|
+
pendingVcOpenings.delete(factoryId);
|
|
51
|
+
burnTimers.delete(factoryId);
|
|
52
|
+
void bundle.leaseProvider.burnReservation(reservationId, reason).catch(() => { });
|
|
53
|
+
}, ttlMs));
|
|
54
|
+
};
|
|
55
|
+
const registerPeer = (factoryId, peer) => {
|
|
56
|
+
const set = factoryPeers.get(factoryId) ?? new Set();
|
|
57
|
+
set.add(peer);
|
|
58
|
+
factoryPeers.set(factoryId, set);
|
|
59
|
+
};
|
|
60
|
+
const fanOut = async (ctx, factoryId, type) => {
|
|
61
|
+
const peers = factoryPeers.get(factoryId);
|
|
62
|
+
if (!peers)
|
|
63
|
+
return;
|
|
64
|
+
for (const peer of peers) {
|
|
65
|
+
await ctx.sendTo(peer, type, { factoryId }).catch(() => { });
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
// ── Opening ────────────────────────────────────────────────────────────────
|
|
69
|
+
const handleProposal = async (ctx) => {
|
|
70
|
+
const factory = ctx.message.payload;
|
|
71
|
+
if (!factory || factory.status !== 'opening' || !factory.pendingCommitment) {
|
|
72
|
+
throw new Error('factory proposal must be an opening factory');
|
|
73
|
+
}
|
|
74
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
75
|
+
throw new Error('local signer is not a factory participant');
|
|
76
|
+
}
|
|
77
|
+
for (const [partyId, sig] of Object.entries(factory.pendingSignatures ?? {})) {
|
|
78
|
+
if (!verifyFactorySignature(factory, partyId, sig, verify)) {
|
|
79
|
+
throw new Error(`factory proposal: invalid signature for '${partyId}'`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!ctx.policy.autoAccept) {
|
|
83
|
+
const approved = approval
|
|
84
|
+
? await approval({ factoryId: factory.factoryId, proposer: Object.keys(factory.pendingSignatures ?? {})[0] ?? '', participants: factory.participants.length })
|
|
85
|
+
: false;
|
|
86
|
+
if (!approved)
|
|
87
|
+
throw new Error('factory opening rejected: approval required');
|
|
88
|
+
}
|
|
89
|
+
const opening = await signFactoryOpening(factory, bundle);
|
|
90
|
+
pendingOpenings.set(factory.factoryId, opening);
|
|
91
|
+
scheduleBurn(factory.factoryId, opening.reservationId, 'factory-open-timeout');
|
|
92
|
+
await ctx.send('FACTORY_ACCEPT', {
|
|
93
|
+
factoryId: factory.factoryId,
|
|
94
|
+
partyId: opening.partyId,
|
|
95
|
+
signature: opening.signature,
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
const handleAccept = async (ctx) => {
|
|
99
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
100
|
+
const factory = factories.get(factoryId);
|
|
101
|
+
if (!factory)
|
|
102
|
+
throw new Error(`factory accept for unknown factory ${factoryId}`);
|
|
103
|
+
if (!verifyFactorySignature(factory, partyId, signature, verify)) {
|
|
104
|
+
throw new Error(`factory accept: invalid signature from '${partyId}'`);
|
|
105
|
+
}
|
|
106
|
+
const updated = applyFactorySignature(factory, partyId, signature);
|
|
107
|
+
factories.set(factoryId, updated);
|
|
108
|
+
if (updated.status === 'active') {
|
|
109
|
+
onOpened?.(updated, ctx.peer);
|
|
110
|
+
await fanOut(ctx, factoryId, 'FACTORY_FINALIZED');
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const handleFinalized = async (ctx) => {
|
|
114
|
+
const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
|
|
115
|
+
const pending = pendingOpenings.get(factoryId);
|
|
116
|
+
if (!pending)
|
|
117
|
+
return;
|
|
118
|
+
pendingOpenings.delete(factoryId);
|
|
119
|
+
const timer = burnTimers.get(factoryId);
|
|
120
|
+
if (timer) {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
burnTimers.delete(factoryId);
|
|
123
|
+
}
|
|
124
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-finalized:${factoryId}`);
|
|
125
|
+
};
|
|
126
|
+
// ── Closing ────────────────────────────────────────────────────────────────
|
|
127
|
+
const handleCloseProposal = async (ctx) => {
|
|
128
|
+
const { factoryId, draft } = ctx.message.payload;
|
|
129
|
+
const factory = factories.get(factoryId);
|
|
130
|
+
if (!factory)
|
|
131
|
+
throw new Error(`factory close proposal for unknown factory ${factoryId}`);
|
|
132
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
133
|
+
throw new Error('local signer is not a factory participant');
|
|
134
|
+
}
|
|
135
|
+
// Bind the proposal to our own view: rebuild and compare.
|
|
136
|
+
const local = buildFactorySettlement(factory);
|
|
137
|
+
if (toHex(local.txDigest) !== toHex(draft.txDigest) || local.settlementTxHex !== draft.settlementTxHex) {
|
|
138
|
+
throw new Error('factory close proposal: settlement draft does not match local factory state');
|
|
139
|
+
}
|
|
140
|
+
if (!ctx.policy.autoAccept) {
|
|
141
|
+
const approved = approval
|
|
142
|
+
? await approval({ factoryId, proposer: '', participants: factory.participants.length })
|
|
143
|
+
: false;
|
|
144
|
+
if (!approved)
|
|
145
|
+
throw new Error('factory close rejected: approval required');
|
|
146
|
+
}
|
|
147
|
+
const sig = await signFactorySettlement(factory, local, bundle);
|
|
148
|
+
pendingSettlements.set(factoryId, sig);
|
|
149
|
+
scheduleBurn(factoryId, sig.reservationId, 'factory-close-timeout');
|
|
150
|
+
await ctx.send('FACTORY_CLOSE_ACCEPT', {
|
|
151
|
+
factoryId,
|
|
152
|
+
partyId: sig.partyId,
|
|
153
|
+
signature: sig.signature,
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
const handleCloseAccept = async (ctx) => {
|
|
157
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
158
|
+
const factory = factories.get(factoryId);
|
|
159
|
+
if (!factory)
|
|
160
|
+
throw new Error(`factory close accept for unknown factory ${factoryId}`);
|
|
161
|
+
const draft = closeDrafts.get(factoryId);
|
|
162
|
+
if (!draft)
|
|
163
|
+
throw new Error(`no settlement draft for factory ${factoryId}`);
|
|
164
|
+
if (!verifyFactorySettlementSignature(factory, draft.txDigest, partyId, signature, verify)) {
|
|
165
|
+
throw new Error(`factory close accept: invalid signature from '${partyId}'`);
|
|
166
|
+
}
|
|
167
|
+
const sigs = closeSignatures.get(factoryId) ?? {};
|
|
168
|
+
sigs[partyId] = { partyId, signature, reservationId: '' };
|
|
169
|
+
closeSignatures.set(factoryId, sigs);
|
|
170
|
+
if (factory.participants.every((p) => sigs[p.partyId])) {
|
|
171
|
+
const payload = await assembleFactorySettlement(factory, draft, sigs, chainProvider, { verify });
|
|
172
|
+
// commit the initiator's OWN held reservation (the only one with an id)
|
|
173
|
+
const own = Object.values(sigs).find((s) => s.reservationId);
|
|
174
|
+
if (own?.reservationId) {
|
|
175
|
+
await bundle.leaseProvider.commitKeyUse(own.reservationId, `factory-settled:${factoryId}`);
|
|
176
|
+
}
|
|
177
|
+
onClosed?.(payload, ctx.peer);
|
|
178
|
+
await fanOut(ctx, factoryId, 'FACTORY_CLOSE_FINALIZED');
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const handleCloseFinalized = async (ctx) => {
|
|
182
|
+
const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
|
|
183
|
+
const pending = pendingSettlements.get(factoryId);
|
|
184
|
+
if (!pending)
|
|
185
|
+
return;
|
|
186
|
+
pendingSettlements.delete(factoryId);
|
|
187
|
+
const timer = burnTimers.get(factoryId);
|
|
188
|
+
if (timer) {
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
burnTimers.delete(factoryId);
|
|
191
|
+
}
|
|
192
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-settled:${factoryId}`);
|
|
193
|
+
};
|
|
194
|
+
// ── Virtual channel open ─────────────────────────────────────────────────────
|
|
195
|
+
const handleVcProposal = async (ctx) => {
|
|
196
|
+
const { factoryId, plan } = ctx.message.payload;
|
|
197
|
+
const factory = factories.get(factoryId);
|
|
198
|
+
if (!factory)
|
|
199
|
+
throw new Error(`vc proposal for unknown factory ${factoryId}`);
|
|
200
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
201
|
+
throw new Error('local signer is not a factory participant');
|
|
202
|
+
}
|
|
203
|
+
const local = buildVirtualChannelOpen(factory, plan.parties, plan.amounts, plan.vcId);
|
|
204
|
+
if (toHex(local.commitment) !== toHex(plan.commitment)) {
|
|
205
|
+
throw new Error('vc proposal: commitment does not match local factory state');
|
|
206
|
+
}
|
|
207
|
+
if (!ctx.policy.autoAccept) {
|
|
208
|
+
const approved = approval
|
|
209
|
+
? await approval({ factoryId, proposer: '', participants: factory.participants.length })
|
|
210
|
+
: false;
|
|
211
|
+
if (!approved)
|
|
212
|
+
throw new Error('virtual channel open rejected: approval required');
|
|
213
|
+
}
|
|
214
|
+
const sig = await signVirtualChannelOpen(factory, local, bundle);
|
|
215
|
+
pendingVcOpenings.set(plan.vcId, sig);
|
|
216
|
+
scheduleBurn(plan.vcId, sig.reservationId, 'vc-open-timeout');
|
|
217
|
+
await ctx.send('VC_ACCEPT', { factoryId, partyId: sig.partyId, signature: sig.signature });
|
|
218
|
+
};
|
|
219
|
+
const handleVcAccept = async (ctx) => {
|
|
220
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
221
|
+
const factory = factories.get(factoryId);
|
|
222
|
+
if (!factory)
|
|
223
|
+
throw new Error(`vc accept for unknown factory ${factoryId}`);
|
|
224
|
+
const plan = vcPlans.get(ctx.correlationId);
|
|
225
|
+
if (!plan)
|
|
226
|
+
throw new Error(`no VC plan for ${ctx.correlationId}`);
|
|
227
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, partyId, signature, verify)) {
|
|
228
|
+
throw new Error(`vc accept: invalid signature from '${partyId}'`);
|
|
229
|
+
}
|
|
230
|
+
const sigs = vcSignatures.get(ctx.correlationId) ?? {};
|
|
231
|
+
sigs[partyId] = { partyId, signature, reservationId: '' };
|
|
232
|
+
vcSignatures.set(ctx.correlationId, sigs);
|
|
233
|
+
if (factory.participants.every((p) => sigs[p.partyId])) {
|
|
234
|
+
const { factory: updated, channel } = assembleVirtualChannelOpen(factory, plan, sigs, verify);
|
|
235
|
+
factories.set(factoryId, updated);
|
|
236
|
+
const own = Object.values(sigs).find((s) => s.reservationId);
|
|
237
|
+
if (own?.reservationId) {
|
|
238
|
+
await bundle.leaseProvider.commitKeyUse(own.reservationId, `vc-opened:${plan.vcId}`);
|
|
239
|
+
}
|
|
240
|
+
onVcOpened?.(updated, channel, ctx.peer);
|
|
241
|
+
await fanOut(ctx, factoryId, 'VC_FINALIZED');
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
const handleVcFinalized = async (ctx) => {
|
|
245
|
+
const vcId = ctx.correlationId;
|
|
246
|
+
const pending = pendingVcOpenings.get(vcId);
|
|
247
|
+
if (!pending)
|
|
248
|
+
return;
|
|
249
|
+
pendingVcOpenings.delete(vcId);
|
|
250
|
+
const timer = burnTimers.get(vcId);
|
|
251
|
+
if (timer) {
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
burnTimers.delete(vcId);
|
|
254
|
+
}
|
|
255
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `vc-opened:${vcId}`);
|
|
256
|
+
};
|
|
257
|
+
const handlers = {
|
|
258
|
+
FACTORY_PROPOSAL: handleProposal,
|
|
259
|
+
FACTORY_ACCEPT: handleAccept,
|
|
260
|
+
FACTORY_FINALIZED: handleFinalized,
|
|
261
|
+
FACTORY_CLOSE_PROPOSAL: handleCloseProposal,
|
|
262
|
+
FACTORY_CLOSE_ACCEPT: handleCloseAccept,
|
|
263
|
+
FACTORY_CLOSE_FINALIZED: handleCloseFinalized,
|
|
264
|
+
VC_PROPOSAL: handleVcProposal,
|
|
265
|
+
VC_ACCEPT: handleVcAccept,
|
|
266
|
+
VC_FINALIZED: handleVcFinalized,
|
|
267
|
+
};
|
|
268
|
+
const openFactory = async (peer, coordination, factory) => {
|
|
269
|
+
if (factory.status !== 'opening')
|
|
270
|
+
throw new Error('openFactory requires an opening factory');
|
|
271
|
+
factories.set(factory.factoryId, factory);
|
|
272
|
+
registerPeer(factory.factoryId, peer);
|
|
273
|
+
await coordination.sendProposal({
|
|
274
|
+
peer,
|
|
275
|
+
kind: 'FACTORY_PROPOSAL',
|
|
276
|
+
correlationId: factory.factoryId,
|
|
277
|
+
channelId: factory.factoryId,
|
|
278
|
+
payload: factory,
|
|
279
|
+
});
|
|
280
|
+
};
|
|
281
|
+
const closeFactory = async (peer, coordination, factory) => {
|
|
282
|
+
if (factory.status !== 'active')
|
|
283
|
+
throw new Error('closeFactory requires an active factory');
|
|
284
|
+
factories.set(factory.factoryId, factory);
|
|
285
|
+
registerPeer(factory.factoryId, peer);
|
|
286
|
+
const draft = buildFactorySettlement(factory);
|
|
287
|
+
const own = await signFactorySettlement(factory, draft, bundle);
|
|
288
|
+
closeDrafts.set(factory.factoryId, draft);
|
|
289
|
+
closeSignatures.set(factory.factoryId, { [own.partyId]: own });
|
|
290
|
+
await coordination.sendProposal({
|
|
291
|
+
peer,
|
|
292
|
+
kind: 'FACTORY_CLOSE_PROPOSAL',
|
|
293
|
+
correlationId: factory.factoryId,
|
|
294
|
+
channelId: factory.factoryId,
|
|
295
|
+
payload: { factoryId: factory.factoryId, draft },
|
|
296
|
+
});
|
|
297
|
+
};
|
|
298
|
+
const openVirtualChannel = async (peer, coordination, factory, parties, amounts) => {
|
|
299
|
+
if (factory.status !== 'active')
|
|
300
|
+
throw new Error('openVirtualChannel requires an active factory');
|
|
301
|
+
factories.set(factory.factoryId, factory);
|
|
302
|
+
registerPeer(factory.factoryId, peer);
|
|
303
|
+
const plan = buildVirtualChannelOpen(factory, parties, amounts);
|
|
304
|
+
const own = await signVirtualChannelOpen(factory, plan, bundle);
|
|
305
|
+
vcPlans.set(plan.vcId, plan);
|
|
306
|
+
vcSignatures.set(plan.vcId, { [own.partyId]: own });
|
|
307
|
+
await coordination.sendProposal({
|
|
308
|
+
peer,
|
|
309
|
+
kind: 'VC_PROPOSAL',
|
|
310
|
+
correlationId: plan.vcId,
|
|
311
|
+
channelId: factory.factoryId,
|
|
312
|
+
payload: { factoryId: factory.factoryId, plan },
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
return { handlers, openFactory, closeFactory, openVirtualChannel };
|
|
316
|
+
}
|