@totemsdk/omnia-factory 0.7.1 → 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/README.md CHANGED
@@ -68,3 +68,8 @@ await provider.broadcastTxPoW(settlementHex);
68
68
  - [`@totemsdk/omnia-router`](https://www.npmjs.com/package/@totemsdk/omnia-router) — route payments across factory and direct channels
69
69
  - [`@totemsdk/wots-lease`](https://www.npmjs.com/package/@totemsdk/wots-lease) — WOTS key safety for factory signing
70
70
  - [`@totemsdk/tx-builder`](https://www.npmjs.com/package/@totemsdk/tx-builder) — builds the N-of-N funding transaction
71
+
72
+
73
+ ## Testing
74
+
75
+ Tests live outside the published package in `tests/unit/omnia-factory/`. Package `test:*` scripts are repository delegates; tests are not shipped.
@@ -39,6 +39,19 @@ 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>;
42
55
  /** A factory opening built without any signatures or broadcast. */
43
56
  export interface FactoryOpeningPlan {
44
57
  factory: ChannelFactory;
@@ -78,7 +91,9 @@ export declare function finalizeFactoryOpening(plan: FactoryOpeningPlan, opts: F
78
91
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
79
92
  * must match a registered participant not yet signed).
80
93
  */
81
- export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
94
+ export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle, opts?: {
95
+ deferCommit?: boolean;
96
+ }): Promise<ChannelFactory>;
82
97
  /** A co-signer's opening signature, held until the opening is confirmed. */
83
98
  export interface FactoryOpeningSignature {
84
99
  factoryId: string;
@@ -114,3 +129,10 @@ export declare function applyFactorySignature(factory: ChannelFactory, partyId:
114
129
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
115
130
  */
116
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;
@@ -2,6 +2,8 @@
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;
5
7
  exports.buildFactoryOpening = buildFactoryOpening;
6
8
  exports.finalizeFactoryOpening = finalizeFactoryOpening;
7
9
  exports.acceptFactory = acceptFactory;
@@ -9,6 +11,7 @@ exports.signFactoryOpening = signFactoryOpening;
9
11
  exports.verifyFactorySignature = verifyFactorySignature;
10
12
  exports.applyFactorySignature = applyFactorySignature;
11
13
  exports.reallocate = reallocate;
14
+ exports.assertFactoryFinalized = assertFactoryFinalized;
12
15
  const wasm_1 = require("@totemsdk/core/wasm");
13
16
  const wasm_2 = require("@totemsdk/core/wasm");
14
17
  const core_1 = require("@totemsdk/core");
@@ -122,125 +125,69 @@ function generateFactoryId(participants, tokenId, tokenScale) {
122
125
  * Defaults to 0.
123
126
  */
124
127
  async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
125
- if (participants.length < 2) {
126
- throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
127
- }
128
- // Identify the proposer by public key digest.
129
- const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
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);
130
137
  if (!proposer) {
131
138
  throw new Error('signer.publicKeyDigest does not match any registered factory participant');
132
139
  }
133
- const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
134
- const allocations = {};
135
- for (const p of participants) {
136
- allocations[p.partyId] = p.contributionAmount;
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');
137
151
  }
138
- const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
139
- const factoryId = generateFactoryId(participants, tokenId, tokenScale);
140
- // ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
141
- let fundingTxId;
142
- let fundingCoinId;
143
- let pendingCommitment;
144
- const allHaveCoinId = participants.every(p => p.fundingCoinId);
145
- if (allHaveCoinId && chainProvider) {
146
- const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
147
- // The transaction input address must be the *funding coin's* address, not
148
- // the participant's settlement address. Callers supply it directly or via
149
- // the funding coin script.
150
- const inputAddresses = participants.map(p => {
151
- const m = materialByParty.get(p.partyId);
152
- return m?.coinAddress ?? (m?.script ? (0, core_1.computeScriptAddress)(m.script) : '');
153
- });
154
- if (inputAddresses.some(a => !a)) {
155
- throw new Error('createFactory on-chain requires funding material (coinAddress or script) for every participant');
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');
156
170
  }
157
- const tip = await chainProvider.getTip();
158
- const escapeBlock = tip.block + script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS;
159
- 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)]);
160
- // Production signatures must cover the canonical Minima transaction ID.
161
- pendingCommitment = (0, omnia_1.computeOmniaTxDigest)(fundingDraft);
162
- // Assemble the real witness: one CoinProof + ScriptProof + signature per
163
- // input coin (the factory's own MULTISIG script is the *output* script).
164
- const signatures = [];
165
- const coinProofs = [];
166
- const scriptProofs = [];
167
- for (const p of participants) {
168
- const m = materialByParty.get(p.partyId);
169
- if (!m)
170
- throw new Error(`Missing funding material for factory party '${p.partyId}'`);
171
- coinProofs.push(m.coinProof);
172
- let scriptProof = m.scriptProof;
173
- if (!scriptProof) {
174
- if (!m.script)
175
- throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
176
- scriptProof = (0, core_1.buildScriptProof)(m.script);
177
- }
178
- scriptProofs.push(scriptProof);
179
- if (m.signature) {
180
- signatures.push(m.signature);
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;
181
179
  }
182
- else if (m.signer) {
183
- signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
180
+ else if (material.signer) {
181
+ fundingSignatures[participant.partyId] = Uint8Array.from(await material.signer(plan.fundingDigest));
184
182
  }
185
183
  else {
186
- throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
184
+ throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
187
185
  }
188
186
  }
189
- const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
190
- const witnessBytes = (0, omnia_1.serializeOmniaWitness)({ signatures, coinProofs, scriptProofs });
191
- if (chainProvider.submitTransaction) {
192
- const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
193
- if (submitted.success === false || !submitted.txpowid) {
194
- throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
195
- }
196
- fundingTxId = submitted.txpowid;
197
- }
198
- else {
199
- const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
200
- const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
201
- const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
202
- const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
203
- const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
204
- if (broadcast.success === false) {
205
- throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
206
- }
207
- fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
208
- }
209
- fundingCoinId = (0, omnia_1.minimaOutputCoinIdsForDraft)(fundingDraft)[0];
210
- }
211
- else {
212
- // In-memory / test path: sign the factory state commitment instead.
213
- pendingCommitment = (0, commitment_js_1.computeFactoryStateCommitment)(factoryId, 1, allocations, []);
187
+ factory = await finalizeFactoryOpening(plan, { fundingSignatures, openingSignatures: factory.pendingSignatures }, chainProvider);
214
188
  }
215
- // Sign with the proposer's lease (full bundle preserved so verify override is available).
216
- const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
217
- const initialEntry = {
218
- sequence: 0,
219
- timestamp: Date.now(),
220
- event: 'create',
221
- allocations: { ...allocations },
222
- virtualChannelIds: [],
223
- };
224
- const factory = {
225
- factoryId,
226
- participants,
227
- totalValue,
228
- tokenId,
229
- tokenScale,
230
- allocations: { ...allocations },
231
- virtualChannels: [],
232
- currentSequence: 0,
233
- status: 'opening',
234
- stateLog: [initialEntry],
235
- fundingScript: script,
236
- fundingAddress: address,
237
- fundingTxId,
238
- fundingCoinId,
239
- pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
240
- pendingSignatures: { [proposer.partyId]: proposerSig },
241
- };
242
189
  // If proposer is the only participant (edge case), activate immediately.
243
- if (participants.length === 1) {
190
+ if (factory.participants.length === 1) {
244
191
  return commitOpening(factory);
245
192
  }
246
193
  return factory;
@@ -383,7 +330,7 @@ async function finalizeFactoryOpening(plan, opts, chainProvider) {
383
330
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
384
331
  * must match a registered participant not yet signed).
385
332
  */
386
- async function acceptFactory(factory, bundle) {
333
+ async function acceptFactory(factory, bundle, opts) {
387
334
  if (factory.status !== 'opening') {
388
335
  throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
389
336
  }
@@ -397,13 +344,14 @@ async function acceptFactory(factory, bundle) {
397
344
  if (factory.pendingSignatures[participant.partyId]) {
398
345
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
399
346
  }
400
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
347
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
401
348
  const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
402
349
  const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
403
350
  const updatedFactory = { ...factory, pendingSignatures: newSigs };
404
- // 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.
405
353
  const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
406
- if (allSigned) {
354
+ if (allSigned && !opts?.deferCommit) {
407
355
  return commitOpening(updatedFactory);
408
356
  }
409
357
  return updatedFactory;
@@ -425,7 +373,7 @@ async function signFactoryOpening(factory, bundle) {
425
373
  if (factory.pendingSignatures[participant.partyId]) {
426
374
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
427
375
  }
428
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
376
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
429
377
  const reservation = await bundle.leaseProvider.reserveKeyUse({
430
378
  treeId: `omnia-factory-${factory.factoryId}`,
431
379
  purpose: 'factory-open',
@@ -458,7 +406,7 @@ function verifyFactorySignature(factory, partyId, signature, verify) {
458
406
  const participant = factory.participants.find(p => p.partyId === partyId);
459
407
  if (!participant)
460
408
  return false;
461
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
409
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
462
410
  const verifyFn = verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
463
411
  try {
464
412
  return verifyFn(signature, commitment, participant.publicKeyDigest);
@@ -558,3 +506,125 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
558
506
  enforceConservation(updated);
559
507
  return updated;
560
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
+ }
@@ -3,7 +3,7 @@ export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, Factory
3
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';
4
4
  export { computeFactoryStateCommitment } from './commitment.js';
5
5
  export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
6
- export { createFactory, buildFactoryOpening, finalizeFactoryOpening, 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';
7
7
  export type { FactoryOpeningSignature } from './factory.js';
8
8
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
9
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.finalizeFactoryOpening = exports.buildFactoryOpening = 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,6 +26,8 @@ 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; } });
29
31
  Object.defineProperty(exports, "buildFactoryOpening", { enumerable: true, get: function () { return factory_js_1.buildFactoryOpening; } });
30
32
  Object.defineProperty(exports, "finalizeFactoryOpening", { enumerable: true, get: function () { return factory_js_1.finalizeFactoryOpening; } });
31
33
  Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
@@ -34,6 +36,7 @@ Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: f
34
36
  Object.defineProperty(exports, "signFactoryOpening", { enumerable: true, get: function () { return factory_js_1.signFactoryOpening; } });
35
37
  Object.defineProperty(exports, "verifyFactorySignature", { enumerable: true, get: function () { return factory_js_1.verifyFactorySignature; } });
36
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; } });
37
40
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
38
41
  var coordination_js_1 = require("./coordination.js");
39
42
  Object.defineProperty(exports, "createFactoryCoordination", { enumerable: true, get: function () { return coordination_js_1.createFactoryCoordination; } });
package/dist/factory.d.ts CHANGED
@@ -39,6 +39,19 @@ 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>;
42
55
  /** A factory opening built without any signatures or broadcast. */
43
56
  export interface FactoryOpeningPlan {
44
57
  factory: ChannelFactory;
@@ -78,7 +91,9 @@ export declare function finalizeFactoryOpening(plan: FactoryOpeningPlan, opts: F
78
91
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
79
92
  * must match a registered participant not yet signed).
80
93
  */
81
- export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
94
+ export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle, opts?: {
95
+ deferCommit?: boolean;
96
+ }): Promise<ChannelFactory>;
82
97
  /** A co-signer's opening signature, held until the opening is confirmed. */
83
98
  export interface FactoryOpeningSignature {
84
99
  factoryId: string;
@@ -114,3 +129,10 @@ export declare function applyFactorySignature(factory: ChannelFactory, partyId:
114
129
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
115
130
  */
116
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;
package/dist/factory.js CHANGED
@@ -111,125 +111,69 @@ function generateFactoryId(participants, tokenId, tokenScale) {
111
111
  * Defaults to 0.
112
112
  */
113
113
  export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
114
- if (participants.length < 2) {
115
- throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
116
- }
117
- // Identify the proposer by public key digest.
118
- const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
114
+ // One plan, one factory ID: build the opening once and reuse it for the
115
+ // proposal, the local record and the funding transaction. Rebuilding here
116
+ // would generate a different ID (the ID includes a random nonce) and the
117
+ // peer would accept a factory this host never stored.
118
+ const plan = await buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding);
119
+ return createFactoryFromPlan(plan, bundle, chainProvider);
120
+ }
121
+ function findProposer(factory, bundle) {
122
+ const proposer = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
119
123
  if (!proposer) {
120
124
  throw new Error('signer.publicKeyDigest does not match any registered factory participant');
121
125
  }
122
- const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
123
- const allocations = {};
124
- for (const p of participants) {
125
- allocations[p.partyId] = p.contributionAmount;
126
+ return proposer;
127
+ }
128
+ /**
129
+ * Sign the opening commitment for a plan and record the proposer's signature.
130
+ * Nothing is broadcast and no funding signature is requested, so callers can
131
+ * propose the factory to the peer first (CAN-020 ordering).
132
+ */
133
+ export async function proposeFactoryOpening(plan, bundle) {
134
+ const proposer = findProposer(plan.factory, bundle);
135
+ if (!plan.factory.pendingCommitment) {
136
+ throw new Error('Factory plan has no pending commitment');
126
137
  }
127
- const { script, address } = buildAndHashFactoryScript(participants);
128
- const factoryId = generateFactoryId(participants, tokenId, tokenScale);
129
- // ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
130
- let fundingTxId;
131
- let fundingCoinId;
132
- let pendingCommitment;
133
- const allHaveCoinId = participants.every(p => p.fundingCoinId);
134
- if (allHaveCoinId && chainProvider) {
135
- const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
136
- // The transaction input address must be the *funding coin's* address, not
137
- // the participant's settlement address. Callers supply it directly or via
138
- // the funding coin script.
139
- const inputAddresses = participants.map(p => {
140
- const m = materialByParty.get(p.partyId);
141
- return m?.coinAddress ?? (m?.script ? computeScriptAddress(m.script) : '');
142
- });
143
- if (inputAddresses.some(a => !a)) {
144
- throw new Error('createFactory on-chain requires funding material (coinAddress or script) for every participant');
138
+ const commitment = Buffer.from(plan.factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
139
+ const sig = await leaseSign(plan.factory.factoryId, commitment, 'factory-open', proposer, bundle);
140
+ return {
141
+ ...plan.factory,
142
+ pendingSignatures: { [proposer.partyId]: sig },
143
+ };
144
+ }
145
+ /**
146
+ * Finish a plan: collect the funding-witness signatures from the plan's
147
+ * funding materials (or use the supplied ones), broadcast the funding
148
+ * transaction when the plan is on-chain, and commit the opening once every
149
+ * participant has signed.
150
+ */
151
+ export async function createFactoryFromPlan(plan, bundle, chainProvider) {
152
+ let factory = await proposeFactoryOpening(plan, bundle);
153
+ if (plan.onChain) {
154
+ if (!chainProvider || !plan.fundingTxBytes || !plan.fundingDigest) {
155
+ throw new Error('Factory funding requires a chain provider and a complete funding plan');
145
156
  }
146
- const tip = await chainProvider.getTip();
147
- const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
148
- const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
149
- // Production signatures must cover the canonical Minima transaction ID.
150
- pendingCommitment = computeOmniaTxDigest(fundingDraft);
151
- // Assemble the real witness: one CoinProof + ScriptProof + signature per
152
- // input coin (the factory's own MULTISIG script is the *output* script).
153
- const signatures = [];
154
- const coinProofs = [];
155
- const scriptProofs = [];
156
- for (const p of participants) {
157
- const m = materialByParty.get(p.partyId);
158
- if (!m)
159
- throw new Error(`Missing funding material for factory party '${p.partyId}'`);
160
- coinProofs.push(m.coinProof);
161
- let scriptProof = m.scriptProof;
162
- if (!scriptProof) {
163
- if (!m.script)
164
- throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
165
- scriptProof = buildScriptProof(m.script);
166
- }
167
- scriptProofs.push(scriptProof);
168
- if (m.signature) {
169
- signatures.push(m.signature);
157
+ const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
158
+ const fundingSignatures = {};
159
+ for (const participant of factory.participants) {
160
+ const material = materials.get(participant.partyId);
161
+ if (!material)
162
+ throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
163
+ if (material.signature) {
164
+ fundingSignatures[participant.partyId] = material.signature;
170
165
  }
171
- else if (m.signer) {
172
- signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
166
+ else if (material.signer) {
167
+ fundingSignatures[participant.partyId] = Uint8Array.from(await material.signer(plan.fundingDigest));
173
168
  }
174
169
  else {
175
- throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
170
+ throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
176
171
  }
177
172
  }
178
- const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
179
- const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
180
- if (chainProvider.submitTransaction) {
181
- const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
182
- if (submitted.success === false || !submitted.txpowid) {
183
- throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
184
- }
185
- fundingTxId = submitted.txpowid;
186
- }
187
- else {
188
- const txnDifficulty = await resolveTxPowTarget(chainProvider);
189
- const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
190
- const mined = await mineTxPoW(txBody, txnDifficulty);
191
- const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
192
- const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
193
- if (broadcast.success === false) {
194
- throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
195
- }
196
- fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
197
- }
198
- fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
199
- }
200
- else {
201
- // In-memory / test path: sign the factory state commitment instead.
202
- pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
173
+ factory = await finalizeFactoryOpening(plan, { fundingSignatures, openingSignatures: factory.pendingSignatures }, chainProvider);
203
174
  }
204
- // Sign with the proposer's lease (full bundle preserved so verify override is available).
205
- const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
206
- const initialEntry = {
207
- sequence: 0,
208
- timestamp: Date.now(),
209
- event: 'create',
210
- allocations: { ...allocations },
211
- virtualChannelIds: [],
212
- };
213
- const factory = {
214
- factoryId,
215
- participants,
216
- totalValue,
217
- tokenId,
218
- tokenScale,
219
- allocations: { ...allocations },
220
- virtualChannels: [],
221
- currentSequence: 0,
222
- status: 'opening',
223
- stateLog: [initialEntry],
224
- fundingScript: script,
225
- fundingAddress: address,
226
- fundingTxId,
227
- fundingCoinId,
228
- pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
229
- pendingSignatures: { [proposer.partyId]: proposerSig },
230
- };
231
175
  // If proposer is the only participant (edge case), activate immediately.
232
- if (participants.length === 1) {
176
+ if (factory.participants.length === 1) {
233
177
  return commitOpening(factory);
234
178
  }
235
179
  return factory;
@@ -372,7 +316,7 @@ export async function finalizeFactoryOpening(plan, opts, chainProvider) {
372
316
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
373
317
  * must match a registered participant not yet signed).
374
318
  */
375
- export async function acceptFactory(factory, bundle) {
319
+ export async function acceptFactory(factory, bundle, opts) {
376
320
  if (factory.status !== 'opening') {
377
321
  throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
378
322
  }
@@ -386,13 +330,14 @@ export async function acceptFactory(factory, bundle) {
386
330
  if (factory.pendingSignatures[participant.partyId]) {
387
331
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
388
332
  }
389
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
333
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
390
334
  const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
391
335
  const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
392
336
  const updatedFactory = { ...factory, pendingSignatures: newSigs };
393
- // When all N parties have signed, commit the opening.
337
+ // When all N parties have signed, commit the opening unless the host is
338
+ // waiting for funding evidence (on-chain) or the proposer's FINALIZED.
394
339
  const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
395
- if (allSigned) {
340
+ if (allSigned && !opts?.deferCommit) {
396
341
  return commitOpening(updatedFactory);
397
342
  }
398
343
  return updatedFactory;
@@ -414,7 +359,7 @@ export async function signFactoryOpening(factory, bundle) {
414
359
  if (factory.pendingSignatures[participant.partyId]) {
415
360
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
416
361
  }
417
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
362
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
418
363
  const reservation = await bundle.leaseProvider.reserveKeyUse({
419
364
  treeId: `omnia-factory-${factory.factoryId}`,
420
365
  purpose: 'factory-open',
@@ -447,7 +392,7 @@ export function verifyFactorySignature(factory, partyId, signature, verify) {
447
392
  const participant = factory.participants.find(p => p.partyId === partyId);
448
393
  if (!participant)
449
394
  return false;
450
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
395
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
451
396
  const verifyFn = verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
452
397
  try {
453
398
  return verifyFn(signature, commitment, participant.publicKeyDigest);
@@ -547,3 +492,125 @@ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseP
547
492
  enforceConservation(updated);
548
493
  return updated;
549
494
  }
495
+ // ─── Peer-supplied state validation ──────────────────────────────────────────
496
+ function jsonSafeForCompare(value) {
497
+ if (typeof value === 'bigint')
498
+ return value.toString();
499
+ if (Array.isArray(value))
500
+ return value.map(jsonSafeForCompare);
501
+ if (value && typeof value === 'object') {
502
+ const entries = Object.entries(value)
503
+ .sort(([a], [b]) => a.localeCompare(b))
504
+ .map(([k, v]) => [k, jsonSafeForCompare(v)]);
505
+ return Object.fromEntries(entries);
506
+ }
507
+ return value;
508
+ }
509
+ function factoryTermsFingerprint(f) {
510
+ return JSON.stringify(jsonSafeForCompare({
511
+ factoryId: f.factoryId,
512
+ participants: f.participants,
513
+ totalValue: f.totalValue,
514
+ tokenId: f.tokenId,
515
+ tokenScale: f.tokenScale,
516
+ allocations: f.allocations,
517
+ virtualChannels: f.virtualChannels,
518
+ currentSequence: f.currentSequence,
519
+ stateLog: f.stateLog,
520
+ fundingScript: f.fundingScript,
521
+ fundingAddress: f.fundingAddress,
522
+ pendingCommitment: f.pendingCommitment,
523
+ }));
524
+ }
525
+ /**
526
+ * Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
527
+ * accepted factory. The peer may only fill in the funding references and add
528
+ * valid opening signatures; every term, commitment and existing signature must
529
+ * be identical. Returns the validated factory to store.
530
+ */
531
+ export function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
532
+ if (!incoming || incoming.factoryId !== known.factoryId) {
533
+ throw new Error('FACTORY_FINALIZED for a different factory');
534
+ }
535
+ if (senderPublicKeyDigest && !known.participants.some(p => p.publicKeyDigest === senderPublicKeyDigest)) {
536
+ throw new Error('FACTORY_FINALIZED sender is not a factory participant');
537
+ }
538
+ const terms = (f) => JSON.stringify(jsonSafeForCompare({
539
+ participants: f.participants,
540
+ totalValue: f.totalValue,
541
+ tokenId: f.tokenId,
542
+ tokenScale: f.tokenScale,
543
+ allocations: f.allocations,
544
+ virtualChannels: f.virtualChannels,
545
+ fundingScript: f.fundingScript,
546
+ fundingAddress: f.fundingAddress,
547
+ }));
548
+ if (terms(known) !== terms(incoming)) {
549
+ throw new Error('FACTORY_FINALIZED changes factory terms');
550
+ }
551
+ if (known.fundingTxId && incoming.fundingTxId !== known.fundingTxId) {
552
+ throw new Error('FACTORY_FINALIZED changes the funding transaction');
553
+ }
554
+ if (known.fundingCoinId && incoming.fundingCoinId !== known.fundingCoinId) {
555
+ throw new Error('FACTORY_FINALIZED changes the funding coin');
556
+ }
557
+ if (known.status === 'closed' && incoming.status !== 'closed') {
558
+ throw new Error('FACTORY_FINALIZED cannot reopen a closed factory');
559
+ }
560
+ // The expected transition for a proposal this host accepted with every
561
+ // participant signature present is the deterministic commit: sequence 1, an
562
+ // 'accept' log entry, cleared pending commitment and signatures.
563
+ if (known.status === 'opening' && incoming.status === 'active') {
564
+ if (known.currentSequence !== 0 || incoming.currentSequence !== 1) {
565
+ throw new Error('FACTORY_FINALIZED has an invalid sequence for an opening');
566
+ }
567
+ if (!known.pendingCommitment) {
568
+ throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
569
+ }
570
+ const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
571
+ const signatures = known.pendingSignatures ?? {};
572
+ for (const participant of known.participants) {
573
+ const sig = signatures[participant.partyId];
574
+ if (!sig)
575
+ throw new Error(`FACTORY_FINALIZED activates a factory missing the signature for '${participant.partyId}'`);
576
+ if (!verifyChannelSignature(sig, commitment, participant.publicKeyDigest)) {
577
+ throw new Error(`FACTORY_FINALIZED activates a factory with an invalid signature for '${participant.partyId}'`);
578
+ }
579
+ }
580
+ if (incoming.pendingCommitment) {
581
+ throw new Error('FACTORY_FINALIZED must clear the pending commitment when it activates');
582
+ }
583
+ if (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0) {
584
+ throw new Error('FACTORY_FINALIZED must clear pending signatures when it activates');
585
+ }
586
+ const log = incoming.stateLog ?? [];
587
+ if (log.length !== (known.stateLog?.length ?? 0) + 1) {
588
+ throw new Error('FACTORY_FINALIZED has an unexpected state log');
589
+ }
590
+ const last = log[log.length - 1];
591
+ if (!last || last.event !== 'accept' || last.sequence !== 1) {
592
+ throw new Error('FACTORY_FINALIZED is missing the accept log entry');
593
+ }
594
+ if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
595
+ throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
596
+ }
597
+ return { ...incoming, pendingSignatures: {} };
598
+ }
599
+ if (known.status === 'active' && incoming.status === 'active') {
600
+ // Funding references may be filled in after activation; terms are already checked.
601
+ return { ...incoming };
602
+ }
603
+ if (known.status === 'opening' && incoming.status === 'opening') {
604
+ // Funding references only; signatures may not be removed or altered.
605
+ const knownSigs = known.pendingSignatures ?? {};
606
+ const incomingSigs = incoming.pendingSignatures ?? {};
607
+ for (const [partyId, sig] of Object.entries(knownSigs)) {
608
+ const next = incomingSigs[partyId];
609
+ if (!next || Buffer.from(next).toString('hex') !== Buffer.from(sig).toString('hex')) {
610
+ throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
611
+ }
612
+ }
613
+ return { ...incoming, pendingSignatures: { ...incomingSigs } };
614
+ }
615
+ throw new Error('FACTORY_FINALIZED has an unsupported status transition');
616
+ }
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, Factory
3
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';
4
4
  export { computeFactoryStateCommitment } from './commitment.js';
5
5
  export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
6
- export { createFactory, buildFactoryOpening, finalizeFactoryOpening, 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';
7
7
  export type { FactoryOpeningSignature } from './factory.js';
8
8
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
9
9
  export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  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';
2
2
  export { computeFactoryStateCommitment } from './commitment.js';
3
- export { createFactory, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
3
+ export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
4
4
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
5
5
  export { createFactoryCoordination, } from './coordination.js';
6
6
  export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-factory",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "description": "Channel factory layer for Omnia — N-of-N MULTISIG funding, virtual channel management, and factory settlement",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -25,19 +25,16 @@
25
25
  "NOTICE"
26
26
  ],
27
27
  "dependencies": {
28
- "@totemsdk/core": "^1.4.2",
29
- "@totemsdk/omnia": "^2.4.0",
30
- "@totemsdk/wots-lease": "^1.0.2",
28
+ "@totemsdk/wots-lease": "^1.0.3",
29
+ "@totemsdk/omnia": "^2.4.4",
31
30
  "@totemsdk/txpow": "^1.1.1",
32
- "@totemsdk/tx-builder": "^0.2.2",
33
- "@totemsdk/chain-provider": "^0.3.2",
34
- "@totemsdk/storage": "^0.2.2"
31
+ "@totemsdk/chain-provider": "^0.3.3",
32
+ "@totemsdk/tx-builder": "^0.3.3",
33
+ "@totemsdk/storage": "^0.2.2",
34
+ "@totemsdk/core": "^1.5.0"
35
35
  },
36
36
  "devDependencies": {
37
- "@types/jest": "^30.0.0",
38
37
  "@types/node": "^20.0.0",
39
- "jest": "^30.4.2",
40
- "ts-jest": "^29.0.0",
41
38
  "typescript": "^7.0.2"
42
39
  },
43
40
  "engines": {
@@ -77,7 +74,7 @@
77
74
  "scripts": {
78
75
  "build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
79
76
  "clean": "rm -rf dist rust/pkg rust/pkg-node rust/target",
80
- "test": "jest",
77
+ "test": "jest --config ../../tests/jest/omnia-factory.cjs",
81
78
  "build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
82
79
  }
83
80
  }