@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.
@@ -1,5 +1,6 @@
1
1
  import type { ChainStateProvider } from '@totemsdk/chain-provider';
2
2
  import type { ChannelFactory, FactoryParticipant, FactoryFundingMaterial, WotsLeaseBundle } from './types.js';
3
+ import { buildAndHashFactoryScript } from './script.js';
3
4
  /**
4
5
  * Enforce the factory's balance conservation invariant:
5
6
  * sum(allocations) + sum(virtualChannel.totalValue) === totalValue
@@ -38,7 +39,20 @@ export declare function enforceConservation(factory: ChannelFactory): void;
38
39
  * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
39
40
  * Defaults to 0.
40
41
  */
41
- export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
42
+ export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[], scriptOptions?: Parameters<typeof buildAndHashFactoryScript>[1]): Promise<ChannelFactory>;
43
+ /**
44
+ * Sign the opening commitment for a plan and record the proposer's signature.
45
+ * Nothing is broadcast and no funding signature is requested, so callers can
46
+ * propose the factory to the peer first (CAN-020 ordering).
47
+ */
48
+ export declare function proposeFactoryOpening(plan: FactoryOpeningPlan, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
49
+ /**
50
+ * Finish a plan: collect the funding-witness signatures from the plan's
51
+ * funding materials (or use the supplied ones), broadcast the funding
52
+ * transaction when the plan is on-chain, and commit the opening once every
53
+ * participant has signed.
54
+ */
55
+ export declare function createFactoryFromPlan(plan: FactoryOpeningPlan, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider): Promise<ChannelFactory>;
42
56
  /** A factory opening built without any signatures or broadcast. */
43
57
  export interface FactoryOpeningPlan {
44
58
  factory: ChannelFactory;
@@ -46,6 +60,12 @@ export interface FactoryOpeningPlan {
46
60
  fundingDigest?: Uint8Array;
47
61
  fundingCoinId?: string;
48
62
  fundingMaterials?: FactoryFundingMaterial[];
63
+ /** State variables seeded into the funding output (OMN-060 roots included). */
64
+ fundingStateVariables?: Array<{
65
+ port: number;
66
+ value: string | bigint;
67
+ type: string;
68
+ }>;
49
69
  onChain: boolean;
50
70
  }
51
71
  export interface FinalizeFactoryOpeningOptions {
@@ -53,12 +73,23 @@ export interface FinalizeFactoryOpeningOptions {
53
73
  fundingSignatures?: Record<string, Uint8Array>;
54
74
  /** Factory opening signatures to record on the proposal. */
55
75
  openingSignatures: Record<string, Uint8Array>;
76
+ /**
77
+ * OMN-063: confirmations required before an on-chain factory becomes active.
78
+ * Default 1. A factory whose funding cannot be observed at depth stays
79
+ * `opening` instead of being advertised as operational.
80
+ */
81
+ minConfirmations?: number;
56
82
  }
57
83
  /**
58
84
  * Build a factory and (when every participant supplies a funding coin) its
59
85
  * deterministic funding draft, without signing or broadcasting.
60
86
  */
61
- export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[]): Promise<FactoryOpeningPlan>;
87
+ export declare function buildFactoryOpening(participants: FactoryParticipant[], tokenId: string, tokenScale: number, chainProvider?: ChainStateProvider, funding?: FactoryFundingMaterial[],
88
+ /**
89
+ * OMN-058: `enforceCheckpoints` uses the checkpoint-mode covenant, so every
90
+ * allocation change must consume and recreate the factory coin (RFC-079 §4).
91
+ */
92
+ scriptOptions?: Parameters<typeof buildAndHashFactoryScript>[1]): Promise<FactoryOpeningPlan>;
62
93
  /**
63
94
  * Broadcast the prepared factory funding (when on-chain) and record opening
64
95
  * signatures. When every participant signature is supplied the factory commits.
@@ -78,7 +109,9 @@ export declare function finalizeFactoryOpening(plan: FactoryOpeningPlan, opts: F
78
109
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
79
110
  * must match a registered participant not yet signed).
80
111
  */
81
- export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
112
+ export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle, opts?: {
113
+ deferCommit?: boolean;
114
+ }): Promise<ChannelFactory>;
82
115
  /** A co-signer's opening signature, held until the opening is confirmed. */
83
116
  export interface FactoryOpeningSignature {
84
117
  factoryId: string;
@@ -114,3 +147,10 @@ export declare function applyFactorySignature(factory: ChannelFactory, partyId:
114
147
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
115
148
  */
116
149
  export declare function reallocate(factory: ChannelFactory, fromPartyId: string, toPartyId: string, amount: bigint, leaseProviders: Record<string, WotsLeaseBundle>): Promise<ChannelFactory>;
150
+ /**
151
+ * Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
152
+ * accepted factory. The peer may only fill in the funding references and add
153
+ * valid opening signatures; every term, commitment and existing signature must
154
+ * be identical. Returns the validated factory to store.
155
+ */
156
+ 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");
@@ -121,126 +124,70 @@ function generateFactoryId(participants, tokenId, tokenScale) {
121
124
  * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
122
125
  * Defaults to 0.
123
126
  */
124
- 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);
127
+ async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding, scriptOptions = { settlement: 'full-distribution', enforceCheckpoints: true }) {
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, scriptOptions);
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}'`);
187
- }
188
- }
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'}`);
184
+ throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
206
185
  }
