@totemsdk/omnia-factory 0.7.2 → 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,12 +110,12 @@ 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) {
113
+ export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding, scriptOptions = { settlement: 'full-distribution', enforceCheckpoints: true }) {
114
114
  // One plan, one factory ID: build the opening once and reuse it for the
115
115
  // proposal, the local record and the funding transaction. Rebuilding here
116
116
  // would generate a different ID (the ID includes a random nonce) and the
117
117
  // peer would accept a factory this host never stored.
118
- const plan = await buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding);
118
+ const plan = await buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding, scriptOptions);
119
119
  return createFactoryFromPlan(plan, bundle, chainProvider);
120
120
  }
121
121
  function findProposer(factory, bundle) {
@@ -182,7 +182,12 @@ export async function createFactoryFromPlan(plan, bundle, chainProvider) {
182
182
  * Build a factory and (when every participant supplies a funding coin) its
183
183
  * deterministic funding draft, without signing or broadcasting.
184
184
  */
185
- 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 }) {
186
191
  if (participants.length < 2) {
187
192
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
188
193
  }
@@ -190,12 +195,13 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
190
195
  const allocations = {};
191
196
  for (const p of participants)
192
197
  allocations[p.partyId] = p.contributionAmount;
193
- const { script, address } = buildAndHashFactoryScript(participants);
198
+ const { script, address } = buildAndHashFactoryScript(participants, scriptOptions);
194
199
  const factoryId = generateFactoryId(participants, tokenId, tokenScale);
195
200
  let fundingTxBytes;
196
201
  let fundingDigest;
197
202
  let fundingCoinId;
198
203
  let pendingCommitment;
204
+ let seededStateVariables;
199
205
  const allHaveCoinId = participants.every(p => p.fundingCoinId);
200
206
  if (allHaveCoinId && chainProvider) {
201
207
  const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
@@ -208,7 +214,18 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
208
214
  }
209
215
  const tip = await chainProvider.getTip();
210
216
  const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
211
- 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);
212
229
  fundingDigest = computeOmniaTxDigest(fundingDraft);
213
230
  fundingTxBytes = omniaDraftToMinimaBytes(fundingDraft);
214
231
  fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
@@ -241,8 +258,17 @@ export async function buildFactoryOpening(participants, tokenId, tokenScale, cha
241
258
  fundingCoinId: undefined,
242
259
  pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
243
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,
244
271
  };
245
- return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
246
272
  }
247
273
  /**
248
274
  * Broadcast the prepared factory funding (when on-chain) and record opening
@@ -296,6 +322,21 @@ export async function finalizeFactoryOpening(plan, opts, chainProvider) {
296
322
  fundingTxId,
297
323
  fundingCoinId: plan.fundingCoinId,
298
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
+ }
299
340
  }
300
341
  factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
301
342
  const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
@@ -457,6 +498,10 @@ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseP
457
498
  if (factory.status !== 'active') {
458
499
  throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
459
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
+ }
460
505
  if (amount <= 0n) {
461
506
  throw new Error(`Reallocation amount must be positive, got ${amount}`);
462
507
  }
@@ -594,23 +639,81 @@ export function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
594
639
  if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
595
640
  throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
596
641
  }
597
- return { ...incoming, pendingSignatures: {} };
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
+ };
598
653
  }
599
654
  if (known.status === 'active' && incoming.status === 'active') {
600
- // Funding references may be filled in after activation; terms are already checked.
601
- return { ...incoming };
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
+ };
602
677
  }
603
678
  if (known.status === 'opening' && incoming.status === 'opening') {
604
- // Funding references only; signatures may not be removed or altered.
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');
605
690
  const knownSigs = known.pendingSignatures ?? {};
606
691
  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')) {
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')) {
610
700
  throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
611
701
  }
702
+ if (!verifyChannelSignature(sig, commitment, participant.publicKeyDigest)) {
703
+ throw new Error(`FACTORY_FINALIZED carries an invalid signature for '${partyId}'`);
704
+ }
612
705
  }
613
- return { ...incoming, pendingSignatures: { ...incomingSigs } };
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
+ };
614
717
  }
615
718
  throw new Error('FACTORY_FINALIZED has an unsupported status transition');
616
719
  }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,11 @@
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
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';
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
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 { assertFactoryDistributable, buildFactoryDistribution, factoryDistributionPayouts, } from './distribution.js';
4
+ export { buildFactoryCheckpoint, factoryCheckpointStateVariables, assertFactoryCheckpointTransition, factoryCheckpointSnapshot, } from './checkpoint.js';
3
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';
package/dist/script.d.ts CHANGED
@@ -3,6 +3,12 @@ import type { FactoryParticipant } from './types.js';
3
3
  export declare const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
4
4
  /** State port carrying the absolute escape block (STATE(103)). */
