@totemsdk/omnia-factory 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /**
3
2
  * Durable factory signing-state store (RFC-007 G9).
4
3
  *
@@ -13,22 +12,20 @@
13
12
  * Backed by the shared revision-CAS snapshot store: single-key, whole-record
14
13
  * update, corruption surfaced (never treated as absence), no silent downgrade.
15
14
  */
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.createDurableFactoryStore = createDurableFactoryStore;
18
- const snapshot_1 = require("@totemsdk/storage/snapshot");
19
- const errors_1 = require("@totemsdk/storage/errors");
15
+ import { createRevisionedSnapshotStore, } from '@totemsdk/storage/snapshot';
16
+ import { StorageError } from '@totemsdk/storage/errors';
20
17
  const DEFAULT_NAMESPACE = 'totem_omnia_factory:v1:';
21
18
  function assertRegistryState(state) {
22
19
  if (typeof state !== 'object' || state === null || Array.isArray(state)) {
23
- throw new errors_1.StorageError('omnia-factory registry state is not an object', 'corrupt');
20
+ throw new StorageError('omnia-factory registry state is not an object', 'corrupt');
24
21
  }
25
22
  const value = state.factories;
26
23
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
27
- throw new errors_1.StorageError('omnia-factory registry state is missing section "factories"', 'corrupt');
24
+ throw new StorageError('omnia-factory registry state is missing section "factories"', 'corrupt');
28
25
  }
29
26
  }
