@totemsdk/omnia-factory 0.7.0 → 0.7.2
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/LICENSE +202 -21
- package/NOTICE +60 -0
- package/README.md +5 -0
- package/dist/cjs/factory.d.ts +48 -1
- package/dist/cjs/factory.js +274 -79
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/virtual.js +2 -0
- package/dist/factory.d.ts +48 -1
- package/dist/factory.js +269 -79
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/virtual.js +2 -0
- package/package.json +12 -14
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/package.json +1 -1
package/dist/factory.js
CHANGED
|
@@ -111,98 +111,112 @@ function generateFactoryId(participants, tokenId, tokenScale) {
|
|
|
111
111
|
* Defaults to 0.
|
|
112
112
|
*/
|
|
113
113
|
export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
//
|
|
118
|
-
const
|
|
114
|
+
// One plan, one factory ID: build the opening once and reuse it for the
|
|
115
|
+
// proposal, the local record and the funding transaction. Rebuilding here
|
|
116
|
+
// would generate a different ID (the ID includes a random nonce) and the
|
|
117
|
+
// peer would accept a factory this host never stored.
|
|
118
|
+
const plan = await buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding);
|
|
119
|
+
return createFactoryFromPlan(plan, bundle, chainProvider);
|
|
120
|
+
}
|
|
121
|
+
function findProposer(factory, bundle) {
|
|
122
|
+
const proposer = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
119
123
|
if (!proposer) {
|
|
120
124
|
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
121
125
|
}
|
|
126
|
+
return proposer;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Sign the opening commitment for a plan and record the proposer's signature.
|
|
130
|
+
* Nothing is broadcast and no funding signature is requested, so callers can
|
|
131
|
+
* propose the factory to the peer first (CAN-020 ordering).
|
|
132
|
+
*/
|
|
133
|
+
export async function proposeFactoryOpening(plan, bundle) {
|
|
134
|
+
const proposer = findProposer(plan.factory, bundle);
|
|
135
|
+
if (!plan.factory.pendingCommitment) {
|
|
136
|
+
throw new Error('Factory plan has no pending commitment');
|
|
137
|
+
}
|
|
138
|
+
const commitment = Buffer.from(plan.factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
139
|
+
const sig = await leaseSign(plan.factory.factoryId, commitment, 'factory-open', proposer, bundle);
|
|
140
|
+
return {
|
|
141
|
+
...plan.factory,
|
|
142
|
+
pendingSignatures: { [proposer.partyId]: sig },
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Finish a plan: collect the funding-witness signatures from the plan's
|
|
147
|
+
* funding materials (or use the supplied ones), broadcast the funding
|
|
148
|
+
* transaction when the plan is on-chain, and commit the opening once every
|
|
149
|
+
* participant has signed.
|
|
150
|
+
*/
|
|
151
|
+
export async function createFactoryFromPlan(plan, bundle, chainProvider) {
|
|
152
|
+
let factory = await proposeFactoryOpening(plan, bundle);
|
|
153
|
+
if (plan.onChain) {
|
|
154
|
+
if (!chainProvider || !plan.fundingTxBytes || !plan.fundingDigest) {
|
|
155
|
+
throw new Error('Factory funding requires a chain provider and a complete funding plan');
|
|
156
|
+
}
|
|
157
|
+
const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
|
|
158
|
+
const fundingSignatures = {};
|
|
159
|
+
for (const participant of factory.participants) {
|
|
160
|
+
const material = materials.get(participant.partyId);
|
|
161
|
+
if (!material)
|
|
162
|
+
throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
|
|
163
|
+
if (material.signature) {
|
|
164
|
+
fundingSignatures[participant.partyId] = material.signature;
|
|
165
|
+
}
|
|
166
|
+
else if (material.signer) {
|
|
167
|
+
fundingSignatures[participant.partyId] = Uint8Array.from(await material.signer(plan.fundingDigest));
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
throw new Error(`Missing signature or signer for factory party '${participant.partyId}'`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
factory = await finalizeFactoryOpening(plan, { fundingSignatures, openingSignatures: factory.pendingSignatures }, chainProvider);
|
|
174
|
+
}
|
|
175
|
+
// If proposer is the only participant (edge case), activate immediately.
|
|
176
|
+
if (factory.participants.length === 1) {
|
|
177
|
+
return commitOpening(factory);
|
|
178
|
+
}
|
|
179
|
+
return factory;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Build a factory and (when every participant supplies a funding coin) its
|
|
183
|
+
* deterministic funding draft, without signing or broadcasting.
|
|
184
|
+
*/
|
|
185
|
+
export async function buildFactoryOpening(participants, tokenId, tokenScale, chainProvider, funding) {
|
|
186
|
+
if (participants.length < 2) {
|
|
187
|
+
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
188
|
+
}
|
|
122
189
|
const totalValue = participants.reduce((sum, p) => sum + p.contributionAmount, 0n);
|
|
123
190
|
const allocations = {};
|
|
124
|
-
for (const p of participants)
|
|
191
|
+
for (const p of participants)
|
|
125
192
|
allocations[p.partyId] = p.contributionAmount;
|
|
126
|
-
}
|
|
127
193
|
const { script, address } = buildAndHashFactoryScript(participants);
|
|
128
194
|
const factoryId = generateFactoryId(participants, tokenId, tokenScale);
|
|
129
|
-
|
|
130
|
-
let
|
|
195
|
+
let fundingTxBytes;
|
|
196
|
+
let fundingDigest;
|
|
131
197
|
let fundingCoinId;
|
|
132
198
|
let pendingCommitment;
|
|
133
199
|
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
134
200
|
if (allHaveCoinId && chainProvider) {
|
|
135
201
|
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
136
|
-
// The transaction input address must be the *funding coin's* address, not
|
|
137
|
-
// the participant's settlement address. Callers supply it directly or via
|
|
138
|
-
// the funding coin script.
|
|
139
202
|
const inputAddresses = participants.map(p => {
|
|
140
203
|
const m = materialByParty.get(p.partyId);
|
|
141
204
|
return m?.coinAddress ?? (m?.script ? computeScriptAddress(m.script) : '');
|
|
142
205
|
});
|
|
143
206
|
if (inputAddresses.some(a => !a)) {
|
|
144
|
-
throw new Error('
|
|
207
|
+
throw new Error('Factory opening on-chain requires funding material (coinAddress or script) for every participant');
|
|
145
208
|
}
|
|
146
209
|
const tip = await chainProvider.getTip();
|
|
147
210
|
const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
148
211
|
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
// Assemble the real witness: one CoinProof + ScriptProof + signature per
|
|
152
|
-
// input coin (the factory's own MULTISIG script is the *output* script).
|
|
153
|
-
const signatures = [];
|
|
154
|
-
const coinProofs = [];
|
|
155
|
-
const scriptProofs = [];
|
|
156
|
-
for (const p of participants) {
|
|
157
|
-
const m = materialByParty.get(p.partyId);
|
|
158
|
-
if (!m)
|
|
159
|
-
throw new Error(`Missing funding material for factory party '${p.partyId}'`);
|
|
160
|
-
coinProofs.push(m.coinProof);
|
|
161
|
-
let scriptProof = m.scriptProof;
|
|
162
|
-
if (!scriptProof) {
|
|
163
|
-
if (!m.script)
|
|
164
|
-
throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
|
|
165
|
-
scriptProof = buildScriptProof(m.script);
|
|
166
|
-
}
|
|
167
|
-
scriptProofs.push(scriptProof);
|
|
168
|
-
if (m.signature) {
|
|
169
|
-
signatures.push(m.signature);
|
|
170
|
-
}
|
|
171
|
-
else if (m.signer) {
|
|
172
|
-
signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
|
|
173
|
-
}
|
|
174
|
-
else {
|
|
175
|
-
throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
179
|
-
const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
|
|
180
|
-
if (chainProvider.submitTransaction) {
|
|
181
|
-
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
182
|
-
if (submitted.success === false || !submitted.txpowid) {
|
|
183
|
-
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
184
|
-
}
|
|
185
|
-
fundingTxId = submitted.txpowid;
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
const txnDifficulty = await resolveTxPowTarget(chainProvider);
|
|
189
|
-
const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
|
|
190
|
-
const mined = await mineTxPoW(txBody, txnDifficulty);
|
|
191
|
-
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
192
|
-
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
193
|
-
if (broadcast.success === false) {
|
|
194
|
-
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
195
|
-
}
|
|
196
|
-
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
197
|
-
}
|
|
212
|
+
fundingDigest = computeOmniaTxDigest(fundingDraft);
|
|
213
|
+
fundingTxBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
198
214
|
fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
|
|
215
|
+
pendingCommitment = fundingDigest;
|
|
199
216
|
}
|
|
200
217
|
else {
|
|
201
|
-
// In-memory / test path: sign the factory state commitment instead.
|
|
202
218
|
pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
|
|
203
219
|
}
|
|
204
|
-
// Sign with the proposer's lease (full bundle preserved so verify override is available).
|
|
205
|
-
const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
|
|
206
220
|
const initialEntry = {
|
|
207
221
|
sequence: 0,
|
|
208
222
|
timestamp: Date.now(),
|
|
@@ -223,16 +237,69 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
|
|
|
223
237
|
stateLog: [initialEntry],
|
|
224
238
|
fundingScript: script,
|
|
225
239
|
fundingAddress: address,
|
|
226
|
-
fundingTxId,
|
|
227
|
-
fundingCoinId,
|
|
240
|
+
fundingTxId: undefined,
|
|
241
|
+
fundingCoinId: undefined,
|
|
228
242
|
pendingCommitment: Buffer.from(pendingCommitment).toString('hex'),
|
|
229
|
-
pendingSignatures: {
|
|
243
|
+
pendingSignatures: {},
|
|
230
244
|
};
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
245
|
+
return { factory, fundingTxBytes, fundingDigest, fundingCoinId, fundingMaterials: funding, onChain: fundingTxBytes !== undefined };
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Broadcast the prepared factory funding (when on-chain) and record opening
|
|
249
|
+
* signatures. When every participant signature is supplied the factory commits.
|
|
250
|
+
*/
|
|
251
|
+
export async function finalizeFactoryOpening(plan, opts, chainProvider) {
|
|
252
|
+
let factory = plan.factory;
|
|
253
|
+
if (plan.onChain) {
|
|
254
|
+
if (!chainProvider || !plan.fundingTxBytes)
|
|
255
|
+
throw new Error('Factory funding requires a chain provider');
|
|
256
|
+
const materials = new Map((plan.fundingMaterials ?? []).map(m => [m.partyId, m]));
|
|
257
|
+
const signatures = [];
|
|
258
|
+
const coinProofs = [];
|
|
259
|
+
const scriptProofs = [];
|
|
260
|
+
for (const participant of factory.participants) {
|
|
261
|
+
const signature = opts.fundingSignatures?.[participant.partyId];
|
|
262
|
+
if (!signature)
|
|
263
|
+
throw new Error(`Missing funding signature for factory party '${participant.partyId}'`);
|
|
264
|
+
const material = materials.get(participant.partyId);
|
|
265
|
+
if (!material)
|
|
266
|
+
throw new Error(`Missing funding material for factory party '${participant.partyId}'`);
|
|
267
|
+
coinProofs.push(material.coinProof);
|
|
268
|
+
const scriptProof = material.scriptProof ?? (material.script ? buildScriptProof(material.script) : undefined);
|
|
269
|
+
if (!scriptProof)
|
|
270
|
+
throw new Error(`Missing script or scriptProof for factory party '${participant.partyId}'`);
|
|
271
|
+
scriptProofs.push(scriptProof);
|
|
272
|
+
signatures.push(signature);
|
|
273
|
+
}
|
|
274
|
+
const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
|
|
275
|
+
let fundingTxId;
|
|
276
|
+
if (chainProvider.submitTransaction) {
|
|
277
|
+
const submitted = await chainProvider.submitTransaction(plan.fundingTxBytes, witnessBytes);
|
|
278
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
279
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
280
|
+
}
|
|
281
|
+
fundingTxId = submitted.txpowid;
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
const txnDifficulty = await resolveTxPowTarget(chainProvider);
|
|
285
|
+
const txBody = serializeTxBody(plan.fundingTxBytes, witnessBytes, { txnDifficulty });
|
|
286
|
+
const mined = await mineTxPoW(txBody, txnDifficulty);
|
|
287
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
288
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
289
|
+
if (broadcast.success === false) {
|
|
290
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
291
|
+
}
|
|
292
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
293
|
+
}
|
|
294
|
+
factory = {
|
|
295
|
+
...factory,
|
|
296
|
+
fundingTxId,
|
|
297
|
+
fundingCoinId: plan.fundingCoinId,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
factory = { ...factory, pendingSignatures: { ...opts.openingSignatures } };
|
|
301
|
+
const allSigned = factory.participants.every(p => factory.pendingSignatures[p.partyId] !== undefined);
|
|
302
|
+
return allSigned ? commitOpening(factory) : factory;
|
|
236
303
|
}
|
|
237
304
|
// ─── acceptFactory ────────────────────────────────────────────────────────────
|
|
238
305
|
/**
|
|
@@ -249,7 +316,7 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
|
|
|
249
316
|
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
250
317
|
* must match a registered participant not yet signed).
|
|
251
318
|
*/
|
|
252
|
-
export async function acceptFactory(factory, bundle) {
|
|
319
|
+
export async function acceptFactory(factory, bundle, opts) {
|
|
253
320
|
if (factory.status !== 'opening') {
|
|
254
321
|
throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
|
|
255
322
|
}
|
|
@@ -263,13 +330,14 @@ export async function acceptFactory(factory, bundle) {
|
|
|
263
330
|
if (factory.pendingSignatures[participant.partyId]) {
|
|
264
331
|
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
265
332
|
}
|
|
266
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
333
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
267
334
|
const sig = await leaseSign(factory.factoryId, commitment, 'factory-open', participant, bundle);
|
|
268
335
|
const newSigs = { ...factory.pendingSignatures, [participant.partyId]: sig };
|
|
269
336
|
const updatedFactory = { ...factory, pendingSignatures: newSigs };
|
|
270
|
-
// When all N parties have signed, commit the opening
|
|
337
|
+
// When all N parties have signed, commit the opening unless the host is
|
|
338
|
+
// waiting for funding evidence (on-chain) or the proposer's FINALIZED.
|
|
271
339
|
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
272
|
-
if (allSigned) {
|
|
340
|
+
if (allSigned && !opts?.deferCommit) {
|
|
273
341
|
return commitOpening(updatedFactory);
|
|
274
342
|
}
|
|
275
343
|
return updatedFactory;
|
|
@@ -291,7 +359,7 @@ export async function signFactoryOpening(factory, bundle) {
|
|
|
291
359
|
if (factory.pendingSignatures[participant.partyId]) {
|
|
292
360
|
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
293
361
|
}
|
|
294
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
362
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
295
363
|
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
296
364
|
treeId: `omnia-factory-${factory.factoryId}`,
|
|
297
365
|
purpose: 'factory-open',
|
|
@@ -324,7 +392,7 @@ export function verifyFactorySignature(factory, partyId, signature, verify) {
|
|
|
324
392
|
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
325
393
|
if (!participant)
|
|
326
394
|
return false;
|
|
327
|
-
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
395
|
+
const commitment = Buffer.from(factory.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
328
396
|
const verifyFn = verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
|
|
329
397
|
try {
|
|
330
398
|
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
@@ -424,3 +492,125 @@ export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseP
|
|
|
424
492
|
enforceConservation(updated);
|
|
425
493
|
return updated;
|
|
426
494
|
}
|
|
495
|
+
// ─── Peer-supplied state validation ──────────────────────────────────────────
|
|
496
|
+
function jsonSafeForCompare(value) {
|
|
497
|
+
if (typeof value === 'bigint')
|
|
498
|
+
return value.toString();
|
|
499
|
+
if (Array.isArray(value))
|
|
500
|
+
return value.map(jsonSafeForCompare);
|
|
501
|
+
if (value && typeof value === 'object') {
|
|
502
|
+
const entries = Object.entries(value)
|
|
503
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
504
|
+
.map(([k, v]) => [k, jsonSafeForCompare(v)]);
|
|
505
|
+
return Object.fromEntries(entries);
|
|
506
|
+
}
|
|
507
|
+
return value;
|
|
508
|
+
}
|
|
509
|
+
function factoryTermsFingerprint(f) {
|
|
510
|
+
return JSON.stringify(jsonSafeForCompare({
|
|
511
|
+
factoryId: f.factoryId,
|
|
512
|
+
participants: f.participants,
|
|
513
|
+
totalValue: f.totalValue,
|
|
514
|
+
tokenId: f.tokenId,
|
|
515
|
+
tokenScale: f.tokenScale,
|
|
516
|
+
allocations: f.allocations,
|
|
517
|
+
virtualChannels: f.virtualChannels,
|
|
518
|
+
currentSequence: f.currentSequence,
|
|
519
|
+
stateLog: f.stateLog,
|
|
520
|
+
fundingScript: f.fundingScript,
|
|
521
|
+
fundingAddress: f.fundingAddress,
|
|
522
|
+
pendingCommitment: f.pendingCommitment,
|
|
523
|
+
}));
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Validate a peer-supplied `FACTORY_FINALIZED` transition against the locally
|
|
527
|
+
* accepted factory. The peer may only fill in the funding references and add
|
|
528
|
+
* valid opening signatures; every term, commitment and existing signature must
|
|
529
|
+
* be identical. Returns the validated factory to store.
|
|
530
|
+
*/
|
|
531
|
+
export function assertFactoryFinalized(known, incoming, senderPublicKeyDigest) {
|
|
532
|
+
if (!incoming || incoming.factoryId !== known.factoryId) {
|
|
533
|
+
throw new Error('FACTORY_FINALIZED for a different factory');
|
|
534
|
+
}
|
|
535
|
+
if (senderPublicKeyDigest && !known.participants.some(p => p.publicKeyDigest === senderPublicKeyDigest)) {
|
|
536
|
+
throw new Error('FACTORY_FINALIZED sender is not a factory participant');
|
|
537
|
+
}
|
|
538
|
+
const terms = (f) => JSON.stringify(jsonSafeForCompare({
|
|
539
|
+
participants: f.participants,
|
|
540
|
+
totalValue: f.totalValue,
|
|
541
|
+
tokenId: f.tokenId,
|
|
542
|
+
tokenScale: f.tokenScale,
|
|
543
|
+
allocations: f.allocations,
|
|
544
|
+
virtualChannels: f.virtualChannels,
|
|
545
|
+
fundingScript: f.fundingScript,
|
|
546
|
+
fundingAddress: f.fundingAddress,
|
|
547
|
+
}));
|
|
548
|
+
if (terms(known) !== terms(incoming)) {
|
|
549
|
+
throw new Error('FACTORY_FINALIZED changes factory terms');
|
|
550
|
+
}
|
|
551
|
+
if (known.fundingTxId && incoming.fundingTxId !== known.fundingTxId) {
|
|
552
|
+
throw new Error('FACTORY_FINALIZED changes the funding transaction');
|
|
553
|
+
}
|
|
554
|
+
if (known.fundingCoinId && incoming.fundingCoinId !== known.fundingCoinId) {
|
|
555
|
+
throw new Error('FACTORY_FINALIZED changes the funding coin');
|
|
556
|
+
}
|
|
557
|
+
if (known.status === 'closed' && incoming.status !== 'closed') {
|
|
558
|
+
throw new Error('FACTORY_FINALIZED cannot reopen a closed factory');
|
|
559
|
+
}
|
|
560
|
+
// The expected transition for a proposal this host accepted with every
|
|
561
|
+
// participant signature present is the deterministic commit: sequence 1, an
|
|
562
|
+
// 'accept' log entry, cleared pending commitment and signatures.
|
|
563
|
+
if (known.status === 'opening' && incoming.status === 'active') {
|
|
564
|
+
if (known.currentSequence !== 0 || incoming.currentSequence !== 1) {
|
|
565
|
+
throw new Error('FACTORY_FINALIZED has an invalid sequence for an opening');
|
|
566
|
+
}
|
|
567
|
+
if (!known.pendingCommitment) {
|
|
568
|
+
throw new Error('FACTORY_FINALIZED for a proposal without a pending commitment');
|
|
569
|
+
}
|
|
570
|
+
const commitment = Buffer.from(known.pendingCommitment.replace(/^0x/i, ''), 'hex');
|
|
571
|
+
const signatures = known.pendingSignatures ?? {};
|
|
572
|
+
for (const participant of known.participants) {
|
|
573
|
+
const sig = signatures[participant.partyId];
|
|
574
|
+
if (!sig)
|
|
575
|
+
throw new Error(`FACTORY_FINALIZED activates a factory missing the signature for '${participant.partyId}'`);
|
|
576
|
+
if (!verifyChannelSignature(sig, commitment, participant.publicKeyDigest)) {
|
|
577
|
+
throw new Error(`FACTORY_FINALIZED activates a factory with an invalid signature for '${participant.partyId}'`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (incoming.pendingCommitment) {
|
|
581
|
+
throw new Error('FACTORY_FINALIZED must clear the pending commitment when it activates');
|
|
582
|
+
}
|
|
583
|
+
if (incoming.pendingSignatures && Object.keys(incoming.pendingSignatures).length > 0) {
|
|
584
|
+
throw new Error('FACTORY_FINALIZED must clear pending signatures when it activates');
|
|
585
|
+
}
|
|
586
|
+
const log = incoming.stateLog ?? [];
|
|
587
|
+
if (log.length !== (known.stateLog?.length ?? 0) + 1) {
|
|
588
|
+
throw new Error('FACTORY_FINALIZED has an unexpected state log');
|
|
589
|
+
}
|
|
590
|
+
const last = log[log.length - 1];
|
|
591
|
+
if (!last || last.event !== 'accept' || last.sequence !== 1) {
|
|
592
|
+
throw new Error('FACTORY_FINALIZED is missing the accept log entry');
|
|
593
|
+
}
|
|
594
|
+
if (JSON.stringify(jsonSafeForCompare(last.allocations)) !== JSON.stringify(jsonSafeForCompare(known.allocations))) {
|
|
595
|
+
throw new Error('FACTORY_FINALIZED changes allocations in the accept entry');
|
|
596
|
+
}
|
|
597
|
+
return { ...incoming, pendingSignatures: {} };
|
|
598
|
+
}
|
|
599
|
+
if (known.status === 'active' && incoming.status === 'active') {
|
|
600
|
+
// Funding references may be filled in after activation; terms are already checked.
|
|
601
|
+
return { ...incoming };
|
|
602
|
+
}
|
|
603
|
+
if (known.status === 'opening' && incoming.status === 'opening') {
|
|
604
|
+
// Funding references only; signatures may not be removed or altered.
|
|
605
|
+
const knownSigs = known.pendingSignatures ?? {};
|
|
606
|
+
const incomingSigs = incoming.pendingSignatures ?? {};
|
|
607
|
+
for (const [partyId, sig] of Object.entries(knownSigs)) {
|
|
608
|
+
const next = incomingSigs[partyId];
|
|
609
|
+
if (!next || Buffer.from(next).toString('hex') !== Buffer.from(sig).toString('hex')) {
|
|
610
|
+
throw new Error(`FACTORY_FINALIZED removes or alters the signature for '${partyId}'`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return { ...incoming, pendingSignatures: { ...incomingSigs } };
|
|
614
|
+
}
|
|
615
|
+
throw new Error('FACTORY_FINALIZED has an unsupported status transition');
|
|
616
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
export type { FactoryOpeningPlan, FinalizeFactoryOpeningOptions } from './factory.js';
|
|
1
2
|
export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
2
3
|
export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
|
|
3
4
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
5
|
export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
|
|
5
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
|
+
export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
|
|
6
7
|
export type { FactoryOpeningSignature } from './factory.js';
|
|
7
8
|
export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
|
|
8
9
|
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
3
|
+
export { createFactory, createFactoryFromPlan, proposeFactoryOpening, buildFactoryOpening, finalizeFactoryOpening, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, assertFactoryFinalized, } from './factory.js';
|
|
4
4
|
// RFC-035 B2 — factory opening round-trip over the coordination transport.
|
|
5
5
|
export { createFactoryCoordination, } from './coordination.js';
|
|
6
6
|
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
package/dist/virtual.js
CHANGED
|
@@ -147,12 +147,14 @@ export function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
|
147
147
|
publicKeyDigest: partyAMeta.publicKeyDigest,
|
|
148
148
|
addressIndex: partyAMeta.addressIndex,
|
|
149
149
|
settlementAddress: partyAMeta.settlementAddress,
|
|
150
|
+
transportPubkey: partyAMeta.transportPubkey,
|
|
150
151
|
};
|
|
151
152
|
const partyB = {
|
|
152
153
|
partyId: partyBId,
|
|
153
154
|
publicKeyDigest: partyBMeta.publicKeyDigest,
|
|
154
155
|
addressIndex: partyBMeta.addressIndex,
|
|
155
156
|
settlementAddress: partyBMeta.settlementAddress,
|
|
157
|
+
transportPubkey: partyBMeta.transportPubkey,
|
|
156
158
|
};
|
|
157
159
|
const channel = {
|
|
158
160
|
channelId: plan.vcId,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@totemsdk/omnia-factory",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
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",
|
|
@@ -21,22 +21,20 @@
|
|
|
21
21
|
"rust/pkg/",
|
|
22
22
|
"rust/pkg-node/",
|
|
23
23
|
"README.md",
|
|
24
|
-
"LICENSE"
|
|
24
|
+
"LICENSE",
|
|
25
|
+
"NOTICE"
|
|
25
26
|
],
|
|
26
27
|
"dependencies": {
|
|
27
|
-
"@totemsdk/
|
|
28
|
-
"@totemsdk/
|
|
29
|
-
"@totemsdk/
|
|
30
|
-
"@totemsdk/
|
|
31
|
-
"@totemsdk/
|
|
32
|
-
"@totemsdk/
|
|
33
|
-
"@totemsdk/
|
|
28
|
+
"@totemsdk/wots-lease": "^1.0.3",
|
|
29
|
+
"@totemsdk/omnia": "^2.4.4",
|
|
30
|
+
"@totemsdk/txpow": "^1.1.1",
|
|
31
|
+
"@totemsdk/chain-provider": "^0.3.3",
|
|
32
|
+
"@totemsdk/tx-builder": "^0.3.3",
|
|
33
|
+
"@totemsdk/storage": "^0.2.2",
|
|
34
|
+
"@totemsdk/core": "^1.5.0"
|
|
34
35
|
},
|
|
35
36
|
"devDependencies": {
|
|
36
|
-
"@types/jest": "^30.0.0",
|
|
37
37
|
"@types/node": "^20.0.0",
|
|
38
|
-
"jest": "^30.4.2",
|
|
39
|
-
"ts-jest": "^29.0.0",
|
|
40
38
|
"typescript": "^7.0.2"
|
|
41
39
|
},
|
|
42
40
|
"engines": {
|
|
@@ -45,7 +43,7 @@
|
|
|
45
43
|
"publishConfig": {
|
|
46
44
|
"access": "public"
|
|
47
45
|
},
|
|
48
|
-
"license": "
|
|
46
|
+
"license": "Apache-2.0",
|
|
49
47
|
"author": "Totem SDK",
|
|
50
48
|
"homepage": "https://docs.totem.ing",
|
|
51
49
|
"bugs": {
|
|
@@ -76,7 +74,7 @@
|
|
|
76
74
|
"scripts": {
|
|
77
75
|
"build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
|
|
78
76
|
"clean": "rm -rf dist rust/pkg rust/pkg-node rust/target",
|
|
79
|
-
"test": "jest",
|
|
77
|
+
"test": "jest --config ../../tests/jest/omnia-factory.cjs",
|
|
80
78
|
"build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
|
|
81
79
|
}
|
|
82
80
|
}
|
package/rust/pkg/package.json
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
],
|
|
7
7
|
"description": "Channel factory commitment layer — N-of-N MULTISIG script building, state commitment hashing, balance conservation enforcement (Rust/WASM)",
|
|
8
8
|
"version": "0.1.0",
|
|
9
|
-
"license": "
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
10
|
"repository": {
|
|
11
11
|
"type": "git",
|
|
12
12
|
"url": "https://github.com/Totem-Edge/totem-sdk"
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
],
|
|
6
6
|
"description": "Channel factory commitment layer — N-of-N MULTISIG script building, state commitment hashing, balance conservation enforcement (Rust/WASM)",
|
|
7
7
|
"version": "0.1.0",
|
|
8
|
-
"license": "
|
|
8
|
+
"license": "Apache-2.0",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
11
|
"url": "https://github.com/Totem-Edge/totem-sdk"
|