5
5
  export declare const FACTORY_ESCAPE_PORT = 103;
6
+ /**
7
+ * OMN-058/RFC-079 §4: checkpoint sequence (STATE(104)). Seeded at funding and
8
+ * advanced by exactly one on every checkpoint spend, so a checkpoint can never
9
+ * be replayed against a newer state.
10
+ */
11
+ export declare const FACTORY_CHECKPOINT_SEQUENCE_PORT = 104;
6
12
  /**
7
13
  * State port carrying the committed party-set root (STATE(111)) — the MMR root
8
14
  * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
@@ -71,13 +77,41 @@ export interface FactoryDistributionScriptConfig {
71
77
  balanceRootPort?: number;
72
78
  }
73
79
  /**
74
- * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
75
- * distribution. After the committed escape block **any** party may broadcast the
76
- * distribution (all-party `MULTISIG`), with no counterparty liveness and no
77
- * on-chain root recomputation. The committed party-set and balance roots are
78
- * pinned (`SAMESTATE`) so the set and balances cannot move.
80
+ * Pre-signed all-party distribution (RFC-048 §12.4) — kept as a **separate**
81
+ * mechanism for a dedicated distribution coin.
82
+ *
83
+ * This script authorizes the spend with `MULTISIG` after the escape height. It
84
+ * does **not** verify the payout set; allocation correctness comes from the
85
+ * pre-signed transaction that the parties exchange. Do not describe or use it as
86
+ * an allocation verifier — use `buildFactoryDistributionScript` (output-enforced)
87
+ * or the `settlement: 'full-distribution'` funding branch instead.
88
+ */
89
+ export declare function buildFactoryPresignedDistributionScript(config: FactoryDistributionScriptConfig): string;
90
+ /**
91
+ * OMN-058/RFC-079 §4A — output-enforced full distribution for a factory coin.
92
+ *
93
+ * After the committed escape block, any participant may settle the factory by
94
+ * paying **every** committed share. The covenant reads the shares from the spent
95
+ * coin (`PREVSTATE`), pins the output count, each destination, each amount and
96
+ * the total, so neither the broadcaster nor an outsider can redirect or resize a
97
+ * payout. One participant signature authorizes the trigger.
98
+ *
99
+ * Use `buildFactoryDistribution` to materialize the matching transaction.
79
100
  */
80
101
  export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
