@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
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildFactorySettlement = buildFactorySettlement;
|
|
4
|
+
exports.signFactorySettlement = signFactorySettlement;
|
|
5
|
+
exports.verifyFactorySettlementSignature = verifyFactorySettlementSignature;
|
|
6
|
+
exports.assembleFactorySettlement = assembleFactorySettlement;
|
|
7
|
+
exports.closeFactory = closeFactory;
|
|
8
|
+
exports.buildDisputePayload = buildDisputePayload;
|
|
9
|
+
const wasm_1 = require("@totemsdk/core/wasm");
|
|
10
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
11
|
+
const txpow_1 = require("@totemsdk/txpow");
|
|
12
|
+
/**
|
|
13
|
+
* Build the cooperative settlement TX + digest (no signing). Exported so peers
|
|
14
|
+
* can independently rebuild and bind a proposal (RFC-035 B3).
|
|
15
|
+
*/
|
|
16
|
+
function buildFactorySettlement(factory) {
|
|
17
|
+
if (factory.status !== 'active') {
|
|
18
|
+
throw new Error(`buildFactorySettlement requires factory status 'active', got '${factory.status}'`);
|
|
19
|
+
}
|
|
20
|
+
if (!factory.fundingCoinId) {
|
|
21
|
+
throw new Error('buildFactorySettlement requires factory.fundingCoinId to be set. ' +
|
|
22
|
+
'Create the factory with fundingCoinIds + chainProvider so the funding TX is mined first.');
|
|
23
|
+
}
|
|
24
|
+
if (factory.virtualChannels.length > 0) {
|
|
25
|
+
const ids = factory.virtualChannels.map(vc => vc.channelId).join(', ');
|
|
26
|
+
throw new Error(`closeFactory requires all virtual channels to be closed first. Open channels: ${ids}`);
|
|
27
|
+
}
|
|
28
|
+
const outputs = [];
|
|
29
|
+
for (const participant of factory.participants) {
|
|
30
|
+
const amount = factory.allocations[participant.partyId] ?? 0n;
|
|
31
|
+
if (amount <= 0n)
|
|
32
|
+
continue;
|
|
33
|
+
outputs.push({
|
|
34
|
+
address: participant.settlementAddress ?? participant.publicKeyDigest,
|
|
35
|
+
amount: (0, omnia_1.toRawMinima)(amount, factory.tokenScale),
|
|
36
|
+
tokenId: factory.tokenId,
|
|
37
|
+
storeState: false,
|
|
38
|
+
stateVariables: [],
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const settlementDraft = {
|
|
42
|
+
type: 'settlement',
|
|
43
|
+
inputs: [{
|
|
44
|
+
coinId: factory.fundingCoinId,
|
|
45
|
+
address: factory.fundingAddress,
|
|
46
|
+
amount: (0, omnia_1.toRawMinima)(factory.totalValue, factory.tokenScale),
|
|
47
|
+
tokenId: factory.tokenId,
|
|
48
|
+
scriptHex: factory.fundingScript,
|
|
49
|
+
}],
|
|
50
|
+
outputs,
|
|
51
|
+
storeState: true,
|
|
52
|
+
stateVariables: [{ port: 100, value: true, type: 'bool' }],
|
|
53
|
+
};
|
|
54
|
+
return {
|
|
55
|
+
settlementDraft,
|
|
56
|
+
settlementTxHex: (0, omnia_1.serializeTxDraft)(settlementDraft),
|
|
57
|
+
txDigest: (0, omnia_1.computeTxDraftDigest)(settlementDraft),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Produce this party's settlement signature WITHOUT committing the lease
|
|
62
|
+
* (RFC-035 B3). The caller commits on `FACTORY_CLOSE_FINALIZED` or burns on expiry.
|
|
63
|
+
*/
|
|
64
|
+
async function signFactorySettlement(factory, draft, bundle) {
|
|
65
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
66
|
+
if (!participant) {
|
|
67
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
68
|
+
}
|
|
69
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
70
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
71
|
+
purpose: 'factory-settlement',
|
|
72
|
+
payloadHash: Buffer.from(draft.txDigest).toString('hex'),
|
|
73
|
+
});
|
|
74
|
+
let sig;
|
|
75
|
+
try {
|
|
76
|
+
sig = await bundle.signer.sign(draft.txDigest, reservation.indices);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
83
|
+
if (!verifyFn(sig, draft.txDigest, participant.publicKeyDigest)) {
|
|
84
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
85
|
+
throw new Error(`Settlement signature verification failed for party '${participant.partyId}'`);
|
|
86
|
+
}
|
|
87
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
88
|
+
}
|
|
89
|
+
/** Verify a remote settlement signature against a factory participant. */
|
|
90
|
+
function verifyFactorySettlementSignature(factory, txDigest, partyId, signature, verify) {
|
|
91
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
92
|
+
if (!participant)
|
|
93
|
+
return false;
|
|
94
|
+
const verifyFn = verify ?? omnia_1.verifyChannelSignature;
|
|
95
|
+
try {
|
|
96
|
+
return verifyFn(signature, txDigest, participant.publicKeyDigest);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Assemble N-of-N settlement signatures into the MULTISIG witness + payload, and
|
|
104
|
+
* (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
|
|
105
|
+
*/
|
|
106
|
+
async function assembleFactorySettlement(factory, draft, signatures, chainProvider, options) {
|
|
107
|
+
const witnessParts = [];
|
|
108
|
+
for (const p of factory.participants) {
|
|
109
|
+
const s = signatures[p.partyId];
|
|
110
|
+
if (!s)
|
|
111
|
+
throw new Error(`Missing settlement signature for party '${p.partyId}' — close requires all N`);
|
|
112
|
+
if (!verifyFactorySettlementSignature(factory, draft.txDigest, p.partyId, s.signature, options?.verify)) {
|
|
113
|
+
throw new Error(`Settlement signature verification failed for party '${p.partyId}'`);
|
|
114
|
+
}
|
|
115
|
+
witnessParts.push(s.signature);
|
|
116
|
+
}
|
|
117
|
+
const witnessBytes = witnessParts.reduce((a, b) => (0, wasm_1.concatBytes)(a, b));
|
|
118
|
+
const payload = {
|
|
119
|
+
factoryId: factory.factoryId,
|
|
120
|
+
sequence: factory.currentSequence,
|
|
121
|
+
settlementTxHex: draft.settlementTxHex,
|
|
122
|
+
finalAllocations: { ...factory.allocations },
|
|
123
|
+
};
|
|
124
|
+
if (chainProvider) {
|
|
125
|
+
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(draft.settlementDraft);
|
|
126
|
+
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes);
|
|
127
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txpow_1.TX_POW_MIN_DIFFICULTY);
|
|
128
|
+
const fullTxPoW = (0, wasm_1.concatBytes)((0, wasm_1.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
129
|
+
await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
130
|
+
payload.txpowId = Buffer.from(mined.txpowId).toString('hex');
|
|
131
|
+
}
|
|
132
|
+
return payload;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Cooperative N-of-N factory close (central/local path).
|
|
136
|
+
*
|
|
137
|
+
* Builds the settlement TX, collects all N signatures (each committing its own
|
|
138
|
+
* lease via the full WOTS cycle), assembles the witness, and — when a
|
|
139
|
+
* `chainProvider` is supplied — mines + broadcasts the settlement TxPoW.
|
|
140
|
+
*
|
|
141
|
+
* @param factory - Active factory with no open virtual channels.
|
|
142
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
143
|
+
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
144
|
+
*/
|
|
145
|
+
async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
146
|
+
for (const p of factory.participants) {
|
|
147
|
+
if (!leaseProviders[p.partyId]) {
|
|
148
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const draft = buildFactorySettlement(factory);
|
|
152
|
+
const signatures = {};
|
|
153
|
+
for (const p of factory.participants) {
|
|
154
|
+
const sig = await signFactorySettlement(factory, draft, leaseProviders[p.partyId]);
|
|
155
|
+
await leaseProviders[p.partyId].leaseProvider.commitKeyUse(sig.reservationId, `factory-settlement-${factory.factoryId}`);
|
|
156
|
+
signatures[p.partyId] = sig;
|
|
157
|
+
}
|
|
158
|
+
return assembleFactorySettlement(factory, draft, signatures, chainProvider, {
|
|
159
|
+
verify: (sig, digest, pkd) => {
|
|
160
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === pkd);
|
|
161
|
+
const bundle = participant ? leaseProviders[participant.partyId] : undefined;
|
|
162
|
+
const fn = bundle?.verify ?? omnia_1.verifyChannelSignature;
|
|
163
|
+
return fn(sig, digest, pkd);
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
// ─── buildDisputePayload ──────────────────────────────────────────────────────
|
|
168
|
+
/**
|
|
169
|
+
* Build a unilateral factory close (dispute) payload.
|
|
170
|
+
*
|
|
171
|
+
* Includes the full `stateLog` (with monotonically increasing `sequence` entries)
|
|
172
|
+
* for on-chain or arbitration verification. Virtual channels still open at
|
|
173
|
+
* dispute time are included by ID so the dispute resolver can adjudicate their
|
|
174
|
+
* balances independently.
|
|
175
|
+
*/
|
|
176
|
+
function buildDisputePayload(factory, evidence) {
|
|
177
|
+
const logEntry = {
|
|
178
|
+
sequence: factory.currentSequence,
|
|
179
|
+
timestamp: Date.now(),
|
|
180
|
+
event: 'dispute',
|
|
181
|
+
allocations: { ...factory.allocations },
|
|
182
|
+
virtualChannelIds: factory.virtualChannels.map(vc => vc.channelId),
|
|
183
|
+
};
|
|
184
|
+
return {
|
|
185
|
+
factoryId: factory.factoryId,
|
|
186
|
+
latestSequence: factory.currentSequence,
|
|
187
|
+
fundingTxId: factory.fundingTxId ?? '',
|
|
188
|
+
allocations: { ...factory.allocations },
|
|
189
|
+
virtualChannelIds: factory.virtualChannels.map(vc => vc.channelId),
|
|
190
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
191
|
+
evidence,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { OmniaChannel } from '@totemsdk/omnia';
|
|
2
|
+
import type { ChannelSigner } from '@totemsdk/omnia';
|
|
3
|
+
import type { SigningIndices } from '@totemsdk/wots-lease';
|
|
4
|
+
export type { OmniaChannel };
|
|
5
|
+
export type FactoryStatus = 'opening' | 'active' | 'closing' | 'closed';
|
|
6
|
+
export interface FactoryParticipant {
|
|
7
|
+
partyId: string;
|
|
8
|
+
publicKeyDigest: string;
|
|
9
|
+
addressIndex: number;
|
|
10
|
+
/** Amount this participant contributes to the factory. */
|
|
11
|
+
contributionAmount: bigint;
|
|
12
|
+
/**
|
|
13
|
+
* UTXO coin ID this participant contributes to the factory funding TX.
|
|
14
|
+
* When ALL participants supply a fundingCoinId and a chainProvider is given
|
|
15
|
+
* to `createFactory`, the N-input → 1-output funding TX is built, mined,
|
|
16
|
+
* and broadcast on-chain. Omit for in-memory / test-only factories.
|
|
17
|
+
*/
|
|
18
|
+
fundingCoinId?: string;
|
|
19
|
+
/** Address to receive funds on cooperative settlement. Falls back to publicKeyDigest. */
|
|
20
|
+
settlementAddress?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Minimal lease operations required by the factory signing cycle.
|
|
24
|
+
*
|
|
25
|
+
* This is a structural subset of `WotsLeaseProvider` from `@totemsdk/wots-lease`.
|
|
26
|
+
* Any real `WotsLeaseProvider` satisfies this interface. In tests, only these
|
|
27
|
+
* three methods need to be mocked — no other watermark or sync methods required.
|
|
28
|
+
*/
|
|
29
|
+
export interface FactoryLeaseOps {
|
|
30
|
+
reserveKeyUse(params: {
|
|
31
|
+
treeId: string;
|
|
32
|
+
purpose?: string;
|
|
33
|
+
payloadHash?: string;
|
|
34
|
+
ttlMs?: number;
|
|
35
|
+
}): Promise<{
|
|
36
|
+
reservationId: string;
|
|
37
|
+
indices: SigningIndices;
|
|
38
|
+
expiresAt: number;
|
|
39
|
+
}>;
|
|
40
|
+
commitKeyUse(reservationId: string, txId: string): Promise<void>;
|
|
41
|
+
burnReservation(reservationId: string, reason: string): Promise<void>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Bundle of `FactoryLeaseOps` + `ChannelSigner` for one factory participant.
|
|
45
|
+
*
|
|
46
|
+
* In production, wire a real `WotsLeaseProvider` (which satisfies `FactoryLeaseOps`
|
|
47
|
+
* structurally) and a `ChannelSigner` backed by the participant's WOTS tree key.
|
|
48
|
+
* In tests, provide mock implementations of all three methods on `leaseProvider`.
|
|
49
|
+
*
|
|
50
|
+
* The optional `verify` callback overrides the default `wotsVerifyDigest` from
|
|
51
|
+
* `@totemsdk/core`, allowing test code to inject a no-op verifier without
|
|
52
|
+
* requiring real WOTS key material.
|
|
53
|
+
*/
|
|
54
|
+
export interface WotsLeaseBundle {
|
|
55
|
+
leaseProvider: FactoryLeaseOps;
|
|
56
|
+
signer: ChannelSigner;
|
|
57
|
+
/**
|
|
58
|
+
* Optional verify override. When absent, the implementation falls back to
|
|
59
|
+
* `wotsVerifyDigest(sig, commitment, fromHex(pkd))` from `@totemsdk/core`.
|
|
60
|
+
*
|
|
61
|
+
* Signature: `(sig, commitment, pkd_hex) => boolean`
|
|
62
|
+
*/
|
|
63
|
+
verify?: (sig: Uint8Array, commitment: Uint8Array, pkdHex: string) => boolean;
|
|
64
|
+
}
|
|
65
|
+
export type FactorySignature = Uint8Array;
|
|
66
|
+
export interface FactoryLogEntry {
|
|
67
|
+
sequence: number;
|
|
68
|
+
timestamp: number;
|
|
69
|
+
event: 'create' | 'accept' | 'reallocate' | 'virtual_open' | 'virtual_close' | 'dispute';
|
|
70
|
+
allocations: Record<string, bigint>;
|
|
71
|
+
virtualChannelIds: string[];
|
|
72
|
+
}
|
|
73
|
+
export interface ChannelFactory {
|
|
74
|
+
factoryId: string;
|
|
75
|
+
participants: FactoryParticipant[];
|
|
76
|
+
totalValue: bigint;
|
|
77
|
+
tokenId: string;
|
|
78
|
+
/**
|
|
79
|
+
* Token scale exponent, matching Minima's `Token.mTokenScale`:
|
|
80
|
+
* `tokenAmount = minimaRawAmount × 10^scale`. Native Minima (tokenId `0x00`)
|
|
81
|
+
* has scale 0. Coloured coins use `MINIMA_MAX_DECIMAL_PLACES − scale`
|
|
82
|
+
* (44 − scale) decimal places. All factory amounts are held in scaled token
|
|
83
|
+
* units; TX builders convert to raw Minima via `toRawMinima()`.
|
|
84
|
+
*/
|
|
85
|
+
tokenScale: number;
|
|
86
|
+
/** Current committed allocations: sum must equal `totalValue − sum(vc.totalValue)`. */
|
|
87
|
+
allocations: Record<string, bigint>;
|
|
88
|
+
/** Currently open virtual channels backed by this factory's shared UTXO. */
|
|
89
|
+
virtualChannels: OmniaChannel[];
|
|
90
|
+
/** Monotonically increasing. Incremented on every committed state transition. */
|
|
91
|
+
currentSequence: number;
|
|
92
|
+
status: FactoryStatus;
|
|
93
|
+
stateLog: FactoryLogEntry[];
|
|
94
|
+
/** N-of-N MULTISIG KISSVM script for the factory's on-chain UTXO. */
|
|
95
|
+
fundingScript: string;
|
|
96
|
+
/** Script address (SHA3-256 of normalised script). */
|
|
97
|
+
fundingAddress: string;
|
|
98
|
+
/** TxPoW ID of the factory funding TX (hex) — set after createFactory mines the TX. */
|
|
99
|
+
fundingTxId?: string;
|
|
100
|
+
/** CoinID of the factory's shared UTXO — required for settlement and dispute. */
|
|
101
|
+
fundingCoinId?: string;
|
|
102
|
+
/**
|
|
103
|
+
* Hex-encoded commitment (TX draft digest or state hash) that all participants
|
|
104
|
+
* must sign during the current opening or signing round.
|
|
105
|
+
* Set by `createFactory`; cleared when the factory becomes 'active'.
|
|
106
|
+
*/
|
|
107
|
+
pendingCommitment?: string;
|
|
108
|
+
/**
|
|
109
|
+
* Partial signatures collected so far for the pending commitment.
|
|
110
|
+
* Keyed by `partyId`. Cleared when all N parties have signed.
|
|
111
|
+
*/
|
|
112
|
+
pendingSignatures: Record<string, FactorySignature>;
|
|
113
|
+
}
|
|
114
|
+
export interface FactorySettlementPayload {
|
|
115
|
+
factoryId: string;
|
|
116
|
+
sequence: number;
|
|
117
|
+
/** Serialized settlement OmniaTxDraft (hex) — built by `serializeTxDraft` from @totemsdk/omnia. */
|
|
118
|
+
settlementTxHex: string;
|
|
119
|
+
finalAllocations: Record<string, bigint>;
|
|
120
|
+
/** SHA3-256 TxPoW ID (hex) — populated when closeFactory is given a chainProvider. */
|
|
121
|
+
txpowId?: string;
|
|
122
|
+
}
|
|
123
|
+
export interface FactoryDisputePayload {
|
|
124
|
+
factoryId: string;
|
|
125
|
+
latestSequence: number;
|
|
126
|
+
fundingTxId: string;
|
|
127
|
+
allocations: Record<string, bigint>;
|
|
128
|
+
virtualChannelIds: string[];
|
|
129
|
+
stateLog: FactoryLogEntry[];
|
|
130
|
+
evidence: string;
|
|
131
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type OmniaChannel } from '@totemsdk/omnia';
|
|
2
|
+
import type { ChannelFactory, WotsLeaseBundle } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Open a virtual channel between two factory participants.
|
|
5
|
+
*
|
|
6
|
+
* ALL N factory participants must agree (N-of-N WOTS signature collection)
|
|
7
|
+
* before the virtual channel is committed and allocations deducted. This ensures
|
|
8
|
+
* the shared factory UTXO's off-chain state is consistent and dispute-provable.
|
|
9
|
+
*
|
|
10
|
+
* The commitment is bound to `currentSequence + 1` — the post-commit sequence —
|
|
11
|
+
* preventing replay of the same openVC commitment against a future factory state.
|
|
12
|
+
*
|
|
13
|
+
* The returned `OmniaChannel` has `channelType: 'virtual'` and `factoryRef` set.
|
|
14
|
+
* Its `fundingTxId`/`fundingCoinId` reference the factory's shared UTXO.
|
|
15
|
+
* It is ready for off-chain state updates via `@totemsdk/omnia` primitives
|
|
16
|
+
* (`updateState`, `addHTLC`, `signState`, etc.).
|
|
17
|
+
*
|
|
18
|
+
* @param factory - Active factory.
|
|
19
|
+
* @param parties - Tuple `[partyAId, partyBId]` of the two channel parties.
|
|
20
|
+
* @param amounts - Capacity per party: `Record<partyId, bigint>`.
|
|
21
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
22
|
+
* @param channelId - Optional explicit channel ID; auto-generated if omitted.
|
|
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
|
+
};
|
|
55
|
+
export declare function openVirtualChannel(factory: ChannelFactory, parties: [string, string], amounts: Record<string, bigint>, leaseProviders: Record<string, WotsLeaseBundle>, channelId?: string): Promise<{
|
|
56
|
+
factory: ChannelFactory;
|
|
57
|
+
channel: OmniaChannel;
|
|
58
|
+
}>;
|
|
59
|
+
/**
|
|
60
|
+
* Close a virtual channel and return its final balances to factory allocations.
|
|
61
|
+
*
|
|
62
|
+
* ALL N factory participants must agree (N-of-N WOTS signature collection).
|
|
63
|
+
* The commitment is bound to `currentSequence + 1`.
|
|
64
|
+
*
|
|
65
|
+
* Final balances are taken from `channel.latestState.balances` (the last agreed
|
|
66
|
+
* off-chain state from `@totemsdk/omnia`'s state machine) or fall back to
|
|
67
|
+
* `channel.balances` (the initial opening split) if no state updates have occurred.
|
|
68
|
+
*
|
|
69
|
+
* No on-chain TX is needed: the factory's shared UTXO remains intact.
|
|
70
|
+
*
|
|
71
|
+
* @param factory - Active factory.
|
|
72
|
+
* @param channel - The virtual `OmniaChannel` to close (with `latestState` set if updated).
|
|
73
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
74
|
+
*/
|
|
75
|
+
export declare function closeVirtualChannel(factory: ChannelFactory, channel: OmniaChannel, leaseProviders: Record<string, WotsLeaseBundle>): Promise<ChannelFactory>;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildVirtualChannelOpen = buildVirtualChannelOpen;
|
|
4
|
+
exports.signVirtualChannelOpen = signVirtualChannelOpen;
|
|
5
|
+
exports.verifyVirtualChannelOpenSignature = verifyVirtualChannelOpenSignature;
|
|
6
|
+
exports.assembleVirtualChannelOpen = assembleVirtualChannelOpen;
|
|
7
|
+
exports.openVirtualChannel = openVirtualChannel;
|
|
8
|
+
exports.closeVirtualChannel = closeVirtualChannel;
|
|
9
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
10
|
+
const factory_js_1 = require("./factory.js");
|
|
11
|
+
const commitment_js_1 = require("./commitment.js");
|
|
12
|
+
// ─── Internal helpers ─────────────────────────────────────────────────────────
|
|
13
|
+
function generateChannelId(factoryId, partyAId, partyBId) {
|
|
14
|
+
const nonce = Array.from(globalThis.crypto?.getRandomValues?.(new Uint8Array(8)) ?? new Uint8Array(8)).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
15
|
+
return `vc-${factoryId.slice(0, 8)}-${partyAId}-${partyBId}-${nonce}`;
|
|
16
|
+
}
|
|
17
|
+
/** Run the WOTS lease cycle for one party and verify the produced signature. */
|
|
18
|
+
async function leaseSign(factoryId, commitment, purpose, partyId, publicKeyDigest, bundle) {
|
|
19
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
20
|
+
treeId: `omnia-factory-${factoryId}`,
|
|
21
|
+
purpose,
|
|
22
|
+
payloadHash: Buffer.from(commitment).toString('hex'),
|
|
23
|
+
});
|
|
24
|
+
let sig;
|
|
25
|
+
try {
|
|
26
|
+
sig = await bundle.signer.sign(commitment, reservation.indices);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
30
|
+
throw err;
|
|
31
|
+
}
|
|
32
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
33
|
+
if (!verifyFn(sig, commitment, publicKeyDigest)) {
|
|
34
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
35
|
+
throw new Error(`Signature verification failed for party '${partyId}' — aborting virtual channel operation`);
|
|
36
|
+
}
|
|
37
|
+
await bundle.leaseProvider.commitKeyUse(reservation.reservationId, `factory-vc-${factoryId}`);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Collect N-of-N signatures from all factory participants for a state commitment.
|
|
41
|
+
* Commitment is bound to `newSequence` (the post-commit sequence) for replay resistance.
|
|
42
|
+
*/
|
|
43
|
+
async function collectNofN(factoryId, commitment, purpose, participants, leaseProviders) {
|
|
44
|
+
for (const p of participants) {
|
|
45
|
+
if (!leaseProviders[p.partyId]) {
|
|
46
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — all N participants must provide one`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for (const p of participants) {
|
|
50
|
+
await leaseSign(factoryId, commitment, purpose, p.partyId, p.publicKeyDigest, leaseProviders[p.partyId]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Validate + build the VC-open plan (no signing). Exported so peers can bind. */
|
|
54
|
+
function buildVirtualChannelOpen(factory, parties, amounts, channelId) {
|
|
55
|
+
if (factory.status !== 'active') {
|
|
56
|
+
throw new Error(`openVirtualChannel requires factory status 'active', got '${factory.status}'`);
|
|
57
|
+
}
|
|
58
|
+
const [partyAId, partyBId] = parties;
|
|
59
|
+
const amountA = amounts[partyAId] ?? 0n;
|
|
60
|
+
const amountB = amounts[partyBId] ?? 0n;
|
|
61
|
+
if (amountA < 0n || amountB < 0n)
|
|
62
|
+
throw new Error('Virtual channel amounts must be non-negative');
|
|
63
|
+
if (amountA + amountB === 0n)
|
|
64
|
+
throw new Error('Virtual channel must have positive total value');
|
|
65
|
+
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
66
|
+
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
67
|
+
if (!partyAMeta)
|
|
68
|
+
throw new Error(`Party '${partyAId}' not found in factory`);
|
|
69
|
+
if (!partyBMeta)
|
|
70
|
+
throw new Error(`Party '${partyBId}' not found in factory`);
|
|
71
|
+
const allocA = factory.allocations[partyAId] ?? 0n;
|
|
72
|
+
const allocB = factory.allocations[partyBId] ?? 0n;
|
|
73
|
+
if (allocA < amountA)
|
|
74
|
+
throw new Error(`Party '${partyAId}' has insufficient allocation: ${allocA} < ${amountA}`);
|
|
75
|
+
if (allocB < amountB)
|
|
76
|
+
throw new Error(`Party '${partyBId}' has insufficient allocation: ${allocB} < ${amountB}`);
|
|
77
|
+
const vcId = channelId ?? generateChannelId(factory.factoryId, partyAId, partyBId);
|
|
78
|
+
const newSequence = factory.currentSequence + 1;
|
|
79
|
+
const newAllocations = {
|
|
80
|
+
...factory.allocations,
|
|
81
|
+
[partyAId]: allocA - amountA,
|
|
82
|
+
[partyBId]: allocB - amountB,
|
|
83
|
+
};
|
|
84
|
+
const newVcIds = [...factory.virtualChannels.map(vc => vc.channelId), vcId];
|
|
85
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
86
|
+
return {
|
|
87
|
+
vcId,
|
|
88
|
+
parties,
|
|
89
|
+
amounts: { [partyAId]: amountA, [partyBId]: amountB },
|
|
90
|
+
newSequence,
|
|
91
|
+
newAllocations,
|
|
92
|
+
newVcIds,
|
|
93
|
+
commitment,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Produce this party's VC-open signature WITHOUT committing the lease
|
|
98
|
+
* (RFC-035 B3). The caller commits on `VC_FINALIZED` or burns on expiry.
|
|
99
|
+
*/
|
|
100
|
+
async function signVirtualChannelOpen(factory, plan, bundle) {
|
|
101
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
102
|
+
if (!participant) {
|
|
103
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
104
|
+
}
|
|
105
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
106
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
107
|
+
purpose: 'factory-vc-open',
|
|
108
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
109
|
+
});
|
|
110
|
+
let sig;
|
|
111
|
+
try {
|
|
112
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
119
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
120
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
121
|
+
throw new Error(`Virtual-channel signature verification failed for party '${participant.partyId}'`);
|
|
122
|
+
}
|
|
123
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
124
|
+
}
|
|
125
|
+
function verifyVirtualChannelOpenSignature(factory, commitment, partyId, signature, verify) {
|
|
126
|
+
const participant = factory.participants.find(p => p.partyId === partyId);
|
|
127
|
+
if (!participant)
|
|
128
|
+
return false;
|
|
129
|
+
const verifyFn = verify ?? omnia_1.verifyChannelSignature;
|
|
130
|
+
try {
|
|
131
|
+
return verifyFn(signature, commitment, participant.publicKeyDigest);
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Assemble N-of-N VC-open signatures into the updated factory + virtual channel.
|
|
139
|
+
*/
|
|
140
|
+
function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
|
|
141
|
+
for (const p of factory.participants) {
|
|
142
|
+
const s = signatures[p.partyId];
|
|
143
|
+
if (!s)
|
|
144
|
+
throw new Error(`Missing virtual-channel signature for party '${p.partyId}' — open requires all N`);
|
|
145
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
146
|
+
throw new Error(`Virtual-channel signature verification failed for party '${p.partyId}'`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const [partyAId, partyBId] = plan.parties;
|
|
150
|
+
const partyAMeta = factory.participants.find(p => p.partyId === partyAId);
|
|
151
|
+
const partyBMeta = factory.participants.find(p => p.partyId === partyBId);
|
|
152
|
+
const now = Date.now();
|
|
153
|
+
const partyA = {
|
|
154
|
+
partyId: partyAId,
|
|
155
|
+
publicKeyDigest: partyAMeta.publicKeyDigest,
|
|
156
|
+
addressIndex: partyAMeta.addressIndex,
|
|
157
|
+
settlementAddress: partyAMeta.settlementAddress,
|
|
158
|
+
};
|
|
159
|
+
const partyB = {
|
|
160
|
+
partyId: partyBId,
|
|
161
|
+
publicKeyDigest: partyBMeta.publicKeyDigest,
|
|
162
|
+
addressIndex: partyBMeta.addressIndex,
|
|
163
|
+
settlementAddress: partyBMeta.settlementAddress,
|
|
164
|
+
};
|
|
165
|
+
const channel = {
|
|
166
|
+
channelId: plan.vcId,
|
|
167
|
+
fundingTxId: factory.fundingTxId ?? '',
|
|
168
|
+
fundingCoinId: factory.fundingCoinId ?? '',
|
|
169
|
+
fundingScript: factory.fundingScript,
|
|
170
|
+
programId: omnia_1.DefaultEltooPaymentProgram.id,
|
|
171
|
+
programVersion: omnia_1.DefaultEltooPaymentProgram.version,
|
|
172
|
+
fundingAddress: factory.fundingAddress,
|
|
173
|
+
tokenId: factory.tokenId,
|
|
174
|
+
tokenScale: factory.tokenScale,
|
|
175
|
+
totalValue: plan.amounts[partyAId] + plan.amounts[partyBId],
|
|
176
|
+
parties: [partyA, partyB],
|
|
177
|
+
balances: { [partyAId]: plan.amounts[partyAId], [partyBId]: plan.amounts[partyBId] },
|
|
178
|
+
pendingHTLCs: [],
|
|
179
|
+
currentSequence: 0,
|
|
180
|
+
latestState: null,
|
|
181
|
+
stateLog: [],
|
|
182
|
+
status: 'active',
|
|
183
|
+
channelType: 'virtual',
|
|
184
|
+
factoryRef: factory.factoryId,
|
|
185
|
+
createdAt: now,
|
|
186
|
+
updatedAt: now,
|
|
187
|
+
};
|
|
188
|
+
const logEntry = {
|
|
189
|
+
sequence: plan.newSequence,
|
|
190
|
+
timestamp: now,
|
|
191
|
+
event: 'virtual_open',
|
|
192
|
+
allocations: plan.newAllocations,
|
|
193
|
+
virtualChannelIds: plan.newVcIds,
|
|
194
|
+
};
|
|
195
|
+
const updated = {
|
|
196
|
+
...factory,
|
|
197
|
+
allocations: plan.newAllocations,
|
|
198
|
+
virtualChannels: [...factory.virtualChannels, channel],
|
|
199
|
+
currentSequence: plan.newSequence,
|
|
200
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
201
|
+
};
|
|
202
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
203
|
+
return { factory: updated, channel };
|
|
204
|
+
}
|
|
205
|
+
async function openVirtualChannel(factory, parties, amounts, leaseProviders, channelId) {
|
|
206
|
+
for (const p of factory.participants) {
|
|
207
|
+
if (!leaseProviders[p.partyId]) {
|
|
208
|
+
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — openVirtualChannel requires all N`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const plan = buildVirtualChannelOpen(factory, parties, amounts, channelId);
|
|
212
|
+
const signatures = {};
|
|
213
|
+
for (const p of factory.participants) {
|
|
214
|
+
const sig = await signVirtualChannelOpen(factory, plan, leaseProviders[p.partyId]);
|
|
215
|
+
await leaseProviders[p.partyId].leaseProvider.commitKeyUse(sig.reservationId, `factory-vc-open-${factory.factoryId}`);
|
|
216
|
+
signatures[p.partyId] = sig;
|
|
217
|
+
}
|
|
218
|
+
return assembleVirtualChannelOpen(factory, plan, signatures, (sig, digest, pkd) => {
|
|
219
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === pkd);
|
|
220
|
+
const bundle = participant ? leaseProviders[participant.partyId] : undefined;
|
|
221
|
+
return (bundle?.verify ?? omnia_1.verifyChannelSignature)(sig, digest, pkd);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
// ─── closeVirtualChannel ─────────────────────────────────────────────────────
|
|
225
|
+
/**
|
|
226
|
+
* Close a virtual channel and return its final balances to factory allocations.
|
|
227
|
+
*
|
|
228
|
+
* ALL N factory participants must agree (N-of-N WOTS signature collection).
|
|
229
|
+
* The commitment is bound to `currentSequence + 1`.
|
|
230
|
+
*
|
|
231
|
+
* Final balances are taken from `channel.latestState.balances` (the last agreed
|
|
232
|
+
* off-chain state from `@totemsdk/omnia`'s state machine) or fall back to
|
|
233
|
+
* `channel.balances` (the initial opening split) if no state updates have occurred.
|
|
234
|
+
*
|
|
235
|
+
* No on-chain TX is needed: the factory's shared UTXO remains intact.
|
|
236
|
+
*
|
|
237
|
+
* @param factory - Active factory.
|
|
238
|
+
* @param channel - The virtual `OmniaChannel` to close (with `latestState` set if updated).
|
|
239
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
240
|
+
*/
|
|
241
|
+
async function closeVirtualChannel(factory, channel, leaseProviders) {
|
|
242
|
+
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
243
|
+
if (!existing)
|
|
244
|
+
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
245
|
+
// Use latest agreed state's balances; fall back to initial balances.
|
|
246
|
+
const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
|
|
247
|
+
const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
|
|
248
|
+
if (finalSum !== channel.totalValue) {
|
|
249
|
+
throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
|
|
250
|
+
}
|
|
251
|
+
const newSequence = factory.currentSequence + 1;
|
|
252
|
+
const newAllocations = { ...factory.allocations };
|
|
253
|
+
for (const [partyId, amount] of Object.entries(finalAllocations)) {
|
|
254
|
+
newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
|
|
255
|
+
}
|
|
256
|
+
const remainingVcIds = factory.virtualChannels
|
|
257
|
+
.filter(c => c.channelId !== channel.channelId)
|
|
258
|
+
.map(c => c.channelId);
|
|
259
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, remainingVcIds);
|
|
260
|
+
await collectNofN(factory.factoryId, commitment, 'factory-vc-close', factory.participants, leaseProviders);
|
|
261
|
+
const logEntry = {
|
|
262
|
+
sequence: newSequence,
|
|
263
|
+
timestamp: Date.now(),
|
|
264
|
+
event: 'virtual_close',
|
|
265
|
+
allocations: newAllocations,
|
|
266
|
+
virtualChannelIds: remainingVcIds,
|
|
267
|
+
};
|
|
268
|
+
const updated = {
|
|
269
|
+
...factory,
|
|
270
|
+
allocations: newAllocations,
|
|
271
|
+
virtualChannels: factory.virtualChannels.filter(c => c.channelId !== channel.channelId),
|
|
272
|
+
currentSequence: newSequence,
|
|
273
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
274
|
+
};
|
|
275
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
276
|
+
return updated;
|
|
277
|
+
}
|