30
- function createDurableFactoryStore(adapter, options = {}) {
31
- const snapshots = (0, snapshot_1.createRevisionedSnapshotStore)(adapter, {
27
+ export function createDurableFactoryStore(adapter, options = {}) {
28
+ const snapshots = createRevisionedSnapshotStore(adapter, {
32
29
  namespace: options.namespace ?? DEFAULT_NAMESPACE,
33
30
  requireAckMode: options.requireAckMode,
34
31
  empty: () => ({ factories: {} }),
package/dist/factory.d.ts CHANGED
@@ -54,6 +54,27 @@ export declare function createFactory(participants: FactoryParticipant[], tokenI
54
54
  * must match a registered participant not yet signed).
55
55
  */
56
56
  export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
57
+ /** A co-signer's opening signature, held until the opening is confirmed. */
58
+ export interface FactoryOpeningSignature {
59
+ factoryId: string;
60
+ partyId: string;
61
+ signature: Uint8Array;
62
+ reservationId: string;
63
+ }
64
+ /**
65
+ * Produce this party's opening signature WITHOUT committing the lease
66
+ * (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
67
+ * mirroring the splice accept round so a peer can gather N-of-N signatures
68
+ * without stranding or prematurely committing one-time keys.
69
+ */
70
+ export declare function signFactoryOpening(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<FactoryOpeningSignature>;
71
+ /** Verify a remote opening signature against a factory participant. */
72
+ export declare function verifyFactorySignature(factory: ChannelFactory, partyId: string, signature: Uint8Array, verify?: (sig: Uint8Array, commitment: Uint8Array, pkd: string) => boolean): boolean;
73
+ /**
74
+ * Merge a co-signer's opening signature (RFC-035 B2). When all N participants
75
+ * have signed, the opening commits (`'opening'` → `'active'`).
76
+ */
77
+ export declare function applyFactorySignature(factory: ChannelFactory, partyId: string, signature: Uint8Array): ChannelFactory;
57
78
  /**
58
79
  * Move factory allocation between two participants (atomic N-of-N).
59
80
  *
package/dist/factory.js CHANGED
@@ -1,15 +1,9 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.enforceConservation = enforceConservation;
4
- exports.createFactory = createFactory;
5
- exports.acceptFactory = acceptFactory;
6
- exports.reallocate = reallocate;
7
- const core_1 = require("@totemsdk/core");
8
- const core_2 = require("@totemsdk/core");
9
- const omnia_1 = require("@totemsdk/omnia");
10
- const txpow_1 = require("@totemsdk/txpow");
11
- const script_js_1 = require("./script.js");
12
- const commitment_js_1 = require("./commitment.js");
1
+ import { sha3_256 } from '@totemsdk/core/wasm';
2
+ import { concatBytes } from '@totemsdk/core/wasm';
3
+ import { buildFundingTx, omniaDraftToMinimaBytes, computeTxDraftDigest, verifyChannelSignature, } from '@totemsdk/omnia';
4
+ import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
5
+ import { buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS } from './script.js';
6
+ import { computeFactoryStateCommitment } from './commitment.js';
13
7
  // ─── Balance conservation ────────────────────────────────────────────────────
14
8
  /**
15
9
  * Enforce the factory's balance conservation invariant:
@@ -17,7 +11,7 @@ const commitment_js_1 = require("./commitment.js");
17
11
  *
18
12
  * Throws on violation. Called after every committed state transition.
19
13
  */
20
- function enforceConservation(factory) {
14
+ export function enforceConservation(factory) {
21
15
  const allocSum = Object.values(factory.allocations).reduce((a, b) => a + b, 0n);
22
16
  const vcSum = factory.virtualChannels.reduce((acc, vc) => acc + vc.totalValue, 0n);
23
17
  if (allocSum + vcSum !== factory.totalValue) {
@@ -30,8 +24,8 @@ function enforceConservation(factory) {
30
24
  * Execute the full WOTS lease cycle for one party (reserve → sign → verify → commit).
31
25
  *
32
26
  * Verification uses the optional `bundle.verify` override first; falls back to
33
- * `wotsVerifyDigest` from `@totemsdk/core`. If verification fails, the reservation
34
- * is burned and an error is thrown.
27
+ * `verifyChannelSignature` from `@totemsdk/omnia` (RFC-037: the wallet's unified
28
+ * WOTS scheme). If verification fails, the reservation is burned and an error is thrown.
35
29
  */
36
30
  async function leaseSign(factoryId, commitment, purpose, participant, bundle) {
37
31
  const reservation = await bundle.leaseProvider.reserveKeyUse({
@@ -49,8 +43,7 @@ async function leaseSign(factoryId, commitment, purpose, participant, bundle) {
49
43
  }
50
44
  // Verify the signature against the REGISTERED participant public key digest —
51
45
  // not self-reported from the signer, ensuring the signer matches the factory record.
52
- const verifyFn = bundle.verify
53
- ?? ((s, c, pkd) => (0, core_2.wotsVerifyDigest)(s, c, (0, core_2.hexToBytes)(pkd)));
46
+ const verifyFn = bundle.verify ?? verifyChannelSignature;
54
47
  if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
55
48
  await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
56
49
  throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
@@ -82,7 +75,7 @@ function generateFactoryId(participants, tokenId, tokenScale) {
82
75
  tokenScale,
83
76
  nonce,
84
77
  });
85
- return Buffer.from((0, core_1.sha3_256)(new TextEncoder().encode(input))).toString('hex');
78
+ return Buffer.from(sha3_256(new TextEncoder().encode(input))).toString('hex');
86
79
  }
87
80
  // ─── createFactory ────────────────────────────────────────────────────────────
88
81
  /**
@@ -116,7 +109,7 @@ function generateFactoryId(participants, tokenId, tokenScale) {
116
109
  * is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
117
110
  * Defaults to 0.
118
111
  */
119
- async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
112
+ export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
120
113
  if (participants.length < 2) {
121
114
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
122
115
  }
@@ -130,7 +123,7 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
130
123
  for (const p of participants) {
131
124
  allocations[p.partyId] = p.contributionAmount;
132
125
  }
133
- const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
126
+ const { script, address } = buildAndHashFactoryScript(participants);
134
127
  const factoryId = generateFactoryId(participants, tokenId, tokenScale);
135
128
  // ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
136
129
  let fundingTxId;
@@ -138,20 +131,22 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
138
131
  let pendingCommitment;
139
132
  const allHaveCoinId = participants.every(p => p.fundingCoinId);
140
133
  if (allHaveCoinId && chainProvider) {
141
- const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), participants.map(p => p.settlementAddress ?? p.publicKeyDigest));
134
+ const tip = await chainProvider.getTip();
135
+ const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
136
+ const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), participants.map(p => p.settlementAddress ?? p.publicKeyDigest), [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
142
137
  // All parties co-sign the TX digest — the exact on-chain TX structure.
143
- pendingCommitment = (0, omnia_1.computeTxDraftDigest)(fundingDraft);
144
- const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
145
- const txBody = (0, txpow_1.serializeTxBody)(draftBytes, new Uint8Array(0));
146
- const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
147
- const fullTxPoW = (0, core_2.concatBytes)((0, core_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
138
+ pendingCommitment = computeTxDraftDigest(fundingDraft);
139
+ const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
140
+ const txBody = serializeTxBody(draftBytes, new Uint8Array(0));
141
+ const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
142
+ const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
148
143
  await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
149
144
  fundingTxId = Buffer.from(mined.txpowId).toString('hex');
150
145
  fundingCoinId = `${fundingTxId}-0`;
151
146
  }
152
147
  else {
153
148
  // In-memory / test path: sign the factory state commitment instead.
154
- pendingCommitment = (0, commitment_js_1.computeFactoryStateCommitment)(factoryId, 1, allocations, []);
149
+ pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
155
150
  }
156
151
  // Sign with the proposer's lease (full bundle preserved so verify override is available).
157
152
  const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
@@ -201,7 +196,7 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
201
196
  * @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
202
197
  * must match a registered participant not yet signed).
203
198
  */
204
- async function acceptFactory(factory, bundle) {
199
+ export async function acceptFactory(factory, bundle) {
205
200
  if (factory.status !== 'opening') {
206
201
  throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
207
202
  }
@@ -226,6 +221,84 @@ async function acceptFactory(factory, bundle) {
226
221
  }
227
222
  return updatedFactory;
228
223
  }
224
+ /**
225
+ * Produce this party's opening signature WITHOUT committing the lease
226
+ * (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
227
+ * mirroring the splice accept round so a peer can gather N-of-N signatures
228
+ * without stranding or prematurely committing one-time keys.
229
+ */
230
+ export async function signFactoryOpening(factory, bundle) {
231
+ if (factory.status !== 'opening' || !factory.pendingCommitment) {
232
+ throw new Error(`signFactoryOpening requires an 'opening' factory, got '${factory.status}'`);
233
+ }
234
+ const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
235
+ if (!participant) {
236
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
237
+ }
238
+ if (factory.pendingSignatures[participant.partyId]) {
239
+ throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
240
+ }
241
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
242
+ const reservation = await bundle.leaseProvider.reserveKeyUse({
243
+ treeId: `omnia-factory-${factory.factoryId}`,
244
+ purpose: 'factory-open',
245
+ payloadHash: Buffer.from(commitment).toString('hex'),
246
+ });
247
+ let sig;
248
+ try {
249
+ sig = await bundle.signer.sign(commitment, reservation.indices);
250
+ }
251
+ catch (err) {
252
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
253
+ throw err;
254
+ }
255
+ const verifyFn = bundle.verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
256
+ if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
257
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
258
+ throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
259
+ }
260
+ return {
261
+ factoryId: factory.factoryId,
262
+ partyId: participant.partyId,
263
+ signature: sig,
264
+ reservationId: reservation.reservationId,
265
+ };
266
+ }
267
+ /** Verify a remote opening signature against a factory participant. */
268
+ export function verifyFactorySignature(factory, partyId, signature, verify) {
269
+ if (!factory.pendingCommitment)
270
+ return false;
271
+ const participant = factory.participants.find(p => p.partyId === partyId);
272
+ if (!participant)
273
+ return false;
274
+ const commitment = Buffer.from(factory.pendingCommitment, 'hex');
275
+ const verifyFn = verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
276
+ try {
277
+ return verifyFn(signature, commitment, participant.publicKeyDigest);
278
+ }
279
+ catch {
280
+ return false;
281
+ }
282
+ }
283
+ /**
284
+ * Merge a co-signer's opening signature (RFC-035 B2). When all N participants
285
+ * have signed, the opening commits (`'opening'` → `'active'`).
286
+ */
287
+ export function applyFactorySignature(factory, partyId, signature) {
288
+ if (factory.status !== 'opening') {
289
+ throw new Error(`applyFactorySignature requires factory status 'opening', got '${factory.status}'`);
290
+ }
291
+ if (!factory.participants.find(p => p.partyId === partyId)) {
292
+ throw new Error(`'${partyId}' is not a registered factory participant`);
293
+ }
294
+ if (factory.pendingSignatures[partyId]) {
295
+ throw new Error(`Party '${partyId}' has already co-signed this factory proposal`);
296
+ }
297
+ const newSigs = { ...factory.pendingSignatures, [partyId]: signature };
298
+ const updated = { ...factory, pendingSignatures: newSigs };
299
+ const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
300
+ return allSigned ? commitOpening(updated) : updated;
301
+ }
229
302
  function commitOpening(factory) {
230
303
  const logEntry = {
231
304
  sequence: 1,
@@ -259,7 +332,7 @@ function commitOpening(factory) {
259
332
  * @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
260
333
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
261
334
  */
262
- async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
335
+ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
263
336
  if (factory.status !== 'active') {
264
337
  throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
265
338
  }
@@ -280,7 +353,7 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
280
353
  };
281
354
  const newSequence = factory.currentSequence + 1;
282
355
  const vcIds = factory.virtualChannels.map(vc => vc.channelId);
283
- const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, vcIds);
356
+ const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, vcIds);
284
357
  await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
285
358
  const logEntry = {
286
359
  sequence: newSequence,
package/dist/index.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
2
- export { buildFactoryScript, buildAndHashFactoryScript, scriptAddress, normalizeScript, } from './script.js';
2
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, scriptAddress, normalizeScript, } from './script.js';
3
3
  export { computeFactoryStateCommitment } from './commitment.js';
4
- export { createFactory, acceptFactory, reallocate, enforceConservation, } from './factory.js';
5
- export { openVirtualChannel, closeVirtualChannel, } from './virtual.js';
6
- export { closeFactory, buildDisputePayload, } from './settlement.js';
4
+ export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
5
+ export type { FactoryOpeningSignature } from './factory.js';
6
+ export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
7
+ export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
8
+ export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, } from './virtual.js';
9
+ export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
10
+ export type { FactorySettlementDraft, FactorySettlementSignature, } from './settlement.js';
7
11
  export { createDurableFactoryStore, } from './durable-factory-store.js';
8
12
  export type { FactoryRegistryState, DurableFactoryStore, DurableFactoryStoreOptions, } from './durable-factory-store.js';
package/dist/index.js CHANGED
@@ -1,23 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDurableFactoryStore = exports.buildDisputePayload = exports.closeFactory = exports.closeVirtualChannel = exports.openVirtualChannel = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
4
- var script_js_1 = require("./script.js");
5
- Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
6
- Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
7
- Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: function () { return script_js_1.scriptAddress; } });
8
- Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
9
- var commitment_js_1 = require("./commitment.js");
10
- Object.defineProperty(exports, "computeFactoryStateCommitment", { enumerable: true, get: function () { return commitment_js_1.computeFactoryStateCommitment; } });
11
- var factory_js_1 = require("./factory.js");
12
- Object.defineProperty(exports, "createFactory", { enumerable: true, get: function () { return factory_js_1.createFactory; } });
13
- Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
14
- Object.defineProperty(exports, "reallocate", { enumerable: true, get: function () { return factory_js_1.reallocate; } });
15
- Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: function () { return factory_js_1.enforceConservation; } });
16
- var virtual_js_1 = require("./virtual.js");
17
- Object.defineProperty(exports, "openVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.openVirtualChannel; } });
18
- Object.defineProperty(exports, "closeVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.closeVirtualChannel; } });
19
- var settlement_js_1 = require("./settlement.js");
20
- Object.defineProperty(exports, "closeFactory", { enumerable: true, get: function () { return settlement_js_1.closeFactory; } });
21
- Object.defineProperty(exports, "buildDisputePayload", { enumerable: true, get: function () { return settlement_js_1.buildDisputePayload; } });
22
- var durable_factory_store_js_1 = require("./durable-factory-store.js");
23
- Object.defineProperty(exports, "createDurableFactoryStore", { enumerable: true, get: function () { return durable_factory_store_js_1.createDurableFactoryStore; } });
1
+ export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, scriptAddress, normalizeScript, } from './script.js';
2
+ export { computeFactoryStateCommitment } from './commitment.js';
3
+ export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
4
+ // RFC-035 B2 — factory opening round-trip over the coordination transport.
5
+ export { createFactoryCoordination, } from './coordination.js';
6
+ export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
7
+ export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
8
+ export { createDurableFactoryStore, } from './durable-factory-store.js';
package/dist/script.d.ts CHANGED
@@ -1,21 +1,48 @@
1
1
  import type { FactoryParticipant } from './types.js';
2
+ /** Blocks after the funding tip at which the unilateral escape opens. */
3
+ export declare const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
4
+ /** State port carrying the absolute escape block (STATE(103)). */
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;
8
+ export interface FactoryScriptOptions {
9
+ /** Reserved for callers; the escape block is carried in STATE(103) at funding. */
10
+ escapeBlock?: number;
11
+ }
2
12
  /**
3
- * Build the N-of-N MULTISIG MAST funding script for a channel factory.
4
- *
5
- * Spending rules:
6
- * - Any cooperative close (SETTLEMENT=true): all N parties sign, spend after
7
- * minimal coinage (1 block) so the factory can be closed immediately after
8
- * a confirmed update.
9
- * - Non-settlement path: all N parties must still sign (ASSERT MULTISIG(N ...))
10
- * but can spend in the same block (no coinage requirement) — used for future
11
- * optimistic factory updates if desired.
13
+ * Per-party allocation state variables (port 200+k = party k's balance), seeded
14
+ * into the factory funding output so the timeout escape can pay each party its
15
+ * committed share.
16
+ */
17
+ export declare function factoryBalanceStateVariables(participants: FactoryParticipant[]): {
18
+ port: number;
19
+ value: bigint;
20
+ type: 'number';
21
+ }[];
22
+ /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
23
+ export declare function factoryEscapeStateVariable(escapeBlock: number): {
24
+ port: number;
25
+ value: bigint;
26
+ type: 'number';
27
+ };
28
+ /**
29
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory
30
+ * (RFC-039, CUSTODY-POLICY §2).
12
31
  *
13
- * `storestate=true` is achieved by encoding STATE(100) in the output state
14
- * variables of every factory TX.
32
+ * Spend paths:
33
+ * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
34
+ * `SETTLEMENT=true` closes after minimal coinage (1 block).
35
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
36
+ * single party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its
37
+ * own settlement address, zero its state (`STATE(200+k) EQ 0`), keep the
38
+ * other parties' balances unchanged, and return the remainder to the factory
39
+ * script. Repeated withdrawals cannot double-claim because each zeroes its
40
+ * own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
41
+ * so the escape clock cannot be pushed by any counterparty.
15
42
  *
16
43
  * Minimum 2 participants required.
17
44
  */
18
- export declare function buildFactoryScript(participants: FactoryParticipant[]): string;
45
+ export declare function buildFactoryScript(participants: FactoryParticipant[], _options?: FactoryScriptOptions): string;
19
46
  export declare function normalizeScript(script: string): string;
20
47
  /** Compute the SHA3-256 script-hash address for a factory script. */
21
48
  export declare function scriptAddress(script: string): string;
@@ -23,7 +50,7 @@ export declare function scriptAddress(script: string): string;
23
50
  * Build the factory script and compute its canonical address in one step.
24
51
  * The address is used as the output address of the factory funding TX.
25
52
  */
26
- export declare function buildAndHashFactoryScript(participants: FactoryParticipant[]): {
53
+ export declare function buildAndHashFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): {
27
54
  script: string;
28
55
  address: string;
29
56
  };
package/dist/script.js CHANGED
@@ -1,10 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildFactoryScript = buildFactoryScript;
4
- exports.normalizeScript = normalizeScript;
5
- exports.scriptAddress = scriptAddress;
6
- exports.buildAndHashFactoryScript = buildAndHashFactoryScript;
7
- const core_1 = require("@totemsdk/core");
1
+ import { computeScriptAddress } from '@totemsdk/core/scripts';
8
2
  /**
9
3
  * Normalize a hex public key digest to the KISSVM-compatible format:
10
4
  * strip leading 0x/0X and render as upper-case hex with leading '0X'.
@@ -13,51 +7,98 @@ function kissHex(hex) {
13
7
  const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
14
8
  return '0X' + raw.toUpperCase();
15
9
  }
10
+ /** Blocks after the funding tip at which the unilateral escape opens. */
11
+ export const FACTORY_ESCAPE_DELAY_BLOCKS = 256;
12
+ /** State port carrying the absolute escape block (STATE(103)). */
13
+ 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
16
  /**
17
- * Build the N-of-N MULTISIG MAST funding script for a channel factory.
18
- *
19
- * Spending rules:
20
- * - Any cooperative close (SETTLEMENT=true): all N parties sign, spend after
21
- * minimal coinage (1 block) so the factory can be closed immediately after
22
- * a confirmed update.
23
- * - Non-settlement path: all N parties must still sign (ASSERT MULTISIG(N ...))
24
- * but can spend in the same block (no coinage requirement) — used for future
25
- * optimistic factory updates if desired.
17
+ * Per-party allocation state variables (port 200+k = party k's balance), seeded
18
+ * into the factory funding output so the timeout escape can pay each party its
19
+ * committed share.
20
+ */
21
+ export function factoryBalanceStateVariables(participants) {
22
+ return participants.map((p, k) => ({
23
+ port: FACTORY_BALANCE_PORT_BASE + k,
24
+ value: p.contributionAmount,
25
+ type: 'number',
26
+ }));
27
+ }
28
+ /** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
29
+ export function factoryEscapeStateVariable(escapeBlock) {
30
+ if (!Number.isInteger(escapeBlock) || escapeBlock < 0) {
31
+ throw new Error(`escapeBlock must be a non-negative integer, got ${JSON.stringify(escapeBlock)}`);
32
+ }
33
+ return { port: FACTORY_ESCAPE_PORT, value: BigInt(escapeBlock), type: 'number' };
34
+ }
35
+ /**
36
+ * Build the N-of-N MULTISIG MAST funding script for a channel factory
37
+ * (RFC-039, CUSTODY-POLICY §2).
26
38
  *
27
- * `storestate=true` is achieved by encoding STATE(100) in the output state
28
- * variables of every factory TX.
39
+ * Spend paths:
40
+ * - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
41
+ * `SETTLEMENT=true` closes after minimal coinage (1 block).
42
+ * - **Unilateral escape** (after the absolute block in `STATE(103)`): any
43
+ * single party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its
44
+ * own settlement address, zero its state (`STATE(200+k) EQ 0`), keep the
45
+ * other parties' balances unchanged, and return the remainder to the factory
46
+ * script. Repeated withdrawals cannot double-claim because each zeroes its
47
+ * own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
48
+ * so the escape clock cannot be pushed by any counterparty.
29
49
  *
30
50
  * Minimum 2 participants required.
31
51
  */
32
- function buildFactoryScript(participants) {
52
+ export function buildFactoryScript(participants, _options = {}) {
33
53
  if (participants.length < 2) {
34
54
  throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
35
55
  }
36
- const n = participants.length;
37
- const pks = participants.map(p => kissHex(p.publicKeyDigest)).join(' ');
38
- return [
56
+ const count = participants.length;
57
+ const pks = participants.map((p) => kissHex(p.publicKeyDigest));
58
+ const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
59
+ const lines = [
39
60
  'LET SETTLEMENT=STATE(100)',
40
- `ASSERT MULTISIG(${n} ${pks})`,
41
- 'IF SETTLEMENT THEN',
42
- ' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF',
43
- 'ELSE',
44
- ' RETURN TRUE',
45
- 'ENDIF',
46
- ].join('\n');
61
+ `ASSERT SAMESTATE(${FACTORY_ESCAPE_PORT} ${FACTORY_ESCAPE_PORT})`,
62
+ `IF @BLOCK GT STATE(${FACTORY_ESCAPE_PORT}) THEN`,
63
+ ];
64
+ participants.forEach((_, k) => {
65
+ const port = FACTORY_BALANCE_PORT_BASE + k;
66
+ lines.push(` LET SHARE${k}=STATE(${port})`);
67
+ lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
68
+ lines.push(` IF SHARE${k} GT 0 THEN`);
69
+ lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
70
+ for (let j = 0; j < count; j++) {
71
+ if (j === k)
72
+ continue;
73
+ lines.push(` ASSERT STATE(${FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${FACTORY_BALANCE_PORT_BASE + j})`);
74
+ }
75
+ lines.push(` ASSERT STATE(${port}) EQ 0`);
76
+ lines.push(` RETURN VERIFYOUT(@INPUT @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
77
+ lines.push(' ENDIF');
78
+ lines.push(' ENDIF');
79
+ });
80
+ lines.push('ENDIF');
81
+ lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
82
+ lines.push('IF SETTLEMENT THEN');
83
+ lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
84
+ lines.push('ELSE');
85
+ lines.push(' RETURN TRUE');
86
+ lines.push('ENDIF');
87
+ return lines.join('\n');
47
88
  }
48
- function normalizeScript(script) {
89
+ export function normalizeScript(script) {
49
90
  return script.trim().toUpperCase();
50
91
  }
51
92
  /** Compute the SHA3-256 script-hash address for a factory script. */
52
- function scriptAddress(script) {
53
- return (0, core_1.computeScriptAddress)(script);
93
+ export function scriptAddress(script) {
94
+ return computeScriptAddress(script);
54
95
  }
55
96
  /**
56
97
  * Build the factory script and compute its canonical address in one step.
57
98
  * The address is used as the output address of the factory funding TX.
58
99
  */
59
- function buildAndHashFactoryScript(participants) {
60
- const script = buildFactoryScript(participants);
100
+ export function buildAndHashFactoryScript(participants, options = {}) {
101
+ const script = buildFactoryScript(participants, options);
61
102
  const address = scriptAddress(script);
62
103
  return { script, address };
63
104
  }
@@ -1,19 +1,43 @@
1
+ import type { OmniaTxDraft } from '@totemsdk/omnia';
1
2
  import type { ChainStateProvider } from '@totemsdk/chain-provider';
2
3
  import type { ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, WotsLeaseBundle } from './types.js';
4
+ /** Deterministic settlement TX material for a factory (RFC-035 B3). */
5
+ export interface FactorySettlementDraft {
6
+ settlementDraft: OmniaTxDraft;
7
+ settlementTxHex: string;
8
+ txDigest: Uint8Array;
9
+ }
10
+ /** A participant's settlement signature, held until the close is confirmed. */
11
+ export interface FactorySettlementSignature {
12
+ partyId: string;
13
+ signature: Uint8Array;
14
+ reservationId: string;
15
+ }
3
16
  /**
4
- * Cooperative N-of-N factory close.
17
+ * Build the cooperative settlement TX + digest (no signing). Exported so peers
18
+ * can independently rebuild and bind a proposal (RFC-035 B3).
19
+ */
20
+ export declare function buildFactorySettlement(factory: ChannelFactory): FactorySettlementDraft;
21
+ /**
22
+ * Produce this party's settlement signature WITHOUT committing the lease
23
+ * (RFC-035 B3). The caller commits on `FACTORY_CLOSE_FINALIZED` or burns on expiry.
24
+ */
25
+ export declare function signFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, bundle: WotsLeaseBundle): Promise<FactorySettlementSignature>;
26
+ /** Verify a remote settlement signature against a factory participant. */
27
+ export declare function verifyFactorySettlementSignature(factory: ChannelFactory, txDigest: Uint8Array, partyId: string, signature: Uint8Array, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): boolean;
28
+ /**
29
+ * Assemble N-of-N settlement signatures into the MULTISIG witness + payload, and
30
+ * (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
31
+ */
32
+ export declare function assembleFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, signatures: Record<string, FactorySettlementSignature>, chainProvider?: ChainStateProvider, options?: {
33
+ verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean;
34
+ }): Promise<FactorySettlementPayload>;
35
+ /**
36
+ * Cooperative N-of-N factory close (central/local path).
5
37
  *
6
- * Flow:
7
- * 1. Fail fast if `factory.fundingCoinId` is not set — settlement TX requires
8
- * a concrete input coin.
9
- * 2. Build the settlement OmniaTxDraft (N outputs, one per participant with a
10
- * positive allocation) spending the factory's N-of-N MULTISIG input.
11
- * 3. Compute the TX draft digest via `computeTxDraftDigest` from `@totemsdk/omnia`.
12
- * 4. Collect N-of-N signatures — all participants sign + verify the TX digest
13
- * via the full WOTS lease cycle (reserve → sign → verify → commit).
14
- * 5. Encode the concatenated WOTS signatures as the settlement TX witness.
15
- * 6. When `chainProvider` is supplied: mine via `@totemsdk/txpow`'s `mineTxPoW`,
16
- * assemble the full TxPoW blob, and broadcast.
38
+ * Builds the settlement TX, collects all N signatures (each committing its own
39
+ * lease via the full WOTS cycle), assembles the witness, and — when a
40
+ * `chainProvider` is supplied — mines + broadcasts the settlement TxPoW.
17
41
  *
18
42
  * @param factory - Active factory with no open virtual channels.
19
43
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.