102
+ /**
103
+ * OMN-060: deterministic party-set root committed by STATE(111).
104
+ * Canonical: parties sorted by id, `id:pubkeyDigest`.
105
+ */
106
+ export declare function computeFactoryPartyRoot(participants: FactoryParticipant[]): string;
107
+ /** OMN-060: deterministic balance root committed by STATE(112). */
108
+ export declare function computeFactoryBalanceRoot(allocations: Record<string, bigint>): string;
109
+ /** Committed balance-set root state variable (STATE(112)) for the funding output. */
110
+ export declare function factoryBalanceRootStateVariable(root: string): {
111
+ port: number;
112
+ value: string;
113
+ type: 'hex';
114
+ };
81
115
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
82
116
  export declare function factoryPartyRootStateVariable(root: string): {
83
117
  port: number;
@@ -97,6 +131,22 @@ export declare const FACTORY_MAX_PARTICIPANTS: number;
97
131
  export interface FactoryScriptOptions {
98
132
  /** Reserved for callers; the escape block is carried in STATE(103) at funding. */
99
133
  escapeBlock?: number;
134
+ /**
135
+ * OMN-058 checkpoint mode (RFC-079 §4). When true, the cooperative branch only
136
+ * accepts a same-script, same-value successor whose sequence advanced by one.
137
+ * Every allocation change then has an on-chain artifact, and the unilateral
138
+ * escape pays the latest checkpoint instead of the original funding split.
139
+ *
140
+ * Off by default: the off-chain factory design stays available, with OMN-058
141
+ * open until the contestable protocol lands.
142
+ */
143
+ enforceCheckpoints?: boolean;
144
+ /**
145
+ * OMN-058/RFC-079 §4A: add the output-enforced full-distribution branch.
146
+ * Any participant can settle every committed share in one transaction; the
147
+ * covenant pins each destination, amount, the output count and conservation.
148
+ */
149
+ settlement?: 'per-party' | 'full-distribution';
100
150
  }
101
151
  /**
102
152
  * Per-party allocation state variables (port base+k = party k's balance), seeded
@@ -107,6 +157,7 @@ export declare function factoryBalanceStateVariables(participants: FactoryPartic
107
157
  port: number;
108
158
  value: bigint;
109
159
  type: 'number';
160
+ scale: number;
110
161
  }[];
111
162
  /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
112
163
  export declare function factoryEscapeStateVariable(escapeBlock: number): {
@@ -115,23 +166,28 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
115
166
  type: 'number';
116
167
  };
117
168
  /**
118
- * Build the N-of-N MULTISIG MAST funding script for a channel factory
119
- * (RFC-039, CUSTODY-POLICY §2).
169
+ * Build the factory funding script.
120
170
  *
121
171
  * Spend paths:
122
- * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
123
- * `settlement=true` closes after minimal coinage (1 block).
124
- * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
125
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
126
- * (the spent coin's share) to its own settlement address, zero its state in
127
- * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
128
- * unchanged, and return the remainder to the factory script. Repeated
129
- * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
130
- * so the escape clock cannot be pushed by any counterparty.
172
+ * - **Cooperative / checkpoint** (any time, all parties): `MULTISIG(N …)`.
173
+ * With `enforceCheckpoints`, the successor must stay at this script, keep the
174
+ * value and advance `STATE(104)` by exactly one.
175
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any single
176
+ * party may withdraw its committed share `PREVSTATE(base+k)` to its own
177
+ * settlement address. With a remainder, the successor keeps the script, the
178
+ * other shares are untouched and the withdrawing port is zeroed.
179
+ * - **Full distribution** (`settlement: 'full-distribution'`, after the same
180
+ * block): one transaction pays **every** committed share. The covenant pins
181
+ * the output count, each destination and each amount read from `PREVSTATE`,
182
+ * so a broadcaster cannot redirect or resize a payout. One participant
183
+ * signature is enough to trigger it.
184
+ *
185
+ * The escape branches are terminal (no successor state), so the state-continuity
186
+ * assertions live in the cooperative path only.
131
187
  *
132
188
  * Minimum 2 participants required.
133
189
  */
134
- export declare function buildFactoryScript(participants: FactoryParticipant[], _options?: FactoryScriptOptions): string;
190
+ export declare function buildFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): string;
135
191
  export declare function normalizeScript(script: string): string;
136
192
  /** Compute the SHA3-256 script-hash address for a factory script. */
137
193
  export declare function scriptAddress(script: string): string;
