@totemsdk/omnia-factory 0.2.0 → 0.3.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 +380 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +38 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/script.d.ts +47 -0
- package/dist/cjs/script.js +105 -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.d.ts +42 -0
- package/dist/durable-factory-store.js +56 -0
- package/dist/factory.d.ts +21 -0
- package/dist/factory.js +101 -30
- package/dist/index.d.ts +10 -4
- package/dist/index.js +8 -21
- package/dist/script.d.ts +31 -13
- package/dist/script.js +68 -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 +20 -13
- 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
package/dist/factory.js
CHANGED
|
@@ -1,15 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
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 } 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
|
-
* `
|
|
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(
|
|
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 } =
|
|
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,20 @@ 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 =
|
|
134
|
+
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));
|
|
142
135
|
// All parties co-sign the TX digest — the exact on-chain TX structure.
|
|
143
|
-
pendingCommitment =
|
|
144
|
-
const draftBytes =
|
|
145
|
-
const txBody =
|
|
146
|
-
const mined = await
|
|
147
|
-
const fullTxPoW =
|
|
136
|
+
pendingCommitment = computeTxDraftDigest(fundingDraft);
|
|
137
|
+
const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
138
|
+
const txBody = serializeTxBody(draftBytes, new Uint8Array(0));
|
|
139
|
+
const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
|
|
140
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
148
141
|
await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
149
142
|
fundingTxId = Buffer.from(mined.txpowId).toString('hex');
|
|
150
143
|
fundingCoinId = `${fundingTxId}-0`;
|
|
151
144
|
}
|
|
152
145
|
else {
|
|
153
146
|
// In-memory / test path: sign the factory state commitment instead.
|
|
154
|
-
pendingCommitment =
|
|
147
|
+
pendingCommitment = computeFactoryStateCommitment(factoryId, 1, allocations, []);
|
|
155
148
|
}
|
|
156
149
|
// Sign with the proposer's lease (full bundle preserved so verify override is available).
|
|
157
150
|
const proposerSig = await leaseSign(factoryId, pendingCommitment, 'factory-open', proposer, bundle);
|
|
@@ -201,7 +194,7 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
|
|
|
201
194
|
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
202
195
|
* must match a registered participant not yet signed).
|
|
203
196
|
*/
|
|
204
|
-
async function acceptFactory(factory, bundle) {
|
|
197
|
+
export async function acceptFactory(factory, bundle) {
|
|
205
198
|
if (factory.status !== 'opening') {
|
|
206
199
|
throw new Error(`acceptFactory requires factory status 'opening', got '${factory.status}'`);
|
|
207
200
|
}
|
|
@@ -226,6 +219,84 @@ async function acceptFactory(factory, bundle) {
|
|
|
226
219
|
}
|
|
227
220
|
return updatedFactory;
|
|
228
221
|
}
|
|
222
|
+
/**
|
|
223
|
+
* Produce this party's opening signature WITHOUT committing the lease
|
|
224
|
+
* (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
|
|
225
|
+
* mirroring the splice accept round so a peer can gather N-of-N signatures
|
|
226
|
+
* without stranding or prematurely committing one-time keys.
|
|
227
|
+
*/
|
|
228
|
+
export async function signFactoryOpening(factory, bundle) {
|
|
229
|
+
if (factory.status !== 'opening' || !factory.pendingCommitment) {
|
|
230
|
+
throw new Error(`signFactoryOpening requires an 'opening' factory, got '${factory.status}'`);
|
|
231
|
+
}
|
|
232
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
233
|
+
if (!participant) {
|
|
234
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
235
|
+
}
|
|
236
|
+
if (factory.pendingSignatures[participant.partyId]) {
|
|
237
|
+
throw new Error(`Party '${participant.partyId}' has already co-signed this factory proposal`);
|
|
238
|
+
}
|
|
239
|
+
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
240
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
241
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
242
|
+
purpose: 'factory-open',
|
|
243
|
+
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
244
|
+
});
|
|
245
|
+
let sig;
|
|
246
|
+
try {
|
|
247
|
+
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
248
|
+
}
|
|
249
|
+
catch (err) {
|
|
250
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
251
|
+
throw err;
|
|
252
|
+
}
|
|
253
|
+
const verifyFn = bundle.verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
|
|
254
|
+
if (!verifyFn(sig, commitment, participant.publicKeyDigest)) {
|
|
255
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
256
|
+
throw new Error(`Signature verification failed for party '${participant.partyId}' — refusing to commit`);
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
factoryId: factory.factoryId,
|
|
260
|
+
partyId: participant.partyId,
|
|
261
|
+
signature: sig,
|
|
262
|
+
reservationId: reservation.reservationId,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/** Verify a remote opening signature against a factory participant. */
|
|
266
|
+
export function verifyFactorySignature(factory, partyId, signature, verify) {
|
|
267
|
+
if (!factory.pendingCommitment)
|
|
268
|
+
return false;
|
|
269
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
270
|
+
if (!participant)
|
|
271
|
+
return false;
|
|
272
|
+
const commitment = Buffer.from(factory.pendingCommitment, 'hex');
|
|
273
|
+
const verifyFn = verify ?? ((s, c, pkd) => verifyChannelSignature(s, c, pkd));
|
|
274
|
+
try {
|
|
275
|
+
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Merge a co-signer's opening signature (RFC-035 B2). When all N participants
|
|
283
|
+
* have signed, the opening commits (`'opening'` → `'active'`).
|
|
284
|
+
*/
|
|
285
|
+
export function applyFactorySignature(factory, partyId, signature) {
|
|
286
|
+
if (factory.status !== 'opening') {
|
|
287
|
+
throw new Error(`applyFactorySignature requires factory status 'opening', got '${factory.status}'`);
|
|
288
|
+
}
|
|
289
|
+
if (!factory.participants.find(p => p.partyId === partyId)) {
|
|
290
|
+
throw new Error(`'${partyId}' is not a registered factory participant`);
|
|
291
|
+
}
|
|
292
|
+
if (factory.pendingSignatures[partyId]) {
|
|
293
|
+
throw new Error(`Party '${partyId}' has already co-signed this factory proposal`);
|
|
294
|
+
}
|
|
295
|
+
const newSigs = { ...factory.pendingSignatures, [partyId]: signature };
|
|
296
|
+
const updated = { ...factory, pendingSignatures: newSigs };
|
|
297
|
+
const allSigned = factory.participants.every(p => newSigs[p.partyId] !== undefined);
|
|
298
|
+
return allSigned ? commitOpening(updated) : updated;
|
|
299
|
+
}
|
|
229
300
|
function commitOpening(factory) {
|
|
230
301
|
const logEntry = {
|
|
231
302
|
sequence: 1,
|
|
@@ -259,7 +330,7 @@ function commitOpening(factory) {
|
|
|
259
330
|
* @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
|
|
260
331
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
261
332
|
*/
|
|
262
|
-
async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
|
|
333
|
+
export async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProviders) {
|
|
263
334
|
if (factory.status !== 'active') {
|
|
264
335
|
throw new Error(`reallocate requires factory status 'active', got '${factory.status}'`);
|
|
265
336
|
}
|
|
@@ -280,7 +351,7 @@ async function reallocate(factory, fromPartyId, toPartyId, amount, leaseProvider
|
|
|
280
351
|
};
|
|
281
352
|
const newSequence = factory.currentSequence + 1;
|
|
282
353
|
const vcIds = factory.virtualChannels.map(vc => vc.channelId);
|
|
283
|
-
const commitment =
|
|
354
|
+
const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, vcIds);
|
|
284
355
|
await collectNofN(factory.factoryId, commitment, 'factory-reallocate', factory.participants, leaseProviders);
|
|
285
356
|
const logEntry = {
|
|
286
357
|
sequence: newSequence,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +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, scriptAddress, normalizeScript, } from './script.js';
|
|
3
3
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
|
-
export { createFactory, acceptFactory, reallocate, enforceConservation, } from './factory.js';
|
|
5
|
-
export {
|
|
6
|
-
export {
|
|
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';
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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; } });
|
|
1
|
+
export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, 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,39 @@
|
|
|
1
1
|
import type { FactoryParticipant } from './types.js';
|
|
2
|
+
/** Default coinage (blocks) after which any party may unilaterally withdraw. */
|
|
3
|
+
export declare const FACTORY_TIMEOUT_BLOCKS = 256;
|
|
4
|
+
/** State port base for per-party allocations: party k ⇒ port 200+k. */
|
|
5
|
+
export declare const FACTORY_BALANCE_PORT_BASE = 200;
|
|
6
|
+
export interface FactoryScriptOptions {
|
|
7
|
+
/** Coinage threshold for the unilateral per-party escape (default 256). */
|
|
8
|
+
timeoutBlocks?: number;
|
|
9
|
+
}
|
|
2
10
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
* Per-party allocation state variables (port 200+k = party k's balance), seeded
|
|
12
|
+
* into the factory funding output so the timeout escape can pay each party its
|
|
13
|
+
* committed share.
|
|
14
|
+
*/
|
|
15
|
+
export declare function factoryBalanceStateVariables(participants: FactoryParticipant[]): {
|
|
16
|
+
port: number;
|
|
17
|
+
value: bigint;
|
|
18
|
+
type: 'number';
|
|
19
|
+
}[];
|
|
20
|
+
/**
|
|
21
|
+
* Build the N-of-N MULTISIG MAST funding script for a channel factory
|
|
22
|
+
* (RFC-044, CUSTODY-POLICY §2).
|
|
12
23
|
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
24
|
+
* Spend paths:
|
|
25
|
+
* - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
|
|
26
|
+
* `SETTLEMENT=true` closes after minimal coinage (1 block).
|
|
27
|
+
* - **Unilateral escape** (after `@COINAGE GTE timeoutBlocks`): any single
|
|
28
|
+
* party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its own
|
|
29
|
+
* settlement address, zero its state (`STATE(200+k) EQ 0`), keep the other
|
|
30
|
+
* parties' balances unchanged, and return the remainder to the factory
|
|
31
|
+
* script. Repeated withdrawals cannot double-claim because each zeroes its
|
|
32
|
+
* own port.
|
|
15
33
|
*
|
|
16
34
|
* Minimum 2 participants required.
|
|
17
35
|
*/
|
|
18
|
-
export declare function buildFactoryScript(participants: FactoryParticipant[]): string;
|
|
36
|
+
export declare function buildFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): string;
|
|
19
37
|
export declare function normalizeScript(script: string): string;
|
|
20
38
|
/** Compute the SHA3-256 script-hash address for a factory script. */
|
|
21
39
|
export declare function scriptAddress(script: string): string;
|
|
@@ -23,7 +41,7 @@ export declare function scriptAddress(script: string): string;
|
|
|
23
41
|
* Build the factory script and compute its canonical address in one step.
|
|
24
42
|
* The address is used as the output address of the factory funding TX.
|
|
25
43
|
*/
|
|
26
|
-
export declare function buildAndHashFactoryScript(participants: FactoryParticipant[]): {
|
|
44
|
+
export declare function buildAndHashFactoryScript(participants: FactoryParticipant[], options?: FactoryScriptOptions): {
|
|
27
45
|
script: string;
|
|
28
46
|
address: string;
|
|
29
47
|
};
|
package/dist/script.js
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
|
|
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,91 @@ 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
|
+
/** Default coinage (blocks) after which any party may unilaterally withdraw. */
|
|
11
|
+
export const FACTORY_TIMEOUT_BLOCKS = 256;
|
|
12
|
+
/** State port base for per-party allocations: party k ⇒ port 200+k. */
|
|
13
|
+
export const FACTORY_BALANCE_PORT_BASE = 200;
|
|
16
14
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
15
|
+
* Per-party allocation state variables (port 200+k = party k's balance), seeded
|
|
16
|
+
* into the factory funding output so the timeout escape can pay each party its
|
|
17
|
+
* committed share.
|
|
18
|
+
*/
|
|
19
|
+
export function factoryBalanceStateVariables(participants) {
|
|
20
|
+
return participants.map((p, k) => ({
|
|
21
|
+
port: FACTORY_BALANCE_PORT_BASE + k,
|
|
22
|
+
value: p.contributionAmount,
|
|
23
|
+
type: 'number',
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Build the N-of-N MULTISIG MAST funding script for a channel factory
|
|
28
|
+
* (RFC-044, CUSTODY-POLICY §2).
|
|
26
29
|
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
30
|
+
* Spend paths:
|
|
31
|
+
* - **Cooperative / update** (any time): `MULTISIG(N …)` — all parties sign.
|
|
32
|
+
* `SETTLEMENT=true` closes after minimal coinage (1 block).
|
|
33
|
+
* - **Unilateral escape** (after `@COINAGE GTE timeoutBlocks`): any single
|
|
34
|
+
* party k may withdraw its allocation `SHARE_k = STATE(200+k)` to its own
|
|
35
|
+
* settlement address, zero its state (`STATE(200+k) EQ 0`), keep the other
|
|
36
|
+
* parties' balances unchanged, and return the remainder to the factory
|
|
37
|
+
* script. Repeated withdrawals cannot double-claim because each zeroes its
|
|
38
|
+
* own port.
|
|
29
39
|
*
|
|
30
40
|
* Minimum 2 participants required.
|
|
31
41
|
*/
|
|
32
|
-
function buildFactoryScript(participants) {
|
|
42
|
+
export function buildFactoryScript(participants, options = {}) {
|
|
33
43
|
if (participants.length < 2) {
|
|
34
44
|
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
35
45
|
}
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
-
|
|
46
|
+
const count = participants.length;
|
|
47
|
+
const timeout = options.timeoutBlocks ?? FACTORY_TIMEOUT_BLOCKS;
|
|
48
|
+
if (!Number.isInteger(timeout) || timeout < 0) {
|
|
49
|
+
throw new Error(`timeoutBlocks must be a non-negative integer, got ${JSON.stringify(timeout)}`);
|
|
50
|
+
}
|
|
51
|
+
const pks = participants.map((p) => kissHex(p.publicKeyDigest));
|
|
52
|
+
const payouts = participants.map((p) => kissHex(p.settlementAddress ?? p.publicKeyDigest));
|
|
53
|
+
const lines = [
|
|
39
54
|
'LET SETTLEMENT=STATE(100)',
|
|
40
|
-
`
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
55
|
+
`IF @COINAGE GTE ${timeout} THEN`,
|
|
56
|
+
];
|
|
57
|
+
participants.forEach((_, k) => {
|
|
58
|
+
const port = FACTORY_BALANCE_PORT_BASE + k;
|
|
59
|
+
lines.push(` LET SHARE${k}=STATE(${port})`);
|
|
60
|
+
lines.push(` IF SIGNEDBY(${pks[k]}) THEN`);
|
|
61
|
+
lines.push(` IF SHARE${k} GT 0 THEN`);
|
|
62
|
+
lines.push(` ASSERT VERIFYOUT(0 ${payouts[k]} SHARE${k} @TOKENID FALSE)`);
|
|
63
|
+
for (let j = 0; j < count; j++) {
|
|
64
|
+
if (j === k)
|
|
65
|
+
continue;
|
|
66
|
+
lines.push(` ASSERT STATE(${FACTORY_BALANCE_PORT_BASE + j}) EQ PREVSTATE(${FACTORY_BALANCE_PORT_BASE + j})`);
|
|
67
|
+
}
|
|
68
|
+
lines.push(` ASSERT STATE(${port}) EQ 0`);
|
|
69
|
+
lines.push(` RETURN VERIFYOUT(@INPUT @ADDRESS @AMOUNT SUB SHARE${k} @TOKENID TRUE)`);
|
|
70
|
+
lines.push(' ENDIF');
|
|
71
|
+
lines.push(' ENDIF');
|
|
72
|
+
});
|
|
73
|
+
lines.push('ENDIF');
|
|
74
|
+
lines.push(`ASSERT MULTISIG(${count} ${pks.join(' ')})`);
|
|
75
|
+
lines.push('IF SETTLEMENT THEN');
|
|
76
|
+
lines.push(' IF @COINAGE GTE 1 THEN RETURN TRUE ENDIF');
|
|
77
|
+
lines.push('ELSE');
|
|
78
|
+
lines.push(' RETURN TRUE');
|
|
79
|
+
lines.push('ENDIF');
|
|
80
|
+
return lines.join('\n');
|
|
47
81
|
}
|
|
48
|
-
function normalizeScript(script) {
|
|
82
|
+
export function normalizeScript(script) {
|
|
49
83
|
return script.trim().toUpperCase();
|
|
50
84
|
}
|
|
51
85
|
/** Compute the SHA3-256 script-hash address for a factory script. */
|
|
52
|
-
function scriptAddress(script) {
|
|
53
|
-
return
|
|
86
|
+
export function scriptAddress(script) {
|
|
87
|
+
return computeScriptAddress(script);
|
|
54
88
|
}
|
|
55
89
|
/**
|
|
56
90
|
* Build the factory script and compute its canonical address in one step.
|
|
57
91
|
* The address is used as the output address of the factory funding TX.
|
|
58
92
|
*/
|
|
59
|
-
function buildAndHashFactoryScript(participants) {
|
|
60
|
-
const script = buildFactoryScript(participants);
|
|
93
|
+
export function buildAndHashFactoryScript(participants, options = {}) {
|
|
94
|
+
const script = buildFactoryScript(participants, options);
|
|
61
95
|
const address = scriptAddress(script);
|
|
62
96
|
return { script, address };
|
|
63
97
|
}
|
package/dist/settlement.d.ts
CHANGED
|
@@ -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
|
-
*
|
|
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
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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.
|