@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.
Files changed (40) hide show
  1. package/dist/cjs/commitment.d.ts +16 -0
  2. package/dist/cjs/commitment.js +30 -0
  3. package/dist/cjs/coordination.d.ts +52 -0
  4. package/dist/cjs/coordination.js +319 -0
  5. package/dist/cjs/durable-factory-store.d.ts +42 -0
  6. package/dist/cjs/durable-factory-store.js +59 -0
  7. package/dist/cjs/factory.d.ts +91 -0
  8. package/dist/cjs/factory.js +380 -0
  9. package/dist/cjs/index.d.ts +12 -0
  10. package/dist/cjs/index.js +38 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/script.d.ts +47 -0
  13. package/dist/cjs/script.js +105 -0
  14. package/dist/cjs/settlement.d.ts +55 -0
  15. package/dist/cjs/settlement.js +193 -0
  16. package/dist/cjs/types.d.ts +131 -0
  17. package/dist/cjs/types.js +2 -0
  18. package/dist/cjs/virtual.d.ts +75 -0
  19. package/dist/cjs/virtual.js +277 -0
  20. package/dist/commitment.js +3 -6
  21. package/dist/coordination.d.ts +52 -0
  22. package/dist/coordination.js +316 -0
  23. package/dist/durable-factory-store.d.ts +42 -0
  24. package/dist/durable-factory-store.js +56 -0
  25. package/dist/factory.d.ts +21 -0
  26. package/dist/factory.js +101 -30
  27. package/dist/index.d.ts +10 -4
  28. package/dist/index.js +8 -21
  29. package/dist/script.d.ts +31 -13
  30. package/dist/script.js +68 -34
  31. package/dist/settlement.d.ts +36 -12
  32. package/dist/settlement.js +108 -70
  33. package/dist/types.js +1 -2
  34. package/dist/virtual.d.ts +31 -0
  35. package/dist/virtual.js +110 -59
  36. package/package.json +20 -13
  37. package/rust/pkg/omnia_factory_wasm_bg.wasm +0 -0
  38. package/rust/pkg/package.json +1 -1
  39. package/rust/pkg-node/omnia_factory_wasm_bg.wasm +0 -0
  40. package/rust/pkg-node/package.json +1 -1
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeFactoryStateCommitment = computeFactoryStateCommitment;
4
- const core_1 = require("@totemsdk/core");
1
+ import { sha3_256 } from '@totemsdk/core/wasm';
5
2
  /**
6
3
  * Compute the canonical 32-byte state commitment for N-of-N factory signing.
7
4
  *
@@ -17,7 +14,7 @@ const core_1 = require("@totemsdk/core");
17
14
  * This commitment is what every party signs via `FactorySignerOps.sign`, and
18
15
  * what `FactorySignerOps.verify` checks against each stored signature.
19
16
  */
20
- function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
17
+ export function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations, virtualChannelIds) {
21
18
  const canonical = {
22
19
  factoryId,
23
20
  sequence,
@@ -26,5 +23,5 @@ function computeFactoryStateCommitment(factoryId, sequence, pendingAllocations,
26
23
  .map(([k, v]) => [k, v.toString()])),
27
24
  virtualChannelIds: [...virtualChannelIds].sort(),
28
25
  };
29
- return (0, core_1.sha3_256)(new TextEncoder().encode(JSON.stringify(canonical)));
26
+ return sha3_256(new TextEncoder().encode(JSON.stringify(canonical)));
30
27
  }