package/dist/script.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { computeScriptAddress } from '@totemsdk/core/scripts';
2
- import { MMRTree, hexToBytes, bytesToHex, serializeMMRProof, createMMRDataLeafNode, toNodeScript, wotsAddressData } from '@totemsdk/core';
2
+ import { sha3_256 } from '@totemsdk/core';
3
+ import { MINIMA_DECIMALS, MMRTree, hexToBytes, bytesToHex, serializeMMRProof, createMMRDataLeafNode, toNodeScript, wotsAddressData } from '@totemsdk/core';
3
4
  /**
4
5
  * Normalize a hex public key digest to the KISSVM-compatible format:
5
6
  * strip leading 0x/0X and render as upper-case hex with a lowercase 0x prefix.
@@ -12,6 +13,12 @@ function kissHex(hex) {
12
13
  export const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
13
14
  /** State port carrying the absolute escape block (STATE(103)). */
14
15
  export const FACTORY_ESCAPE_PORT = 103;
16
+ /**
17
+ * OMN-058/RFC-079 §4: checkpoint sequence (STATE(104)). Seeded at funding and
18
+ * advanced by exactly one on every checkpoint spend, so a checkpoint can never
19
+ * be replayed against a newer state.
20
+ */
21
+ export const FACTORY_CHECKPOINT_SEQUENCE_PORT = 104;
15
22
  /**
16
23
  * State port carrying the committed party-set root (STATE(111)) — the MMR root
17
24
  * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
@@ -141,13 +148,16 @@ export function factoryDistributionOutputs(participants, tokenId = '0x00') {
141
148
  });
142
149
  }
143
150
  /**
144
- * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
145
- * distribution. After the committed escape block **any** party may broadcast the
146
- * distribution (all-party `MULTISIG`), with no counterparty liveness and no
147
- * on-chain root recomputation. The committed party-set and balance roots are
148
- * pinned (`SAMESTATE`) so the set and balances cannot move.
151
+ * Pre-signed all-party distribution (RFC-048 §12.4) — kept as a **separate**
152
+ * mechanism for a dedicated distribution coin.
153
+ *
154
+ * This script authorizes the spend with `MULTISIG` after the escape height. It
155
+ * does **not** verify the payout set; allocation correctness comes from the
156
+ * pre-signed transaction that the parties exchange. Do not describe or use it as
157
+ * an allocation verifier — use `buildFactoryDistributionScript` (output-enforced)
158
+ * or the `settlement: 'full-distribution'` funding branch instead.
149
159
  */
