@totemsdk/omnia-factory 0.5.2 → 0.5.5

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,6 +1,7 @@
1
1
  export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, scriptAddress, normalizeScript, } from './script.js';
2
+ 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
3
  export { computeFactoryStateCommitment } from './commitment.js';
4
+ export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
4
5
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
6
  export type { FactoryOpeningSignature } from './factory.js';
6
7
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
package/dist/cjs/index.js CHANGED
@@ -1,11 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
3
+ exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
4
4
  var script_js_1 = require("./script.js");
5
5
  Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
6
6
  Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
7
7
  Object.defineProperty(exports, "factoryBalanceStateVariables", { enumerable: true, get: function () { return script_js_1.factoryBalanceStateVariables; } });
8
8
  Object.defineProperty(exports, "factoryEscapeStateVariable", { enumerable: true, get: function () { return script_js_1.factoryEscapeStateVariable; } });
9
+ Object.defineProperty(exports, "factoryPartySetRoot", { enumerable: true, get: function () { return script_js_1.factoryPartySetRoot; } });
10
+ Object.defineProperty(exports, "factoryPartyRootStateVariable", { enumerable: true, get: function () { return script_js_1.factoryPartyRootStateVariable; } });
11
+ Object.defineProperty(exports, "factoryPartyProof", { enumerable: true, get: function () { return script_js_1.factoryPartyProof; } });
12
+ Object.defineProperty(exports, "factoryBalanceSetRoot", { enumerable: true, get: function () { return script_js_1.factoryBalanceSetRoot; } });
13
+ Object.defineProperty(exports, "factoryBalanceProof", { enumerable: true, get: function () { return script_js_1.factoryBalanceProof; } });
14
+ Object.defineProperty(exports, "factoryDistributionOutputs", { enumerable: true, get: function () { return script_js_1.factoryDistributionOutputs; } });
15
+ Object.defineProperty(exports, "buildFactoryDistributionScript", { enumerable: true, get: function () { return script_js_1.buildFactoryDistributionScript; } });
16
+ Object.defineProperty(exports, "FACTORY_BALANCE_PORT_BASE", { enumerable: true, get: function () { return script_js_1.FACTORY_BALANCE_PORT_BASE; } });
17
+ Object.defineProperty(exports, "FACTORY_ESCAPE_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_PORT; } });
18
+ Object.defineProperty(exports, "FACTORY_ESCAPE_DELAY_BLOCKS", { enumerable: true, get: function () { return script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS; } });
19
+ Object.defineProperty(exports, "FACTORY_MAX_PARTICIPANTS", { enumerable: true, get: function () { return script_js_1.FACTORY_MAX_PARTICIPANTS; } });
20
+ Object.defineProperty(exports, "FACTORY_PARTY_ROOT_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_PARTY_ROOT_PORT; } });
21
+ Object.defineProperty(exports, "FACTORY_BALANCE_ROOT_PORT", { enumerable: true, get: function () { return script_js_1.FACTORY_BALANCE_ROOT_PORT; } });
22
+ Object.defineProperty(exports, "MSHS_PORT_FLOOR", { enumerable: true, get: function () { return script_js_1.MSHS_PORT_FLOOR; } });
9
23
  Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: function () { return script_js_1.scriptAddress; } });
10
24
  Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
11
25
  var commitment_js_1 = require("./commitment.js");
