@totemsdk/omnia-factory 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/factory.js CHANGED
@@ -3,7 +3,7 @@ import { concatBytes } from '@totemsdk/core/wasm';
3
3
  import { buildScriptProof, computeScriptAddress } from '@totemsdk/core';
4
4
  import { buildFundingTx, omniaDraftToMinimaBytes, computeOmniaTxDigest, minimaOutputCoinIdsForDraft, serializeOmniaWitness, verifyChannelSignature, } from '@totemsdk/omnia';
5
5
  import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
6
- import { buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS } from './script.js';
6
+ import { buildAndHashFactoryScript, computeFactoryBalanceRoot, computeFactoryPartyRoot, factoryBalanceRootStateVariable, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartyRootStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS, } from './script.js';
7
7
  import { computeFactoryStateCommitment } from './commitment.js';
8
8
  // ─── Balance conservation ────────────────────────────────────────────────────
9
9
  /**
@@ -110,126 +110,70 @@ function generateFactoryId(participants, tokenId, tokenScale) {
110
110
  * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
111
111
  * Defaults to 0.
112
112
  */
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);
113
+ export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding, scriptOptions = { settlement: 'full-distribution', enforceCheckpoints: true }) {
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, scriptOptions);
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}'`);
176
- }
177
- }
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'}`);
170
+ throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
195
171
  }
196
- fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
197
172
  }
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;
@@ -238,7 +182,12 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
238
182
  * Build a factory and (when every participant supplies a funding coin) its
239
183
  * deterministic funding draft, without signing or broadcasting.
240
184
  */
241
- export async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding) {
185
+ export async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding,
186
+ /**
187
+ * OMN-058: `enforceCheckpoints` uses the checkpoint-mode covenant, so every
188
+ * allocation change must consume and recreate the factory coin (RFC-079 §4).
189
+ */
190
+ scriptOptions = { settlement: 'full-distribution', enforceCheckpoints: true }) {
242
191
  if (participants.length < 2) {
243
192
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
244
193
  }
@@ -246,12 +195,13 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
246
195
  const allocations = {};
247
196
  for (const p of participants)
248
197
  allocations[p.partyId] = p.contributionAmount;
249
- const { script, address } = buildAndHashFactoryScript(participants);
198
+ const { script, address } = buildAndHashFactoryScript(participants, scriptOptions);
250
199
  const factoryId = generateFactoryId(participants, tokenId, tokenScale);
251
200
  let fundingTxBytes;
252
201
  let fundingDigest;
253
202
  let fundingCoinId;
254
203
  let pendingCommitment;
204
+ let seededStateVariables;
255
205
  const allHaveCoinId = participants.every(p => p.fundingCoinId);
256
206
  if (allHaveCoinId && chainProvider) {
257
207
  const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
@@ -264,7 +214,18 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
264
214
  }
265
215
  const tip = await chainProvider.getTip();
266
216
  const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
267
- const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
217
+ const fundingStateVariables = [
218
+ ...factoryBalanceStateVariables(participants),
219
+ factoryEscapeStateVariable(escapeBlock),
220
+ // OMN-058: the checkpoint sequence starts at zero on the funding coin.
221
+ { port: 104, value: 0n, type: 'number' },
222
+ // OMN-060: the covenant asserts SAMESTATE over these roots, so they must
223
+ // exist in the funding output or the assertion is vacuous.
224
+ factoryPartyRootStateVariable(computeFactoryPartyRoot(participants)),
225
+ factoryBalanceRootStateVariable(computeFactoryBalanceRoot(allocations)),
226
+ ];
227
+ seededStateVariables = fundingStateVariables;
228
+ const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, fundingStateVariables);
268
229
  fundingDigest = computeOmniaTxDigest(fundingDraft);
269
230
  fundingTxBytes = omniaDraftToMinimaBytes(fundingDraft);
270
231
  fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
@@ -297,8 +258,17 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
297
258
  fundingCoinId: undefined,
298
259
  pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
299
260
  pendingSignatures: {},
261
+ enforceCheckpoints: scriptOptions.enforceCheckpoints === true,
262
+ };
263
+ return {
264
+ factory,
265
+ fundingTxBytes,
266
+ fundingDigest,
267
+ fundingCoinId,
268
+ fundingMaterials: funding,
269
+ ...(seededStateVariables ? { fundingStateVariables: seededStateVariables } : {}),
270
+ onChain: fundingTxBytes !== undefined,
300
271
  };
301
- return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
302
272
  }