150
- export function buildFactoryDistributionScript(config) {
160
+ export function buildFactoryPresignedDistributionScript(config) {
151
161
  const participants = config.participants;
152
162
  if (!Array.isArray(participants) || participants.length < 1) {
153
163
  throw new Error('buildFactoryDistributionScript requires at least one participant');
@@ -172,6 +182,81 @@ export function buildFactoryDistributionScript(config) {
172
182
  `RETURN FALSE`,
173
183
  ].join('\n');
174
184
  }
185
+ /**
186
+ * OMN-058/RFC-079 §4A — output-enforced full distribution for a factory coin.
187
+ *
188
+ * After the committed escape block, any participant may settle the factory by
189
+ * paying **every** committed share. The covenant reads the shares from the spent
190
+ * coin (`PREVSTATE`), pins the output count, each destination, each amount and
191
+ * the total, so neither the broadcaster nor an outsider can redirect or resize a
192
+ * payout. One participant signature authorizes the trigger.
193
+ *
194
+ * Use `buildFactoryDistribution` to materialize the matching transaction.
195
+ */
196
+ export function buildFactoryDistributionScript(config) {
197
+ const participants = config.participants;
198
+ if (!Array.isArray(participants) || participants.length < 1) {
199
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
200
+ }
201
+ const pks = participants.map((p, i) => {
202
+ if (!p.publicKeyDigest)
203
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
204
+ return kissHex(p.publicKeyDigest);
205
+ });
206
+ const payouts = participants.map((p, i) => {
207
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
208
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
209
+ throw new Error(`participant[${i}] payout address must be a 64-hex digest`);
210
+ }
211
+ return wotsAddressData(raw);
212
+ });
213
+ const escapePort = config.escapePort ?? FACTORY_ESCAPE_PORT;
214
+ const count = participants.length;
215
+ const lines = [
216
+ '// Output-enforced factory distribution (OMN-058 / RFC-079 §4A)',
217
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
218
+ ' ASSERT @TOTIN EQ 1',
219
+ ' ASSERT @INPUT EQ 0',
220
+ ` ASSERT @TOTOUT EQ ${count}`,
221
+ ];
222
+ const terms = participants.map((_, k) => `PREVSTATE(${FACTORY_BALANCE_PORT_BASE + k})`);
223
+ lines.push(` ASSERT ${terms.join(' + ')} EQ @AMOUNT`);
224
+ participants.forEach((_, k) => {
225
+ lines.push(` ASSERT VERIFYOUT(${k} ${payouts[k]} PREVSTATE(${FACTORY_BALANCE_PORT_BASE + k}) @TOKENID FALSE)`);
226
+ });
227
+ lines.push(` ASSERT (${pks.map((pk) => `SIGNEDBY(${pk})`).join(' OR ')})`);
228
+ lines.push(' RETURN TRUE');
229
+ lines.push('ENDIF');
230
+ lines.push('RETURN FALSE');
231
+ return toNodeScript(lines.join('\n'));
232
+ }
233
+ /**
234
+ * OMN-060: deterministic party-set root committed by STATE(111).
235
+ * Canonical: parties sorted by id, `id:pubkeyDigest`.
236
+ */
237
+ export function computeFactoryPartyRoot(participants) {
238
+ const canonical = [...participants]
239
+ .map((p) => `${p.partyId}:${p.publicKeyDigest.replace(/^0x/i, '').toLowerCase()}`)
240
+ .sort()
241
+ .join('|');
242
+ return '0x' + bytesToHex(sha3_256(new TextEncoder().encode('totemsdk/factory/party-root/v1|' + canonical))).toLowerCase();
243
+ }
244
+ /** OMN-060: deterministic balance root committed by STATE(112). */
245
+ export function computeFactoryBalanceRoot(allocations) {
246
+ const canonical = Object.entries(allocations)
247
+ .map(([partyId, amount]) => `${partyId}:${amount.toString()}`)
248
+ .sort()
249
+ .join('|');
250
+ return '0x' + bytesToHex(sha3_256(new TextEncoder().encode('totemsdk/factory/balance-root/v1|' + canonical))).toLowerCase();
251
+ }
252
+ /** Committed balance-set root state variable (STATE(112)) for the funding output. */
253
+ export function factoryBalanceRootStateVariable(root) {
254
+ const raw = root.replace(/^0x/i, '');
255
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
256
+ throw new Error(`factoryBalanceRootStateVariable: root must be 32 bytes of hex; got ${JSON.stringify(root)}`);
257
+ }
258
+ return { port: FACTORY_BALANCE_ROOT_PORT, value: '0x' + raw, type: 'hex' };
259
+ }
175
260
  /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
