@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,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compute the canonical 32-byte state commitment for N-of-N factory signing.
|
|
3
|
+
*
|
|
4
|
+
* Covers:
|
|
5
|
+
* - factoryId (factory context isolation)
|
|
6
|
+
* - sequence (monotonicity; prevents replay of old state)
|
|
7
|
+
* - pendingAllocations (the proposed allocation split being signed)
|
|
8
|
+
* - virtualChannelIds (list of currently open VCs; prevents forgery of VC state)
|
|
9
|
+
*
|
|
10
|
+
* All fields are sorted lexicographically for determinism regardless of the
|
|
11
|
+
* order in which keys appear in the caller's objects.
|
|
12
|
+
*
|
|
13
|
+
* This commitment is what every party signs via `FactorySignerOps.sign`, and
|
|
14
|
+
* what `FactorySignerOps.verify` checks against each stored signature.
|
|
15
|
+
*/
|
|
16
|
+
export declare function computeFactoryStateCommitment(factoryId: string, sequence: number, pendingAllocations: Record<string, bigint>, virtualChannelIds: string[]): Uint8Array;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.computeFactoryStateCommitment = computeFactoryStateCommitment;
|
|
4
|
+
const wasm_1 = require("@totemsdk/core/wasm");
|
|
5
|
+
/**
|
|
6
|
+
* Compute the canonical 32-byte state commitment for N-of-N factory signing.
|
|
7
|
+
*
|
|
8
|
+
* Covers:
|
|
9
|
+
* - factoryId (factory context isolation)
|
|
10
|
+
* - sequence (monotonicity; prevents replay of old state)
|
|
11
|
+
* - pendingAllocations (the proposed allocation split being signed)
|
|
12
|
+
* - virtualChannelIds (list of currently open VCs; prevents forgery of VC state)
|
|
13
|
+
*
|
|
14
|
+
* All fields are sorted lexicographically for determinism regardless of the
|
|
15
|
+
* order in which keys appear in the caller's objects.
|
|
16
|
+
*
|
|
17
|
+
* This commitment is what every party signs via `FactorySignerOps.sign`, and
|
|
18
|
+
* what `FactorySignerOps.verify` checks against each stored signature.
|
|
19
|
+
*/
|
|
20
|
+
function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
|
|
21
|
+
const canonical = {
|
|
22
|
+
factoryId,
|
|
23
|
+
sequence,
|
|
24
|
+
allocations: Object.fromEntries(Object.entries(pendingAllocations)
|
|
25
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
26
|
+
.map(([k, v]) => [k, v.toString()])),
|
|
27
|
+
virtualChannelIds: [...virtualChannelIds].sort(),
|
|
28
|
+
};
|
|
29
|
+
return (0, wasm_1.sha3_256)(new TextEncoder().encode(JSON.stringify(canonical)));
|
|
30
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory peer round-trips (RFC-035 B2 open, B3 close).
|
|
3
|
+
*
|
|
4
|
+
* Opening:
|
|
5
|
+
* initiator ── FACTORY_PROPOSAL (opening factory) ─▶ co-signer ×(N-1)
|
|
6
|
+
* initiator ◀─ FACTORY_ACCEPT (own opening signature) ── co-signer
|
|
7
|
+
* initiator ── FACTORY_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
8
|
+
*
|
|
9
|
+
* Closing (cooperative N-of-N settlement):
|
|
10
|
+
* initiator ── FACTORY_CLOSE_PROPOSAL (settlement draft) ─▶ co-signer ×(N-1)
|
|
11
|
+
* initiator ◀─ FACTORY_CLOSE_ACCEPT (own settlement signature) ── co-signer
|
|
12
|
+
* initiator assembles + (optional) mines/broadcasts, then
|
|
13
|
+
* ── FACTORY_CLOSE_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
14
|
+
*
|
|
15
|
+
* Each party commits/burns its **own** lease: the initiator on assemble, the
|
|
16
|
+
* co-signers on the `*_FINALIZED` confirmation (burns on TTL).
|
|
17
|
+
*/
|
|
18
|
+
import type { OmniaPeer, OmniaCoordination, CoordinationHandlers } from '@totemsdk/omnia';
|
|
19
|
+
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
20
|
+
import type { ChannelFactory, FactorySettlementPayload, OmniaChannel, WotsLeaseBundle } from './types.js';
|
|
21
|
+
export type VerifySignature = (signature: Uint8Array, commitment: Uint8Array, publicKeyDigest: string) => boolean;
|
|
22
|
+
export type FactoryStore = Map<string, ChannelFactory>;
|
|
23
|
+
export interface FactoryApprovalRequest {
|
|
24
|
+
factoryId: string;
|
|
25
|
+
proposer: string;
|
|
26
|
+
participants: number;
|
|
27
|
+
}
|
|
28
|
+
export type FactoryApproval = (request: FactoryApprovalRequest) => Promise<boolean>;
|
|
29
|
+
export interface FactoryCoordinationDeps {
|
|
30
|
+
/** This peer's factories (its own copies). */
|
|
31
|
+
factories: FactoryStore;
|
|
32
|
+
/** This peer's signing bundle. */
|
|
33
|
+
bundle: WotsLeaseBundle;
|
|
34
|
+
verifySignature?: VerifySignature;
|
|
35
|
+
approval?: FactoryApproval;
|
|
36
|
+
onOpened?: (factory: ChannelFactory, peer: OmniaPeer) => void;
|
|
37
|
+
onClosed?: (payload: FactorySettlementPayload, peer: OmniaPeer) => void;
|
|
38
|
+
onVcOpened?: (factory: ChannelFactory, channel: OmniaChannel, peer: OmniaPeer) => void;
|
|
39
|
+
/** Initiator-only: mine + broadcast the settlement TxPoW. */
|
|
40
|
+
chainProvider?: ChainStateProvider;
|
|
41
|
+
ttlMs?: number;
|
|
42
|
+
}
|
|
43
|
+
export interface FactoryCoordination {
|
|
44
|
+
handlers: CoordinationHandlers;
|
|
45
|
+
/** Send a FACTORY_PROPOSAL for an 'opening' factory. */
|
|
46
|
+
openFactory(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory): Promise<void>;
|
|
47
|
+
/** Send a FACTORY_CLOSE_PROPOSAL and gather N-of-N settlement signatures. */
|
|
48
|
+
closeFactory(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory): Promise<void>;
|
|
49
|
+
/** Send a VC_PROPOSAL and gather N-of-N virtual-channel-open signatures. */
|
|
50
|
+
openVirtualChannel(peer: OmniaPeer, coordination: OmniaCoordination, factory: ChannelFactory, parties: [string, string], amounts: Record<string, bigint>): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
export declare function createFactoryCoordination(deps: FactoryCoordinationDeps): FactoryCoordination;
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Factory peer round-trips (RFC-035 B2 open, B3 close).
|
|
4
|
+
*
|
|
5
|
+
* Opening:
|
|
6
|
+
* initiator ── FACTORY_PROPOSAL (opening factory) ─▶ co-signer ×(N-1)
|
|
7
|
+
* initiator ◀─ FACTORY_ACCEPT (own opening signature) ── co-signer
|
|
8
|
+
* initiator ── FACTORY_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
9
|
+
*
|
|
10
|
+
* Closing (cooperative N-of-N settlement):
|
|
11
|
+
* initiator ── FACTORY_CLOSE_PROPOSAL (settlement draft) ─▶ co-signer ×(N-1)
|
|
12
|
+
* initiator ◀─ FACTORY_CLOSE_ACCEPT (own settlement signature) ── co-signer
|
|
13
|
+
* initiator assembles + (optional) mines/broadcasts, then
|
|
14
|
+
* ── FACTORY_CLOSE_FINALIZED ─▶ all co-signers (commit their held leaf)
|
|
15
|
+
*
|
|
16
|
+
* Each party commits/burns its **own** lease: the initiator on assemble, the
|
|
17
|
+
* co-signers on the `*_FINALIZED` confirmation (burns on TTL).
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.createFactoryCoordination = createFactoryCoordination;
|
|
21
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
22
|
+
const factory_js_1 = require("./factory.js");
|
|
23
|
+
const settlement_js_1 = require("./settlement.js");
|
|
24
|
+
const virtual_js_1 = require("./virtual.js");
|
|
25
|
+
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
26
|
+
function toHex(bytes) {
|
|
27
|
+
return Buffer.from(bytes).toString('hex');
|
|
28
|
+
}
|
|
29
|
+
function createFactoryCoordination(deps) {
|
|
30
|
+
const { factories, bundle, approval, onOpened, onClosed, onVcOpened, chainProvider } = deps;
|
|
31
|
+
const verify = deps.verifySignature ?? ((sig, commitment, pkd) => (0, omnia_1.verifyChannelSignature)(sig, commitment, pkd));
|
|
32
|
+
const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;
|
|
33
|
+
const pendingOpenings = new Map();
|
|
34
|
+
const pendingSettlements = new Map();
|
|
35
|
+
const pendingVcOpenings = new Map();
|
|
36
|
+
const burnTimers = new Map();
|
|
37
|
+
const factoryPeers = new Map();
|
|
38
|
+
// Initiator-side close state.
|
|
39
|
+
const closeDrafts = new Map();
|
|
40
|
+
const closeSignatures = new Map();
|
|
41
|
+
// Initiator-side VC-open state.
|
|
42
|
+
const vcPlans = new Map();
|
|
43
|
+
const vcSignatures = new Map();
|
|
44
|
+
const scheduleBurn = (factoryId, reservationId, reason) => {
|
|
45
|
+
burnTimers.set(factoryId, setTimeout(() => {
|
|
46
|
+
const had = pendingOpenings.has(factoryId) ||
|
|
47
|
+
pendingSettlements.has(factoryId) ||
|
|
48
|
+
pendingVcOpenings.has(factoryId);
|
|
49
|
+
if (!had)
|
|
50
|
+
return;
|
|
51
|
+
pendingOpenings.delete(factoryId);
|
|
52
|
+
pendingSettlements.delete(factoryId);
|
|
53
|
+
pendingVcOpenings.delete(factoryId);
|
|
54
|
+
burnTimers.delete(factoryId);
|
|
55
|
+
void bundle.leaseProvider.burnReservation(reservationId, reason).catch(() => { });
|
|
56
|
+
}, ttlMs));
|
|
57
|
+
};
|
|
58
|
+
const registerPeer = (factoryId, peer) => {
|
|
59
|
+
const set = factoryPeers.get(factoryId) ?? new Set();
|
|
60
|
+
set.add(peer);
|
|
61
|
+
factoryPeers.set(factoryId, set);
|
|
62
|
+
};
|
|
63
|
+
const fanOut = async (ctx, factoryId, type) => {
|
|
64
|
+
const peers = factoryPeers.get(factoryId);
|
|
65
|
+
if (!peers)
|
|
66
|
+
return;
|
|
67
|
+
for (const peer of peers) {
|
|
68
|
+
await ctx.sendTo(peer, type, { factoryId }).catch(() => { });
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
// ── Opening ────────────────────────────────────────────────────────────────
|
|
72
|
+
const handleProposal = async (ctx) => {
|
|
73
|
+
const factory = ctx.message.payload;
|
|
74
|
+
if (!factory || factory.status !== 'opening' || !factory.pendingCommitment) {
|
|
75
|
+
throw new Error('factory proposal must be an opening factory');
|
|
76
|
+
}
|
|
77
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
78
|
+
throw new Error('local signer is not a factory participant');
|
|
79
|
+
}
|
|
80
|
+
for (const [partyId, sig] of Object.entries(factory.pendingSignatures ?? {})) {
|
|
81
|
+
if (!(0, factory_js_1.verifyFactorySignature)(factory, partyId, sig, verify)) {
|
|
82
|
+
throw new Error(`factory proposal: invalid signature for '${partyId}'`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (!ctx.policy.autoAccept) {
|
|
86
|
+
const approved = approval
|
|
87
|
+
? await approval({ factoryId: factory.factoryId, proposer: Object.keys(factory.pendingSignatures ?? {})[0] ?? '', participants: factory.participants.length })
|
|
88
|
+
: false;
|
|
89
|
+
if (!approved)
|
|
90
|
+
throw new Error('factory opening rejected: approval required');
|
|
91
|
+
}
|
|
92
|
+
const opening = await (0, factory_js_1.signFactoryOpening)(factory, bundle);
|
|
93
|
+
pendingOpenings.set(factory.factoryId, opening);
|
|
94
|
+
scheduleBurn(factory.factoryId, opening.reservationId, 'factory-open-timeout');
|
|
95
|
+
await ctx.send('FACTORY_ACCEPT', {
|
|
96
|
+
factoryId: factory.factoryId,
|
|
97
|
+
partyId: opening.partyId,
|
|
98
|
+
signature: opening.signature,
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
const handleAccept = async (ctx) => {
|
|
102
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
103
|
+
const factory = factories.get(factoryId);
|
|
104
|
+
if (!factory)
|
|
105
|
+
throw new Error(`factory accept for unknown factory ${factoryId}`);
|
|
106
|
+
if (!(0, factory_js_1.verifyFactorySignature)(factory, partyId, signature, verify)) {
|
|
107
|
+
throw new Error(`factory accept: invalid signature from '${partyId}'`);
|
|
108
|
+
}
|
|
109
|
+
const updated = (0, factory_js_1.applyFactorySignature)(factory, partyId, signature);
|
|
110
|
+
factories.set(factoryId, updated);
|
|
111
|
+
if (updated.status === 'active') {
|
|
112
|
+
onOpened?.(updated, ctx.peer);
|
|
113
|
+
await fanOut(ctx, factoryId, 'FACTORY_FINALIZED');
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const handleFinalized = async (ctx) => {
|
|
117
|
+
const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
|
|
118
|
+
const pending = pendingOpenings.get(factoryId);
|
|
119
|
+
if (!pending)
|
|
120
|
+
return;
|
|
121
|
+
pendingOpenings.delete(factoryId);
|
|
122
|
+
const timer = burnTimers.get(factoryId);
|
|
123
|
+
if (timer) {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
burnTimers.delete(factoryId);
|
|
126
|
+
}
|
|
127
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-finalized:${factoryId}`);
|
|
128
|
+
};
|
|
129
|
+
// ── Closing ────────────────────────────────────────────────────────────────
|
|
130
|
+
const handleCloseProposal = async (ctx) => {
|
|
131
|
+
const { factoryId, draft } = ctx.message.payload;
|
|
132
|
+
const factory = factories.get(factoryId);
|
|
133
|
+
if (!factory)
|
|
134
|
+
throw new Error(`factory close proposal for unknown factory ${factoryId}`);
|
|
135
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
136
|
+
throw new Error('local signer is not a factory participant');
|
|
137
|
+
}
|
|
138
|
+
// Bind the proposal to our own view: rebuild and compare.
|
|
139
|
+
const local = (0, settlement_js_1.buildFactorySettlement)(factory);
|
|
140
|
+
if (toHex(local.txDigest) !== toHex(draft.txDigest) || local.settlementTxHex !== draft.settlementTxHex) {
|
|
141
|
+
throw new Error('factory close proposal: settlement draft does not match local factory state');
|
|
142
|
+
}
|
|
143
|
+
if (!ctx.policy.autoAccept) {
|
|
144
|
+
const approved = approval
|
|
145
|
+
? await approval({ factoryId, proposer: '', participants: factory.participants.length })
|
|
146
|
+
: false;
|
|
147
|
+
if (!approved)
|
|
148
|
+
throw new Error('factory close rejected: approval required');
|
|
149
|
+
}
|
|
150
|
+
const sig = await (0, settlement_js_1.signFactorySettlement)(factory, local, bundle);
|
|
151
|
+
pendingSettlements.set(factoryId, sig);
|
|
152
|
+
scheduleBurn(factoryId, sig.reservationId, 'factory-close-timeout');
|
|
153
|
+
await ctx.send('FACTORY_CLOSE_ACCEPT', {
|
|
154
|
+
factoryId,
|
|
155
|
+
partyId: sig.partyId,
|
|
156
|
+
signature: sig.signature,
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
const handleCloseAccept = async (ctx) => {
|
|
160
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
161
|
+
const factory = factories.get(factoryId);
|
|
162
|
+
if (!factory)
|
|
163
|
+
throw new Error(`factory close accept for unknown factory ${factoryId}`);
|
|
164
|
+
const draft = closeDrafts.get(factoryId);
|
|
165
|
+
if (!draft)
|
|
166
|
+
throw new Error(`no settlement draft for factory ${factoryId}`);
|
|
167
|
+
if (!(0, settlement_js_1.verifyFactorySettlementSignature)(factory, draft.txDigest, partyId, signature, verify)) {
|
|
168
|
+
throw new Error(`factory close accept: invalid signature from '${partyId}'`);
|
|
169
|
+
}
|
|
170
|
+
const sigs = closeSignatures.get(factoryId) ?? {};
|
|
171
|
+
sigs[partyId] = { partyId, signature, reservationId: '' };
|
|
172
|
+
closeSignatures.set(factoryId, sigs);
|
|
173
|
+
if (factory.participants.every((p) => sigs[p.partyId])) {
|
|
174
|
+
const payload = await (0, settlement_js_1.assembleFactorySettlement)(factory, draft, sigs, chainProvider, { verify });
|
|
175
|
+
// commit the initiator's OWN held reservation (the only one with an id)
|
|
176
|
+
const own = Object.values(sigs).find((s) => s.reservationId);
|
|
177
|
+
if (own?.reservationId) {
|
|
178
|
+
await bundle.leaseProvider.commitKeyUse(own.reservationId, `factory-settled:${factoryId}`);
|
|
179
|
+
}
|
|
180
|
+
onClosed?.(payload, ctx.peer);
|
|
181
|
+
await fanOut(ctx, factoryId, 'FACTORY_CLOSE_FINALIZED');
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const handleCloseFinalized = async (ctx) => {
|
|
185
|
+
const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
|
|
186
|
+
const pending = pendingSettlements.get(factoryId);
|
|
187
|
+
if (!pending)
|
|
188
|
+
return;
|
|
189
|
+
pendingSettlements.delete(factoryId);
|
|
190
|
+
const timer = burnTimers.get(factoryId);
|
|
191
|
+
if (timer) {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
burnTimers.delete(factoryId);
|
|
194
|
+
}
|
|
195
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-settled:${factoryId}`);
|
|
196
|
+
};
|
|
197
|
+
// ── Virtual channel open ─────────────────────────────────────────────────────
|
|
198
|
+
const handleVcProposal = async (ctx) => {
|
|
199
|
+
const { factoryId, plan } = ctx.message.payload;
|
|
200
|
+
const factory = factories.get(factoryId);
|
|
201
|
+
if (!factory)
|
|
202
|
+
throw new Error(`vc proposal for unknown factory ${factoryId}`);
|
|
203
|
+
if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
|
|
204
|
+
throw new Error('local signer is not a factory participant');
|
|
205
|
+
}
|
|
206
|
+
const local = (0, virtual_js_1.buildVirtualChannelOpen)(factory, plan.parties, plan.amounts, plan.vcId);
|
|
207
|
+
if (toHex(local.commitment) !== toHex(plan.commitment)) {
|
|
208
|
+
throw new Error('vc proposal: commitment does not match local factory state');
|
|
209
|
+
}
|
|
210
|
+
if (!ctx.policy.autoAccept) {
|
|
211
|
+
const approved = approval
|
|
212
|
+
? await approval({ factoryId, proposer: '', participants: factory.participants.length })
|
|
213
|
+
: false;
|
|
214
|
+
if (!approved)
|
|
215
|
+
throw new Error('virtual channel open rejected: approval required');
|
|
216
|
+
}
|
|
217
|
+
const sig = await (0, virtual_js_1.signVirtualChannelOpen)(factory, local, bundle);
|
|
218
|
+
pendingVcOpenings.set(plan.vcId, sig);
|
|
219
|
+
scheduleBurn(plan.vcId, sig.reservationId, 'vc-open-timeout');
|
|
220
|
+
await ctx.send('VC_ACCEPT', { factoryId, partyId: sig.partyId, signature: sig.signature });
|
|
221
|
+
};
|
|
222
|
+
const handleVcAccept = async (ctx) => {
|
|
223
|
+
const { factoryId, partyId, signature } = ctx.message.payload;
|
|
224
|
+
const factory = factories.get(factoryId);
|
|
225
|
+
if (!factory)
|
|
226
|
+
throw new Error(`vc accept for unknown factory ${factoryId}`);
|
|
227
|
+
const plan = vcPlans.get(ctx.correlationId);
|
|
228
|
+
if (!plan)
|
|
229
|
+
throw new Error(`no VC plan for ${ctx.correlationId}`);
|
|
230
|
+
if (!(0, virtual_js_1.verifyVirtualChannelOpenSignature)(factory, plan.commitment, partyId, signature, verify)) {
|
|
231
|
+
throw new Error(`vc accept: invalid signature from '${partyId}'`);
|
|
232
|
+
}
|
|
233
|
+
const sigs = vcSignatures.get(ctx.correlationId) ?? {};
|
|
234
|
+
sigs[partyId] = { partyId, signature, reservationId: '' };
|
|
235
|
+
vcSignatures.set(ctx.correlationId, sigs);
|
|
236
|
+
if (factory.participants.every((p) => sigs[p.partyId])) {
|
|
237
|
+
const { factory: updated, channel } = (0, virtual_js_1.assembleVirtualChannelOpen)(factory, plan, sigs, verify);
|
|
238
|
+
factories.set(factoryId, updated);
|
|
239
|
+
const own = Object.values(sigs).find((s) => s.reservationId);
|
|
240
|
+
if (own?.reservationId) {
|
|
241
|
+
await bundle.leaseProvider.commitKeyUse(own.reservationId, `vc-opened:${plan.vcId}`);
|
|
242
|
+
}
|
|
243
|
+
onVcOpened?.(updated, channel, ctx.peer);
|
|
244
|
+
await fanOut(ctx, factoryId, 'VC_FINALIZED');
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
const handleVcFinalized = async (ctx) => {
|
|
248
|
+
const vcId = ctx.correlationId;
|
|
249
|
+
const pending = pendingVcOpenings.get(vcId);
|
|
250
|
+
if (!pending)
|
|
251
|
+
return;
|
|
252
|
+
pendingVcOpenings.delete(vcId);
|
|
253
|
+
const timer = burnTimers.get(vcId);
|
|
254
|
+
if (timer) {
|
|
255
|
+
clearTimeout(timer);
|
|
256
|
+
burnTimers.delete(vcId);
|
|
257
|
+
}
|
|
258
|
+
await bundle.leaseProvider.commitKeyUse(pending.reservationId, `vc-opened:${vcId}`);
|
|
259
|
+
};
|
|
260
|
+
const handlers = {
|
|
261
|
+
FACTORY_PROPOSAL: handleProposal,
|
|
262
|
+
FACTORY_ACCEPT: handleAccept,
|
|
263
|
+
FACTORY_FINALIZED: handleFinalized,
|
|
264
|
+
FACTORY_CLOSE_PROPOSAL: handleCloseProposal,
|
|
265
|
+
FACTORY_CLOSE_ACCEPT: handleCloseAccept,
|
|
266
|
+
FACTORY_CLOSE_FINALIZED: handleCloseFinalized,
|
|
267
|
+
VC_PROPOSAL: handleVcProposal,
|
|
268
|
+
VC_ACCEPT: handleVcAccept,
|
|
269
|
+
VC_FINALIZED: handleVcFinalized,
|
|
270
|
+
};
|
|
271
|
+
const openFactory = async (peer, coordination, factory) => {
|
|
272
|
+
if (factory.status !== 'opening')
|
|
273
|
+
throw new Error('openFactory requires an opening factory');
|
|
274
|
+
factories.set(factory.factoryId, factory);
|
|
275
|
+
registerPeer(factory.factoryId, peer);
|
|
276
|
+
await coordination.sendProposal({
|
|
277
|
+
peer,
|
|
278
|
+
kind: 'FACTORY_PROPOSAL',
|
|
279
|
+
correlationId: factory.factoryId,
|
|
280
|
+
channelId: factory.factoryId,
|
|
281
|
+
payload: factory,
|
|
282
|
+
});
|
|
283
|
+
};
|
|
284
|
+
const closeFactory = async (peer, coordination, factory) => {
|
|
285
|
+
if (factory.status !== 'active')
|
|
286
|
+
throw new Error('closeFactory requires an active factory');
|
|
287
|
+
factories.set(factory.factoryId, factory);
|
|
288
|
+
registerPeer(factory.factoryId, peer);
|
|
289
|
+
const draft = (0, settlement_js_1.buildFactorySettlement)(factory);
|
|
290
|
+
const own = await (0, settlement_js_1.signFactorySettlement)(factory, draft, bundle);
|
|
291
|
+
closeDrafts.set(factory.factoryId, draft);
|
|
292
|
+
closeSignatures.set(factory.factoryId, { [own.partyId]: own });
|
|
293
|
+
await coordination.sendProposal({
|
|
294
|
+
peer,
|
|
295
|
+
kind: 'FACTORY_CLOSE_PROPOSAL',
|
|
296
|
+
correlationId: factory.factoryId,
|
|
297
|
+
channelId: factory.factoryId,
|
|
298
|
+
payload: { factoryId: factory.factoryId, draft },
|
|
299
|
+
});
|
|
300
|
+
};
|
|
301
|
+
const openVirtualChannel = async (peer, coordination, factory, parties, amounts) => {
|
|
302
|
+
if (factory.status !== 'active')
|
|
303
|
+
throw new Error('openVirtualChannel requires an active factory');
|
|
304
|
+
factories.set(factory.factoryId, factory);
|
|
305
|
+
registerPeer(factory.factoryId, peer);
|
|
306
|
+
const plan = (0, virtual_js_1.buildVirtualChannelOpen)(factory, parties, amounts);
|
|
307
|
+
const own = await (0, virtual_js_1.signVirtualChannelOpen)(factory, plan, bundle);
|
|
308
|
+
vcPlans.set(plan.vcId, plan);
|
|
309
|
+
vcSignatures.set(plan.vcId, { [own.partyId]: own });
|
|
310
|
+
await coordination.sendProposal({
|
|
311
|
+
peer,
|
|
312
|
+
kind: 'VC_PROPOSAL',
|
|
313
|
+
correlationId: plan.vcId,
|
|
314
|
+
channelId: factory.factoryId,
|
|
315
|
+
payload: { factoryId: factory.factoryId, plan },
|
|
316
|
+
});
|
|
317
|
+
};
|
|
318
|
+
return { handlers, openFactory, closeFactory, openVirtualChannel };
|
|
319
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable factory signing-state store (RFC-007 G9).
|
|
3
|
+
*
|
|
4
|
+
* `createFactory`/`acceptFactory`/`reallocate` are pure functions that return
|
|
5
|
+
* updated `ChannelFactory` records; this store makes the actionable part of that
|
|
6
|
+
* state — `pendingCommitment`, `pendingSignatures` (partial-signature counts),
|
|
7
|
+
* and `stateLog` — durable, so it survives a host restart with no partial-funding
|
|
8
|
+
* loss. A factory that was mid-signing-round (N of N signatures collected) reopens
|
|
9
|
+
* with every already-collected signature intact and can resume exactly where it
|
|
10
|
+
* left off.
|
|
11
|
+
*
|
|
12
|
+
* Backed by the shared revision-CAS snapshot store: single-key, whole-record
|
|
13
|
+
* update, corruption surfaced (never treated as absence), no silent downgrade.
|
|
14
|
+
*/
|
|
15
|
+
import type { StorageAdapterWithCapabilities, CasStore, WriteAckMode } from '@totemsdk/storage/types';
|
|
16
|
+
import type { ChannelFactory } from './types.js';
|
|
17
|
+
export interface FactoryRegistryState {
|
|
18
|
+
factories: Record<string, ChannelFactory>;
|
|
19
|
+
}
|
|
20
|
+
export interface DurableFactoryStoreOptions {
|
|
21
|
+
/** Key namespace prefix; default `totem_omnia_factory:v1:`. */
|
|
22
|
+
readonly namespace?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Required write acknowledgment; default `durably-acknowledged`. Pass
|
|
25
|
+
* `volatile` only for tests/scratch adapters (e.g. `MemoryStore`).
|
|
26
|
+
*/
|
|
27
|
+
readonly requireAckMode?: WriteAckMode;
|
|
28
|
+
}
|
|
29
|
+
export interface DurableFactoryStore {
|
|
30
|
+
/** Persist a factory (create/accept/reallocate state transition). */
|
|
31
|
+
saveFactory(factory: ChannelFactory): Promise<void>;
|
|
32
|
+
getFactory(factoryId: string): Promise<ChannelFactory | undefined>;
|
|
33
|
+
/** All factories known to the registry. */
|
|
34
|
+
listFactories(): Promise<ChannelFactory[]>;
|
|
35
|
+
/** Current registry transition counter (0 before the first write). */
|
|
36
|
+
getRevision(): Promise<number>;
|
|
37
|
+
/** True once any factory record has been persisted. */
|
|
38
|
+
hasState(): Promise<boolean>;
|
|
39
|
+
/** Current persisted registry state. */
|
|
40
|
+
getSnapshot(): Promise<FactoryRegistryState>;
|
|
41
|
+
}
|
|
42
|
+
export declare function createDurableFactoryStore(adapter: StorageAdapterWithCapabilities & CasStore, options?: DurableFactoryStoreOptions): DurableFactoryStore;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Durable factory signing-state store (RFC-007 G9).
|
|
4
|
+
*
|
|
5
|
+
* `createFactory`/`acceptFactory`/`reallocate` are pure functions that return
|
|
6
|
+
* updated `ChannelFactory` records; this store makes the actionable part of that
|
|
7
|
+
* state — `pendingCommitment`, `pendingSignatures` (partial-signature counts),
|
|
8
|
+
* and `stateLog` — durable, so it survives a host restart with no partial-funding
|
|
9
|
+
* loss. A factory that was mid-signing-round (N of N signatures collected) reopens
|
|
10
|
+
* with every already-collected signature intact and can resume exactly where it
|
|
11
|
+
* left off.
|
|
12
|
+
*
|
|
13
|
+
* Backed by the shared revision-CAS snapshot store: single-key, whole-record
|
|
14
|
+
* update, corruption surfaced (never treated as absence), no silent downgrade.
|
|
15
|
+
*/
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.createDurableFactoryStore = createDurableFactoryStore;
|
|
18
|
+
const snapshot_1 = require("@totemsdk/storage/snapshot");
|
|
19
|
+
const errors_1 = require("@totemsdk/storage/errors");
|
|
20
|
+
const DEFAULT_NAMESPACE = 'totem_omnia_factory:v1:';
|
|
21
|
+
function assertRegistryState(state) {
|
|
22
|
+
if (typeof state !== 'object' || state === null || Array.isArray(state)) {
|
|
23
|
+
throw new errors_1.StorageError('omnia-factory registry state is not an object', 'corrupt');
|
|
24
|
+
}
|
|
25
|
+
const value = state.factories;
|
|
26
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
27
|
+
throw new errors_1.StorageError('omnia-factory registry state is missing section "factories"', 'corrupt');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function createDurableFactoryStore(adapter, options = {}) {
|
|
31
|
+
const snapshots = (0, snapshot_1.createRevisionedSnapshotStore)(adapter, {
|
|
32
|
+
namespace: options.namespace ?? DEFAULT_NAMESPACE,
|
|
33
|
+
requireAckMode: options.requireAckMode,
|
|
34
|
+
empty: () => ({ factories: {} }),
|
|
35
|
+
validate: assertRegistryState,
|
|
36
|
+
});
|
|
37
|
+
async function mutate(fn) {
|
|
38
|
+
await snapshots.mutate(fn);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
async saveFactory(factory) {
|
|
42
|
+
await mutate((state) => {
|
|
43
|
+
const factories = { ...state.factories, [factory.factoryId]: factory };
|
|
44
|
+
return { ...state, factories };
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
async getFactory(factoryId) {
|
|
48
|
+
return (await snapshots.load()).factories[factoryId];
|
|
49
|
+
},
|
|
50
|
+
async listFactories() {
|
|
51
|
+
return Object.values((await snapshots.load()).factories);
|
|
52
|
+
},
|
|
53
|
+
getRevision: () => snapshots.getRevision(),
|
|
54
|
+
hasState: () => snapshots.hasState(),
|
|
55
|
+
async getSnapshot() {
|
|
56
|
+
return snapshots.load();
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
2
|
+
import type { ChannelFactory, FactoryParticipant, WotsLeaseBundle } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Enforce the factory's balance conservation invariant:
|
|
5
|
+
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
6
|
+
*
|
|
7
|
+
* Throws on violation. Called after every committed state transition.
|
|
8
|
+
*/
|
|
9
|
+
export declare function enforceConservation(factory: ChannelFactory): void;
|
|
10
|
+
/**
|
|
11
|
+
* Create a factory proposal (proposer step).
|
|
12
|
+
*
|
|
13
|
+
* The calling party (`signer.publicKeyDigest` matches one of `participants`)
|
|
14
|
+
* signs the factory opening commitment via `leaseProvider`, performing the full
|
|
15
|
+
* WOTS reserve → sign → verify → commit cycle.
|
|
16
|
+
*
|
|
17
|
+
* When ALL participants supply `fundingCoinId` and `chainProvider` is given,
|
|
18
|
+
* the N-input → 1-output funding TX is built (via `@totemsdk/omnia`'s
|
|
19
|
+
* `buildFundingTx`), mined (via `@totemsdk/txpow`'s `mineTxPoW`), and broadcast.
|
|
20
|
+
* The TX draft digest is used as the factory opening commitment so that all
|
|
21
|
+
* parties are co-signing the EXACT on-chain TX structure.
|
|
22
|
+
*
|
|
23
|
+
* Without `fundingCoinId`s or `chainProvider`, the factory is in-memory only
|
|
24
|
+
* (useful for testing and off-chain simulation); the commitment falls back to
|
|
25
|
+
* the factory state commitment hash.
|
|
26
|
+
*
|
|
27
|
+
* The returned factory is in `'opening'` status. Every other participant must
|
|
28
|
+
* call `acceptFactory(factory, leaseProvider, signer)` before the factory
|
|
29
|
+
* transitions to `'active'`.
|
|
30
|
+
*
|
|
31
|
+
* @param participants - All N factory participants with their contribution amounts.
|
|
32
|
+
* @param tokenId - Token ID (e.g. `'0x00'` for native Minima).
|
|
33
|
+
* @param leaseProvider - WOTS lease provider for the proposer's key slot.
|
|
34
|
+
* @param signer - Proposer's channel signer (`signer.publicKeyDigest` must match
|
|
35
|
+
* one of the registered participants).
|
|
36
|
+
* @param chainProvider - Optional: build + mine + broadcast the factory funding TX.
|
|
37
|
+
* @param tokenScale - Token scale exponent (Minima `Token.mTokenScale`). Native Minima
|
|
38
|
+
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
39
|
+
* Defaults to 0.
|
|
40
|
+
*/
|
|
41
|
+
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number): Promise<ChannelFactory>;
|
|
42
|
+
/**
|
|
43
|
+
* Counterparty co-signs the factory proposal.
|
|
44
|
+
*
|
|
45
|
+
* Each non-proposing participant calls this once. When ALL N parties have
|
|
46
|
+
* signed (proposer via `createFactory` + N-1 counterparties via `acceptFactory`),
|
|
47
|
+
* the factory transitions from `'opening'` to `'active'`.
|
|
48
|
+
*
|
|
49
|
+
* Uses the full WOTS lease cycle: reserve → sign → verify → commit.
|
|
50
|
+
*
|
|
51
|
+
* @param factory - Factory in `'opening'` status returned by `createFactory`.
|
|
52
|
+
* @param leaseProvider - This counterparty's WOTS lease provider.
|
|
53
|
+
* @param signer - This counterparty's channel signer (`signer.publicKeyDigest`
|
|
54
|
+
* must match a registered participant not yet signed).
|
|
55
|
+
*/
|
|
56
|
+
export declare function acceptFactory(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<ChannelFactory>;
|
|
57
|
+
/** A co-signer's opening signature, held until the opening is confirmed. */
|
|
58
|
+
export interface FactoryOpeningSignature {
|
|
59
|
+
factoryId: string;
|
|
60
|
+
partyId: string;
|
|
61
|
+
signature: Uint8Array;
|
|
62
|
+
reservationId: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Produce this party's opening signature WITHOUT committing the lease
|
|
66
|
+
* (RFC-035 B2). The caller commits on `FACTORY_FINALIZED` or burns on expiry —
|
|
67
|
+
* mirroring the splice accept round so a peer can gather N-of-N signatures
|
|
68
|
+
* without stranding or prematurely committing one-time keys.
|
|
69
|
+
*/
|
|
70
|
+
export declare function signFactoryOpening(factory: ChannelFactory, bundle: WotsLeaseBundle): Promise<FactoryOpeningSignature>;
|
|
71
|
+
/** Verify a remote opening signature against a factory participant. */
|
|
72
|
+
export declare function verifyFactorySignature(factory: ChannelFactory, partyId: string, signature: Uint8Array, verify?: (sig: Uint8Array, commitment: Uint8Array, pkd: string) => boolean): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Merge a co-signer's opening signature (RFC-035 B2). When all N participants
|
|
75
|
+
* have signed, the opening commits (`'opening'` → `'active'`).
|
|
76
|
+
*/
|
|
77
|
+
export declare function applyFactorySignature(factory: ChannelFactory, partyId: string, signature: Uint8Array): ChannelFactory;
|
|
78
|
+
/**
|
|
79
|
+
* Move factory allocation between two participants (atomic N-of-N).
|
|
80
|
+
*
|
|
81
|
+
* All N leaseProviders must be supplied; each party signs the new state
|
|
82
|
+
* commitment in turn. The state commits atomically — no intermediate "pending"
|
|
83
|
+
* object is returned.
|
|
84
|
+
*
|
|
85
|
+
* @param factory - Active factory.
|
|
86
|
+
* @param fromPartyId - Party giving up allocation.
|
|
87
|
+
* @param toPartyId - Party receiving allocation.
|
|
88
|
+
* @param amount - Amount to transfer (must be positive and within `fromPartyId`'s balance).
|
|
89
|
+
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
90
|
+
*/
|
|
91
|
+
export declare function reallocate(factory: ChannelFactory, fromPartyId: string, toPartyId: string, amount: bigint, leaseProviders: Record<string, WotsLeaseBundle>): Promise<ChannelFactory>;
|