@totemsdk/omnia-factory 0.7.2 → 0.9.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/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) {
package/dist/types.d.ts CHANGED
@@ -92,6 +92,13 @@ export interface FactoryLogEntry {
92
92
  allocations: Record<string, bigint>;
93
93
  virtualChannelIds: string[];
94
94
  }
95
+ /**
96
+ * OMN-095: the two production capability levels of a factory.
97
+ *
98
+ * `checkpoint` is the only mode that can back a unilateral exit. `none` is a
99
+ * release restriction, not an equivalent alternative.
100
+ */
101
+ export type FactoryAllocationEnforcement = 'checkpoint' | 'none';
95
102
  export interface ChannelFactory {
96
103
  factoryId: string;
97
104
  participants: FactoryParticipant[];
@@ -109,6 +116,25 @@ export interface ChannelFactory {
109
116
  allocations: Record<string, bigint>;
110
117
  /** Currently open virtual channels backed by this factory's shared UTXO. */
111
118
  virtualChannels: OmniaChannel[];
119
+ /**
120
+ * OMN-058: the covenant only permits cooperative spends that recreate the
121
+ * coin at the same script/value with the checkpoint sequence advanced
122
+ * (`enforceCheckpoints`). When set, off-chain allocation changes (virtual
123
+ * channels) are refused until they can be committed as a checkpoint, so a
124
+ * unilateral escape can never pay a stale split.
125
+ */
126
+ enforceCheckpoints?: boolean;
127
+ /**
128
+ * OMN-095: what a participant's latest allocation is enforceable to.
129
+ *
130
+ * - `checkpoint` — the covenant only accepts a same-script, same-value
131
+ * successor whose sequence advanced by one, so a unilateral exit pays the
132
+ * latest **confirmed** allocation.
133
+ * - `none` — the legacy off-chain mode. The timeout escape pays the original
134
+ * funding split, so a newer off-chain allocation is *not* unilaterally
135
+ * enforceable. Creating this mode requires an explicit opt-in.
136
+ */
137
+ allocationEnforcement?: FactoryAllocationEnforcement;
112
138
  /** Monotonically increasing. Incremented on every committed state transition. */
113
139
  currentSequence: number;
114
140
  status: FactoryStatus;
package/dist/virtual.js CHANGED
@@ -47,6 +47,14 @@ export function buildVirtualChannelOpen(factory, parties, amounts, channelId) {
47
47
  if (factory.status !== 'active') {
48
48
  throw new Error(`openVirtualChannel requires factory status 'active', got '${factory.status}'`);
49
49
  }
50
+ if (factory.enforceCheckpoints) {
51
+ // OMN-058: an off-chain allocation change would leave the on-chain coin
52
+ // paying the previous split. Refuse until the change can be committed as a
53
+ // checkpoint transaction (same script, same value, sequence + 1).
54
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: opening a virtual channel changes the committed allocation `
55
+ + 'and must be committed with a factory checkpoint transaction first. '
56
+ + 'Create the factory with { enforceCheckpoints: false } only for a factory that will not rely on unilateral exits.');
57
+ }
50
58
  const [partyAId, partyBId] = parties;
51
59
  const amountA = amounts[partyAId] ?? 0n;
52
60
  const amountB = amounts[partyBId] ?? 0n;
@@ -219,6 +227,10 @@ export function buildVirtualChannelClose(factory, channel) {
219
227
  const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
220
228
  if (!existing)
221
229
  throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
230
+ if (factory.enforceCheckpoints) {
231
+ throw new Error(`factory ${factory.factoryId} uses checkpoint mode: closing a virtual channel changes the committed allocation `
232
+ + 'and must be committed with a factory checkpoint transaction first.');
233
+ }
222
234
  const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
223
235
  const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
224
236
  if (finalSum !== channel.totalValue) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-factory",
3
- "version": "0.7.2",
3
+ "version": "0.9.0",
4
4
  "description": "Channel factory layer for Omnia — N-of-N MULTISIG funding, virtual channel management, and factory settlement",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -25,13 +25,13 @@
25
25
  "NOTICE"
26
26
  ],
27
27
  "dependencies": {
28
+ "@totemsdk/core": "^1.6.1",
29
+ "@totemsdk/omnia": "^4.0.0",
28
30
  "@totemsdk/wots-lease": "^1.0.3",
29
- "@totemsdk/omnia": "^2.4.4",
31
+ "@totemsdk/tx-builder": "^0.4.0",
30
32
  "@totemsdk/txpow": "^1.1.1",
31
- "@totemsdk/chain-provider": "^0.3.3",
32
- "@totemsdk/tx-builder": "^0.3.3",
33
- "@totemsdk/storage": "^0.2.2",
34
- "@totemsdk/core": "^1.5.0"
33
+ "@totemsdk/chain-provider": "^0.5.0",
34
+ "@totemsdk/storage": "^0.2.3"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/node": "^20.0.0",