176
261
  export function factoryPartyRootStateVariable(root) {
177
262
  const raw = root.replace(/^0x/i, '');
@@ -196,10 +281,13 @@ export const FACTORY_MAX_PARTICIPANTS = MSHS_PORT_FLOOR - FACTORY_BALANCE_PORT_B
196
281
  * committed share.
197
282
  */
198
283
  export function factoryBalanceStateVariables(participants) {
284
+ // OMN-034: these ports are used as exact payout amounts by the unilateral
285
+ // escape script, so they must carry MiniNumber scale 44 like every coin amount.
199
286
  return participants.map((p, k) => ({
200
287
  port: FACTORY_BALANCE_PORT_BASE + k,
201
288
  value: p.contributionAmount,
202
289
  type: 'number',
290
+ scale: MINIMA_DECIMALS,
203
291
  }));
204
292
  }
205
293
  /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
@@ -210,23 +298,28 @@ export function factoryEscapeStateVariable(escapeBlock) {
210
298
  return { port: FACTORY_ESCAPE_PORT, value: BigInt(escapeBlock), type: 'number' };
211
299
  }
212
300
  /**
213
- * Build the N-of-N MULTISIG MAST funding script for a channel factory
214
- * (RFC-039, CUSTODY-POLICY §2).
301
+ * Build the factory funding script.
215
302
  *
216
303
  * Spend paths:
217
- * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
218
- * `settlement=true` closes after minimal coinage (1 block).
219
- * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
220
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
221
- * (the spent coin's share) to its own settlement address, zero its state in
222
- * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
223
- * unchanged, and return the remainder to the factory script. Repeated
224
- * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
225
- * so the escape clock cannot be pushed by any counterparty.
304
+ * - **Cooperative / checkpoint** (any time, all parties): `MULTISIG(N …)`.
305
+ * With `enforceCheckpoints`, the successor must stay at this script, keep the
306
+ * value and advance `STATE(104)` by exactly one.
307
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any single
308
+ * party may withdraw its committed share `PREVSTATE(base+k)` to its own
309
+ * settlement address. With a remainder, the successor keeps the script, the
310
+ * other shares are untouched and the withdrawing port is zeroed.
311
+ * - **Full distribution** (`settlement: 'full-distribution'`, after the same
312
+ * block): one transaction pays **every** committed share. The covenant pins
313
+ * the output count, each destination and each amount read from `PREVSTATE`,
314
+ * so a broadcaster cannot redirect or resize a payout. One participant
315
+ * signature is enough to trigger it.
316
+ *
317
+ * The escape branches are terminal (no successor state), so the state-continuity
318
+ * assertions live in the cooperative path only.
226
319
  *
227
320
  * Minimum 2 participants required.
228
321
  */
229
- export function buildFactoryScript(participants, _options = {}) {
322
+ export function buildFactoryScript(participants, options = {}) {
230
323
  if (participants.length < 2) {
231
324
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
232
325
  }
@@ -236,42 +329,72 @@ export function buildFactoryScript(participants, _options = {}) {
236
329
  const count = participants.length;
237
330
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
238
331
  const payouts = participants.map((p) => wotsAddressData(p.settlementAddress ?? p.publicKeyDigest));
332
+ const enforceCheckpoints = options.enforceCheckpoints === true;
333
+ const fullDistribution = options.settlement === 'full-distribution';
239
334
  const lines = [
240
335
  'LET settlement=STATE(100)',
241
- `ASSERT SAMESTATE(${FACTORY_ESCAPE_PORT} ${FACTORY_ESCAPE_PORT})`,
242
- // RFC-048 §12.4/§12.5: the committed party-set root is immutable on every spend.
243
- `ASSERT SAMESTATE(${FACTORY_PARTY_ROOT_PORT} ${FACTORY_PARTY_ROOT_PORT})`,
244
336
  `IF @BLOCK GT PREVSTATE(${FACTORY_ESCAPE_PORT}) THEN`,
245
337
  ];
338
+ if (fullDistribution) {
339
+ // OMN-058/RFC-079 §4A: output-enforced settlement. Every amount is read from
340
+ // the coin being spent, never from the transaction's own claims.
341
+ lines.push(' // Full distribution: pay every committed share in one transaction.');
342
+ lines.push(' IF @TOTIN EQ 1 THEN');
343
+ lines.push(` IF @TOTOUT EQ ${count} THEN`);
344
+ // Gate on the last payout address so a per-party escape (which leaves the
345
+ // remainder at the factory script) falls through to its own branch instead
346
+ // of failing this one.
347
+ lines.push(` IF GETOUTADDR(${count - 1}) EQ ${payouts[count - 1]} THEN`);
348
+ lines.push(' ASSERT @INPUT EQ 0');
349
+ const terms = participants.map((_, k) => `PREVSTATE(${FACTORY_BALANCE_PORT_BASE + k})`);
350
+ lines.push(` ASSERT ${terms.join(' + ')} EQ @AMOUNT`);
351
+ participants.forEach((_, k) => {
352
+ lines.push(` ASSERT VERIFYOUT(${k} ${payouts[k]} PREVSTATE(${FACTORY_BALANCE_PORT_BASE + k}) @TOKENID FALSE)`);
353
+ });
354
+ lines.push(` ASSERT (${pks.map((pk) => `SIGNEDBY(${pk})`).join(' OR ')})`);
355
+ lines.push(' RETURN TRUE');
356
+ lines.push(' ENDIF');
357
+ lines.push(' ENDIF');
358
+ lines.push(' ENDIF');
359
+ }
246
360
  participants.forEach((_, k) => {
247
361
  const port = FACTORY_BALANCE_PORT_BASE + k;
248
362
  lines.push(` LET share=PREVSTATE(${port})`);
249
363
  lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
250
- lines.push(` IF share GT 0 THEN`);
364
+ lines.push(' IF share GT 0 THEN');
251
365
  lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} share @TOKENID FALSE)`);
366
+ // Whole-share exit: no successor state exists, so no remainder and no state
367
+ // continuity assertions.
368
+ lines.push(' IF @AMOUNT EQ share THEN');
369
+ lines.push(' ASSERT @TOTOUT EQ 1');
370
+ lines.push(' RETURN TRUE');
371
+ lines.push(' ENDIF');
252
372
  for (let j = 0; j < count; j++) {
253
373
  if (j === k)
254
374
  continue;
255
375
  lines.push(` ASSERT STATE(${FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${FACTORY_BALANCE_PORT_BASE + j})`);
256
376
  }
257
377
  lines.push(` ASSERT STATE(${port}) EQ 0`);
258
- // Whole-share guard (mirrors the VTXO script): when the withdrawing party's
259
- // share is the entire output there is no remainder, so a 0-amount output is
260
- // never required.
261
- lines.push(` IF @AMOUNT GT share THEN`);
262
- lines.push(` RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)`);
263
- lines.push(' ENDIF');
264
- lines.push(' RETURN TRUE');
378
+ lines.push(' RETURN VERIFYOUT(1 @ADDRESS @AMOUNT - share @TOKENID TRUE)');
265
379
  lines.push(' ENDIF');
266
380
  lines.push(' ENDIF');
267
381
  });
268
382
  lines.push('ENDIF');
383
+ // Cooperative path: the successor keeps the escape clock and the party set.
384
+ lines.push(`ASSERT SAMESTATE(${FACTORY_ESCAPE_PORT} ${FACTORY_ESCAPE_PORT})`);
385
+ lines.push(`ASSERT SAMESTATE(${FACTORY_PARTY_ROOT_PORT} ${FACTORY_PARTY_ROOT_PORT})`);
269
386
  lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
270
387
  lines.push('IF settlement THEN');
271
388
  lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
272
389
  lines.push('ELSE');
390
+ if (enforceCheckpoints) {
391
+ // Checkpoint continuity: same script, same value, sequence advanced by one.
392
+ lines.push(` ASSERT STATE(${FACTORY_CHECKPOINT_SEQUENCE_PORT}) EQ INC(PREVSTATE(${FACTORY_CHECKPOINT_SEQUENCE_PORT}))`);
393
+ lines.push(' ASSERT VERIFYOUT(@INPUT @ADDRESS @AMOUNT @TOKENID TRUE)');
394
+ }
273
395
  lines.push(' RETURN TRUE');
274
396
  lines.push('ENDIF');
397
+ lines.push('RETURN FALSE');
275
398
  return toNodeScript(lines.join('\n'));
276
399
  }
277
400
  export function normalizeScript(script) {