@@ -3,14 +3,103 @@ 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
- /** State port base for per-party allocations: party k ⇒ port 200+k. */
7
- export declare const FACTORY_BALANCE_PORT_BASE = 200;
6
+ /**
7
+ * State port carrying the committed party-set root (STATE(111)) — the MMR root
8
+ * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
9
+ * every spend (`SAMESTATE`), so the participant set is cryptographically fixed
10
+ * and immutable, independent of the per-party enumeration. This is the factory's
11
+ * adoption of the VTXO committed-set root and the anchor for future per-leaf
12
+ * (proof-based) scaling.
13
+ */
14
+ export declare const FACTORY_PARTY_ROOT_PORT = 111;
15
+ /**
16
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
17
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
18
+ */
19
+ export declare const FACTORY_BALANCE_ROOT_PORT = 112;
20
+ /** MMR root (hex, no `0x`) over the participants' public-key digests.
21
+ *
22
+ * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
23
+ * party set is padded to the next power of two with the **zero digest** sentinel
24
+ * (a fixed, publicly known padding leaf). The root is thus a Minima-native MMR
25
+ * root — the same structure the VTXO batch root commits and the on-chain `PROOF`
26
+ * verifies — over an arbitrary number of participants.
27
+ */
28
+ export declare function factoryPartySetRoot(participants: FactoryParticipant[]): string;
29
+ /**
30
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
31
+ * the committed party-set root — the witness for a per-leaf
32
+ * `buildMmrMembershipCovenant` escape (RFC-048 §12.4).
33
+ */
34
+ export declare function factoryPartyProof(participants: FactoryParticipant[], index: number): string;
35
+ /**
36
+ * Balance set-root (RFC-048 §12.4) — the MMR root over `(pubkey, balance)` leaves,
37
+ * where each participant's `contributionAmount` is the **leaf sum**. This commits
38
+ * the exact distribution of the factory balance (`rootSum` = the total) and is the
39
+ * scalable, off-chain commitment that replaces per-party balance ports.
40
+ */
41
+ export declare function factoryBalanceSetRoot(participants: FactoryParticipant[]): {
42
+ root: string;
43
+ rootSum: bigint;
44
+ };
45
+ /**
46
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
47
+ * the committed balance set-root — the witness for a `buildMmrMembershipCovenant`
48
+ * balance escape (leaf sum = the participant's balance).
49
+ */
50
+ export declare function factoryBalanceProof(participants: FactoryParticipant[], index: number): string;
51
+ export interface FactoryDistributionOutput {
52
+ /** Payout destination (hex pubkey digest). */
53
+ address: string;
54
+ /** Committed balance (atoms). */
55
+ amount: bigint;
56
+ tokenId: string;
57
+ }
58
+ /**
59
+ * The exact payout set the pre-signed all-party distribution must contain — one
60
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
61
+ * equals `factoryBalanceSetRoot(...).rootSum`.
62
+ */
63
+ export declare function factoryDistributionOutputs(participants: FactoryParticipant[], tokenId?: string): FactoryDistributionOutput[];
64
+ export interface FactoryDistributionScriptConfig {
65
+ participants: FactoryParticipant[];
66
+ /** State port carrying the escape block. Default `FACTORY_ESCAPE_PORT` (103). */
67
+ escapePort?: number;
68
+ /** State port carrying the committed party-set root. Default `FACTORY_PARTY_ROOT_PORT` (111). */
69
+ partyRootPort?: number;
70
+ /** State port carrying the committed balance set-root. Default `FACTORY_BALANCE_ROOT_PORT` (112). */
71
+ balanceRootPort?: number;
72
+ }
73
+ /**
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.
79
+ */
80
+ export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
81
+ /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
82
+ export declare function factoryPartyRootStateVariable(root: string): {
83
+ port: number;
84
+ value: string;
85
+ type: 'hex';
86
+ };
87
+ /** State port base for per-party allocations: party k ⇒ `base + k` (below the MSHS floor). */
88
+ export declare const FACTORY_BALANCE_PORT_BASE = 128;
89
+ /** Lowest port reserved for MSHS-2 (MASH); Omnia ports MUST stay below this.
90
+ * The node installs the MASH authorization bundle at ports **230–255**
91
+ * (`bundleBase = 256 − (4 + k) = 230`): the header R / ROOTS_BLOB /
92
+ * SECRETS_BLOB / TREE_SIG at 230–233 and PROOF at 234–255. A composite
93
+ * MASH + Omnia coin must therefore keep Omnia ports ≤ 229. */
94
+ export declare const MSHS_PORT_FLOOR = 230;
95
+ /** Maximum participants whose balance ports remain below the MSHS floor. */
96
+ export declare const FACTORY_MAX_PARTICIPANTS: number;
8
97
  export interface FactoryScriptOptions {
9
98
  /** Reserved for callers; the escape block is carried in STATE(103) at funding. */
10
99
  escapeBlock?: number;
11
100
  }
12
101
  /**
13
- * Per-party allocation state variables (port 200+k = party k's balance), seeded
102
+ * Per-party allocation state variables (port base+k = party k's balance), seeded
14
103
  * into the factory funding output so the timeout escape can pay each party its
15
104
  * committed share.
16
105
  */
@@ -33,9 +122,9 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
33
122
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
34
123
  * `SETTLEMENT=true` closes after minimal coinage (1 block).
