@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
package/dist/settlement.js
CHANGED
|
@@ -1,49 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
exports.buildDisputePayload = buildDisputePayload;
|
|
5
|
-
const core_1 = require("@totemsdk/core");
|
|
6
|
-
const omnia_1 = require("@totemsdk/omnia");
|
|
7
|
-
const txpow_1 = require("@totemsdk/txpow");
|
|
8
|
-
// ─── closeFactory ─────────────────────────────────────────────────────────────
|
|
1
|
+
import { concatBytes } from '@totemsdk/core/wasm';
|
|
2
|
+
import { serializeTxDraft, omniaDraftToMinimaBytes, computeTxDraftDigest, toRawMinima, verifyChannelSignature, } from '@totemsdk/omnia';
|
|
3
|
+
import { mineTxPoW, TX_POW_MIN_DIFFICULTY, serializeTxBody } from '@totemsdk/txpow';
|
|
9
4
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* Flow:
|
|
13
|
-
* 1. Fail fast if `factory.fundingCoinId` is not set — settlement TX requires
|
|
14
|
-
* a concrete input coin.
|
|
15
|
-
* 2. Build the settlement OmniaTxDraft (N outputs, one per participant with a
|
|
16
|
-
* positive allocation) spending the factory's N-of-N MULTISIG input.
|
|
17
|
-
* 3. Compute the TX draft digest via `computeTxDraftDigest` from `@totemsdk/omnia`.
|
|
18
|
-
* 4. Collect N-of-N signatures — all participants sign + verify the TX digest
|
|
19
|
-
* via the full WOTS lease cycle (reserve → sign → verify → commit).
|
|
20
|
-
* 5. Encode the concatenated WOTS signatures as the settlement TX witness.
|
|
21
|
-
* 6. When `chainProvider` is supplied: mine via `@totemsdk/txpow`'s `mineTxPoW`,
|
|
22
|
-
* assemble the full TxPoW blob, and broadcast.
|
|
23
|
-
*
|
|
24
|
-
* @param factory - Active factory with no open virtual channels.
|
|
25
|
-
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
26
|
-
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
5
|
+
* Build the cooperative settlement TX + digest (no signing). Exported so peers
|
|
6
|
+
* can independently rebuild and bind a proposal (RFC-035 B3).
|
|
27
7
|
*/
|
|
28
|
-
|
|
8
|
+
export function buildFactorySettlement(factory) {
|
|
29
9
|
if (factory.status !== 'active') {
|
|
30
|
-
throw new Error(`
|
|
10
|
+
throw new Error(`buildFactorySettlement requires factory status 'active', got '${factory.status}'`);
|
|
31
11
|
}
|
|
32
12
|
if (!factory.fundingCoinId) {
|
|
33
|
-
throw new Error('
|
|
13
|
+
throw new Error('buildFactorySettlement requires factory.fundingCoinId to be set. ' +
|
|
34
14
|
'Create the factory with fundingCoinIds + chainProvider so the funding TX is mined first.');
|
|
35
15
|
}
|
|
36
16
|
if (factory.virtualChannels.length > 0) {
|
|
37
17
|
const ids = factory.virtualChannels.map(vc => vc.channelId).join(', ');
|
|
38
18
|
throw new Error(`closeFactory requires all virtual channels to be closed first. Open channels: ${ids}`);
|
|
39
19
|
}
|
|
40
|
-
// ── Step 1: Validate all leaseProviders present ───────────────────────────
|
|
41
|
-
for (const p of factory.participants) {
|
|
42
|
-
if (!leaseProviders[p.partyId]) {
|
|
43
|
-
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
// ── Step 2: Build settlement TX ───────────────────────────────────────────
|
|
47
20
|
const outputs = [];
|
|
48
21
|
for (const participant of factory.participants) {
|
|
49
22
|
const amount = factory.allocations[participant.partyId] ?? 0n;
|
|
@@ -51,7 +24,7 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
51
24
|
continue;
|
|
52
25
|
outputs.push({
|
|
53
26
|
address: participant.settlementAddress ?? participant.publicKeyDigest,
|
|
54
|
-
amount:
|
|
27
|
+
amount: toRawMinima(amount, factory.tokenScale),
|
|
55
28
|
tokenId: factory.tokenId,
|
|
56
29
|
storeState: false,
|
|
57
30
|
stateVariables: [],
|
|
@@ -62,7 +35,7 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
62
35
|
inputs: [{
|
|
63
36
|
coinId: factory.fundingCoinId,
|
|
64
37
|
address: factory.fundingAddress,
|
|
65
|
-
amount:
|
|
38
|
+
amount: toRawMinima(factory.totalValue, factory.tokenScale),
|
|
66
39
|
tokenId: factory.tokenId,
|
|
67
40
|
scriptHex: factory.fundingScript,
|
|
68
41
|
}],
|
|
@@ -70,54 +43,119 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
70
43
|
storeState: true,
|
|
71
44
|
stateVariables: [{ port: 100, value: true, type: 'bool' }],
|
|
72
45
|
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
46
|
+
return {
|
|
47
|
+
settlementDraft,
|
|
48
|
+
settlementTxHex: serializeTxDraft(settlementDraft),
|
|
49
|
+
txDigest: computeTxDraftDigest(settlementDraft),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Produce this party's settlement signature WITHOUT committing the lease
|
|
54
|
+
* (RFC-035 B3). The caller commits on `FACTORY_CLOSE_FINALIZED` or burns on expiry.
|
|
55
|
+
*/
|
|
56
|
+
export async function signFactorySettlement(factory, draft, bundle) {
|
|
57
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
58
|
+
if (!participant) {
|
|
59
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
60
|
+
}
|
|
61
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
62
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
63
|
+
purpose: 'factory-settlement',
|
|
64
|
+
payloadHash: Buffer.from(draft.txDigest).toString('hex'),
|
|
65
|
+
});
|
|
66
|
+
let sig;
|
|
67
|
+
try {
|
|
68
|
+
sig = await bundle.signer.sign(draft.txDigest, reservation.indices);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
const verifyFn = bundle.verify ?? verifyChannelSignature;
|
|
75
|
+
if (!verifyFn(sig, draft.txDigest, participant.publicKeyDigest)) {
|
|
76
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
77
|
+
throw new Error(`Settlement signature verification failed for party '${participant.partyId}'`);
|
|
78
|
+
}
|
|
79
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
80
|
+
}
|
|
81
|
+
/** Verify a remote settlement signature against a factory participant. */
|
|
82
|
+
export function verifyFactorySettlementSignature(factory, txDigest, partyId, signature, verify) {
|
|
83
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
84
|
+
if (!participant)
|
|
85
|
+
return false;
|
|
86
|
+
const verifyFn = verify ?? verifyChannelSignature;
|
|
87
|
+
try {
|
|
88
|
+
return verifyFn(signature, txDigest, participant.publicKeyDigest);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Assemble N-of-N settlement signatures into the MULTISIG witness + payload, and
|
|
96
|
+
* (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
|
|
97
|
+
*/
|
|
98
|
+
export async function assembleFactorySettlement(factory, draft, signatures, chainProvider, options) {
|
|
77
99
|
const witnessParts = [];
|
|
78
100
|
for (const p of factory.participants) {
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
payloadHash: Buffer.from(txDigest).toString('hex'),
|
|
84
|
-
});
|
|
85
|
-
let sig;
|
|
86
|
-
try {
|
|
87
|
-
sig = await bundle.signer.sign(txDigest, reservation.indices);
|
|
88
|
-
}
|
|
89
|
-
catch (err) {
|
|
90
|
-
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
91
|
-
throw err;
|
|
92
|
-
}
|
|
93
|
-
const verifyFn = bundle.verify
|
|
94
|
-
?? ((s, c, pkd) => (0, core_1.wotsVerifyDigest)(s, c, (0, core_1.hexToBytes)(pkd)));
|
|
95
|
-
if (!verifyFn(sig, txDigest, p.publicKeyDigest)) {
|
|
96
|
-
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
101
|
+
const s = signatures[p.partyId];
|
|
102
|
+
if (!s)
|
|
103
|
+
throw new Error(`Missing settlement signature for party '${p.partyId}' — close requires all N`);
|
|
104
|
+
if (!verifyFactorySettlementSignature(factory, draft.txDigest, p.partyId, s.signature, options?.verify)) {
|
|
97
105
|
throw new Error(`Settlement signature verification failed for party '${p.partyId}'`);
|
|
98
106
|
}
|
|
99
|
-
|
|
100
|
-
witnessParts.push(sig);
|
|
107
|
+
witnessParts.push(s.signature);
|
|
101
108
|
}
|
|
102
|
-
|
|
103
|
-
const witnessBytes = witnessParts.reduce((a, b) => (0, core_1.concatBytes)(a, b));
|
|
109
|
+
const witnessBytes = witnessParts.reduce((a, b) => concatBytes(a, b));
|
|
104
110
|
const payload = {
|
|
105
111
|
factoryId: factory.factoryId,
|
|
106
112
|
sequence: factory.currentSequence,
|
|
107
|
-
settlementTxHex,
|
|
113
|
+
settlementTxHex: draft.settlementTxHex,
|
|
108
114
|
finalAllocations: { ...factory.allocations },
|
|
109
115
|
};
|
|
110
|
-
// ── Step 4: Mine + broadcast ──────────────────────────────────────────────
|
|
111
116
|
if (chainProvider) {
|
|
112
|
-
const draftBytes = (
|
|
113
|
-
const txBody =
|
|
114
|
-
const mined = await
|
|
115
|
-
const fullTxPoW =
|
|
117
|
+
const draftBytes = omniaDraftToMinimaBytes(draft.settlementDraft);
|
|
118
|
+
const txBody = serializeTxBody(draftBytes, witnessBytes);
|
|
119
|
+
const mined = await mineTxPoW(txBody, TX_POW_MIN_DIFFICULTY);
|
|
120
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
116
121
|
await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
117
122
|
payload.txpowId = Buffer.from(mined.txpowId).toString('hex');
|
|
118
123
|
}
|
|
119
124
|
return payload;
|
|
120
125
|
}
|
|
126
|
+
/**
|
|
127
|
+
* Cooperative N-of-N factory close (central/local path).
|
|
128
|
+
*
|
|
129
|
+
* Builds the settlement TX, collects all N signatures (each committing its own
|
|
130
|
+
* lease via the full WOTS cycle), assembles the witness, and — when a
|
|
131
|
+
* `chainProvider` is supplied — mines + broadcasts the settlement TxPoW.
|
|
132
|
+
*
|
|
133
|
+
* @param factory - Active factory with no open virtual channels.
|
|
134
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
135
|
+
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
136
|
+
*/
|
|
137
|
+
export async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
138
|
+
for (const p of factory.participants) {
|
|
139
|
+
if (!leaseProviders[p.partyId]) {
|
|
140
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const draft = buildFactorySettlement(factory);
|
|
144
|
+
const signatures = {};
|
|
145
|
+
for (const p of factory.participants) {
|
|
146
|
+
const sig = await signFactorySettlement(factory, draft, leaseProviders[p.partyId]);
|
|
147
|
+
await leaseProviders[p.partyId].leaseProvider.commitKeyUse(sig.reservationId, `factory-settlement-${factory.factoryId}`);
|
|
148
|
+
signatures[p.partyId] = sig;
|
|
149
|
+
}
|
|
150
|
+
return assembleFactorySettlement(factory, draft, signatures, chainProvider, {
|
|
151
|
+
verify: (sig, digest, pkd) => {
|
|
152
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === pkd);
|
|
153
|
+
const bundle = participant ? leaseProviders[participant.partyId] : undefined;
|
|
154
|
+
const fn = bundle?.verify ?? verifyChannelSignature;
|
|
155
|
+
return fn(sig, digest, pkd);
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
}
|
|
121
159
|
// ─── buildDisputePayload ──────────────────────────────────────────────────────
|
|
122
160
|
/**
|
|
123
161
|
* Build a unilateral factory close (dispute) payload.
|
|
@@ -127,7 +165,7 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
127
165
|
* dispute time are included by ID so the dispute resolver can adjudicate their
|
|
128
166
|
* balances independently.
|
|
129
167
|
*/
|
|
130
|
-
function buildDisputePayload(factory, evidence) {
|
|
168
|
+
export function buildDisputePayload(factory, evidence) {
|
|
131
169
|
const logEntry = {
|
|
132
170
|
sequence: factory.currentSequence,
|
|
133
171
|
timestamp: Date.now(),
|
package/dist/types.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1
|
+
export {};
|
package/dist/virtual.d.ts
CHANGED
|
@@ -21,6 +21,37 @@ import type { ChannelFactory, WotsLeaseBundle } from './types.js';
|
|
|
21
21
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
22
22
|
* @param channelId - Optional explicit channel ID; auto-generated if omitted.
|
|
23
23
|
*/
|
|
24
|
+
/** Deterministic virtual-channel open plan (RFC-035 B3). */
|
|
25
|
+
export interface VirtualChannelOpenPlan {
|
|
26
|
+
vcId: string;
|
|
27
|
+
parties: [string, string];
|
|
28
|
+
amounts: Record<string, bigint>;
|
|
29
|
+
newSequence: number;
|
|
30
|
+
newAllocations: Record<string, bigint>;
|
|
31
|
+
newVcIds: string[];
|
|
32
|
+
commitment: Uint8Array;
|
|
33
|
+
}
|
|
34
|
+
/** A participant's VC-open signature, held until the open is confirmed. */
|
|
35
|
+
export interface VirtualChannelOpenSignature {
|
|
36
|
+
partyId: string;
|
|
37
|
+
signature: Uint8Array;
|
|
38
|
+
reservationId: string;
|
|
39
|
+
}
|
|
40
|
+
/** Validate + build the VC-open plan (no signing). Exported so peers can bind. */
|
|
41
|
+
export declare function buildVirtualChannelOpen(factory: ChannelFactory, parties: [string, string], amounts: Record<string, bigint>, channelId?: string): VirtualChannelOpenPlan;
|
|
42
|
+
/**
|
|
43
|
+
* Produce this party's VC-open signature WITHOUT committing the lease
|
|
44
|
+
* (RFC-035 B3). The caller commits on `VC_FINALIZED` or burns on expiry.
|
|
45
|
+
*/
|
|
46
|
+
export declare function signVirtualChannelOpen(factory: ChannelFactory, plan: VirtualChannelOpenPlan, bundle: WotsLeaseBundle): Promise<VirtualChannelOpenSignature>;
|
|
47
|
+
export declare function verifyVirtualChannelOpenSignature(factory: ChannelFactory, commitment: Uint8Array, partyId: string, signature: Uint8Array, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Assemble N-of-N VC-open signatures into the updated factory + virtual channel.
|
|
50
|
+
*/
|
|
51
|
+
export declare function assembleVirtualChannelOpen(factory: ChannelFactory, plan: VirtualChannelOpenPlan, signatures: Record<string, VirtualChannelOpenSignature>, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): {
|
|
52
|
+
factory: ChannelFactory;
|
|
53
|
+
channel: OmniaChannel;
|
|
54
|
+
};
|
|
24
55
|
export declare function openVirtualChannel(factory: ChannelFactory, parties: [string, string], amounts: Record<string, bigint>, leaseProviders: Record<string, WotsLeaseBundle>, channelId?: string): Promise<{
|
|
25
56
|
factory: ChannelFactory;
|
|
26
57
|
channel: OmniaChannel;
|
package/dist/virtual.js
CHANGED
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
exports.closeVirtualChannel = closeVirtualChannel;
|
|
5
|
-
const omnia_1 = require("@totemsdk/omnia");
|
|
6
|
-
const core_1 = require("@totemsdk/core");
|
|
7
|
-
const factory_js_1 = require("./factory.js");
|
|
8
|
-
const commitment_js_1 = require("./commitment.js");
|
|
1
|
+
import { DefaultEltooPaymentProgram, verifyChannelSignature } from '@totemsdk/omnia';
|
|
2
|
+
import { enforceConservation } from './factory.js';
|
|
3
|
+
import { computeFactoryStateCommitment } from './commitment.js';
|
|
9
4
|
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
10
5
|
function generateChannelId(factoryId, partyAId, partyBId) {
|
|
11
6
|
const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
@@ -26,8 +21,7 @@ async function leaseSign(factoryId, commitment, purpose, partyId, publicKeyDiges
|
|
|
26
21
|
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
27
22
|
throw err;
|
|
28
23
|
}
|
|
29
|
-
const verifyFn = bundle.verify
|
|
30
|
-
?? ((s, c, pkd) => (0, core_1.wotsVerifyDigest)(s, c, (0, core_1.hexToBytes)(pkd)));
|
|
24
|
+
const verifyFn = bundle.verify ?? verifyChannelSignature;
|
|
31
25
|
if (!verifyFn(sig, commitment, publicKeyDigest)) {
|
|
32
26
|
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
33
27
|
throw new Error(`Signature verification failed for party '${partyId}' — aborting virtual channel operation`);
|
|
@@ -48,41 +42,18 @@ async function collectNofN(factoryId, commitment, purpose, participants, leasePr
|
|
|
48
42
|
await leaseSign(factoryId, commitment, purpose, p.partyId, p.publicKeyDigest, leaseProviders[p.partyId]);
|
|
49
43
|
}
|
|
50
44
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
* Open a virtual channel between two factory participants.
|
|
54
|
-
*
|
|
55
|
-
* ALL N factory participants must agree (N-of-N WOTS signature collection)
|
|
56
|
-
* before the virtual channel is committed and allocations deducted. This ensures
|
|
57
|
-
* the shared factory UTXO's off-chain state is consistent and dispute-provable.
|
|
58
|
-
*
|
|
59
|
-
* The commitment is bound to `currentSequence + 1` — the post-commit sequence —
|
|
60
|
-
* preventing replay of the same openVC commitment against a future factory state.
|
|
61
|
-
*
|
|
62
|
-
* The returned `OmniaChannel` has `channelType: 'virtual'` and `factoryRef` set.
|
|
63
|
-
* Its `fundingTxId`/`fundingCoinId` reference the factory's shared UTXO.
|
|
64
|
-
* It is ready for off-chain state updates via `@totemsdk/omnia` primitives
|
|
65
|
-
* (`updateState`, `addHTLC`, `signState`, etc.).
|
|
66
|
-
*
|
|
67
|
-
* @param factory - Active factory.
|
|
68
|
-
* @param parties - Tuple `[partyAId, partyBId]` of the two channel parties.
|
|
69
|
-
* @param amounts - Capacity per party: `Record<partyId, bigint>`.
|
|
70
|
-
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
71
|
-
* @param channelId - Optional explicit channel ID; auto-generated if omitted.
|
|
72
|
-
*/
|
|
73
|
-
async function openVirtualChannel(factory, parties, amounts, leaseProviders, channelId) {
|
|
45
|
+
/** Validate + build the VC-open plan (no signing). Exported so peers can bind. */
|
|
46
|
+
export function buildVirtualChannelOpen(factory, parties, amounts, channelId) {
|
|
74
47
|
if (factory.status !== 'active') {
|
|
75
48
|
throw new Error(`openVirtualChannel requires factory status 'active', got '${factory.status}'`);
|
|
76
49
|
}
|
|
77
50
|
const [partyAId, partyBId] = parties;
|
|
78
51
|
const amountA = amounts[partyAId] ?? 0n;
|
|
79
52
|
const amountB = amounts[partyBId] ?? 0n;
|
|
80
|
-
if (amountA < 0n || amountB < 0n)
|
|
53
|
+
if (amountA < 0n || amountB < 0n)
|
|
81
54
|
throw new Error('Virtual channel amounts must be non-negative');
|
|
82
|
-
|
|
83
|
-
if (amountA + amountB === 0n) {
|
|
55
|
+
if (amountA + amountB === 0n)
|
|
84
56
|
throw new Error('Virtual channel must have positive total value');
|
|
85
|
-
}
|
|
86
57
|
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
87
58
|
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
88
59
|
if (!partyAMeta)
|
|
@@ -91,12 +62,10 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
91
62
|
throw new Error(`Party '${partyBId}' not found in factory`);
|
|
92
63
|
const allocA = factory.allocations[partyAId] ?? 0n;
|
|
93
64
|
const allocB = factory.allocations[partyBId] ?? 0n;
|
|
94
|
-
if (allocA < amountA)
|
|
65
|
+
if (allocA < amountA)
|
|
95
66
|
throw new Error(`Party '${partyAId}' has insufficient allocation: ${allocA} < ${amountA}`);
|
|
96
|
-
|
|
97
|
-
if (allocB < amountB) {
|
|
67
|
+
if (allocB < amountB)
|
|
98
68
|
throw new Error(`Party '${partyBId}' has insufficient allocation: ${allocB} < ${amountB}`);
|
|
99
|
-
}
|
|
100
69
|
const vcId = channelId ?? generateChannelId(factory.factoryId, partyAId, partyBId);
|
|
101
70
|
const newSequence = factory.currentSequence + 1;
|
|
102
71
|
const newAllocations = {
|
|
@@ -105,8 +74,73 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
105
74
|
[partyBId]: allocB - amountB,
|
|
106
75
|
};
|
|
107
76
|
const newVcIds = [...factory.virtualChannels.map(vc => vc.channelId), vcId];
|
|
108
|
-
const commitment =
|
|
109
|
-
|
|
77
|
+
const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
78
|
+
return {
|
|
79
|
+
vcId,
|
|
80
|
+
parties,
|
|
81
|
+
amounts: { [partyAId]: amountA, [partyBId]: amountB },
|
|
82
|
+
newSequence,
|
|
83
|
+
newAllocations,
|
|
84
|
+
newVcIds,
|
|
85
|
+
commitment,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Produce this party's VC-open signature WITHOUT committing the lease
|
|
90
|
+
* (RFC-035 B3). The caller commits on `VC_FINALIZED` or burns on expiry.
|
|
91
|
+
*/
|
|
92
|
+
export async function signVirtualChannelOpen(factory, plan, bundle) {
|
|
93
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
94
|
+
if (!participant) {
|
|
95
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
96
|
+
}
|
|
97
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
98
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
99
|
+
purpose: 'factory-vc-open',
|
|
100
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
101
|
+
});
|
|
102
|
+
let sig;
|
|
103
|
+
try {
|
|
104
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
108
|
+
throw err;
|
|
109
|
+
}
|
|
110
|
+
const verifyFn = bundle.verify ?? verifyChannelSignature;
|
|
111
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
112
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
113
|
+
throw new Error(`Virtual-channel signature verification failed for party '${participant.partyId}'`);
|
|
114
|
+
}
|
|
115
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
116
|
+
}
|
|
117
|
+
export function verifyVirtualChannelOpenSignature(factory, commitment, partyId, signature, verify) {
|
|
118
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
119
|
+
if (!participant)
|
|
120
|
+
return false;
|
|
121
|
+
const verifyFn = verify ?? verifyChannelSignature;
|
|
122
|
+
try {
|
|
123
|
+
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Assemble N-of-N VC-open signatures into the updated factory + virtual channel.
|
|
131
|
+
*/
|
|
132
|
+
export function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
133
|
+
for (const p of factory.participants) {
|
|
134
|
+
const s = signatures[p.partyId];
|
|
135
|
+
if (!s)
|
|
136
|
+
throw new Error(`Missing virtual-channel signature for party '${p.partyId}' — open requires all N`);
|
|
137
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
138
|
+
throw new Error(`Virtual-channel signature verification failed for party '${p.partyId}'`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const [partyAId, partyBId] = plan.parties;
|
|
142
|
+
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
143
|
+
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
110
144
|
const now = Date.now();
|
|
111
145
|
const partyA = {
|
|
112
146
|
partyId: partyAId,
|
|
@@ -120,21 +154,19 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
120
154
|
addressIndex: partyBMeta.addressIndex,
|
|
121
155
|
settlementAddress: partyBMeta.settlementAddress,
|
|
122
156
|
};
|
|
123
|
-
// Construct the virtual OmniaChannel — no new on-chain TX.
|
|
124
|
-
// The channel shares the factory's UTXO; its channelType marks it virtual.
|
|
125
157
|
const channel = {
|
|
126
|
-
channelId: vcId,
|
|
158
|
+
channelId: plan.vcId,
|
|
127
159
|
fundingTxId: factory.fundingTxId ?? '',
|
|
128
160
|
fundingCoinId: factory.fundingCoinId ?? '',
|
|
129
161
|
fundingScript: factory.fundingScript,
|
|
130
|
-
programId:
|
|
131
|
-
programVersion:
|
|
162
|
+
programId: DefaultEltooPaymentProgram.id,
|
|
163
|
+
programVersion: DefaultEltooPaymentProgram.version,
|
|
132
164
|
fundingAddress: factory.fundingAddress,
|
|
133
165
|
tokenId: factory.tokenId,
|
|
134
166
|
tokenScale: factory.tokenScale,
|
|
135
|
-
totalValue:
|
|
167
|
+
totalValue: plan.amounts[partyAId] + plan.amounts[partyBId],
|
|
136
168
|
parties: [partyA, partyB],
|
|
137
|
-
balances: { [partyAId]:
|
|
169
|
+
balances: { [partyAId]: plan.amounts[partyAId], [partyBId]: plan.amounts[partyBId] },
|
|
138
170
|
pendingHTLCs: [],
|
|
139
171
|
currentSequence: 0,
|
|
140
172
|
latestState: null,
|
|
@@ -146,22 +178,41 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
146
178
|
updatedAt: now,
|
|
147
179
|
};
|
|
148
180
|
const logEntry = {
|
|
149
|
-
sequence: newSequence,
|
|
181
|
+
sequence: plan.newSequence,
|
|
150
182
|
timestamp: now,
|
|
151
183
|
event: 'virtual_open',
|
|
152
|
-
allocations: newAllocations,
|
|
153
|
-
virtualChannelIds: newVcIds,
|
|
184
|
+
allocations: plan.newAllocations,
|
|
185
|
+
virtualChannelIds: plan.newVcIds,
|
|
154
186
|
};
|
|
155
187
|
const updated = {
|
|
156
188
|
...factory,
|
|
157
|
-
allocations: newAllocations,
|
|
189
|
+
allocations: plan.newAllocations,
|
|
158
190
|
virtualChannels: [...factory.virtualChannels, channel],
|
|
159
|
-
currentSequence: newSequence,
|
|
191
|
+
currentSequence: plan.newSequence,
|
|
160
192
|
stateLog: [...factory.stateLog, logEntry],
|
|
161
193
|
};
|
|
162
|
-
|
|
194
|
+
enforceConservation(updated);
|
|
163
195
|
return { factory: updated, channel };
|
|
164
196
|
}
|
|
197
|
+
export async function openVirtualChannel(factory, parties, amounts, leaseProviders, channelId) {
|
|
198
|
+
for (const p of factory.participants) {
|
|
199
|
+
if (!leaseProviders[p.partyId]) {
|
|
200
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — openVirtualChannel requires all N`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const plan = buildVirtualChannelOpen(factory, parties, amounts, channelId);
|
|
204
|
+
const signatures = {};
|
|
205
|
+
for (const p of factory.participants) {
|
|
206
|
+
const sig = await signVirtualChannelOpen(factory, plan, leaseProviders[p.partyId]);
|
|
207
|
+
await leaseProviders[p.partyId].leaseProvider.commitKeyUse(sig.reservationId, `factory-vc-open-${factory.factoryId}`);
|
|
208
|
+
signatures[p.partyId] = sig;
|
|
209
|
+
}
|
|
210
|
+
return assembleVirtualChannelOpen(factory, plan, signatures, (sig, digest, pkd) => {
|
|
211
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === pkd);
|
|
212
|
+
const bundle = participant ? leaseProviders[participant.partyId] : undefined;
|
|
213
|
+
return (bundle?.verify ?? verifyChannelSignature)(sig, digest, pkd);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
165
216
|
// ─── closeVirtualChannel ─────────────────────────────────────────────────────
|
|
166
217
|
/**
|
|
167
218
|
* Close a virtual channel and return its final balances to factory allocations.
|
|
@@ -179,7 +230,7 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
179
230
|
* @param channel - The virtual `OmniaChannel` to close (with `latestState` set if updated).
|
|
180
231
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
181
232
|
*/
|
|
182
|
-
async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
233
|
+
export async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
183
234
|
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
184
235
|
if (!existing)
|
|
185
236
|
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
@@ -197,7 +248,7 @@ async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
|
197
248
|
const remainingVcIds = factory.virtualChannels
|
|
198
249
|
.filter(c => c.channelId !== channel.channelId)
|
|
199
250
|
.map(c => c.channelId);
|
|
200
|
-
const commitment =
|
|
251
|
+
const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, remainingVcIds);
|
|
201
252
|
await collectNofN(factory.factoryId, commitment, 'factory-vc-close', factory.participants, leaseProviders);
|
|
202
253
|
const logEntry = {
|
|
203
254
|
sequence: newSequence,
|
|
@@ -213,6 +264,6 @@ async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
|
213
264
|
currentSequence: newSequence,
|
|
214
265
|
stateLog: [...factory.stateLog, logEntry],
|
|
215
266
|
};
|
|
216
|
-
|
|
267
|
+
enforceConservation(updated);
|
|
217
268
|
return updated;
|
|
218
269
|
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@totemsdk/omnia-factory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Channel factory layer for Omnia — N-of-N MULTISIG funding, virtual channel management, and factory settlement",
|
|
5
|
-
"main": "dist/index.js",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
5
|
+
"main": "dist/cjs/index.js",
|
|
6
|
+
"types": "dist/cjs/index.d.ts",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": {
|
|
9
|
-
"
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
"import": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"require": {
|
|
14
|
+
"types": "./dist/cjs/index.d.ts",
|
|
15
|
+
"default": "./dist/cjs/index.js"
|
|
16
|
+
}
|
|
12
17
|
}
|
|
13
18
|
},
|
|
14
19
|
"files": [
|
|
@@ -19,10 +24,10 @@
|
|
|
19
24
|
"LICENSE"
|
|
20
25
|
],
|
|
21
26
|
"dependencies": {
|
|
27
|
+
"@totemsdk/omnia": "^2.0.1",
|
|
22
28
|
"@totemsdk/core": "^1.2.11",
|
|
23
|
-
"@totemsdk/omnia": "^1.0.2",
|
|
24
|
-
"@totemsdk/tx-builder": "^0.2.1",
|
|
25
29
|
"@totemsdk/wots-lease": "^1.0.1",
|
|
30
|
+
"@totemsdk/tx-builder": "^0.2.1",
|
|
26
31
|
"@totemsdk/txpow": "^1.0.2",
|
|
27
32
|
"@totemsdk/chain-provider": "^0.2.1",
|
|
28
33
|
"@totemsdk/storage": "^0.1.0"
|
|
@@ -67,8 +72,9 @@
|
|
|
67
72
|
"virtual-channel",
|
|
68
73
|
"multisig"
|
|
69
74
|
],
|
|
75
|
+
"type": "module",
|
|
70
76
|
"scripts": {
|
|
71
|
-
"build": "
|
|
77
|
+
"build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
|
|
72
78
|
"clean": "rm -rf dist rust/pkg rust/pkg-node rust/target",
|
|
73
79
|
"test": "jest",
|
|
74
80
|
"build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
|
|
Binary file
|
package/rust/pkg/package.json
CHANGED
|
Binary file
|