@totemsdk/omnia-factory 0.7.0 → 0.7.2
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/LICENSE +202 -21
- package/NOTICE +60 -0
- package/README.md +5 -0
- package/dist/cjs/factory.d.ts +48 -1
- package/dist/cjs/factory.js +274 -79
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/virtual.js +2 -0
- package/dist/factory.d.ts +48 -1
- package/dist/factory.js +269 -79
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/virtual.js +2 -0
- package/package.json +12 -14
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/package.json +1 -1
package/dist/cjs/factory.js
CHANGED
|
@@ -2,11 +2,16 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.enforceConservation = enforceConservation;
|
|
4
4
|
exports.createFactory = createFactory;
|
|
5
|
+
exports.proposeFactoryOpening = proposeFactoryOpening;
|
|
6
|
+
exports.createFactoryFromPlan = createFactoryFromPlan;
|
|
7
|
+
exports.buildFactoryOpening = buildFactoryOpening;
|
|
8
|
+
exports.finalizeFactoryOpening = finalizeFactoryOpening;
|
|
5
9
|
exports.acceptFactory = acceptFactory;
|
|
6
10
|
exports.signFactoryOpening = signFactoryOpening;
|
|
7
11
|
exports.verifyFactorySignature = verifyFactorySignature;
|
|
8
12
|
exports.applyFactorySignature = applyFactorySignature;
|
|
9
13
|
exports.reallocate = reallocate;
|
|
14
|
+
exports.assertFactoryFinalized = assertFactoryFinalized;
|
|
10
15
|
const wasm_1 = require("@totemsdk/core/wasm");
|
|
11
16
|
const wasm_2 = require("@totemsdk/core/wasm");
|
|
12
17
|
const core_1 = require("@totemsdk/core");
|
|
@@ -120,98 +125,112 @@ function generateFactoryId(participants, tokenId, tokenScale) {
|
|
|
120
125
|
* Defaults to 0.
|
|
121
126
|
*/
|
|
122
127
|
async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
//
|
|
127
|
-
const
|
|
128
|
+
// One plan, one factory ID: build the opening once and reuse it for the
|
|
129
|
+
// proposal, the local record and the funding transaction. Rebuilding here
|
|
130
|
+
// would generate a different ID (the ID includes a random nonce) and the
|
|
131
|
+
// peer would accept a factory this host never stored.
|
|
132
|
+
const plan = await buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding);
|
|
133
|
+
return createFactoryFromPlan(plan, bundle, chainProvider);
|
|
134
|
+
}
|
|
135
|
+
function findProposer(factory, bundle) {
|
|
136
|
+
const proposer = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
128
137
|
if (!proposer) {
|
|
129
138
|
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
130
139
|
}
|
|
140
|
+
return proposer;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Sign the opening commitment for a plan and record the proposer's signature.
|
|
144
|
+
* Nothing is broadcast and no funding signature is requested, so callers can
|
|
145
|
+
* propose the factory to the peer first (CAN-020 ordering).
|
|
146
|
+
*/
|
|
147
|
+
async function proposeFactoryOpening(plan, bundle) {
|
|
148
|
+
const proposer = findProposer(plan.factory, bundle);
|
|
149
|
+
if (!plan.factory.pendingCommitment) {
|
|
150
|
+
throw new Error('Factory plan has no pending commitment');
|
|
151
|
+
}
|
|
152
|
+
const commitment = Buffer.from(plan.factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
153
|
+
const sig = await leaseSign(plan.factory.factoryId, commitment, 'factory-open', proposer, bundle);
|
|
154
|
+
return {
|
|
155
|
+
...plan.factory,
|
|
156
|
+
pendingSignatures: { [proposer.partyId]: sig },
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Finish a plan: collect the funding-witness signatures from the plan's
|
|
161
|
+
* funding materials (or use the supplied ones), broadcast the funding
|
|
162
|
+
* transaction when the plan is on-chain, and commit the opening once every
|
|
163
|
+
* participant has signed.
|
|
164
|
+
*/
|
|
165
|
+
async function createFactoryFromPlan(plan, bundle, chainProvider) {
|
|
166
|
+
let factory = await proposeFactoryOpening(plan, bundle);
|
|
167
|
+
if (plan.onChain) {
|
|
168
|
+
if (!chainProvider || !plan.fundingTxBytes || !plan.fundingDigest) {
|
|
169
|
+
throw new Error('Factory funding requires a chain provider and a complete funding plan');
|
|
170
|
+
}
|
|
171
|
+
const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
|
|
172
|
+
const fundingSignatures = {};
|
|
173
|
+
for (const participant of factory.participants) {
|
|
174
|
+
const material = materials.get(participant.partyId);
|
|
175
|
+
if (!material)
|
|
176
|
+
throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
|
|
177
|
+
if (material.signature) {
|
|
178
|
+
fundingSignatures[participant.partyId] = material.signature;
|
|
179
|
+
}
|
|
180
|
+
else if (material.signer) {
|
|
181
|
+
fundingSignatures[participant.partyId] = Uint8Array.from(await material.signer(plan.fundingDigest));
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
factory = await finalizeFactoryOpening(plan, { fundingSignatures, openingSignatures: factory.pendingSignatures }, chainProvider);
|
|
188
|
+
}
|
|
189
|
+
// If proposer is the only participant (edge case), activate immediately.
|
|
190
|
+
if (factory.participants.length === 1) {
|
|
191
|
+
return commitOpening(factory);
|
|
192
|
+
}
|
|
193
|
+
return factory;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Build a factory and (when every participant supplies a funding coin) its
|
|
197
|
+
* deterministic funding draft, without signing or broadcasting.
|
|
198
|
+
*/
|
|
199
|
+
async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding) {
|
|
200
|
+
if (participants.length < 2) {
|
|
201
|
+
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
202
|
+
}
|
|
131
203
|
const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
|
|
132
204
|
const allocations = {};
|
|
133
|
-
for (const p of participants)
|
|
205
|
+
for (const p of participants)
|
|
134
206
|
allocations[p.partyId] = p.contributionAmount;
|
|
135
|
-
}
|
|
136
207
|
const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
|
|
137
208
|
const factoryId = generateFactoryId(participants, tokenId, tokenScale);
|
|
138
|
-
|
|
139
|
-
let
|
|
209
|
+
let fundingTxBytes;
|
|
210
|
+
let fundingDigest;
|
|
140
211
|
let fundingCoinId;
|
|
141
212
|
let pendingCommitment;
|
|
142
213
|
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
143
214
|
if (allHaveCoinId && chainProvider) {
|
|
144
215
|
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
145
|
-
// The transaction input address must be the *funding coin's* address, not
|
|
146
|
-
// the participant's settlement address. Callers supply it directly or via
|
|
147
|
-
// the funding coin script.
|
|
148
216
|
const inputAddresses = participants.map(p => {
|
|
149
217
|
const m = materialByParty.get(p.partyId);
|
|
150
218
|
return m?.coinAddress ?? (m?.script ? (0, core_1.computeScriptAddress)(m.script) : '');
|
|
151
219
|
});
|
|
152
220
|
if (inputAddresses.some(a => !a)) {
|
|
153
|
-
throw new Error('
|
|
221
|
+
throw new Error('Factory opening on-chain requires funding material (coinAddress or script) for every participant');
|
|
154
222
|
}
|
|
155
223
|
const tip = await chainProvider.getTip();
|
|
156
224
|
const escapeBlock = tip.block + script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
157
225
|
const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...(0, script_js_1.factoryBalanceStateVariables)(participants), (0, script_js_1.factoryEscapeStateVariable)(escapeBlock)]);
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
// Assemble the real witness: one CoinProof + ScriptProof + signature per
|
|
161
|
-
// input coin (the factory's own MULTISIG script is the *output* script).
|
|
162
|
-
const signatures = [];
|
|
163
|
-
const coinProofs = [];
|
|
164
|
-
const scriptProofs = [];
|
|
165
|
-
for (const p of participants) {
|
|
166
|
-
const m = materialByParty.get(p.partyId);
|
|
167
|
-
if (!m)
|
|
168
|
-
throw new Error(`Missing funding material for factory party '${p.partyId}'`);
|
|
169
|
-
coinProofs.push(m.coinProof);
|
|
170
|
-
let scriptProof = m.scriptProof;
|
|
171
|
-
if (!scriptProof) {
|
|
172
|
-
if (!m.script)
|
|
173
|
-
throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
|
|
174
|
-
scriptProof = (0, core_1.buildScriptProof)(m.script);
|
|
175
|
-
}
|
|
176
|
-
scriptProofs.push(scriptProof);
|
|
177
|
-
if (m.signature) {
|
|
178
|
-
signatures.push(m.signature);
|
|
179
|
-
}
|
|
180
|
-
else if (m.signer) {
|
|
181
|
-
signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
|
|
188
|
-
const witnessBytes = (0, omnia_1.serializeOmniaWitness)({ signatures, coinProofs, scriptProofs });
|
|
189
|
-
if (chainProvider.submitTransaction) {
|
|
190
|
-
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
191
|
-
if (submitted.success === false || !submitted.txpowid) {
|
|
192
|
-
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
193
|
-
}
|
|
194
|
-
fundingTxId = submitted.txpowid;
|
|
195
|
-
}
|
|
196
|
-
else {
|
|
197
|
-
const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
|
|
198
|
-
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
|
|
199
|
-
const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
|
|
200
|
-
const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
201
|
-
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
202
|
-
if (broadcast.success === false) {
|
|
203
|
-
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
204
|
-
}
|
|
205
|
-
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
206
|
-
}
|
|
226
|
+
fundingDigest = (0, omnia_1.computeOmniaTxDigest)(fundingDraft);
|
|
227
|
+
fundingTxBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
|
|
207
228
|
fundingCoinId = (0, omnia_1.minimaOutputCoinIdsForDraft)(fundingDraft)[0];
|
|
229
|
+
pendingCommitment = fundingDigest;
|
|
208
230
|
}
|
|
209
231
|
else {
|
|
210
|
-
// In-memory / test path: sign the factory state commitment instead.
|
|
211
232
|
pendingCommitment = (0, commitment_js_1.computeFactoryStateCommitment)(factoryId, 1, allocations, []);
|
|
212
233
|
}
|
|
213
|
-
// Sign with the proposer's lease (full bundle preserved so verify override is available).
|
|
214
|
-
const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
|
|
215
234
|
const initialEntry = {
|
|
216
235
|
sequence: 0,
|
|
217
236
|
timestamp: Date.now(),
|
|
@@ -232,16 +251,69 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
|
|
|
232
251
|
stateLog: [initialEntry],
|
|
233
252
|
fundingScript: script,
|
|
234
253
|
fundingAddress: address,
|
|
235
|
-
fundingTxId,
|
|
236
|
-
fundingCoinId,
|
|
254
|
+
fundingTxId: undefined,
|
|
255
|
+
fundingCoinId: undefined,
|
|
237
256
|
pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
|
|
238
|
-
pendingSignatures: {
|
|
257
|
+
pendingSignatures: {},
|
|
239
258
|
};
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
259
|
+
return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Broadcast the prepared factory funding (when on-chain) and record opening
|
|
263
|
+
* signatures. When every participant signature is supplied the factory commits.
|
|
264
|
+
*/
|
|
265
|
+
async function finalizeFactoryOpening(plan, opts, chainProvider) {
|
|
266
|
+
let factory = plan.factory;
|
|
267
|
+
if (plan.onChain) {
|
|
268
|
+
if (!chainProvider || !plan.fundingTxBytes)
|
|
269
|
+
throw new Error('Factory funding requires a chain provider');
|
|
270
|
+
const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
|
|
271
|
+
const signatures = [];
|
|
272
|
+
const coinProofs = [];
|
|
273
|
+
const scriptProofs = [];
|
|
274
|
+
for (const participant of factory.participants) {
|
|
275
|
+
const signature = opts.fundingSignatures?.[participant.partyId];
|
|
276
|
+
if (!signature)
|
|
277
|
+
throw new Error(`Missing funding signature for factory party '${participant.partyId}'`);
|
|
278
|
+
const material = materials.get(participant.partyId);
|
|
279
|
+
if (!material)
|
|
280
|
+
throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
|
|
281
|
+
coinProofs.push(material.coinProof);
|
|
282
|
+
const scriptProof = material.scriptProof ?? (material.script ? (0, core_1.buildScriptProof)(material.script) : undefined);
|
|
283
|
+
if (!scriptProof)
|
|
284
|
+
throw new Error(`Missing script or scriptProof for factory party '${participant.partyId}'`);
|
|
285
|
+
scriptProofs.push(scriptProof);
|
|
286
|
+
signatures.push(signature);
|
|
287
|
+
}
|
|
288
|
+
const witnessBytes = (0, omnia_1.serializeOmniaWitness)({ signatures, coinProofs, scriptProofs });
|
|
289
|
+
let fundingTxId;
|
|
290
|
+
if (chainProvider.submitTransaction) {
|
|
291
|
+
const submitted = await chainProvider.submitTransaction(plan.fundingTxBytes, witnessBytes);
|
|
292
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
293
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
294
|
+
}
|
|
295
|
+
fundingTxId = submitted.txpowid;
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
|
|
299
|
+
const txBody = (0, txpow_1.serializeTxBody)(plan.fundingTxBytes, witnessBytes, { txnDifficulty });
|
|
300
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
|
|
301
|
+
const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
302
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
303
|
+
if (broadcast.success === false) {
|
|
304
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
305
|
+
}
|
|
306
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
307
|
+
}
|
|
308
|
+
factory = {
|
|
309
|
+
...factory,
|
|
310
|
+
fundingTxId,
|
|
311
|
+
fundingCoinId: plan.fundingCoinId,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
|
|
315
|
+
const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
|
|
316
|
+
return allSigned ? commitOpening(factory) : factory;
|
|
245
317
|
}
|
|
246
318
|
// ─── acceptFactory ────────────────────────────────────────────────────────────
|
|
247
319
|
/**
|
|
@@ -258,7 +330,7 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
|
|
|
258
330
|
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
259
331
|
* must match a registered participant not yet signed).
|
|
260
332
|
*/
|
|
261
|
-
async function acceptFactory(factory, bundle) {
|
|
333
|
+
async function acceptFactory(factory, bundle, opts) {
|
|
262
334
|
if (factory.status !== 'opening') {
|
|
263
335
|
throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
|
|
264
336
|
}
|
|
@@ -272,13 +344,14 @@ async function acceptFactory(factory, bundle) {
|
|
|
272
344
|
if (factory.pendingSignatures[participant.partyId]) {
|
|
273
345
|
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
274
346
|
}
|
|
275
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
347
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
276
348
|
const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
|
|
277
349
|
const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
|
|
278
350
|
const updatedFactory = { ...factory, pendingSignatures: newSigs };
|
|
279
|
-
// When all N parties have signed, commit the opening
|
|
351
|
+
// When all N parties have signed, commit the opening unless the host is
|
|
352
|
+
// waiting for funding evidence (on-chain) or the proposer's FINALIZED.
|
|
280
353
|
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
281
|
-
if (allSigned) {
|
|
354
|
+
if (allSigned && !opts?.deferCommit) {
|
|
282
355
|
return commitOpening(updatedFactory);
|
|
283
356
|
}
|
|
284
357
|
return updatedFactory;
|
|
@@ -300,7 +373,7 @@ async function signFactoryOpening(factory, bundle) {
|
|
|
300
373
|
if (factory.pendingSignatures[participant.partyId]) {
|
|
301
374
|
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
302
375
|
}
|
|
303
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
376
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
304
377
|
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
305
378
|
treeId: `omnia-factory-${factory.factoryId}`,
|
|
306
379
|
purpose: 'factory-open',
|
|
@@ -333,7 +406,7 @@ function verifyFactorySignature(factory, partyId, signature, verify) {
|
|
|
333
406
|
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
334
407
|
if (!participant)
|
|
335
408
|
return false;
|
|
336
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
409
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
337
410
|
const verifyFn = verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
|
|
338
411
|
try {
|
|
339
412
|
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
@@ -433,3 +506,125 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
|
|
|
433
506
|
enforceConservation(updated);
|
|
434
507
|
return updated;
|
|
435
508
|
}
|
|
509
|
+
// ─── Peer-supplied state validation ──────────────────────────────────────────
|
|
510
|
+
function jsonSafeForCompare(value) {
|
|
511
|
+
if (typeof value === 'bigint')
|
|
512
|
+
return value.toString();
|
|
513
|
+
if (Array.isArray(value))
|
|
514
|
+
return value.map(jsonSafeForCompare);
|
|
515
|
+
if (value && typeof value === 'object') {
|
|
516
|
+
const entries = Object.entries(value)
|
|
517
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
518
|
+
.map(([k, v]) => [k, jsonSafeForCompare(v)]);
|
|
519
|
+
return Object.fromEntries(entries);
|
|
520
|
+
}
|
|
521
|
+
return value;
|
|
522
|
+
}
|
|
523
|
+
function factoryTermsFingerprint(f) {
|
|
524
|
+
return JSON.stringify(jsonSafeForCompare({
|
|
525
|
+
factoryId: f.factoryId,
|
|
526
|
+
participants: f.participants,
|
|
527
|
+
totalValue: f.totalValue,
|
|
528
|
+
tokenId: f.tokenId,
|
|
529
|
+
tokenScale: f.tokenScale,
|
|
530
|
+
allocations: f.allocations,
|
|
531
|
+
virtualChannels: f.virtualChannels,
|
|
532
|
+
currentSequence: f.currentSequence,
|
|
533
|
+
stateLog: f.stateLog,
|
|
534
|
+
fundingScript: f.fundingScript,
|
|
535
|
+
fundingAddress: f.fundingAddress,
|
|
536
|
+
pendingCommitment: f.pendingCommitment,
|
|
537
|
+
}));
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
|
|
541
|
+
* accepted factory. The peer may only fill in the funding references and add
|
|
542
|
+
* valid opening signatures; every term, commitment and existing signature must
|
|
543
|
+
* be identical. Returns the validated factory to store.
|
|
544
|
+
*/
|
|
545
|
+
function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
|
|
546
|
+
if (!incoming || incoming.factoryId !== known.factoryId) {
|
|
547
|
+
throw new Error('FACTORY_FINALIZED for a different factory');
|
|
548
|
+
}
|
|
549
|
+
if (senderPublicKeyDigest && !known.participants.some(p => p.publicKeyDigest === senderPublicKeyDigest)) {
|
|
550
|
+
throw new Error('FACTORY_FINALIZED sender is not a factory participant');
|
|
551
|
+
}
|
|
552
|
+
const terms = (f) => JSON.stringify(jsonSafeForCompare({
|
|
553
|
+
participants: f.participants,
|
|
554
|
+
totalValue: f.totalValue,
|
|
555
|
+
tokenId: f.tokenId,
|
|
556
|
+
tokenScale: f.tokenScale,
|
|
557
|
+
allocations: f.allocations,
|
|
558
|
+
virtualChannels: f.virtualChannels,
|
|
559
|
+
fundingScript: f.fundingScript,
|
|
560
|
+
fundingAddress: f.fundingAddress,
|
|
561
|
+
}));
|
|
562
|
+
if (terms(known) !== terms(incoming)) {
|
|
563
|
+
throw new Error('FACTORY_FINALIZED changes factory terms');
|
|
564
|
+
}
|
|
565
|
+
if (known.fundingTxId && incoming.fundingTxId !== known.fundingTxId) {
|
|
566
|
+
throw new Error('FACTORY_FINALIZED changes the funding transaction');
|
|
567
|
+
}
|
|
568
|
+
if (known.fundingCoinId && incoming.fundingCoinId !== known.fundingCoinId) {
|
|
569
|
+
throw new Error('FACTORY_FINALIZED changes the funding coin');
|
|
570
|
+
}
|
|
571
|
+
if (known.status === 'closed' && incoming.status !== 'closed') {
|
|
572
|
+
throw new Error('FACTORY_FINALIZED cannot reopen a closed factory');
|
|
573
|
+
}
|
|
574
|
+
// The expected transition for a proposal this host accepted with every
|
|
575
|
+
// participant signature present is the deterministic commit: sequence 1, an
|
|
576
|
+
// 'accept' log entry, cleared pending commitment and signatures.
|
|
577
|
+
if (known.status === 'opening' && incoming.status === 'active') {
|
|
578
|
+
if (known.currentSequence !== 0 || incoming.currentSequence !== 1) {
|
|
579
|
+
throw new Error('FACTORY_FINALIZED has an invalid sequence for an opening');
|
|
580
|
+
}
|
|
581
|
+
if (!known.pendingCommitment) {
|
|
582
|
+
throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
|
|
583
|
+
}
|
|
584
|
+
const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
585
|
+
const signatures = known.pendingSignatures ?? {};
|
|
586
|
+
for (const participant of known.participants) {
|
|
587
|
+
const sig = signatures[participant.partyId];
|
|
588
|
+
if (!sig)
|
|
589
|
+
throw new Error(`FACTORY_FINALIZED activates a factory missing the signature for '${participant.partyId}'`);
|
|
590
|
+
if (!(0, omnia_1.verifyChannelSignature)(sig, commitment, participant.publicKeyDigest)) {
|
|
591
|
+
throw new Error(`FACTORY_FINALIZED activates a factory with an invalid signature for '${participant.partyId}'`);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (incoming.pendingCommitment) {
|
|
595
|
+
throw new Error('FACTORY_FINALIZED must clear the pending commitment when it activates');
|
|
596
|
+
}
|
|
597
|
+
if (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0) {
|
|
598
|
+
throw new Error('FACTORY_FINALIZED must clear pending signatures when it activates');
|
|
599
|
+
}
|
|
600
|
+
const log = incoming.stateLog ?? [];
|
|
601
|
+
if (log.length !== (known.stateLog?.length ?? 0) + 1) {
|
|
602
|
+
throw new Error('FACTORY_FINALIZED has an unexpected state log');
|
|
603
|
+
}
|
|
604
|
+
const last = log[log.length - 1];
|
|
605
|
+
if (!last || last.event !== 'accept' || last.sequence !== 1) {
|
|
606
|
+
throw new Error('FACTORY_FINALIZED is missing the accept log entry');
|
|
607
|
+
}
|
|
608
|
+
if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
|
|
609
|
+
throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
|
|
610
|
+
}
|
|
611
|
+
return { ...incoming, pendingSignatures: {} };
|
|
612
|
+
}
|
|
613
|
+
if (known.status === 'active' && incoming.status === 'active') {
|
|
614
|
+
// Funding references may be filled in after activation; terms are already checked.
|
|
615
|
+
return { ...incoming };
|
|
616
|
+
}
|
|
617
|
+
if (known.status === 'opening' && incoming.status === 'opening') {
|
|
618
|
+
// Funding references only; signatures may not be removed or altered.
|
|
619
|
+
const knownSigs = known.pendingSignatures ?? {};
|
|
620
|
+
const incomingSigs = incoming.pendingSignatures ?? {};
|
|
621
|
+
for (const [partyId, sig] of Object.entries(knownSigs)) {
|
|
622
|
+
const next = incomingSigs[partyId];
|
|
623
|
+
if (!next || Buffer.from(next).toString('hex') !== Buffer.from(sig).toString('hex')) {
|
|
624
|
+
throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return { ...incoming, pendingSignatures: { ...incomingSigs } };
|
|
628
|
+
}
|
|
629
|
+
throw new Error('FACTORY_FINALIZED has an unsupported status transition');
|
|
630
|
+
}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
export type { FactoryOpeningPlan, FinalizeFactoryOpeningOptions } from './factory.js';
|
|
1
2
|
export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
2
3
|
export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
|
|
3
4
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
5
|
export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
|
|
5
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
|
+
export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
|
|
6
7
|
export type { FactoryOpeningSignature } from './factory.js';
|
|
7
8
|
export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
|
|
8
9
|
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.assembleVirtualChannelClose = exports.signVirtualChannelClose = exports.buildVirtualChannelClose = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
|
|
3
|
+
exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.assembleVirtualChannelClose = exports.signVirtualChannelClose = exports.buildVirtualChannelClose = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.assertFactoryFinalized = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.finalizeFactoryOpening = exports.buildFactoryOpening = exports.proposeFactoryOpening = exports.createFactoryFromPlan = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
|
|
4
4
|
var script_js_1 = require("./script.js");
|
|
5
5
|
Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
|
|
6
6
|
Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
|
|
@@ -26,12 +26,17 @@ var commitment_js_1 = require("./commitment.js");
|
|
|
26
26
|
Object.defineProperty(exports, "computeFactoryStateCommitment", { enumerable: true, get: function () { return commitment_js_1.computeFactoryStateCommitment; } });
|
|
27
27
|
var factory_js_1 = require("./factory.js");
|
|
28
28
|
Object.defineProperty(exports, "createFactory", { enumerable: true, get: function () { return factory_js_1.createFactory; } });
|
|
29
|
+
Object.defineProperty(exports, "createFactoryFromPlan", { enumerable: true, get: function () { return factory_js_1.createFactoryFromPlan; } });
|
|
30
|
+
Object.defineProperty(exports, "proposeFactoryOpening", { enumerable: true, get: function () { return factory_js_1.proposeFactoryOpening; } });
|
|
31
|
+
Object.defineProperty(exports, "buildFactoryOpening", { enumerable: true, get: function () { return factory_js_1.buildFactoryOpening; } });
|
|
32
|
+
Object.defineProperty(exports, "finalizeFactoryOpening", { enumerable: true, get: function () { return factory_js_1.finalizeFactoryOpening; } });
|
|
29
33
|
Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
|
|
30
34
|
Object.defineProperty(exports, "reallocate", { enumerable: true, get: function () { return factory_js_1.reallocate; } });
|
|
31
35
|
Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: function () { return factory_js_1.enforceConservation; } });
|
|
32
36
|
Object.defineProperty(exports, "signFactoryOpening", { enumerable: true, get: function () { return factory_js_1.signFactoryOpening; } });
|
|
33
37
|
Object.defineProperty(exports, "verifyFactorySignature", { enumerable: true, get: function () { return factory_js_1.verifyFactorySignature; } });
|
|
34
38
|
Object.defineProperty(exports, "applyFactorySignature", { enumerable: true, get: function () { return factory_js_1.applyFactorySignature; } });
|
|
39
|
+
Object.defineProperty(exports, "assertFactoryFinalized", { enumerable: true, get: function () { return factory_js_1.assertFactoryFinalized; } });
|
|
35
40
|
// RFC-035 B2 — factory opening round-trip over the coordination transport.
|
|
36
41
|
var coordination_js_1 = require("./coordination.js");
|
|
37
42
|
Object.defineProperty(exports, "createFactoryCoordination", { enumerable: true, get: function () { return coordination_js_1.createFactoryCoordination; } });
|
package/dist/cjs/virtual.js
CHANGED
|
@@ -158,12 +158,14 @@ function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
|
158
158
|
publicKeyDigest: partyAMeta.publicKeyDigest,
|
|
159
159
|
addressIndex: partyAMeta.addressIndex,
|
|
160
160
|
settlementAddress: partyAMeta.settlementAddress,
|
|
161
|
+
transportPubkey: partyAMeta.transportPubkey,
|
|
161
162
|
};
|
|
162
163
|
const partyB = {
|
|
163
164
|
partyId: partyBId,
|
|
164
165
|
publicKeyDigest: partyBMeta.publicKeyDigest,
|
|
165
166
|
addressIndex: partyBMeta.addressIndex,
|
|
166
167
|
settlementAddress: partyBMeta.settlementAddress,
|
|
168
|
+
transportPubkey: partyBMeta.transportPubkey,
|
|
167
169
|
};
|
|
168
170
|
const channel = {
|
|
169
171
|
channelId: plan.vcId,
|
package/dist/factory.d.ts
CHANGED
|
@@ -39,6 +39,44 @@ export declare function enforceConservation(factory: ChannelFactory): void;
|
|
|
39
39
|
* Defaults to 0.
|
|
40
40
|
*/
|
|
41
41
|
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
|
|
42
|
+
/**
|
|
43
|
+
* Sign the opening commitment for a plan and record the proposer's signature.
|
|
44
|
+
* Nothing is broadcast and no funding signature is requested, so callers can
|
|
45
|
+
* propose the factory to the peer first (CAN-020 ordering).
|
|
46
|
+
*/
|
|
47
|
+
export declare function proposeFactoryOpening(plan: FactoryOpeningPlan, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
|
|
48
|
+
/**
|
|
49
|
+
* Finish a plan: collect the funding-witness signatures from the plan's
|
|
50
|
+
* funding materials (or use the supplied ones), broadcast the funding
|
|
51
|
+
* transaction when the plan is on-chain, and commit the opening once every
|
|
52
|
+
* participant has signed.
|
|
53
|
+
*/
|
|
54
|
+
export declare function createFactoryFromPlan(plan: FactoryOpeningPlan, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider): Promise<ChannelFactory>;
|
|
55
|
+
/** A factory opening built without any signatures or broadcast. */
|
|
56
|
+
export interface FactoryOpeningPlan {
|
|
57
|
+
factory: ChannelFactory;
|
|
58
|
+
fundingTxBytes?: Uint8Array;
|
|
59
|
+
fundingDigest?: Uint8Array;
|
|
60
|
+
fundingCoinId?: string;
|
|
61
|
+
fundingMaterials?: FactoryFundingMaterial[];
|
|
62
|
+
onChain: boolean;
|
|
63
|
+
}
|
|
64
|
+
export interface FinalizeFactoryOpeningOptions {
|
|
65
|
+
/** Funding-witness signatures for every participant (on-chain only). */
|
|
66
|
+
fundingSignatures?: Record<string, Uint8Array>;
|
|
67
|
+
/** Factory opening signatures to record on the proposal. */
|
|
68
|
+
openingSignatures: Record<string, Uint8Array>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Build a factory and (when every participant supplies a funding coin) its
|
|
72
|
+
* deterministic funding draft, without signing or broadcasting.
|
|
73
|
+
*/
|
|
74
|
+
export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[]): Promise<FactoryOpeningPlan>;
|
|
75
|
+
/**
|
|
76
|
+
* Broadcast the prepared factory funding (when on-chain) and record opening
|
|
77
|
+
* signatures. When every participant signature is supplied the factory commits.
|
|
78
|
+
*/
|
|
79
|
+
export declare function finalizeFactoryOpening(plan: FactoryOpeningPlan, opts: FinalizeFactoryOpeningOptions, chainProvider?: ChainStateProvider): Promise<ChannelFactory>;
|
|
42
80
|
/**
|
|
43
81
|
* Counterparty co-signs the factory proposal.
|
|
44
82
|
*
|
|
@@ -53,7 +91,9 @@ export declare function createFactory(participants: FactoryParticipant[], tokenI
|
|
|
53
91
|
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
54
92
|
* must match a registered participant not yet signed).
|
|
55
93
|
*/
|
|
56
|
-
export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle
|
|
94
|
+
export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle, opts?: {
|
|
95
|
+
deferCommit?: boolean;
|
|
96
|
+
}): Promise<ChannelFactory>;
|
|
57
97
|
/** A co-signer's opening signature, held until the opening is confirmed. */
|
|
58
98
|
export interface FactoryOpeningSignature {
|
|
59
99
|
factoryId: string;
|
|
@@ -89,3 +129,10 @@ export declare function applyFactorySignature(factory: ChannelFactory, partyId:
|
|
|
89
129
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
90
130
|
*/
|
|
91
131
|
export declare function reallocate(factory: ChannelFactory, fromPartyId: string, toPartyId: string, amount: bigint, leaseProviders: Record<string, WotsLeaseBundle>): Promise<ChannelFactory>;
|
|
132
|
+
/**
|
|
133
|
+
* Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
|
|
134
|
+
* accepted factory. The peer may only fill in the funding references and add
|
|
135
|
+
* valid opening signatures; every term, commitment and existing signature must
|
|
136
|
+
* be identical. Returns the validated factory to store.
|
|
137
|
+
*/
|
|
138
|
+
export declare function assertFactoryFinalized(known: ChannelFactory, incoming: ChannelFactory, senderPublicKeyDigest?: string): ChannelFactory;
|