303
273
  /**
304
274
  * Broadcast the prepared factory funding (when on-chain) and record opening
@@ -352,6 +322,21 @@ export async function finalizeFactoryOpening(plan, opts, chainProvider) {
352
322
  fundingTxId,
353
323
  fundingCoinId: plan.fundingCoinId,
354
324
  };
325
+ // OMN-063: submission is not finality. Only a coin observed at the required
326
+ // depth may become an active factory.
327
+ const required = opts.minConfirmations ?? 1;
328
+ if (required > 0) {
329
+ let confirmed = false;
330
+ if (plan.fundingCoinId && typeof chainProvider.getTip === 'function') {
331
+ const coin = await chainProvider.getCoin(plan.fundingCoinId);
332
+ const tip = await chainProvider.getTip();
333
+ const created = Number(coin?.created ?? 0);
334
+ confirmed = Boolean(coin && !coin.spent && created > 0 && tip.block - created + 1 >= required);
335
+ }
336
+ if (!confirmed) {
337
+ return { ...factory, pendingSignatures: { ...opts.openingSignatures } };
338
+ }
339
+ }
355
340
  }
356
341
  factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
357
342
  const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
@@ -372,7 +357,7 @@ export async function finalizeFactoryOpening(plan, opts, chainProvider) {
372
357
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
373
358
  * must match a registered participant not yet signed).
374
359
  */