207
- fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
208
186
  }
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;
@@ -249,7 +196,12 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
249
196
  * Build a factory and (when every participant supplies a funding coin) its
250
197
  * deterministic funding draft, without signing or broadcasting.
251
198
  */
252
- async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding) {
199
+ async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding,
200
+ /**
201
+ * OMN-058: `enforceCheckpoints` uses the checkpoint-mode covenant, so every
202
+ * allocation change must consume and recreate the factory coin (RFC-079 §4).
203
+ */
204
+ scriptOptions = { settlement: 'full-distribution', enforceCheckpoints: true }) {
253
205
  if (participants.length < 2) {
254
206
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
255
207
  }
@@ -257,12 +209,13 @@ async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvi
257
209
  const allocations = {};
258
210
  for (const p of participants)
259
211
  allocations[p.partyId] = p.contributionAmount;
260
- const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
212
+ const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants, scriptOptions);
261
213
  const factoryId = generateFactoryId(participants, tokenId, tokenScale);
262
214
  let fundingTxBytes;
263
215
  let fundingDigest;
264
216
  let fundingCoinId;
265
217
  let pendingCommitment;
218
+ let seededStateVariables;
266
219
  const allHaveCoinId = participants.every(p => p.fundingCoinId);
267
220
  if (allHaveCoinId && chainProvider) {
268
221
  const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
@@ -275,7 +228,18 @@ async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvi
275
228
  }
276
229
  const tip = await chainProvider.getTip();
277
230
  const escapeBlock = tip.block + script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS;
278
- 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)]);
231
+ const fundingStateVariables = [
232
+ ...(0, script_js_1.factoryBalanceStateVariables)(participants),
233
+ (0, script_js_1.factoryEscapeStateVariable)(escapeBlock),
234
+ // OMN-058: the checkpoint sequence starts at zero on the funding coin.
235
+ { port: 104, value: 0n, type: 'number' },
236
+ // OMN-060: the covenant asserts SAMESTATE over these roots, so they must
237
+ // exist in the funding output or the assertion is vacuous.
238
+ (0, script_js_1.factoryPartyRootStateVariable)((0, script_js_1.computeFactoryPartyRoot)(participants)),
239
+ (0, script_js_1.factoryBalanceRootStateVariable)((0, script_js_1.computeFactoryBalanceRoot)(allocations)),
240
+ ];
241
+ seededStateVariables = fundingStateVariables;
242
+ const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, fundingStateVariables);
279
243
  fundingDigest = (0, omnia_1.computeOmniaTxDigest)(fundingDraft);
280
244
  fundingTxBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
281
245
  fundingCoinId = (0, omnia_1.minimaOutputCoinIdsForDraft)(fundingDraft)[0];
@@ -308,8 +272,17 @@ async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvi
308
272
  fundingCoinId: undefined,
309
273
  pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
310
274
  pendingSignatures: {},
275
+ enforceCheckpoints: scriptOptions.enforceCheckpoints === true,
276
+ };
277
+ return {
278
+ factory,
279
+ fundingTxBytes,
280
+ fundingDigest,
281
+ fundingCoinId,
282
+ fundingMaterials: funding,
283
+ ...(seededStateVariables ? { fundingStateVariables: seededStateVariables } : {}),
284
+ onChain: fundingTxBytes !== undefined,
311
285
  };
312
- return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
313
286
  }