@@ -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,316 @@
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 { verifyChannelSignature } from '@totemsdk/omnia';
19
+ import { signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
20
+ import { buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
21
+ import { buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
22
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
23
+ function toHex(bytes) {
24
+ return Buffer.from(bytes).toString('hex');
25
+ }
26
+ export function createFactoryCoordination(deps) {
27
+ const { factories, bundle, approval, onOpened, onClosed, onVcOpened, chainProvider } = deps;
28
+ const verify = deps.verifySignature ?? ((sig, commitment, pkd) => verifyChannelSignature(sig, commitment, pkd));
29
+ const ttlMs = deps.ttlMs ?? DEFAULT_TTL_MS;
30
+ const pendingOpenings = new Map();
31
+ const pendingSettlements = new Map();
32
+ const pendingVcOpenings = new Map();
33
+ const burnTimers = new Map();
34
+ const factoryPeers = new Map();
35
+ // Initiator-side close state.
36
+ const closeDrafts = new Map();
37
+ const closeSignatures = new Map();
38
+ // Initiator-side VC-open state.
39
+ const vcPlans = new Map();
40
+ const vcSignatures = new Map();
41
+ const scheduleBurn = (factoryId, reservationId, reason) => {
42
+ burnTimers.set(factoryId, setTimeout(() => {
43
+ const had = pendingOpenings.has(factoryId) ||
44
+ pendingSettlements.has(factoryId) ||
45
+ pendingVcOpenings.has(factoryId);
46
+ if (!had)
47
+ return;
48
+ pendingOpenings.delete(factoryId);
49
+ pendingSettlements.delete(factoryId);
50
+ pendingVcOpenings.delete(factoryId);
51
+ burnTimers.delete(factoryId);
52
+ void bundle.leaseProvider.burnReservation(reservationId, reason).catch(() => { });
53
+ }, ttlMs));
54
+ };
55
+ const registerPeer = (factoryId, peer) => {
56
+ const set = factoryPeers.get(factoryId) ?? new Set();
57
+ set.add(peer);
58
+ factoryPeers.set(factoryId, set);
59
+ };
60
+ const fanOut = async (ctx, factoryId, type) => {
61
+ const peers = factoryPeers.get(factoryId);
62
+ if (!peers)
63
+ return;
64
+ for (const peer of peers) {
65
+ await ctx.sendTo(peer, type, { factoryId }).catch(() => { });
66
+ }
67
+ };
68
+ // ── Opening ────────────────────────────────────────────────────────────────
69
+ const handleProposal = async (ctx) => {
70
+ const factory = ctx.message.payload;
71
+ if (!factory || factory.status !== 'opening' || !factory.pendingCommitment) {
72
+ throw new Error('factory proposal must be an opening factory');
73
+ }
74
+ if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
75
+ throw new Error('local signer is not a factory participant');
76
+ }
77
+ for (const [partyId, sig] of Object.entries(factory.pendingSignatures ?? {})) {
78
+ if (!verifyFactorySignature(factory, partyId, sig, verify)) {
79
+ throw new Error(`factory proposal: invalid signature for '${partyId}'`);
80
+ }
81
+ }
82
+ if (!ctx.policy.autoAccept) {
83
+ const approved = approval
84
+ ? await approval({ factoryId: factory.factoryId, proposer: Object.keys(factory.pendingSignatures ?? {})[0] ?? '', participants: factory.participants.length })
85
+ : false;
86
+ if (!approved)
87
+ throw new Error('factory opening rejected: approval required');
88
+ }
89
+ const opening = await signFactoryOpening(factory, bundle);
90
+ pendingOpenings.set(factory.factoryId, opening);
91
+ scheduleBurn(factory.factoryId, opening.reservationId, 'factory-open-timeout');
92
+ await ctx.send('FACTORY_ACCEPT', {
93
+ factoryId: factory.factoryId,
94
+ partyId: opening.partyId,
95
+ signature: opening.signature,
96
+ });
97
+ };
98
+ const handleAccept = async (ctx) => {
99
+ const { factoryId, partyId, signature } = ctx.message.payload;
100
+ const factory = factories.get(factoryId);
101
+ if (!factory)
102
+ throw new Error(`factory accept for unknown factory ${factoryId}`);
103
+ if (!verifyFactorySignature(factory, partyId, signature, verify)) {
104
+ throw new Error(`factory accept: invalid signature from '${partyId}'`);
105
+ }
106
+ const updated = applyFactorySignature(factory, partyId, signature);
107
+ factories.set(factoryId, updated);
108
+ if (updated.status === 'active') {
109
+ onOpened?.(updated, ctx.peer);
110
+ await fanOut(ctx, factoryId, 'FACTORY_FINALIZED');
111
+ }
112
+ };
113
+ const handleFinalized = async (ctx) => {
114
+ const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
115
+ const pending = pendingOpenings.get(factoryId);
116
+ if (!pending)
117
+ return;
118
+ pendingOpenings.delete(factoryId);
119
+ const timer = burnTimers.get(factoryId);
120
+ if (timer) {
121
+ clearTimeout(timer);
122
+ burnTimers.delete(factoryId);
123
+ }
124
+ await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-finalized:${factoryId}`);
125
+ };
126
+ // ── Closing ────────────────────────────────────────────────────────────────
127
+ const handleCloseProposal = async (ctx) => {
128
+ const { factoryId, draft } = ctx.message.payload;
129
+ const factory = factories.get(factoryId);
130
+ if (!factory)
131
+ throw new Error(`factory close proposal for unknown factory ${factoryId}`);
132
+ if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
133
+ throw new Error('local signer is not a factory participant');
134
+ }
135
+ // Bind the proposal to our own view: rebuild and compare.
136
+ const local = buildFactorySettlement(factory);
137
+ if (toHex(local.txDigest) !== toHex(draft.txDigest) || local.settlementTxHex !== draft.settlementTxHex) {
138
+ throw new Error('factory close proposal: settlement draft does not match local factory state');
139
+ }
140
+ if (!ctx.policy.autoAccept) {
141
+ const approved = approval
142
+ ? await approval({ factoryId, proposer: '', participants: factory.participants.length })
143
+ : false;
144
+ if (!approved)
145
+ throw new Error('factory close rejected: approval required');
146
+ }
147
+ const sig = await signFactorySettlement(factory, local, bundle);
148
+ pendingSettlements.set(factoryId, sig);
149
+ scheduleBurn(factoryId, sig.reservationId, 'factory-close-timeout');
150
+ await ctx.send('FACTORY_CLOSE_ACCEPT', {
151
+ factoryId,
152
+ partyId: sig.partyId,
153
+ signature: sig.signature,
154
+ });
155
+ };
156
+ const handleCloseAccept = async (ctx) => {
157
+ const { factoryId, partyId, signature } = ctx.message.payload;
158
+ const factory = factories.get(factoryId);
159
+ if (!factory)
160
+ throw new Error(`factory close accept for unknown factory ${factoryId}`);
161
+ const draft = closeDrafts.get(factoryId);
162
+ if (!draft)
163
+ throw new Error(`no settlement draft for factory ${factoryId}`);
164
+ if (!verifyFactorySettlementSignature(factory, draft.txDigest, partyId, signature, verify)) {
165
+ throw new Error(`factory close accept: invalid signature from '${partyId}'`);
166
+ }
167
+ const sigs = closeSignatures.get(factoryId) ?? {};
168
+ sigs[partyId] = { partyId, signature, reservationId: '' };
169
+ closeSignatures.set(factoryId, sigs);
170
+ if (factory.participants.every((p) => sigs[p.partyId])) {
171
+ const payload = await assembleFactorySettlement(factory, draft, sigs, chainProvider, { verify });
172
+ // commit the initiator's OWN held reservation (the only one with an id)
173
+ const own = Object.values(sigs).find((s) => s.reservationId);
174
+ if (own?.reservationId) {
175
+ await bundle.leaseProvider.commitKeyUse(own.reservationId, `factory-settled:${factoryId}`);
176
+ }
177
+ onClosed?.(payload, ctx.peer);
178
+ await fanOut(ctx, factoryId, 'FACTORY_CLOSE_FINALIZED');
179
+ }
180
+ };
181
+ const handleCloseFinalized = async (ctx) => {
182
+ const factoryId = ctx.message.payload?.factoryId ?? ctx.correlationId;
183
+ const pending = pendingSettlements.get(factoryId);
184
+ if (!pending)
185
+ return;
186
+ pendingSettlements.delete(factoryId);
187
+ const timer = burnTimers.get(factoryId);
188
+ if (timer) {
189
+ clearTimeout(timer);
190
+ burnTimers.delete(factoryId);
191
+ }
192
+ await bundle.leaseProvider.commitKeyUse(pending.reservationId, `factory-settled:${factoryId}`);
193
+ };
194
+ // ── Virtual channel open ─────────────────────────────────────────────────────
195
+ const handleVcProposal = async (ctx) => {
196
+ const { factoryId, plan } = ctx.message.payload;
197
+ const factory = factories.get(factoryId);
198
+ if (!factory)
199
+ throw new Error(`vc proposal for unknown factory ${factoryId}`);
200
+ if (!factory.participants.find((p) => p.publicKeyDigest === bundle.signer.publicKeyDigest)) {
201
+ throw new Error('local signer is not a factory participant');
202
+ }
203
+ const local = buildVirtualChannelOpen(factory, plan.parties, plan.amounts, plan.vcId);
204
+ if (toHex(local.commitment) !== toHex(plan.commitment)) {
205
+ throw new Error('vc proposal: commitment does not match local factory state');
206
+ }
207
+ if (!ctx.policy.autoAccept) {
208
+ const approved = approval
209
+ ? await approval({ factoryId, proposer: '', participants: factory.participants.length })
210
+ : false;
211
+ if (!approved)
212
+ throw new Error('virtual channel open rejected: approval required');
213
+ }
214
+ const sig = await signVirtualChannelOpen(factory, local, bundle);
215
+ pendingVcOpenings.set(plan.vcId, sig);
216
+ scheduleBurn(plan.vcId, sig.reservationId, 'vc-open-timeout');
217
+ await ctx.send('VC_ACCEPT', { factoryId, partyId: sig.partyId, signature: sig.signature });
218
+ };
219
+ const handleVcAccept = async (ctx) => {
220
+ const { factoryId, partyId, signature } = ctx.message.payload;
221
+ const factory = factories.get(factoryId);
222
+ if (!factory)
223
+ throw new Error(`vc accept for unknown factory ${factoryId}`);
224
+ const plan = vcPlans.get(ctx.correlationId);
225
+ if (!plan)
226
+ throw new Error(`no VC plan for ${ctx.correlationId}`);
227
+ if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, partyId, signature, verify)) {
228
+ throw new Error(`vc accept: invalid signature from '${partyId}'`);
229
+ }
230
+ const sigs = vcSignatures.get(ctx.correlationId) ?? {};
231
+ sigs[partyId] = { partyId, signature, reservationId: '' };
232
+ vcSignatures.set(ctx.correlationId, sigs);
233
+ if (factory.participants.every((p) => sigs[p.partyId])) {
234
+ const { factory: updated, channel } = assembleVirtualChannelOpen(factory, plan, sigs, verify);
235
+ factories.set(factoryId, updated);
236
+ const own = Object.values(sigs).find((s) => s.reservationId);
237
+ if (own?.reservationId) {
238
+ await bundle.leaseProvider.commitKeyUse(own.reservationId, `vc-opened:${plan.vcId}`);
239
+ }
240
+ onVcOpened?.(updated, channel, ctx.peer);
241
+ await fanOut(ctx, factoryId, 'VC_FINALIZED');
242
+ }
243
+ };
244
+ const handleVcFinalized = async (ctx) => {
245
+ const vcId = ctx.correlationId;
246
+ const pending = pendingVcOpenings.get(vcId);
247
+ if (!pending)
248
+ return;
249
+ pendingVcOpenings.delete(vcId);
250
+ const timer = burnTimers.get(vcId);
251
+ if (timer) {
252
+ clearTimeout(timer);
253
+ burnTimers.delete(vcId);
254
+ }
255
+ await bundle.leaseProvider.commitKeyUse(pending.reservationId, `vc-opened:${vcId}`);
256
+ };
257
+ const handlers = {
258
+ FACTORY_PROPOSAL: handleProposal,
259
+ FACTORY_ACCEPT: handleAccept,
260
+ FACTORY_FINALIZED: handleFinalized,
261
+ FACTORY_CLOSE_PROPOSAL: handleCloseProposal,
262
+ FACTORY_CLOSE_ACCEPT: handleCloseAccept,
263
+ FACTORY_CLOSE_FINALIZED: handleCloseFinalized,
264
+ VC_PROPOSAL: handleVcProposal,
265
+ VC_ACCEPT: handleVcAccept,
266
+ VC_FINALIZED: handleVcFinalized,
267
+ };
268
+ const openFactory = async (peer, coordination, factory) => {
269
+ if (factory.status !== 'opening')
270
+ throw new Error('openFactory requires an opening factory');
271
+ factories.set(factory.factoryId, factory);
272
+ registerPeer(factory.factoryId, peer);
273
+ await coordination.sendProposal({
274
+ peer,
275
+ kind: 'FACTORY_PROPOSAL',
276
+ correlationId: factory.factoryId,
277
+ channelId: factory.factoryId,
278
+ payload: factory,
279
+ });
280
+ };
281
+ const closeFactory = async (peer, coordination, factory) => {
282
+ if (factory.status !== 'active')
283
+ throw new Error('closeFactory requires an active factory');
284
+ factories.set(factory.factoryId, factory);
285
+ registerPeer(factory.factoryId, peer);
286
+ const draft = buildFactorySettlement(factory);
287
+ const own = await signFactorySettlement(factory, draft, bundle);
288
+ closeDrafts.set(factory.factoryId, draft);
289
+ closeSignatures.set(factory.factoryId, { [own.partyId]: own });
290
+ await coordination.sendProposal({
291
+ peer,
292
+ kind: 'FACTORY_CLOSE_PROPOSAL',
293
+ correlationId: factory.factoryId,
294
+ channelId: factory.factoryId,
295
+ payload: { factoryId: factory.factoryId, draft },
296
+ });
297
+ };
298
+ const openVirtualChannel = async (peer, coordination, factory, parties, amounts) => {
299
+ if (factory.status !== 'active')
300
+ throw new Error('openVirtualChannel requires an active factory');
301
+ factories.set(factory.factoryId, factory);
302
+ registerPeer(factory.factoryId, peer);
303
+ const plan = buildVirtualChannelOpen(factory, parties, amounts);
304
+ const own = await signVirtualChannelOpen(factory, plan, bundle);
305
+ vcPlans.set(plan.vcId, plan);
306
+ vcSignatures.set(plan.vcId, { [own.partyId]: own });
307
+ await coordination.sendProposal({
308
+ peer,
309
+ kind: 'VC_PROPOSAL',
310
+ correlationId: plan.vcId,
311
+ channelId: factory.factoryId,
312
+ payload: { factoryId: factory.factoryId, plan },
313
+ });
314
+ };
315
+ return { handlers, openFactory, closeFactory, openVirtualChannel };
316
+ }
@@ -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,56 @@
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 { createRevisionedSnapshotStore, } from '@totemsdk/storage/snapshot';
16
+ import { StorageError } from '@totemsdk/storage/errors';
17
+ const DEFAULT_NAMESPACE = 'totem_omnia_factory:v1:';
18
+ function assertRegistryState(state) {
19
+ if (typeof state !== 'object' || state === null || Array.isArray(state)) {
20
+ throw new StorageError('omnia-factory registry state is not an object', 'corrupt');
21
+ }
22
+ const value = state.factories;
23
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
24
+ throw new StorageError('omnia-factory registry state is missing section "factories"', 'corrupt');
25
+ }
26
+ }
27
+ export function createDurableFactoryStore(adapter, options = {}) {
28
+ const snapshots = createRevisionedSnapshotStore(adapter, {
29
+ namespace: options.namespace ?? DEFAULT_NAMESPACE,
30
+ requireAckMode: options.requireAckMode,
31
+ empty: () => ({ factories: {} }),
32
+ validate: assertRegistryState,
33
+ });
34
+ async function mutate(fn) {
35
+ await snapshots.mutate(fn);
36
+ }
37
+ return {
38
+ async saveFactory(factory) {
39
+ await mutate((state) => {
40
+ const factories = { ...state.factories, [factory.factoryId]: factory };
41
+ return { ...state, factories };
42
+ });
43
+ },
44
+ async getFactory(factoryId) {
45
+ return (await snapshots.load()).factories[factoryId];
46
+ },
47
+ async listFactories() {
48
+ return Object.values((await snapshots.load()).factories);
49
+ },
50
+ getRevision: () => snapshots.getRevision(),
51
+ hasState: () => snapshots.hasState(),
52
+ async getSnapshot() {
53
+ return snapshots.load();
54
+ },
55
+ };
56
+ }
package/dist/factory.d.ts CHANGED
@@ -54,6 +54,27 @@ export declare function createFactory(participants: FactoryParticipant[], tokenI
54
54
  * must match a registered participant not yet signed).
55
55
  */
56
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;
57
78
  /**
58
79
  * Move factory allocation between two participants (atomic N-of-N).
59
80
  *