375
- export async function acceptFactory(factory, bundle) {
360
+ export async function acceptFactory(factory, bundle, opts) {
376
361
  if (factory.status !== 'opening') {
377
362
  throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
378
363
  }
@@ -386,13 +371,14 @@ export async function acceptFactory(factory, bundle) {
386
371
  if (factory.pendingSignatures[participant.partyId]) {
387
372
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
388
373
  }
389
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
374
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
390
375
  const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
391
376
  const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
392
377
  const updatedFactory = { ...factory, pendingSignatures: newSigs };
393
- // When all N parties have signed, commit the opening.
378
+ // When all N parties have signed, commit the opening unless the host is
379
+ // waiting for funding evidence (on-chain) or the proposer's FINALIZED.
394
380
  const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
395
- if (allSigned) {
381
+ if (allSigned && !opts?.deferCommit) {
396
382
  return commitOpening(updatedFactory);
397
383
  }
398
384
  return updatedFactory;
@@ -414,7 +400,7 @@ export async function signFactoryOpening(factory, bundle) {
414
400
  if (factory.pendingSignatures[participant.partyId]) {
415
401
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
416
402
  }
417
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
403
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
418
404
  const reservation = await bundle.leaseProvider.reserveKeyUse({
419
405
  treeId: `omnia-factory-${factory.factoryId}`,
420
406
  purpose: 'factory-open',
@@ -447,7 +433,7 @@ export function verifyFactorySignature(factory, partyId, signature, verify) {
447
433
  const participant = factory.participants.find(p => p.partyId === partyId);
448
434
  if (!participant)
449
435
  return false;
450
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
436
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
451
437
  const verifyFn = verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
452
438
  try {
453
439
  return verifyFn(signature, commitment, participant.publicKeyDigest);
@@ -512,6 +498,10 @@ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseP
512
498
  if (factory.status !== 'active') {
513
499
  throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
514
500
  }
501
+ if (factory.enforceCheckpoints) {
502
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: reallocating changes the committed allocation `
503
+ + 'and must be committed with a factory checkpoint transaction first.');
504
+ }
515
505
  if (amount <= 0n) {
516
506
  throw new Error(`Reallocation amount must be positive, got ${amount}`);
517
507
  }
@@ -547,3 +537,183 @@ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseP
547
537
  enforceConservation(updated);
548
538
  return updated;
549
539
  }
540
+ // ─── Peer-supplied state validation ──────────────────────────────────────────
541
+ function jsonSafeForCompare(value) {
542
+ if (typeof value === 'bigint')
543
+ return value.toString();
544
+ if (Array.isArray(value))
545
+ return value.map(jsonSafeForCompare);
546
+ if (value && typeof value === 'object') {
547
+ const entries = Object.entries(value)
548
+ .sort(([a], [b]) => a.localeCompare(b))
549
+ .map(([k, v]) => [k, jsonSafeForCompare(v)]);
550
+ return Object.fromEntries(entries);
551
+ }
552
+ return value;
553
+ }
554
+ function factoryTermsFingerprint(f) {
555
+ return JSON.stringify(jsonSafeForCompare({
556
+ factoryId: f.factoryId,
557
+ participants: f.participants,
558
+ totalValue: f.totalValue,
559
+ tokenId: f.tokenId,
560
+ tokenScale: f.tokenScale,
561
+ allocations: f.allocations,
562
+ virtualChannels: f.virtualChannels,
563
+ currentSequence: f.currentSequence,
564
+ stateLog: f.stateLog,
565
+ fundingScript: f.fundingScript,
566
+ fundingAddress: f.fundingAddress,
567
+ pendingCommitment: f.pendingCommitment,
568
+ }));
569
+ }
570
+ /**
571
+ * Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
572
+ * accepted factory. The peer may only fill in the funding references and add
573
+ * valid opening signatures; every term, commitment and existing signature must
574
+ * be identical. Returns the validated factory to store.
575
+ */
576
+ export function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
577
+ if (!incoming || incoming.factoryId !== known.factoryId) {
578
+ throw new Error('FACTORY_FINALIZED for a different factory');
579
+ }
580
+ if (senderPublicKeyDigest && !known.participants.some(p => p.publicKeyDigest === senderPublicKeyDigest)) {
581
+ throw new Error('FACTORY_FINALIZED sender is not a factory participant');
582
+ }
583
+ const terms = (f) => JSON.stringify(jsonSafeForCompare({
584
+ participants: f.participants,
585
+ totalValue: f.totalValue,
586
+ tokenId: f.tokenId,
587
+ tokenScale: f.tokenScale,
588
+ allocations: f.allocations,
589
+ virtualChannels: f.virtualChannels,
590
+ fundingScript: f.fundingScript,
591
+ fundingAddress: f.fundingAddress,
592
+ }));
593
+ if (terms(known) !== terms(incoming)) {
594
+ throw new Error('FACTORY_FINALIZED changes factory terms');
595
+ }
596
+ if (known.fundingTxId && incoming.fundingTxId !== known.fundingTxId) {
597
+ throw new Error('FACTORY_FINALIZED changes the funding transaction');
598
+ }
599
+ if (known.fundingCoinId && incoming.fundingCoinId !== known.fundingCoinId) {
600
+ throw new Error('FACTORY_FINALIZED changes the funding coin');
601
+ }
602
+ if (known.status === 'closed' && incoming.status !== 'closed') {
603
+ throw new Error('FACTORY_FINALIZED cannot reopen a closed factory');
604
+ }
605
+ // The expected transition for a proposal this host accepted with every
606
+ // participant signature present is the deterministic commit: sequence 1, an
607
+ // 'accept' log entry, cleared pending commitment and signatures.
608
+ if (known.status === 'opening' && incoming.status === 'active') {
609
+ if (known.currentSequence !== 0 || incoming.currentSequence !== 1) {
610
+ throw new Error('FACTORY_FINALIZED has an invalid sequence for an opening');
611
+ }
612
+ if (!known.pendingCommitment) {
613
+ throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
614
+ }
615
+ const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
616
+ const signatures = known.pendingSignatures ?? {};
617
+ for (const participant of known.participants) {
618
+ const sig = signatures[participant.partyId];
619
+ if (!sig)
620
+ throw new Error(`FACTORY_FINALIZED activates a factory missing the signature for '${participant.partyId}'`);
621
+ if (!verifyChannelSignature(sig, commitment, participant.publicKeyDigest)) {
622
+ throw new Error(`FACTORY_FINALIZED activates a factory with an invalid signature for '${participant.partyId}'`);
623
+ }
624
+ }
625
+ if (incoming.pendingCommitment) {
626
+ throw new Error('FACTORY_FINALIZED must clear the pending commitment when it activates');
627
+ }
628
+ if (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0) {
629
+ throw new Error('FACTORY_FINALIZED must clear pending signatures when it activates');
630
+ }
631
+ const log = incoming.stateLog ?? [];
632
+ if (log.length !== (known.stateLog?.length ?? 0) + 1) {
633
+ throw new Error('FACTORY_FINALIZED has an unexpected state log');
634
+ }
635
+ const last = log[log.length - 1];
636
+ if (!last || last.event !== 'accept' || last.sequence !== 1) {
637
+ throw new Error('FACTORY_FINALIZED is missing the accept log entry');
638
+ }
639
+ if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
640
+ throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
641
+ }
642
+ // Rebuild from local state: the peer may only supply the funding references.
643
+ return {
644
+ ...known,
645
+ status: 'active',
646
+ currentSequence: 1,
647
+ stateLog: [...(known.stateLog ?? []), last],
648
+ pendingCommitment: undefined,
649
+ pendingSignatures: {},
650
+ fundingTxId: incoming.fundingTxId ?? known.fundingTxId,
651
+ fundingCoinId: incoming.fundingCoinId ?? known.fundingCoinId,
652
+ };
653
+ }
654
+ if (known.status === 'active' && incoming.status === 'active') {
655
+ // Funding references may be filled in after activation. Nothing else may
656
+ // change: a peer cannot rewrite sequence, log, allocations or the VC set.
657
+ if (incoming.currentSequence !== known.currentSequence) {
658
+ throw new Error('FACTORY_FINALIZED changes the active sequence');
659
+ }
660
+ if (JSON.stringify(jsonSafeForCompare(incoming.stateLog ?? [])) !== JSON.stringify(jsonSafeForCompare(known.stateLog ?? []))) {
661
+ throw new Error('FACTORY_FINALIZED changes the active state log');
662
+ }
663
+ if (JSON.stringify(jsonSafeForCompare(incoming.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
664
+ throw new Error('FACTORY_FINALIZED changes the active allocations');
665
+ }
666
+ if (JSON.stringify(jsonSafeForCompare(incoming.virtualChannels ?? [])) !== JSON.stringify(jsonSafeForCompare(known.virtualChannels ?? []))) {
667
+ throw new Error('FACTORY_FINALIZED changes the active virtual-channel set');
668
+ }
669
+ if (incoming.pendingCommitment || (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0)) {
670
+ throw new Error('FACTORY_FINALIZED carries pending opening state on an active factory');
671
+ }
672
+ return {
673
+ ...known,
674
+ fundingTxId: known.fundingTxId ?? incoming.fundingTxId,
675
+ fundingCoinId: known.fundingCoinId ?? incoming.fundingCoinId,
676
+ };
677
+ }
678
+ if (known.status === 'opening' && incoming.status === 'opening') {
679
+ // Funding references and additional *valid* opening signatures only.
680
+ if (incoming.currentSequence !== known.currentSequence) {
681
+ throw new Error('FACTORY_FINALIZED changes the opening sequence');
682
+ }
683
+ if (JSON.stringify(jsonSafeForCompare(incoming.stateLog ?? [])) !== JSON.stringify(jsonSafeForCompare(known.stateLog ?? []))) {
684
+ throw new Error('FACTORY_FINALIZED changes the opening state log');
685
+ }
686
+ if (!known.pendingCommitment) {
687
+ throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
688
+ }
689
+ const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
690
+ const knownSigs = known.pendingSignatures ?? {};
691
+ const incomingSigs = incoming.pendingSignatures ?? {};
692
+ const byParty = new Map(known.participants.map((participant) => [participant.partyId, participant]));
693
+ for (const [partyId, sig] of Object.entries(incomingSigs)) {
694
+ const participant = byParty.get(partyId);
695
+ if (!participant) {
696
+ throw new Error(`FACTORY_FINALIZED carries a signature from unknown party '${partyId}'`);
697
+ }
698
+ const previous = knownSigs[partyId];
699
+ if (previous && Buffer.from(previous).toString('hex') !== Buffer.from(sig).toString('hex')) {
700
+ throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
701
+ }
702
+ if (!verifyChannelSignature(sig, commitment, participant.publicKeyDigest)) {
703
+ throw new Error(`FACTORY_FINALIZED carries an invalid signature for '${partyId}'`);
704
+ }
705
+ }
706
+ for (const partyId of Object.keys(knownSigs)) {
707
+ if (!incomingSigs[partyId]) {
708
+ throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
709
+ }
710
+ }
711
+ return {
712
+ ...known,
713
+ fundingTxId: known.fundingTxId ?? incoming.fundingTxId,
714
+ fundingCoinId: known.fundingCoinId ?? incoming.fundingCoinId,
715
+ pendingSignatures: { ...incomingSigs },
716
+ };
717
+ }
718
+ throw new Error('FACTORY_FINALIZED has an unsupported status transition');
719
+ }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  export type { FactoryOpeningPlan, FinalizeFactoryOpeningOptions } from './factory.js';
2
2
  export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
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
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, buildFactoryPresignedDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_CHECKPOINT_SEQUENCE_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
+ export { assertFactoryDistributable, buildFactoryDistribution, factoryDistributionPayouts, } from './distribution.js';
6
+ export type { FactoryDistribution, FactoryDistributionEntry, } from './distribution.js';
7
+ export { buildFactoryCheckpoint, factoryCheckpointStateVariables, assertFactoryCheckpointTransition, factoryCheckpointSnapshot, } from './checkpoint.js';
8
+ export type { FactoryCheckpoint, FactoryCheckpointParams, FactoryCheckpointSnapshot, } from './checkpoint.js';
5
9
  export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
6
- export { createFactory, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
10
+ export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
7
11
  export type { FactoryOpeningSignature } from './factory.js';
8
12
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
9
13
  export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
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';
1
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, buildFactoryPresignedDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_CHECKPOINT_SEQUENCE_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 { assertFactoryDistributable, buildFactoryDistribution, factoryDistributionPayouts, } from './distribution.js';
4
+ export { buildFactoryCheckpoint, factoryCheckpointStateVariables, assertFactoryCheckpointTransition, factoryCheckpointSnapshot, } from './checkpoint.js';
5
+ export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
4
6
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
5
7
  export { createFactoryCoordination, } from './coordination.js';
6
8
  export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';