314
287
  /**
315
288
  * Broadcast the prepared factory funding (when on-chain) and record opening
@@ -363,6 +336,21 @@ async function finalizeFactoryOpening(plan, opts, chainProvider) {
363
336
  fundingTxId,
364
337
  fundingCoinId: plan.fundingCoinId,
365
338
  };
339
+ // OMN-063: submission is not finality. Only a coin observed at the required
340
+ // depth may become an active factory.
341
+ const required = opts.minConfirmations ?? 1;
342
+ if (required > 0) {
343
+ let confirmed = false;
344
+ if (plan.fundingCoinId && typeof chainProvider.getTip === 'function') {
345
+ const coin = await chainProvider.getCoin(plan.fundingCoinId);
346
+ const tip = await chainProvider.getTip();
347
+ const created = Number(coin?.created ?? 0);
348
+ confirmed = Boolean(coin && !coin.spent && created > 0 && tip.block - created + 1 >= required);
349
+ }
350
+ if (!confirmed) {
351
+ return { ...factory, pendingSignatures: { ...opts.openingSignatures } };
352
+ }
353
+ }
366
354
  }
367
355
  factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
368
356
  const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
@@ -383,7 +371,7 @@ async function finalizeFactoryOpening(plan, opts, chainProvider) {
383
371
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
384
372
  * must match a registered participant not yet signed).
385
373
  */
