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