35
124
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
36
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(200+k)`
125
+ * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
37
126
  * (the spent coin's share) to its own settlement address, zero its state in
38
- * the successor (`STATE(200+k) EQ 0`), keep the other parties' balances
127
+ * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
39
128
  * unchanged, and return the remainder to the factory script. Repeated
40
129
  * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
41
130
  * so the escape clock cannot be pushed by any counterparty.
@@ -1,6 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_ESCAPE_DELAY_BLOCKS = void 0;
3
+ exports.FACTORY_MAX_PARTICIPANTS = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_ESCAPE_DELAY_BLOCKS = void 0;
4
+ exports.factoryPartySetRoot = factoryPartySetRoot;
5
+ exports.factoryPartyProof = factoryPartyProof;
6
+ exports.factoryBalanceSetRoot = factoryBalanceSetRoot;
7
+ exports.factoryBalanceProof = factoryBalanceProof;
8
+ exports.factoryDistributionOutputs = factoryDistributionOutputs;
9
+ exports.buildFactoryDistributionScript = buildFactoryDistributionScript;
10
+ exports.factoryPartyRootStateVariable = factoryPartyRootStateVariable;
4
11
  exports.factoryBalanceStateVariables = factoryBalanceStateVariables;
5
12
  exports.factoryEscapeStateVariable = factoryEscapeStateVariable;
6
13
  exports.buildFactoryScript = buildFactoryScript;
@@ -8,6 +15,7 @@ exports.normalizeScript = normalizeScript;
8
15
  exports.scriptAddress = scriptAddress;
9
16
  exports.buildAndHashFactoryScript = buildAndHashFactoryScript;
10
17
  const scripts_1 = require("@totemsdk/core/scripts");
18
+ const core_1 = require("@totemsdk/core");
11
19
  /**
12
20
  * Normalize a hex public key digest to the KISSVM-compatible format:
13
21
  * strip leading 0x/0X and render as upper-case hex with leading '0X'.
@@ -20,10 +28,186 @@ function kissHex(hex) {
20
28
  exports.FACTORY_ESCAPE_DELAY_BLOCKS = 256;
21
29
  /** State port carrying the absolute escape block (STATE(103)). */
22
30
  exports.FACTORY_ESCAPE_PORT = 103;
23
- /** State port base for per-party allocations: party k ⇒ port 200+k. */
24
- exports.FACTORY_BALANCE_PORT_BASE = 200;
25
31
  /**
26
- * Per-party allocation state variables (port 200+k = party k's balance), seeded
32
+ * State port carrying the committed party-set root (STATE(111)) — the MMR root
33
+ * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
34
+ * every spend (`SAMESTATE`), so the participant set is cryptographically fixed
35
+ * and immutable, independent of the per-party enumeration. This is the factory's
36
+ * adoption of the VTXO committed-set root and the anchor for future per-leaf
37
+ * (proof-based) scaling.
38
+ */
39
+ exports.FACTORY_PARTY_ROOT_PORT = 111;
40
+ /**
41
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
42
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
43
+ */
44
+ exports.FACTORY_BALANCE_ROOT_PORT = 112;
45
+ /** Public-key digests for the party set, padded to a power of two (Minima MMR). */
46
+ function padPartySet(participants) {
47
+ if (!Array.isArray(participants) || participants.length === 0) {
48
+ throw new Error('factory party set requires at least one participant');
49
+ }
50
+ const pubkeys = participants.map((p, i) => {
51
+ const raw = (p.publicKeyDigest ?? '').replace(/^0x/i, '');
52
+ if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
53
+ throw new Error(`participant[${i}].publicKeyDigest must be a hex string`);
54
+ }
55
+ return (0, core_1.hexToBytes)(raw);
56
+ });
57
+ let size = 1;
58
+ while (size < pubkeys.length)
59
+ size <<= 1;
60
+ while (pubkeys.length < size)
61
+ pubkeys.push(new Uint8Array(32));
62
+ return pubkeys;
63
+ }
64
+ /** MMR root (hex, no `0x`) over the participants' public-key digests.
65
+ *
66
+ * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
67
+ * party set is padded to the next power of two with the **zero digest** sentinel
68
+ * (a fixed, publicly known padding leaf). The root is thus a Minima-native MMR
69
+ * root — the same structure the VTXO batch root commits and the on-chain `PROOF`
70
+ * verifies — over an arbitrary number of participants.
71
+ */
72
+ function factoryPartySetRoot(participants) {
73
+ const root = core_1.MMRTree.fromPublicKeys(padPartySet(participants)).getRoot();
74
+ if (!root)
75
+ throw new Error('factoryPartySetRoot: failed to compute the party-set root');
76
+ return (0, core_1.bytesToHex)(root.data).toLowerCase();
77
+ }
78
+ /**
79
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
80
+ * the committed party-set root — the witness for a per-leaf
81
+ * `buildMmrMembershipCovenant` escape (RFC-048 §12.4).
82
+ */
83
+ function factoryPartyProof(participants, index) {
84
+ if (!Number.isInteger(index) || index < 0 || index >= participants.length) {
85
+ throw new Error(`factoryPartyProof: index ${index} is out of range (0..${participants.length - 1})`);
86
+ }
87
+ const proof = core_1.MMRTree.fromPublicKeys(padPartySet(participants)).getProof(index);
88
+ return (0, core_1.bytesToHex)((0, core_1.serializeMMRProof)(proof)).toLowerCase();
89
+ }
90
+ /**
91
+ * Balance set-root (RFC-048 §12.4) — the MMR root over `(pubkey, balance)` leaves,
92
+ * where each participant's `contributionAmount` is the **leaf sum**. This commits
93
+ * the exact distribution of the factory balance (`rootSum` = the total) and is the
94
+ * scalable, off-chain commitment that replaces per-party balance ports.
95
+ */
96
+ function factoryBalanceSetRoot(participants) {
97
+ const tree = buildBalanceTree(participants);
98
+ const root = tree.getRoot();
99
+ if (!root)
100
+ throw new Error('factoryBalanceSetRoot: failed to compute the balance set-root');
101
+ return { root: (0, core_1.bytesToHex)(root.data).toLowerCase(), rootSum: root.value };
102
+ }
103
+ /**
104
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
105
+ * the committed balance set-root — the witness for a `buildMmrMembershipCovenant`
106
+ * balance escape (leaf sum = the participant's balance).
107
+ */
108
+ function factoryBalanceProof(participants, index) {
109
+ if (!Number.isInteger(index) || index < 0 || index >= participants.length) {
110
+ throw new Error(`factoryBalanceProof: index ${index} is out of range (0..${participants.length - 1})`);
111
+ }
112
+ const proof = buildBalanceTree(participants).getProof(index);
113
+ return (0, core_1.bytesToHex)((0, core_1.serializeMMRProof)(proof)).toLowerCase();
114
+ }
115
+ /** Padded (power-of-two) MMR tree over `(pubkey, balance)` leaves. */
116
+ function buildBalanceTree(participants) {
117
+ if (!Array.isArray(participants) || participants.length === 0) {
118
+ throw new Error('factory balance set requires at least one participant');
119
+ }
120
+ const tree = new core_1.MMRTree();
121
+ for (const [i, p] of participants.entries()) {
122
+ const raw = (p.publicKeyDigest ?? '').replace(/^0x/i, '');
123
+ if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
124
+ throw new Error(`participant[${i}].publicKeyDigest must be a hex string`);
125
+ }
126
+ if (p.contributionAmount < 0n) {
127
+ throw new Error(`participant[${i}].contributionAmount must be non-negative`);
128
+ }
129
+ tree.addLeaf((0, core_1.createMMRDataLeafNode)((0, core_1.hexToBytes)(raw), p.contributionAmount));
130
+ }
131
+ let size = 1;
132
+ while (size < participants.length)
133
+ size <<= 1;
134
+ for (let i = participants.length; i < size; i++) {
135
+ tree.addLeaf((0, core_1.createMMRDataLeafNode)(new Uint8Array(32), 0n));
136
+ }
137
+ return tree;
138
+ }
139
+ /**
140
+ * The exact payout set the pre-signed all-party distribution must contain — one
141
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
142
+ * equals `factoryBalanceSetRoot(...).rootSum`.
143
+ */
144
+ function factoryDistributionOutputs(participants, tokenId = '0x00') {
145
+ if (!Array.isArray(participants) || participants.length === 0) {
146
+ throw new Error('factoryDistributionOutputs requires at least one participant');
147
+ }
148
+ return participants.map((p, i) => {
149
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
150
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
151
+ throw new Error(`factoryDistributionOutputs: participant[${i}] payout address must be a 64-hex digest`);
152
+ }
153
+ if (p.contributionAmount < 0n) {
154
+ throw new Error(`factoryDistributionOutputs: participant[${i}].contributionAmount must be non-negative`);
155
+ }
156
+ return { address: '0x' + raw, amount: p.contributionAmount, tokenId };
157
+ });
158
+ }
159
+ /**
160
+ * Scalable factory escape covenant (RFC-048 §12.4) — the pre-signed all-party
161
+ * distribution. After the committed escape block **any** party may broadcast the
162
+ * distribution (all-party `MULTISIG`), with no counterparty liveness and no
163
+ * on-chain root recomputation. The committed party-set and balance roots are
164
+ * pinned (`SAMESTATE`) so the set and balances cannot move.
165
+ */
166
+ function buildFactoryDistributionScript(config) {
167
+ const participants = config.participants;
168
+ if (!Array.isArray(participants) || participants.length < 1) {
169
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
170
+ }
171
+ const pks = participants.map((p, i) => {
172
+ if (!p.publicKeyDigest)
173
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
174
+ return kissHex(p.publicKeyDigest);
175
+ });
176
+ const escapePort = config.escapePort ?? exports.FACTORY_ESCAPE_PORT;
177
+ const partyRootPort = config.partyRootPort ?? exports.FACTORY_PARTY_ROOT_PORT;
178
+ const balanceRootPort = config.balanceRootPort ?? exports.FACTORY_BALANCE_ROOT_PORT;
179
+ return [
180
+ '// Scalable factory escape — pre-signed all-party distribution (RFC-048 §12.4)',
181
+ `ASSERT SAMESTATE(${escapePort} ${escapePort})`,
182
+ `ASSERT SAMESTATE(${partyRootPort} ${partyRootPort})`,
183
+ `ASSERT SAMESTATE(${balanceRootPort} ${balanceRootPort})`,
184
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
185
+ ` ASSERT MULTISIG(${participants.length} ${pks.join(' ')})`,
186
+ ` RETURN TRUE`,
187
+ `ENDIF`,
188
+ `RETURN FALSE`,
189
+ ].join('\n');
190
+ }
191
+ /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
192
+ function factoryPartyRootStateVariable(root) {
193
+ const raw = root.replace(/^0x/i, '');
194
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
195
+ throw new Error(`factoryPartyRootStateVariable: root must be 32 bytes of hex; got ${JSON.stringify(root)}`);
196
+ }
197
+ return { port: exports.FACTORY_PARTY_ROOT_PORT, value: '0x' + raw, type: 'hex' };
198
+ }
199
+ /** State port base for per-party allocations: party k ⇒ `base + k` (below the MSHS floor). */
200
+ exports.FACTORY_BALANCE_PORT_BASE = 128;
201
+ /** Lowest port reserved for MSHS-2 (MASH); Omnia ports MUST stay below this.
202
+ * The node installs the MASH authorization bundle at ports **230–255**
203
+ * (`bundleBase = 256 − (4 + k) = 230`): the header R / ROOTS_BLOB /
204
+ * SECRETS_BLOB / TREE_SIG at 230–233 and PROOF at 234–255. A composite
205
+ * MASH + Omnia coin must therefore keep Omnia ports ≤ 229. */
206
+ exports.MSHS_PORT_FLOOR = 230;
207
+ /** Maximum participants whose balance ports remain below the MSHS floor. */
208
+ exports.FACTORY_MAX_PARTICIPANTS = exports.MSHS_PORT_FLOOR - exports.FACTORY_BALANCE_PORT_BASE;
209
+ /**
210
+ * Per-party allocation state variables (port base+k = party k's balance), seeded
27
211
  * into the factory funding output so the timeout escape can pay each party its
28
212
  * committed share.
29
213
  */
@@ -49,9 +233,9 @@ function factoryEscapeStateVariable(escapeBlock) {
49
233
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
50
234
  * `SETTLEMENT=true` closes after minimal coinage (1 block).
51
235
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
52
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(200+k)`
236
+ * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
53
237
  * (the spent coin's share) to its own settlement address, zero its state in
54
- * the successor (`STATE(200+k) EQ 0`), keep the other parties' balances
238
+ * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
55
239
  * unchanged, and return the remainder to the factory script. Repeated
56
240
  * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
57
241
  * so the escape clock cannot be pushed by any counterparty.
@@ -62,12 +246,17 @@ function buildFactoryScript(participants, _options = {}) {
62
246
  if (participants.length < 2) {
63
247
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
64
248
  }
249
+ if (participants.length > exports.FACTORY_MAX_PARTICIPANTS) {
250
+ throw new Error(`Factory supports at most ${exports.FACTORY_MAX_PARTICIPANTS} participants (got ${participants.length}) — balance ports would reach the MSHS-2 band (≥${exports.MSHS_PORT_FLOOR})`);
251
+ }
65
252
  const count = participants.length;
66
253
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
67
254
  const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
68
255
  const lines = [
69
256
  'LET SETTLEMENT=STATE(100)',
70
257
  `ASSERT SAMESTATE(${exports.FACTORY_ESCAPE_PORT} ${exports.FACTORY_ESCAPE_PORT})`,
258
+ // RFC-048 §12.4/§12.5: the committed party-set root is immutable on every spend.
259
+ `ASSERT SAMESTATE(${exports.FACTORY_PARTY_ROOT_PORT} ${exports.FACTORY_PARTY_ROOT_PORT})`,
71
260
  `IF @BLOCK GT PREVSTATE(${exports.FACTORY_ESCAPE_PORT}) THEN`,
72
261
  ];
73
262
  participants.forEach((_, k) => {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, scriptAddress, normalizeScript, } from './script.js';
2
+ 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
3
  export { computeFactoryStateCommitment } from './commitment.js';
4
+ export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
4
5
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
6
  export type { FactoryOpeningSignature } from './factory.js';
6
7
  export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, scriptAddress, normalizeScript, } from './script.js';
1
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
2
2
  export { computeFactoryStateCommitment } from './commitment.js';
3
3
  export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
4
4
  // RFC-035 B2 — factory opening round-trip over the coordination transport.
package/dist/script.d.ts CHANGED
@@ -3,14 +3,103 @@ 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
- /** State port base for per-party allocations: party k ⇒ port 200+k. */
7
- export declare const FACTORY_BALANCE_PORT_BASE = 200;
6
+ /**
7
+ * State port carrying the committed party-set root (STATE(111)) — the MMR root
8
+ * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
9
+ * every spend (`SAMESTATE`), so the participant set is cryptographically fixed
10
+ * and immutable, independent of the per-party enumeration. This is the factory's
11
+ * adoption of the VTXO committed-set root and the anchor for future per-leaf
12
+ * (proof-based) scaling.
13
+ */
14
+ export declare const FACTORY_PARTY_ROOT_PORT = 111;
15
+ /**
16
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
17
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
18
+ */
19
+ export declare const FACTORY_BALANCE_ROOT_PORT = 112;
20
+ /** MMR root (hex, no `0x`) over the participants' public-key digests.
21
+ *
22
+ * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
23
+ * party set is padded to the next power of two with the **zero digest** sentinel
24
+ * (a fixed, publicly known padding leaf). The root is thus a Minima-native MMR
25
+ * root — the same structure the VTXO batch root commits and the on-chain `PROOF`
26
+ * verifies — over an arbitrary number of participants.
27
+ */
28
+ export declare function factoryPartySetRoot(participants: FactoryParticipant[]): string;
29
+ /**
30
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
31
+ * the committed party-set root — the witness for a per-leaf
32
+ * `buildMmrMembershipCovenant` escape (RFC-048 §12.4).
33
+ */
34
+ export declare function factoryPartyProof(participants: FactoryParticipant[], index: number): string;
35
+ /**
36
+ * Balance set-root (RFC-048 §12.4) — the MMR root over `(pubkey, balance)` leaves,
37
+ * where each participant's `contributionAmount` is the **leaf sum**. This commits
38
+ * the exact distribution of the factory balance (`rootSum` = the total) and is the
39
+ * scalable, off-chain commitment that replaces per-party balance ports.
40
+ */
41
+ export declare function factoryBalanceSetRoot(participants: FactoryParticipant[]): {
42
+ root: string;
43
+ rootSum: bigint;
44
+ };
45
+ /**
46
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
47
+ * the committed balance set-root — the witness for a `buildMmrMembershipCovenant`
48
+ * balance escape (leaf sum = the participant's balance).
49
+ */
50
+ export declare function factoryBalanceProof(participants: FactoryParticipant[], index: number): string;
51
+ export interface FactoryDistributionOutput {
52
+ /** Payout destination (hex pubkey digest). */
53
+ address: string;
54
+ /** Committed balance (atoms). */
55
+ amount: bigint;
56
+ tokenId: string;
57
+ }
58
+ /**
59
+ * The exact payout set the pre-signed all-party distribution must contain — one
60
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
61
+ * equals `factoryBalanceSetRoot(...).rootSum`.
62
+ */
63
+ export declare function factoryDistributionOutputs(participants: FactoryParticipant[], tokenId?: string): FactoryDistributionOutput[];
64
+ export interface FactoryDistributionScriptConfig {
65
+ participants: FactoryParticipant[];
66
+ /** State port carrying the escape block. Default `FACTORY_ESCAPE_PORT` (103). */
67
+ escapePort?: number;
68
+ /** State port carrying the committed party-set root. Default `FACTORY_PARTY_ROOT_PORT` (111). */
69
+ partyRootPort?: number;
70
+ /** State port carrying the committed balance set-root. Default `FACTORY_BALANCE_ROOT_PORT` (112). */
71
+ balanceRootPort?: number;
72
+ }
73
+ /**
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.
79
+ */
80
+ export declare function buildFactoryDistributionScript(config: FactoryDistributionScriptConfig): string;
81
+ /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
82
+ export declare function factoryPartyRootStateVariable(root: string): {
83
+ port: number;
84
+ value: string;
85
+ type: 'hex';
86
+ };
87
+ /** State port base for per-party allocations: party k ⇒ `base + k` (below the MSHS floor). */
88
+ export declare const FACTORY_BALANCE_PORT_BASE = 128;
89
+ /** Lowest port reserved for MSHS-2 (MASH); Omnia ports MUST stay below this.
90
+ * The node installs the MASH authorization bundle at ports **230–255**
91
+ * (`bundleBase = 256 − (4 + k) = 230`): the header R / ROOTS_BLOB /
92
+ * SECRETS_BLOB / TREE_SIG at 230–233 and PROOF at 234–255. A composite
93
+ * MASH + Omnia coin must therefore keep Omnia ports ≤ 229. */
94
+ export declare const MSHS_PORT_FLOOR = 230;
95
+ /** Maximum participants whose balance ports remain below the MSHS floor. */
96
+ export declare const FACTORY_MAX_PARTICIPANTS: number;
8
97
  export interface FactoryScriptOptions {
9
98
  /** Reserved for callers; the escape block is carried in STATE(103) at funding. */
10
99
  escapeBlock?: number;
11
100
  }
12
101
  /**
13
- * Per-party allocation state variables (port 200+k = party k's balance), seeded
102
+ * Per-party allocation state variables (port base+k = party k's balance), seeded
14
103
  * into the factory funding output so the timeout escape can pay each party its
15
104
  * committed share.
16
105
  */
@@ -33,9 +122,9 @@ export declare function factoryEscapeStateVariable(escapeBlock: number): {
33
122
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
34
123
  * `SETTLEMENT=true` closes after minimal coinage (1 block).
35
124
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
36
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(200+k)`
125
+ * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
37
126
  * (the spent coin's share) to its own settlement address, zero its state in
38
- * the successor (`STATE(200+k) EQ 0`), keep the other parties' balances
127
+ * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
39
128
  * unchanged, and return the remainder to the factory script. Repeated
40
129
  * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
41
130
  * so the escape clock cannot be pushed by any counterparty.
package/dist/script.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { computeScriptAddress } from '@totemsdk/core/scripts';
2
+ import { MMRTree, hexToBytes, bytesToHex, serializeMMRProof, createMMRDataLeafNode } from '@totemsdk/core';
2
3
  /**
3
4
  * Normalize a hex public key digest to the KISSVM-compatible format:
4
5
  * strip leading 0x/0X and render as upper-case hex with leading '0X'.
@@ -11,10 +12,186 @@ function kissHex(hex) {
11
12
  export const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
12
13
  /** State port carrying the absolute escape block (STATE(103)). */
13
14
  export const FACTORY_ESCAPE_PORT = 103;
14
- /** State port base for per-party allocations: party k ⇒ port 200+k. */
15
- export const FACTORY_BALANCE_PORT_BASE = 200;
16
15
  /**
17
- * Per-party allocation state variables (port 200+k = party k's balance), seeded
16
+ * State port carrying the committed party-set root (STATE(111)) — the MMR root
17
+ * of the participant public-key digests (RFC-048 §12.4/§12.5). It is pinned on
18
+ * every spend (`SAMESTATE`), so the participant set is cryptographically fixed
19
+ * and immutable, independent of the per-party enumeration. This is the factory's
20
+ * adoption of the VTXO committed-set root and the anchor for future per-leaf
21
+ * (proof-based) scaling.
22
+ */
23
+ export const FACTORY_PARTY_ROOT_PORT = 111;
24
+ /**
25
+ * State port carrying the committed balance set-root (STATE(112)) — the MMR root
26
+ * over `(pubkey, balance)` leaves (RFC-048 §12.4). Pinned on every spend.
27
+ */
28
+ export const FACTORY_BALANCE_ROOT_PORT = 112;
29
+ /** Public-key digests for the party set, padded to a power of two (Minima MMR). */
30
+ function padPartySet(participants) {
31
+ if (!Array.isArray(participants) || participants.length === 0) {
32
+ throw new Error('factory party set requires at least one participant');
33
+ }
34
+ const pubkeys = participants.map((p, i) => {
35
+ const raw = (p.publicKeyDigest ?? '').replace(/^0x/i, '');
36
+ if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
37
+ throw new Error(`participant[${i}].publicKeyDigest must be a hex string`);
38
+ }
39
+ return hexToBytes(raw);
40
+ });
41
+ let size = 1;
42
+ while (size < pubkeys.length)
43
+ size <<= 1;
44
+ while (pubkeys.length < size)
45
+ pubkeys.push(new Uint8Array(32));
46
+ return pubkeys;
47
+ }
48
+ /** MMR root (hex, no `0x`) over the participants' public-key digests.
49
+ *
50
+ * Minima's `MMRTree` builds a perfect binary tree (power-of-two leaves), so the
51
+ * party set is padded to the next power of two with the **zero digest** sentinel
52
+ * (a fixed, publicly known padding leaf). The root is thus a Minima-native MMR
53
+ * root — the same structure the VTXO batch root commits and the on-chain `PROOF`
54
+ * verifies — over an arbitrary number of participants.
55
+ */
56
+ export function factoryPartySetRoot(participants) {
57
+ const root = MMRTree.fromPublicKeys(padPartySet(participants)).getRoot();
58
+ if (!root)
59
+ throw new Error('factoryPartySetRoot: failed to compute the party-set root');
60
+ return bytesToHex(root.data).toLowerCase();
61
+ }
62
+ /**
63
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
64
+ * the committed party-set root — the witness for a per-leaf
65
+ * `buildMmrMembershipCovenant` escape (RFC-048 §12.4).
66
+ */
67
+ export function factoryPartyProof(participants, index) {
68
+ if (!Number.isInteger(index) || index < 0 || index >= participants.length) {
69
+ throw new Error(`factoryPartyProof: index ${index} is out of range (0..${participants.length - 1})`);
70
+ }
71
+ const proof = MMRTree.fromPublicKeys(padPartySet(participants)).getProof(index);
72
+ return bytesToHex(serializeMMRProof(proof)).toLowerCase();
73
+ }
74
+ /**
75
+ * Balance set-root (RFC-048 §12.4) — the MMR root over `(pubkey, balance)` leaves,
76
+ * where each participant's `contributionAmount` is the **leaf sum**. This commits
77
+ * the exact distribution of the factory balance (`rootSum` = the total) and is the
78
+ * scalable, off-chain commitment that replaces per-party balance ports.
79
+ */
80
+ export function factoryBalanceSetRoot(participants) {
81
+ const tree = buildBalanceTree(participants);
82
+ const root = tree.getRoot();
83
+ if (!root)
84
+ throw new Error('factoryBalanceSetRoot: failed to compute the balance set-root');
85
+ return { root: bytesToHex(root.data).toLowerCase(), rootSum: root.value };
86
+ }
87
+ /**
88
+ * Serialized MMR inclusion proof (hex, no `0x`) for participant `index` against
89
+ * the committed balance set-root — the witness for a `buildMmrMembershipCovenant`
90
+ * balance escape (leaf sum = the participant's balance).
91
+ */
92
+ export function factoryBalanceProof(participants, index) {
93
+ if (!Number.isInteger(index) || index < 0 || index >= participants.length) {
94
+ throw new Error(`factoryBalanceProof: index ${index} is out of range (0..${participants.length - 1})`);
95
+ }
96
+ const proof = buildBalanceTree(participants).getProof(index);
97
+ return bytesToHex(serializeMMRProof(proof)).toLowerCase();
98
+ }
99
+ /** Padded (power-of-two) MMR tree over `(pubkey, balance)` leaves. */
100
+ function buildBalanceTree(participants) {
101
+ if (!Array.isArray(participants) || participants.length === 0) {
102
+ throw new Error('factory balance set requires at least one participant');
103
+ }
104
+ const tree = new MMRTree();
105
+ for (const [i, p] of participants.entries()) {
106
+ const raw = (p.publicKeyDigest ?? '').replace(/^0x/i, '');
107
+ if (raw.length === 0 || !/^[0-9a-fA-F]+$/.test(raw)) {
108
+ throw new Error(`participant[${i}].publicKeyDigest must be a hex string`);
109
+ }
110
+ if (p.contributionAmount < 0n) {
111
+ throw new Error(`participant[${i}].contributionAmount must be non-negative`);
112
+ }
113
+ tree.addLeaf(createMMRDataLeafNode(hexToBytes(raw), p.contributionAmount));
114
+ }
115
+ let size = 1;
116
+ while (size < participants.length)
117
+ size <<= 1;
118
+ for (let i = participants.length; i < size; i++) {
119
+ tree.addLeaf(createMMRDataLeafNode(new Uint8Array(32), 0n));
120
+ }
121
+ return tree;
122
+ }
123
+ /**
124
+ * The exact payout set the pre-signed all-party distribution must contain — one
125
+ * output per participant, paying its committed balance (RFC-048 §12.4). Its sum
126
+ * equals `factoryBalanceSetRoot(...).rootSum`.
127
+ */
128
+ export function factoryDistributionOutputs(participants, tokenId = '0x00') {
129
+ if (!Array.isArray(participants) || participants.length === 0) {
130
+ throw new Error('factoryDistributionOutputs requires at least one participant');
131
+ }
132
+ return participants.map((p, i) => {
133
+ const raw = (p.settlementAddress ?? p.publicKeyDigest ?? '').replace(/^0x/i, '');
134
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
135
+ throw new Error(`factoryDistributionOutputs: participant[${i}] payout address must be a 64-hex digest`);
136
+ }
137
+ if (p.contributionAmount < 0n) {
138
+ throw new Error(`factoryDistributionOutputs: participant[${i}].contributionAmount must be non-negative`);
139
+ }
140
+ return { address: '0x' + raw, amount: p.contributionAmount, tokenId };
141
+ });
142
+ }
143
+ /**
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.
149
+ */
150
+ export function buildFactoryDistributionScript(config) {
151
+ const participants = config.participants;
152
+ if (!Array.isArray(participants) || participants.length < 1) {
153
+ throw new Error('buildFactoryDistributionScript requires at least one participant');
154
+ }
155
+ const pks = participants.map((p, i) => {
156
+ if (!p.publicKeyDigest)
157
+ throw new Error(`participant[${i}].publicKeyDigest is required`);
158
+ return kissHex(p.publicKeyDigest);
159
+ });
160
+ const escapePort = config.escapePort ?? FACTORY_ESCAPE_PORT;
161
+ const partyRootPort = config.partyRootPort ?? FACTORY_PARTY_ROOT_PORT;
162
+ const balanceRootPort = config.balanceRootPort ?? FACTORY_BALANCE_ROOT_PORT;
163
+ return [
164
+ '// Scalable factory escape — pre-signed all-party distribution (RFC-048 §12.4)',
165
+ `ASSERT SAMESTATE(${escapePort} ${escapePort})`,
166
+ `ASSERT SAMESTATE(${partyRootPort} ${partyRootPort})`,
167
+ `ASSERT SAMESTATE(${balanceRootPort} ${balanceRootPort})`,
168
+ `IF @BLOCK GT PREVSTATE(${escapePort}) THEN`,
169
+ ` ASSERT MULTISIG(${participants.length} ${pks.join(' ')})`,
170
+ ` RETURN TRUE`,
171
+ `ENDIF`,
172
+ `RETURN FALSE`,
173
+ ].join('\n');
174
+ }
175
+ /** Committed party-set root state variable (STATE(111)) for the factory funding output. */
176
+ export function factoryPartyRootStateVariable(root) {
177
+ const raw = root.replace(/^0x/i, '');
178
+ if (!/^[0-9a-fA-F]{64}$/.test(raw)) {
179
+ throw new Error(`factoryPartyRootStateVariable: root must be 32 bytes of hex; got ${JSON.stringify(root)}`);
180
+ }
181
+ return { port: FACTORY_PARTY_ROOT_PORT, value: '0x' + raw, type: 'hex' };
182
+ }
183
+ /** State port base for per-party allocations: party k ⇒ `base + k` (below the MSHS floor). */
184
+ export const FACTORY_BALANCE_PORT_BASE = 128;
185
+ /** Lowest port reserved for MSHS-2 (MASH); Omnia ports MUST stay below this.
186
+ * The node installs the MASH authorization bundle at ports **230–255**
187
+ * (`bundleBase = 256 − (4 + k) = 230`): the header R / ROOTS_BLOB /
188
+ * SECRETS_BLOB / TREE_SIG at 230–233 and PROOF at 234–255. A composite
189
+ * MASH + Omnia coin must therefore keep Omnia ports ≤ 229. */
190
+ export const MSHS_PORT_FLOOR = 230;
191
+ /** Maximum participants whose balance ports remain below the MSHS floor. */
192
+ export const FACTORY_MAX_PARTICIPANTS = MSHS_PORT_FLOOR - FACTORY_BALANCE_PORT_BASE;
193
+ /**
194
+ * Per-party allocation state variables (port base+k = party k's balance), seeded
18
195
  * into the factory funding output so the timeout escape can pay each party its
19
196
  * committed share.
20
197
  */
@@ -40,9 +217,9 @@ export function factoryEscapeStateVariable(escapeBlock) {
40
217
  * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
41
218
  * `SETTLEMENT=true` closes after minimal coinage (1 block).
42
219
  * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
43
- * single party k may withdraw its allocation `SHARE_k = PREVSTATE(200+k)`
220
+ * single party k may withdraw its allocation `SHARE_k = PREVSTATE(base+k)`
44
221
  * (the spent coin's share) to its own settlement address, zero its state in
45
- * the successor (`STATE(200+k) EQ 0`), keep the other parties' balances
222
+ * the successor (`STATE(base+k) EQ 0`), keep the other parties' balances
46
223
  * unchanged, and return the remainder to the factory script. Repeated
47
224
  * withdrawals cannot double-claim because each zeroes its own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
48
225
  * so the escape clock cannot be pushed by any counterparty.
@@ -53,12 +230,17 @@ export function buildFactoryScript(participants, _options = {}) {
53
230
  if (participants.length < 2) {
54
231
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
55
232
  }
233
+ if (participants.length > FACTORY_MAX_PARTICIPANTS) {
234
+ throw new Error(`Factory supports at most ${FACTORY_MAX_PARTICIPANTS} participants (got ${participants.length}) — balance ports would reach the MSHS-2 band (≥${MSHS_PORT_FLOOR})`);
235
+ }
56
236
  const count = participants.length;
57
237
  const pks = participants.map((p) => kissHex(p.publicKeyDigest));
58
238
  const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
59
239
  const lines = [
60
240
  'LET SETTLEMENT=STATE(100)',
61
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})`,
62
244
  `IF @BLOCK GT PREVSTATE(${FACTORY_ESCAPE_PORT}) THEN`,
63
245
  ];
64
246
  participants.forEach((_, k) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-factory",
3
- "version": "0.5.2",
3
+ "version": "0.5.5",
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",
@@ -24,13 +24,13 @@
24
24
  "LICENSE"
25
25
  ],
26
26
  "dependencies": {
27
+ "@totemsdk/core": "^1.3.0",
27
28
  "@totemsdk/omnia": "^2.0.1",
28
- "@totemsdk/wots-lease": "^1.0.1",
29
29
  "@totemsdk/tx-builder": "^0.2.1",
30
- "@totemsdk/core": "^1.3.0",
31
30
  "@totemsdk/txpow": "^1.0.2",
32
- "@totemsdk/storage": "^0.1.0",
33
- "@totemsdk/chain-provider": "^0.2.1"
31
+ "@totemsdk/wots-lease": "^1.0.1",
32
+ "@totemsdk/chain-provider": "^0.2.1",
33
+ "@totemsdk/storage": "^0.1.0"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/jest": "^30.0.0",