386
- async function acceptFactory(factory, bundle) {
374
+ async function acceptFactory(factory, bundle, opts) {
387
375
  if (factory.status !== 'opening') {
388
376
  throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
389
377
  }
@@ -397,13 +385,14 @@ async function acceptFactory(factory, bundle) {
397
385
  if (factory.pendingSignatures[participant.partyId]) {
398
386
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
399
387
  }
400
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
388
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
401
389
  const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
402
390
  const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
403
391
  const updatedFactory = { ...factory, pendingSignatures: newSigs };
404
- // When all N parties have signed, commit the opening.
392
+ // When all N parties have signed, commit the opening unless the host is
393
+ // waiting for funding evidence (on-chain) or the proposer's FINALIZED.
405
394
  const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
406
- if (allSigned) {
395
+ if (allSigned && !opts?.deferCommit) {
407
396
  return commitOpening(updatedFactory);
408
397
  }
409
398
  return updatedFactory;
@@ -425,7 +414,7 @@ async function signFactoryOpening(factory, bundle) {
425
414
  if (factory.pendingSignatures[participant.partyId]) {
426
415
  throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
427
416
  }
428
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
417
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
429
418
  const reservation = await bundle.leaseProvider.reserveKeyUse({
430
419
  treeId: `omnia-factory-${factory.factoryId}`,
431
420
  purpose: 'factory-open',
@@ -458,7 +447,7 @@ function verifyFactorySignature(factory, partyId, signature, verify) {
458
447
  const participant = factory.participants.find(p => p.partyId === partyId);
459
448
  if (!participant)
460
449
  return false;
461
- const commitment = Buffer.from(factory.pendingCommitment, 'hex');
450
+ const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
462
451
  const verifyFn = verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
463
452
  try {
464
453
  return verifyFn(signature, commitment, participant.publicKeyDigest);
@@ -523,6 +512,10 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
523
512
  if (factory.status !== 'active') {
524
513
  throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
525
514
  }
515
+ if (factory.enforceCheckpoints) {
516
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: reallocating changes the committed allocation `
517
+ + 'and must be committed with a factory checkpoint transaction first.');
518
+ }
526
519
  if (amount <= 0n) {
527
520
  throw new Error(`Reallocation amount must be positive, got ${amount}`);
528
521
  }
@@ -558,3 +551,183 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
558
551
  enforceConservation(updated);
559
552
  return updated;
560
553
  }
554
+ // ─── Peer-supplied state validation ──────────────────────────────────────────
555
+ function jsonSafeForCompare(value) {
556
+ if (typeof value === 'bigint')
557
+ return value.toString();
558
+ if (Array.isArray(value))
559
+ return value.map(jsonSafeForCompare);
560
+ if (value && typeof value === 'object') {
561
+ const entries = Object.entries(value)
562
+ .sort(([a], [b]) => a.localeCompare(b))
563
+ .map(([k, v]) => [k, jsonSafeForCompare(v)]);
564
+ return Object.fromEntries(entries);
565
+ }
566
+ return value;
567
+ }
568
+ function factoryTermsFingerprint(f) {
569
+ return JSON.stringify(jsonSafeForCompare({
570
+ factoryId: f.factoryId,
571
+ participants: f.participants,
572
+ totalValue: f.totalValue,
573
+ tokenId: f.tokenId,
574
+ tokenScale: f.tokenScale,
575
+ allocations: f.allocations,
576
+ virtualChannels: f.virtualChannels,
577
+ currentSequence: f.currentSequence,
578
+ stateLog: f.stateLog,
579
+ fundingScript: f.fundingScript,
580
+ fundingAddress: f.fundingAddress,
581
+ pendingCommitment: f.pendingCommitment,
582
+ }));
583
+ }
584
+ /**
585
+ * Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
586
+ * accepted factory. The peer may only fill in the funding references and add
587
+ * valid opening signatures; every term, commitment and existing signature must
588
+ * be identical. Returns the validated factory to store.
589
+ */
590
+ function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
591
+ if (!incoming || incoming.factoryId !== known.factoryId) {
592
+ throw new Error('FACTORY_FINALIZED for a different factory');
593
+ }
594
+ if (senderPublicKeyDigest && !known.participants.some(p => p.publicKeyDigest === senderPublicKeyDigest)) {
595
+ throw new Error('FACTORY_FINALIZED sender is not a factory participant');
596
+ }
597
+ const terms = (f) => JSON.stringify(jsonSafeForCompare({
598
+ participants: f.participants,
599
+ totalValue: f.totalValue,
600
+ tokenId: f.tokenId,
601
+ tokenScale: f.tokenScale,
602
+ allocations: f.allocations,
603
+ virtualChannels: f.virtualChannels,
604
+ fundingScript: f.fundingScript,
605
+ fundingAddress: f.fundingAddress,
606
+ }));
607
+ if (terms(known) !== terms(incoming)) {
608
+ throw new Error('FACTORY_FINALIZED changes factory terms');
609
+ }
610
+ if (known.fundingTxId && incoming.fundingTxId !== known.fundingTxId) {
611
+ throw new Error('FACTORY_FINALIZED changes the funding transaction');
612
+ }
613
+ if (known.fundingCoinId && incoming.fundingCoinId !== known.fundingCoinId) {
614
+ throw new Error('FACTORY_FINALIZED changes the funding coin');
615
+ }
616
+ if (known.status === 'closed' && incoming.status !== 'closed') {
617
+ throw new Error('FACTORY_FINALIZED cannot reopen a closed factory');
618
+ }
619
+ // The expected transition for a proposal this host accepted with every
620
+ // participant signature present is the deterministic commit: sequence 1, an
621
+ // 'accept' log entry, cleared pending commitment and signatures.
622
+ if (known.status === 'opening' && incoming.status === 'active') {
623
+ if (known.currentSequence !== 0 || incoming.currentSequence !== 1) {
624
+ throw new Error('FACTORY_FINALIZED has an invalid sequence for an opening');
625
+ }
626
+ if (!known.pendingCommitment) {
627
+ throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
628
+ }
629
+ const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
630
+ const signatures = known.pendingSignatures ?? {};
631
+ for (const participant of known.participants) {
632
+ const sig = signatures[participant.partyId];
633
+ if (!sig)
634
+ throw new Error(`FACTORY_FINALIZED activates a factory missing the signature for '${participant.partyId}'`);
635
+ if (!(0, omnia_1.verifyChannelSignature)(sig, commitment, participant.publicKeyDigest)) {
636
+ throw new Error(`FACTORY_FINALIZED activates a factory with an invalid signature for '${participant.partyId}'`);
637
+ }
638
+ }
639
+ if (incoming.pendingCommitment) {
640
+ throw new Error('FACTORY_FINALIZED must clear the pending commitment when it activates');
641
+ }
642
+ if (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0) {
643
+ throw new Error('FACTORY_FINALIZED must clear pending signatures when it activates');
644
+ }
645
+ const log = incoming.stateLog ?? [];
646
+ if (log.length !== (known.stateLog?.length ?? 0) + 1) {
647
+ throw new Error('FACTORY_FINALIZED has an unexpected state log');
648
+ }
649
+ const last = log[log.length - 1];
650
+ if (!last || last.event !== 'accept' || last.sequence !== 1) {
651
+ throw new Error('FACTORY_FINALIZED is missing the accept log entry');
652
+ }
653
+ if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
654
+ throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
655
+ }
656
+ // Rebuild from local state: the peer may only supply the funding references.
657
+ return {
658
+ ...known,
659
+ status: 'active',
660
+ currentSequence: 1,
661
+ stateLog: [...(known.stateLog ?? []), last],
662
+ pendingCommitment: undefined,
663
+ pendingSignatures: {},
664
+ fundingTxId: incoming.fundingTxId ?? known.fundingTxId,
665
+ fundingCoinId: incoming.fundingCoinId ?? known.fundingCoinId,
666
+ };
667
+ }
668
+ if (known.status === 'active' && incoming.status === 'active') {
669
+ // Funding references may be filled in after activation. Nothing else may
670
+ // change: a peer cannot rewrite sequence, log, allocations or the VC set.
671
+ if (incoming.currentSequence !== known.currentSequence) {
672
+ throw new Error('FACTORY_FINALIZED changes the active sequence');
673
+ }
674
+ if (JSON.stringify(jsonSafeForCompare(incoming.stateLog ?? [])) !== JSON.stringify(jsonSafeForCompare(known.stateLog ?? []))) {
675
+ throw new Error('FACTORY_FINALIZED changes the active state log');
676
+ }
677
+ if (JSON.stringify(jsonSafeForCompare(incoming.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
678
+ throw new Error('FACTORY_FINALIZED changes the active allocations');
679
+ }
680
+ if (JSON.stringify(jsonSafeForCompare(incoming.virtualChannels ?? [])) !== JSON.stringify(jsonSafeForCompare(known.virtualChannels ?? []))) {
681
+ throw new Error('FACTORY_FINALIZED changes the active virtual-channel set');
682
+ }
683
+ if (incoming.pendingCommitment || (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0)) {
684
+ throw new Error('FACTORY_FINALIZED carries pending opening state on an active factory');
685
+ }
686
+ return {
687
+ ...known,
688
+ fundingTxId: known.fundingTxId ?? incoming.fundingTxId,
689
+ fundingCoinId: known.fundingCoinId ?? incoming.fundingCoinId,
690
+ };
691
+ }
692
+ if (known.status === 'opening' && incoming.status === 'opening') {
693
+ // Funding references and additional *valid* opening signatures only.
694
+ if (incoming.currentSequence !== known.currentSequence) {
695
+ throw new Error('FACTORY_FINALIZED changes the opening sequence');
696
+ }
697
+ if (JSON.stringify(jsonSafeForCompare(incoming.stateLog ?? [])) !== JSON.stringify(jsonSafeForCompare(known.stateLog ?? []))) {
698
+ throw new Error('FACTORY_FINALIZED changes the opening state log');
699
+ }
700
+ if (!known.pendingCommitment) {
701
+ throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
702
+ }
703
+ const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
704
+ const knownSigs = known.pendingSignatures ?? {};
705
+ const incomingSigs = incoming.pendingSignatures ?? {};
706
+ const byParty = new Map(known.participants.map((participant) => [participant.partyId, participant]));
707
+ for (const [partyId, sig] of Object.entries(incomingSigs)) {
708
+ const participant = byParty.get(partyId);
709
+ if (!participant) {
710
+ throw new Error(`FACTORY_FINALIZED carries a signature from unknown party '${partyId}'`);
711
+ }
712
+ const previous = knownSigs[partyId];
713
+ if (previous && Buffer.from(previous).toString('hex') !== Buffer.from(sig).toString('hex')) {
714
+ throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
715
+ }
716
+ if (!(0, omnia_1.verifyChannelSignature)(sig, commitment, participant.publicKeyDigest)) {
717
+ throw new Error(`FACTORY_FINALIZED carries an invalid signature for '${partyId}'`);
718
+ }
719
+ }
720
+ for (const partyId of Object.keys(knownSigs)) {
721
+ if (!incomingSigs[partyId]) {
722
+ throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
723
+ }
724
+ }
725
+ return {
726
+ ...known,
727
+ fundingTxId: known.fundingTxId ?? incoming.fundingTxId,
728
+ fundingCoinId: known.fundingCoinId ?? incoming.fundingCoinId,
729
+ pendingSignatures: { ...incomingSigs },
730
+ };
731
+ }
732
+ throw new Error('FACTORY_FINALIZED has an unsupported status transition');
733
+ }
@@ -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';