@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.
- package/dist/cjs/commitment.d.ts +16 -0
- package/dist/cjs/commitment.js +30 -0
- package/dist/cjs/coordination.d.ts +52 -0
- package/dist/cjs/coordination.js +319 -0
- package/dist/cjs/durable-factory-store.d.ts +42 -0
- package/dist/cjs/durable-factory-store.js +59 -0
- package/dist/cjs/factory.d.ts +91 -0
- package/dist/cjs/factory.js +382 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +39 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/script.d.ts +56 -0
- package/dist/cjs/script.js +113 -0
- package/dist/cjs/settlement.d.ts +55 -0
- package/dist/cjs/settlement.js +193 -0
- package/dist/cjs/types.d.ts +131 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/virtual.d.ts +75 -0
- package/dist/cjs/virtual.js +277 -0
- package/dist/commitment.js +3 -6
- package/dist/coordination.d.ts +52 -0
- package/dist/coordination.js +316 -0
- package/dist/durable-factory-store.js +6 -9
- package/dist/factory.d.ts +21 -0
- package/dist/factory.js +103 -30
- package/dist/index.d.ts +8 -4
- package/dist/index.js +8 -23
- package/dist/script.d.ts +40 -13
- package/dist/script.js +75 -34
- package/dist/settlement.d.ts +36 -12
- package/dist/settlement.js +108 -70
- package/dist/types.js +1 -2
- package/dist/virtual.d.ts +31 -0
- package/dist/virtual.js +110 -59
- package/package.json +15 -9
- package/rust/pkg/omnia_factory_wasm_bg.wasm +0 -0
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/omnia_factory_wasm_bg.wasm +0 -0
- package/rust/pkg-node/package.json +1 -1
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.enforceConservation = enforceConservation;
|
|
4
|
+
exports.createFactory = createFactory;
|
|
5
|
+
exports.acceptFactory = acceptFactory;
|
|
6
|
+
exports.signFactoryOpening = signFactoryOpening;
|
|
7
|
+
exports.verifyFactorySignature = verifyFactorySignature;
|
|
8
|
+
exports.applyFactorySignature = applyFactorySignature;
|
|
9
|
+
exports.reallocate = reallocate;
|
|
10
|
+
const wasm_1 = require("@totemsdk/core/wasm");
|
|
11
|
+
const wasm_2 = require("@totemsdk/core/wasm");
|
|
12
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
13
|
+
const txpow_1 = require("@totemsdk/txpow");
|
|
14
|
+
const script_js_1 = require("./script.js");
|
|
15
|
+
const commitment_js_1 = require("./commitment.js");
|
|
16
|
+
// ─── Balance conservation ────────────────────────────────────────────────────
|
|
17
|
+
/**
|
|
18
|
+
* Enforce the factory's balance conservation invariant:
|
|
19
|
+
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
20
|
+
*
|
|
21
|
+
* Throws on violation. Called after every committed state transition.
|
|
22
|
+
*/
|
|
23
|
+
function enforceConservation(factory) {
|
|
24
|
+
const allocSum = Object.values(factory.allocations).reduce((a, b) => a + b, 0n);
|
|
25
|
+
const vcSum = factory.virtualChannels.reduce((acc, vc) => acc + vc.totalValue, 0n);
|
|
26
|
+
if (allocSum + vcSum !== factory.totalValue) {
|
|
27
|
+
throw new Error(`Balance conservation violated: allocations(${allocSum}) + virtualChannels(${vcSum}) ` +
|
|
28
|
+
`!== totalValue(${factory.totalValue})`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
// ─── Internal signing helpers ─────────────────────────────────────────────────
|
|
32
|
+
/**
|
|
33
|
+
* Execute the full WOTS lease cycle for one party (reserve → sign → verify → commit).
|
|
34
|
+
*
|
|
35
|
+
* Verification uses the optional `bundle.verify` override first; falls back to
|
|
36
|
+
* `verifyChannelSignature` from `@totemsdk/omnia` (RFC-037: the wallet's unified
|
|
37
|
+
* WOTS scheme). If verification fails, the reservation is burned and an error is thrown.
|
|
38
|
+
*/
|
|
39
|
+
async function leaseSign(factoryId, commitment, purpose, participant, bundle) {
|
|
40
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
41
|
+
treeId: `omnia-factory-${factoryId}`,
|
|
42
|
+
purpose,
|
|
43
|
+
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
44
|
+
});
|
|
45
|
+
let sig;
|
|
46
|
+
try {
|
|
47
|
+
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
// Verify the signature against the REGISTERED participant public key digest —
|
|
54
|
+
// not self-reported from the signer, ensuring the signer matches the factory record.
|
|
55
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
56
|
+
if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
|
|
57
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
58
|
+
throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
|
|
59
|
+
}
|
|
60
|
+
await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-${factoryId}`);
|
|
61
|
+
return sig;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Collect N-of-N signatures for a given commitment from ALL factory participants.
|
|
65
|
+
* Throws if any participant's bundle is missing or if any signature fails verification.
|
|
66
|
+
*/
|
|
67
|
+
async function collectNofN(factoryId, commitment, purpose, participants, leaseProviders) {
|
|
68
|
+
for (const p of participants) {
|
|
69
|
+
if (!leaseProviders[p.partyId]) {
|
|
70
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const p of participants) {
|
|
74
|
+
await leaseSign(factoryId, commitment, purpose, p, leaseProviders[p.partyId]);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// ─── Factory ID ───────────────────────────────────────────────────────────────
|
|
78
|
+
function generateFactoryId(participants, tokenId, tokenScale) {
|
|
79
|
+
const sorted = [...participants].sort((a, b) => a.partyId.localeCompare(b.partyId));
|
|
80
|
+
const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
81
|
+
const input = JSON.stringify({
|
|
82
|
+
participants: sorted.map(p => ({ partyId: p.partyId, pkd: p.publicKeyDigest })),
|
|
83
|
+
tokenId,
|
|
84
|
+
tokenScale,
|
|
85
|
+
nonce,
|
|
86
|
+
});
|
|
87
|
+
return Buffer.from((0, wasm_1.sha3_256)(new TextEncoder().encode(input))).toString('hex');
|
|
88
|
+
}
|
|
89
|
+
// ─── createFactory ────────────────────────────────────────────────────────────
|
|
90
|
+
/**
|
|
91
|
+
* Create a factory proposal (proposer step).
|
|
92
|
+
*
|
|
93
|
+
* The calling party (`signer.publicKeyDigest` matches one of `participants`)
|
|
94
|
+
* signs the factory opening commitment via `leaseProvider`, performing the full
|
|
95
|
+
* WOTS reserve → sign → verify → commit cycle.
|
|
96
|
+
*
|
|
97
|
+
* When ALL participants supply `fundingCoinId` and `chainProvider` is given,
|
|
98
|
+
* the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
|
|
99
|
+
* `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
|
|
100
|
+
* The TX draft digest is used as the factory opening commitment so that all
|
|
101
|
+
* parties are co-signing the EXACT on-chain TX structure.
|
|
102
|
+
*
|
|
103
|
+
* Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
|
|
104
|
+
* (useful for testing and off-chain simulation); the commitment falls back to
|
|
105
|
+
* the factory state commitment hash.
|
|
106
|
+
*
|
|
107
|
+
* The returned factory is in `'opening'` status. Every other participant must
|
|
108
|
+
* call `acceptFactory(factory, leaseProvider, signer)` before the factory
|
|
109
|
+
* transitions to `'active'`.
|
|
110
|
+
*
|
|
111
|
+
* @param participants - All N factory participants with their contribution amounts.
|
|
112
|
+
* @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
|
|
113
|
+
* @param leaseProvider - WOTS lease provider for the proposer's key slot.
|
|
114
|
+
* @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
|
|
115
|
+
* one of the registered participants).
|
|
116
|
+
* @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
|
|
117
|
+
* @param tokenScale - Token scale exponent (Minima `Token.mTokenScale`). Native Minima
|
|
118
|
+
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
119
|
+
* Defaults to 0.
|
|
120
|
+
*/
|
|
121
|
+
async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
|
|
122
|
+
if (participants.length < 2) {
|
|
123
|
+
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
124
|
+
}
|
|
125
|
+
// Identify the proposer by public key digest.
|
|
126
|
+
const proposer = participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
127
|
+
if (!proposer) {
|
|
128
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
129
|
+
}
|
|
130
|
+
const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
|
|
131
|
+
const allocations = {};
|
|
132
|
+
for (const p of participants) {
|
|
133
|
+
allocations[p.partyId] = p.contributionAmount;
|
|
134
|
+
}
|
|
135
|
+
const { script, address } = (0, script_js_1.buildAndHashFactoryScript)(participants);
|
|
136
|
+
const factoryId = generateFactoryId(participants, tokenId, tokenScale);
|
|
137
|
+
// ── Build + mine + broadcast funding TX (when participants provide UTXOs) ──
|
|
138
|
+
let fundingTxId;
|
|
139
|
+
let fundingCoinId;
|
|
140
|
+
let pendingCommitment;
|
|
141
|
+
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
142
|
+
if (allHaveCoinId && chainProvider) {
|
|
143
|
+
const tip = await chainProvider.getTip();
|
|
144
|
+
const escapeBlock = tip.block + script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
145
|
+
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), [...(0, script_js_1.factoryBalanceStateVariables)(participants), (0, script_js_1.factoryEscapeStateVariable)(escapeBlock)]);
|
|
146
|
+
// All parties co-sign the TX digest — the exact on-chain TX structure.
|
|
147
|
+
pendingCommitment = (0, omnia_1.computeTxDraftDigest)(fundingDraft);
|
|
148
|
+
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
|
|
149
|
+
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, new Uint8Array(0));
|
|
150
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
|
|
151
|
+
const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
152
|
+
await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
153
|
+
fundingTxId = Buffer.from(mined.txpowId).toString('hex');
|
|
154
|
+
fundingCoinId = `${fundingTxId}-0`;
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
// In-memory / test path: sign the factory state commitment instead.
|
|
158
|
+
pendingCommitment = (0, commitment_js_1.computeFactoryStateCommitment)(factoryId, 1, allocations, []);
|
|
159
|
+
}
|
|
160
|
+
// Sign with the proposer's lease (full bundle preserved so verify override is available).
|
|
161
|
+
const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
|
|
162
|
+
const initialEntry = {
|
|
163
|
+
sequence: 0,
|
|
164
|
+
timestamp: Date.now(),
|
|
165
|
+
event: 'create',
|
|
166
|
+
allocations: { ...allocations },
|
|
167
|
+
virtualChannelIds: [],
|
|
168
|
+
};
|
|
169
|
+
const factory = {
|
|
170
|
+
factoryId,
|
|
171
|
+
participants,
|
|
172
|
+
totalValue,
|
|
173
|
+
tokenId,
|
|
174
|
+
tokenScale,
|
|
175
|
+
allocations: { ...allocations },
|
|
176
|
+
virtualChannels: [],
|
|
177
|
+
currentSequence: 0,
|
|
178
|
+
status: 'opening',
|
|
179
|
+
stateLog: [initialEntry],
|
|
180
|
+
fundingScript: script,
|
|
181
|
+
fundingAddress: address,
|
|
182
|
+
fundingTxId,
|
|
183
|
+
fundingCoinId,
|
|
184
|
+
pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
|
|
185
|
+
pendingSignatures: { [proposer.partyId]: proposerSig },
|
|
186
|
+
};
|
|
187
|
+
// If proposer is the only participant (edge case), activate immediately.
|
|
188
|
+
if (participants.length === 1) {
|
|
189
|
+
return commitOpening(factory);
|
|
190
|
+
}
|
|
191
|
+
return factory;
|
|
192
|
+
}
|
|
193
|
+
// ─── acceptFactory ────────────────────────────────────────────────────────────
|
|
194
|
+
/**
|
|
195
|
+
* Counterparty co-signs the factory proposal.
|
|
196
|
+
*
|
|
197
|
+
* Each non-proposing participant calls this once. When ALL N parties have
|
|
198
|
+
* signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
|
|
199
|
+
* the factory transitions from `'opening'` to `'active'`.
|
|
200
|
+
*
|
|
201
|
+
* Uses the full WOTS lease cycle: reserve → sign → verify → commit.
|
|
202
|
+
*
|
|
203
|
+
* @param factory - Factory in `'opening'` status returned by `createFactory`.
|
|
204
|
+
* @param leaseProvider - This counterparty's WOTS lease provider.
|
|
205
|
+
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
206
|
+
* must match a registered participant not yet signed).
|
|
207
|
+
*/
|
|
208
|
+
async function acceptFactory(factory, bundle) {
|
|
209
|
+
if (factory.status !== 'opening') {
|
|
210
|
+
throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
|
|
211
|
+
}
|
|
212
|
+
if (!factory.pendingCommitment) {
|
|
213
|
+
throw new Error('Factory has no pending commitment — internal state error');
|
|
214
|
+
}
|
|
215
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
216
|
+
if (!participant) {
|
|
217
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
218
|
+
}
|
|
219
|
+
if (factory.pendingSignatures[participant.partyId]) {
|
|
220
|
+
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
221
|
+
}
|
|
222
|
+
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
223
|
+
const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
|
|
224
|
+
const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
|
|
225
|
+
const updatedFactory = { ...factory, pendingSignatures: newSigs };
|
|
226
|
+
// When all N parties have signed, commit the opening.
|
|
227
|
+
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
228
|
+
if (allSigned) {
|
|
229
|
+
return commitOpening(updatedFactory);
|
|
230
|
+
}
|
|
231
|
+
return updatedFactory;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Produce this party's opening signature WITHOUT committing the lease
|
|
235
|
+
* (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
|
|
236
|
+
* mirroring the splice accept round so a peer can gather N-of-N signatures
|
|
237
|
+
* without stranding or prematurely committing one-time keys.
|
|
238
|
+
*/
|
|
239
|
+
async function signFactoryOpening(factory, bundle) {
|
|
240
|
+
if (factory.status !== 'opening' || !factory.pendingCommitment) {
|
|
241
|
+
throw new Error(`signFactoryOpening requires an 'opening' factory, got '${factory.status}'`);
|
|
242
|
+
}
|
|
243
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
244
|
+
if (!participant) {
|
|
245
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
246
|
+
}
|
|
247
|
+
if (factory.pendingSignatures[participant.partyId]) {
|
|
248
|
+
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
249
|
+
}
|
|
250
|
+
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
251
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
252
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
253
|
+
purpose: 'factory-open',
|
|
254
|
+
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
255
|
+
});
|
|
256
|
+
let sig;
|
|
257
|
+
try {
|
|
258
|
+
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
262
|
+
throw err;
|
|
263
|
+
}
|
|
264
|
+
const verifyFn = bundle.verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
|
|
265
|
+
if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
|
|
266
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
267
|
+
throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
factoryId: factory.factoryId,
|
|
271
|
+
partyId: participant.partyId,
|
|
272
|
+
signature: sig,
|
|
273
|
+
reservationId: reservation.reservationId,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/** Verify a remote opening signature against a factory participant. */
|
|
277
|
+
function verifyFactorySignature(factory, partyId, signature, verify) {
|
|
278
|
+
if (!factory.pendingCommitment)
|
|
279
|
+
return false;
|
|
280
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
281
|
+
if (!participant)
|
|
282
|
+
return false;
|
|
283
|
+
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
284
|
+
const verifyFn = verify ?? ((s, c, pkd) => (0, omnia_1.verifyChannelSignature)(s, c, pkd));
|
|
285
|
+
try {
|
|
286
|
+
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Merge a co-signer's opening signature (RFC-035 B2). When all N participants
|
|
294
|
+
* have signed, the opening commits (`'opening'` → `'active'`).
|
|
295
|
+
*/
|
|
296
|
+
function applyFactorySignature(factory, partyId, signature) {
|
|
297
|
+
if (factory.status !== 'opening') {
|
|
298
|
+
throw new Error(`applyFactorySignature requires factory status 'opening', got '${factory.status}'`);
|
|
299
|
+
}
|
|
300
|
+
if (!factory.participants.find(p => p.partyId === partyId)) {
|
|
301
|
+
throw new Error(`'${partyId}' is not a registered factory participant`);
|
|
302
|
+
}
|
|
303
|
+
if (factory.pendingSignatures[partyId]) {
|
|
304
|
+
throw new Error(`Party '${partyId}' has already co-signed this factory proposal`);
|
|
305
|
+
}
|
|
306
|
+
const newSigs = { ...factory.pendingSignatures, [partyId]: signature };
|
|
307
|
+
const updated = { ...factory, pendingSignatures: newSigs };
|
|
308
|
+
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
309
|
+
return allSigned ? commitOpening(updated) : updated;
|
|
310
|
+
}
|
|
311
|
+
function commitOpening(factory) {
|
|
312
|
+
const logEntry = {
|
|
313
|
+
sequence: 1,
|
|
314
|
+
timestamp: Date.now(),
|
|
315
|
+
event: 'accept',
|
|
316
|
+
allocations: { ...factory.allocations },
|
|
317
|
+
virtualChannelIds: [],
|
|
318
|
+
};
|
|
319
|
+
const committed = {
|
|
320
|
+
...factory,
|
|
321
|
+
currentSequence: 1,
|
|
322
|
+
status: 'active',
|
|
323
|
+
pendingCommitment: undefined,
|
|
324
|
+
pendingSignatures: {},
|
|
325
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
326
|
+
};
|
|
327
|
+
enforceConservation(committed);
|
|
328
|
+
return committed;
|
|
329
|
+
}
|
|
330
|
+
// ─── reallocate ───────────────────────────────────────────────────────────────
|
|
331
|
+
/**
|
|
332
|
+
* Move factory allocation between two participants (atomic N-of-N).
|
|
333
|
+
*
|
|
334
|
+
* All N leaseProviders must be supplied; each party signs the new state
|
|
335
|
+
* commitment in turn. The state commits atomically — no intermediate "pending"
|
|
336
|
+
* object is returned.
|
|
337
|
+
*
|
|
338
|
+
* @param factory - Active factory.
|
|
339
|
+
* @param fromPartyId - Party giving up allocation.
|
|
340
|
+
* @param toPartyId - Party receiving allocation.
|
|
341
|
+
* @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
|
|
342
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
343
|
+
*/
|
|
344
|
+
async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
|
|
345
|
+
if (factory.status !== 'active') {
|
|
346
|
+
throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
|
|
347
|
+
}
|
|
348
|
+
if (amount <= 0n) {
|
|
349
|
+
throw new Error(`Reallocation amount must be positive, got ${amount}`);
|
|
350
|
+
}
|
|
351
|
+
const fromAlloc = factory.allocations[fromPartyId] ?? 0n;
|
|
352
|
+
if (fromAlloc < amount) {
|
|
353
|
+
throw new Error(`Insufficient allocation for '${fromPartyId}': has ${fromAlloc}, needs ${amount}`);
|
|
354
|
+
}
|
|
355
|
+
if (!factory.participants.find(p => p.partyId === toPartyId)) {
|
|
356
|
+
throw new Error(`'${toPartyId}' is not a registered factory participant`);
|
|
357
|
+
}
|
|
358
|
+
const newAllocations = {
|
|
359
|
+
...factory.allocations,
|
|
360
|
+
[fromPartyId]: fromAlloc - amount,
|
|
361
|
+
[toPartyId]: (factory.allocations[toPartyId] ?? 0n) + amount,
|
|
362
|
+
};
|
|
363
|
+
const newSequence = factory.currentSequence + 1;
|
|
364
|
+
const vcIds = factory.virtualChannels.map(vc => vc.channelId);
|
|
365
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, vcIds);
|
|
366
|
+
await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
|
|
367
|
+
const logEntry = {
|
|
368
|
+
sequence: newSequence,
|
|
369
|
+
timestamp: Date.now(),
|
|
370
|
+
event: 'reallocate',
|
|
371
|
+
allocations: newAllocations,
|
|
372
|
+
virtualChannelIds: vcIds,
|
|
373
|
+
};
|
|
374
|
+
const updated = {
|
|
375
|
+
...factory,
|
|
376
|
+
allocations: newAllocations,
|
|
377
|
+
currentSequence: newSequence,
|
|
378
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
379
|
+
};
|
|
380
|
+
enforceConservation(updated);
|
|
381
|
+
return updated;
|
|
382
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
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';
|
|
3
|
+
export { computeFactoryStateCommitment } from './commitment.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';
|
|
11
|
+
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
|
12
|
+
export type { FactoryRegistryState, DurableFactoryStore, DurableFactoryStoreOptions, } from './durable-factory-store.js';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
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;
|
|
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, "factoryBalanceStateVariables", { enumerable: true, get: function () { return script_js_1.factoryBalanceStateVariables; } });
|
|
8
|
+
Object.defineProperty(exports, "factoryEscapeStateVariable", { enumerable: true, get: function () { return script_js_1.factoryEscapeStateVariable; } });
|
|
9
|
+
Object.defineProperty(exports, "scriptAddress", { enumerable: true, get: function () { return script_js_1.scriptAddress; } });
|
|
10
|
+
Object.defineProperty(exports, "normalizeScript", { enumerable: true, get: function () { return script_js_1.normalizeScript; } });
|
|
11
|
+
var commitment_js_1 = require("./commitment.js");
|
|
12
|
+
Object.defineProperty(exports, "computeFactoryStateCommitment", { enumerable: true, get: function () { return commitment_js_1.computeFactoryStateCommitment; } });
|
|
13
|
+
var factory_js_1 = require("./factory.js");
|
|
14
|
+
Object.defineProperty(exports, "createFactory", { enumerable: true, get: function () { return factory_js_1.createFactory; } });
|
|
15
|
+
Object.defineProperty(exports, "acceptFactory", { enumerable: true, get: function () { return factory_js_1.acceptFactory; } });
|
|
16
|
+
Object.defineProperty(exports, "reallocate", { enumerable: true, get: function () { return factory_js_1.reallocate; } });
|
|
17
|
+
Object.defineProperty(exports, "enforceConservation", { enumerable: true, get: function () { return factory_js_1.enforceConservation; } });
|
|
18
|
+
Object.defineProperty(exports, "signFactoryOpening", { enumerable: true, get: function () { return factory_js_1.signFactoryOpening; } });
|
|
19
|
+
Object.defineProperty(exports, "verifyFactorySignature", { enumerable: true, get: function () { return factory_js_1.verifyFactorySignature; } });
|
|
20
|
+
Object.defineProperty(exports, "applyFactorySignature", { enumerable: true, get: function () { return factory_js_1.applyFactorySignature; } });
|
|
21
|
+
// RFC-035 B2 — factory opening round-trip over the coordination transport.
|
|
22
|
+
var coordination_js_1 = require("./coordination.js");
|
|
23
|
+
Object.defineProperty(exports, "createFactoryCoordination", { enumerable: true, get: function () { return coordination_js_1.createFactoryCoordination; } });
|
|
24
|
+
var virtual_js_1 = require("./virtual.js");
|
|
25
|
+
Object.defineProperty(exports, "openVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.openVirtualChannel; } });
|
|
26
|
+
Object.defineProperty(exports, "closeVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.closeVirtualChannel; } });
|
|
27
|
+
Object.defineProperty(exports, "buildVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.buildVirtualChannelOpen; } });
|
|
28
|
+
Object.defineProperty(exports, "signVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.signVirtualChannelOpen; } });
|
|
29
|
+
Object.defineProperty(exports, "verifyVirtualChannelOpenSignature", { enumerable: true, get: function () { return virtual_js_1.verifyVirtualChannelOpenSignature; } });
|
|
30
|
+
Object.defineProperty(exports, "assembleVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.assembleVirtualChannelOpen; } });
|
|
31
|
+
var settlement_js_1 = require("./settlement.js");
|
|
32
|
+
Object.defineProperty(exports, "closeFactory", { enumerable: true, get: function () { return settlement_js_1.closeFactory; } });
|
|
33
|
+
Object.defineProperty(exports, "buildDisputePayload", { enumerable: true, get: function () { return settlement_js_1.buildDisputePayload; } });
|
|
34
|
+
Object.defineProperty(exports, "buildFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.buildFactorySettlement; } });
|
|
35
|
+
Object.defineProperty(exports, "signFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.signFactorySettlement; } });
|
|
36
|
+
Object.defineProperty(exports, "verifyFactorySettlementSignature", { enumerable: true, get: function () { return settlement_js_1.verifyFactorySettlementSignature; } });
|
|
37
|
+
Object.defineProperty(exports, "assembleFactorySettlement", { enumerable: true, get: function () { return settlement_js_1.assembleFactorySettlement; } });
|
|
38
|
+
var durable_factory_store_js_1 = require("./durable-factory-store.js");
|
|
39
|
+
Object.defineProperty(exports, "createDurableFactoryStore", { enumerable: true, get: function () { return durable_factory_store_js_1.createDurableFactoryStore; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
}
|
|
12
|
+
/**
|
|
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).
|
|
31
|
+
*
|
|
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.
|
|
42
|
+
*
|
|
43
|
+
* Minimum 2 participants required.
|
|
44
|
+
*/
|
|
45
|
+
export declare function buildFactoryScript(participants: FactoryParticipant[], _options?: FactoryScriptOptions): string;
|
|
46
|
+
export declare function normalizeScript(script: string): string;
|
|
47
|
+
/** Compute the SHA3-256 script-hash address for a factory script. */
|
|
48
|
+
export declare function scriptAddress(script: string): string;
|
|
49
|
+
/**
|
|
50
|
+
* Build the factory script and compute its canonical address in one step.
|
|
51
|
+
* The address is used as the output address of the factory funding TX.
|
|
52
|
+
*/
|
|
53
|
+
export declare function buildAndHashFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): {
|
|
54
|
+
script: string;
|
|
55
|
+
address: string;
|
|
56
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FACTORY_BALANCE_PORT_BASE = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_ESCAPE_DELAY_BLOCKS = void 0;
|
|
4
|
+
exports.factoryBalanceStateVariables = factoryBalanceStateVariables;
|
|
5
|
+
exports.factoryEscapeStateVariable = factoryEscapeStateVariable;
|
|
6
|
+
exports.buildFactoryScript = buildFactoryScript;
|
|
7
|
+
exports.normalizeScript = normalizeScript;
|
|
8
|
+
exports.scriptAddress = scriptAddress;
|
|
9
|
+
exports.buildAndHashFactoryScript = buildAndHashFactoryScript;
|
|
10
|
+
const scripts_1 = require("@totemsdk/core/scripts");
|
|
11
|
+
/**
|
|
12
|
+
* Normalize a hex public key digest to the KISSVM-compatible format:
|
|
13
|
+
* strip leading 0x/0X and render as upper-case hex with leading '0X'.
|
|
14
|
+
*/
|
|
15
|
+
function kissHex(hex) {
|
|
16
|
+
const raw = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
|
|
17
|
+
return '0X' + raw.toUpperCase();
|
|
18
|
+
}
|
|
19
|
+
/** Blocks after the funding tip at which the unilateral escape opens. */
|
|
20
|
+
exports.FACTORY_ESCAPE_DELAY_BLOCKS = 256;
|
|
21
|
+
/** State port carrying the absolute escape block (STATE(103)). */
|
|
22
|
+
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
|
+
/**
|
|
26
|
+
* Per-party allocation state variables (port 200+k = party k's balance), seeded
|
|
27
|
+
* into the factory funding output so the timeout escape can pay each party its
|
|
28
|
+
* committed share.
|
|
29
|
+
*/
|
|
30
|
+
function factoryBalanceStateVariables(participants) {
|
|
31
|
+
return participants.map((p, k) => ({
|
|
32
|
+
port: exports.FACTORY_BALANCE_PORT_BASE + k,
|
|
33
|
+
value: p.contributionAmount,
|
|
34
|
+
type: 'number',
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/** Absolute escape-block state variable (STATE(103)) for the factory funding output. */
|
|
38
|
+
function factoryEscapeStateVariable(escapeBlock) {
|
|
39
|
+
if (!Number.isInteger(escapeBlock) || escapeBlock < 0) {
|
|
40
|
+
throw new Error(`escapeBlock must be a non-negative integer, got ${JSON.stringify(escapeBlock)}`);
|
|
41
|
+
}
|
|
42
|
+
return { port: exports.FACTORY_ESCAPE_PORT, value: BigInt(escapeBlock), type: 'number' };
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Build the N-of-N MULTISIG MAST funding script for a channel factory
|
|
46
|
+
* (RFC-039, CUSTODY-POLICY §2).
|
|
47
|
+
*
|
|
48
|
+
* Spend paths:
|
|
49
|
+
* - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
|
|
50
|
+
* `SETTLEMENT=true` closes after minimal coinage (1 block).
|
|
51
|
+
* - **Unilateral escape** (after the absolute block in `STATE(103)`): any
|
|
52
|
+
* single party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its
|
|
53
|
+
* own settlement address, zero its state (`STATE(200+k) EQ 0`), keep the
|
|
54
|
+
* other parties' balances unchanged, and return the remainder to the factory
|
|
55
|
+
* script. Repeated withdrawals cannot double-claim because each zeroes its
|
|
56
|
+
* own port. `STATE(103)` is immutable on every spend (`SAMESTATE(103 103)`),
|
|
57
|
+
* so the escape clock cannot be pushed by any counterparty.
|
|
58
|
+
*
|
|
59
|
+
* Minimum 2 participants required.
|
|
60
|
+
*/
|
|
61
|
+
function buildFactoryScript(participants, _options = {}) {
|
|
62
|
+
if (participants.length < 2) {
|
|
63
|
+
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
64
|
+
}
|
|
65
|
+
const count = participants.length;
|
|
66
|
+
const pks = participants.map((p) => kissHex(p.publicKeyDigest));
|
|
67
|
+
const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
|
|
68
|
+
const lines = [
|
|
69
|
+
'LET SETTLEMENT=STATE(100)',
|
|
70
|
+
`ASSERT SAMESTATE(${exports.FACTORY_ESCAPE_PORT} ${exports.FACTORY_ESCAPE_PORT})`,
|
|
71
|
+
`IF @BLOCK GT STATE(${exports.FACTORY_ESCAPE_PORT}) THEN`,
|
|
72
|
+
];
|
|
73
|
+
participants.forEach((_, k) => {
|
|
74
|
+
const port = exports.FACTORY_BALANCE_PORT_BASE + k;
|
|
75
|
+
lines.push(` LET SHARE${k}=STATE(${port})`);
|
|
76
|
+
lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
|
|
77
|
+
lines.push(` IF SHARE${k} GT 0 THEN`);
|
|
78
|
+
lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
|
|
79
|
+
for (let j = 0; j < count; j++) {
|
|
80
|
+
if (j === k)
|
|
81
|
+
continue;
|
|
82
|
+
lines.push(` ASSERT STATE(${exports.FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${exports.FACTORY_BALANCE_PORT_BASE + j})`);
|
|
83
|
+
}
|
|
84
|
+
lines.push(` ASSERT STATE(${port}) EQ 0`);
|
|
85
|
+
lines.push(` RETURN VERIFYOUT(@INPUT @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
|
|
86
|
+
lines.push(' ENDIF');
|
|
87
|
+
lines.push(' ENDIF');
|
|
88
|
+
});
|
|
89
|
+
lines.push('ENDIF');
|
|
90
|
+
lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
|
|
91
|
+
lines.push('IF SETTLEMENT THEN');
|
|
92
|
+
lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
|
|
93
|
+
lines.push('ELSE');
|
|
94
|
+
lines.push(' RETURN TRUE');
|
|
95
|
+
lines.push('ENDIF');
|
|
96
|
+
return lines.join('\n');
|
|
97
|
+
}
|
|
98
|
+
function normalizeScript(script) {
|
|
99
|
+
return script.trim().toUpperCase();
|
|
100
|
+
}
|
|
101
|
+
/** Compute the SHA3-256 script-hash address for a factory script. */
|
|
102
|
+
function scriptAddress(script) {
|
|
103
|
+
return (0, scripts_1.computeScriptAddress)(script);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Build the factory script and compute its canonical address in one step.
|
|
107
|
+
* The address is used as the output address of the factory funding TX.
|
|
108
|
+
*/
|
|
109
|
+
function buildAndHashFactoryScript(participants, options = {}) {
|
|
110
|
+
const script = buildFactoryScript(participants, options);
|
|
111
|
+
const address = scriptAddress(script);
|
|
112
|
+
return { script, address };
|
|
113
|
+
}
|