@totemsdk/omnia-factory 0.6.0 → 0.7.1

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.
@@ -1,5 +1,6 @@
1
1
  import { concatBytes } from '@totemsdk/core/wasm';
2
- import { serializeTxDraft, omniaDraftToMinimaBytes, computeTxDraftDigest, toRawMinima, verifyChannelSignature, } from '@totemsdk/omnia';
2
+ import { buildScriptProof } from '@totemsdk/core';
3
+ import { serializeTxDraft, omniaDraftToMinimaBytes, computeOmniaTxDigest, serializeOmniaWitness, toRawMinima, verifyChannelSignature, } from '@totemsdk/omnia';
3
4
  import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
4
5
  /**
5
6
  * Build the cooperative settlement TX + digest (no signing). Exported so peers
@@ -46,7 +47,7 @@ export function buildFactorySettlement(factory) {
46
47
  return {
47
48
  settlementDraft,
48
49
  settlementTxHex: serializeTxDraft(settlementDraft),
49
- txDigest: computeTxDraftDigest(settlementDraft),
50
+ txDigest: computeOmniaTxDigest(settlementDraft),
50
51
  };
51
52
  }
52
53
  /**
@@ -96,7 +97,7 @@ export function verifyFactorySettlementSignature(factory, txDigest, partyId, sig
96
97
  * (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
97
98
  */
98
99
  export async function assembleFactorySettlement(factory, draft, signatures, chainProvider, options) {
99
- const witnessParts = [];
100
+ const signaturesOut = [];
100
101
  for (const p of factory.participants) {
101
102
  const s = signatures[p.partyId];
102
103
  if (!s)
@@ -104,9 +105,8 @@ export async function assembleFactorySettlement(factory, draft, signatures, chai
104
105
  if (!verifyFactorySettlementSignature(factory, draft.txDigest, p.partyId, s.signature, options?.verify)) {
105
106
  throw new Error(`Settlement signature verification failed for party '${p.partyId}'`);
106
107
  }
107
- witnessParts.push(s.signature);
108
+ signaturesOut.push(s.signature);
108
109
  }
109
- const witnessBytes = witnessParts.reduce((a, b) => concatBytes(a, b));
110
110
  const payload = {
111
111
  factoryId: factory.factoryId,
112
112
  sequence: factory.currentSequence,
@@ -114,13 +114,35 @@ export async function assembleFactorySettlement(factory, draft, signatures, chai
114
114
  finalAllocations: { ...factory.allocations },
115
115
  };
116
116
  if (chainProvider) {
117
+ if (!options?.coinProof) {
118
+ throw new Error('closeFactory broadcast requires the factory coin proof (coinexport data)');
119
+ }
120
+ // The settlement input is the factory's N-of-N MULTISIG UTXO; the witness
121
+ // needs all N signatures + the coin proof + the funding-script proof.
122
+ const witnessBytes = serializeOmniaWitness({
123
+ signatures: signaturesOut,
124
+ coinProofs: [options.coinProof],
125
+ scriptProofs: [buildScriptProof(factory.fundingScript)],
126
+ });
117
127
  const draftBytes = omniaDraftToMinimaBytes(draft.settlementDraft);
118
- const txnDifficulty = await resolveTxPowTarget(chainProvider);
119
- const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
120
- const mined = await mineTxPoW(txBody, txnDifficulty);
121
- const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
122
- await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
123
- payload.txpowId = Buffer.from(mined.txpowId).toString('hex');
128
+ if (chainProvider.submitTransaction) {
129
+ const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
130
+ if (submitted.success === false || !submitted.txpowid) {
131
+ throw new Error(`Factory settlement submission failed: ${submitted.message ?? 'no txpowid'}`);
132
+ }
133
+ payload.txpowId = submitted.txpowid;
134
+ }
135
+ else {
136
+ const txnDifficulty = await resolveTxPowTarget(chainProvider);
137
+ const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
138
+ const mined = await mineTxPoW(txBody, txnDifficulty);
139
+ const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
140
+ const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
141
+ if (broadcast.success === false) {
142
+ throw new Error(`Factory settlement broadcast failed: ${broadcast.message ?? 'unknown error'}`);
143
+ }
144
+ payload.txpowId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
145
+ }
124
146
  }
125
147
  return payload;
126
148
  }
@@ -135,7 +157,7 @@ export async function assembleFactorySettlement(factory, draft, signatures, chai
135
157
  * @param leaseProviders - WOTS lease bundles for ALL N factory participants.
136
158
  * @param chainProvider - Optional: mine + broadcast the settlement TX.
137
159
  */
138
- export async function closeFactory(factory, leaseProviders, chainProvider) {
160
+ export async function closeFactory(factory, leaseProviders, chainProvider, opts) {
139
161
  for (const p of factory.participants) {
140
162
  if (!leaseProviders[p.partyId]) {
141
163
  throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
@@ -155,6 +177,7 @@ export async function closeFactory(factory, leaseProviders, chainProvider) {
155
177
  const fn = bundle?.verify ?? verifyChannelSignature;
156
178
  return fn(sig, digest, pkd);
157
179
  },
180
+ coinProof: opts?.coinProof,
158
181
  });
159
182
  }
160
183
  // ─── buildDisputePayload ──────────────────────────────────────────────────────
package/dist/types.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface FactoryParticipant {
18
18
  fundingCoinId?: string;
19
19
  /** Address to receive funds on cooperative settlement. Falls back to publicKeyDigest. */
20
20
  settlementAddress?: string;
21
+ /** Native transport identity (ed25519 pubkey) from the signed manifest. */
22
+ transportPubkey?: string;
21
23
  }
22
24
  /**
23
25
  * Minimal lease operations required by the factory signing cycle.
@@ -51,6 +53,26 @@ export interface FactoryLeaseOps {
51
53
  * `@totemsdk/core`, allowing test code to inject a no-op verifier without
52
54
  * requiring real WOTS key material.
53
55
  */
56
+ /**
57
+ * On-chain funding material for one factory participant. Required by
58
+ * `createFactory` when the on-chain funding path is used (every participant
59
+ * supplies a `fundingCoinId` and a `chainProvider` is given).
60
+ */
61
+ export interface FactoryFundingMaterial {
62
+ partyId: string;
63
+ /** Serialized Minima CoinProof for this party's funding coin (coinexport `data`). */
64
+ coinProof: Uint8Array;
65
+ /** Address of the funding coin (must match the coin in `coinProof`). */
66
+ coinAddress?: string;
67
+ /** Funding coin script; used to build its ScriptProof when `scriptProof` is absent. */
68
+ script?: string;
69
+ /** Pre-built serialized ScriptProof for the funding coin's address. */
70
+ scriptProof?: Uint8Array;
71
+ /** Sign the funding TX digest with the funding coin's wallet key. */
72
+ signer?: (digest: Uint8Array) => Promise<Uint8Array> | Uint8Array;
73
+ /** Or a pre-computed serialized Signature over the funding digest. */
74
+ signature?: Uint8Array;
75
+ }
54
76
  export interface WotsLeaseBundle {
55
77
  leaseProvider: FactoryLeaseOps;
56
78
  signer: ChannelSigner;
package/dist/virtual.d.ts CHANGED
@@ -56,6 +56,20 @@ export declare function openVirtualChannel(factory: ChannelFactory, parties: [st
56
56
  factory: ChannelFactory;
57
57
  channel: OmniaChannel;
58
58
  }>;
59
+ /** Deterministic VC-close plan (no signing). Exported for peer co-signing. */
60
+ export interface VirtualChannelClosePlan {
61
+ vcId: string;
62
+ finalAllocations: Record<string, bigint>;
63
+ newSequence: number;
64
+ newAllocations: Record<string, bigint>;
65
+ newVcIds: string[];
66
+ commitment: Uint8Array;
67
+ }
68
+ export declare function buildVirtualChannelClose(factory: ChannelFactory, channel: OmniaChannel): VirtualChannelClosePlan;
69
+ /** Produce this party's VC-close signature without committing the lease. */
70
+ export declare function signVirtualChannelClose(factory: ChannelFactory, plan: VirtualChannelClosePlan, bundle: WotsLeaseBundle): Promise<VirtualChannelOpenSignature>;
71
+ /** Assemble N-of-N VC-close signatures into the updated factory. */
72
+ export declare function assembleVirtualChannelClose(factory: ChannelFactory, plan: VirtualChannelClosePlan, signatures: Record<string, VirtualChannelOpenSignature>, verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean): ChannelFactory;
59
73
  /**
60
74
  * Close a virtual channel and return its final balances to factory allocations.
61
75
  *
package/dist/virtual.js CHANGED
@@ -147,12 +147,14 @@ export function assembleVirtualChannelOpen(factory, plan, signatures, verify) {
147
147
  publicKeyDigest: partyAMeta.publicKeyDigest,
148
148
  addressIndex: partyAMeta.addressIndex,
149
149
  settlementAddress: partyAMeta.settlementAddress,
150
+ transportPubkey: partyAMeta.transportPubkey,
150
151
  };
151
152
  const partyB = {
152
153
  partyId: partyBId,
153
154
  publicKeyDigest: partyBMeta.publicKeyDigest,
154
155
  addressIndex: partyBMeta.addressIndex,
155
156
  settlementAddress: partyBMeta.settlementAddress,
157
+ transportPubkey: partyBMeta.transportPubkey,
156
158
  };
157
159
  const channel = {
158
160
  channelId: plan.vcId,
@@ -213,7 +215,86 @@ export async function openVirtualChannel(factory, parties, amounts, leaseProvide
213
215
  return (bundle?.verify ?? verifyChannelSignature)(sig, digest, pkd);
214
216
  });
215
217
  }
216
- // ─── closeVirtualChannel ─────────────────────────────────────────────────────
218
+ export function buildVirtualChannelClose(factory, channel) {
219
+ const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
220
+ if (!existing)
221
+ throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
222
+ const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
223
+ const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
224
+ if (finalSum !== channel.totalValue) {
225
+ throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
226
+ }
227
+ const newSequence = factory.currentSequence + 1;
228
+ const newAllocations = { ...factory.allocations };
229
+ for (const [partyId, amount] of Object.entries(finalAllocations)) {
230
+ newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
231
+ }
232
+ const newVcIds = factory.virtualChannels
233
+ .filter(c => c.channelId !== channel.channelId)
234
+ .map(c => c.channelId);
235
+ const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, newVcIds);
236
+ return {
237
+ vcId: channel.channelId,
238
+ finalAllocations,
239
+ newSequence,
240
+ newAllocations,
241
+ newVcIds,
242
+ commitment,
243
+ };
244
+ }
245
+ /** Produce this party's VC-close signature without committing the lease. */
246
+ export async function signVirtualChannelClose(factory, plan, bundle) {
247
+ const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
248
+ if (!participant) {
249
+ throw new Error('signer.publicKeyDigest does not match any registered factory participant');
250
+ }
251
+ const reservation = await bundle.leaseProvider.reserveKeyUse({
252
+ treeId: `omnia-factory-${factory.factoryId}`,
253
+ purpose: 'factory-vc-close',
254
+ payloadHash: Buffer.from(plan.commitment).toString('hex'),
255
+ });
256
+ let sig;
257
+ try {
258
+ sig = await bundle.signer.sign(plan.commitment, reservation.indices);
259
+ }
260
+ catch (err) {
261
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
262
+ throw err;
263
+ }
264
+ const verifyFn = bundle.verify ?? verifyChannelSignature;
265
+ if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
266
+ await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
267
+ throw new Error(`Virtual-channel close signature verification failed for party '${participant.partyId}'`);
268
+ }
269
+ return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
270
+ }
271
+ /** Assemble N-of-N VC-close signatures into the updated factory. */
272
+ export function assembleVirtualChannelClose(factory, plan, signatures, verify) {
273
+ for (const p of factory.participants) {
274
+ const s = signatures[p.partyId];
275
+ if (!s)
276
+ throw new Error(`Missing virtual-channel close signature for party '${p.partyId}' — close requires all N`);
277
+ if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
278
+ throw new Error(`Virtual-channel close signature verification failed for party '${p.partyId}'`);
279
+ }
280
+ }
281
+ const logEntry = {
282
+ sequence: plan.newSequence,
283
+ timestamp: Date.now(),
284
+ event: 'virtual_close',
285
+ allocations: plan.newAllocations,
286
+ virtualChannelIds: plan.newVcIds,
287
+ };
288
+ const updated = {
289
+ ...factory,
290
+ allocations: plan.newAllocations,
291
+ virtualChannels: factory.virtualChannels.filter(c => c.channelId !== plan.vcId),
292
+ currentSequence: plan.newSequence,
293
+ stateLog: [...factory.stateLog, logEntry],
294
+ };
295
+ enforceConservation(updated);
296
+ return updated;
297
+ }
217
298
  /**
218
299
  * Close a virtual channel and return its final balances to factory allocations.
219
300
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-factory",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Channel factory layer for Omnia — N-of-N MULTISIG funding, virtual channel management, and factory settlement",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -21,16 +21,17 @@
21
21
  "rust/pkg/",
22
22
  "rust/pkg-node/",
23
23
  "README.md",
24
- "LICENSE"
24
+ "LICENSE",
25
+ "NOTICE"
25
26
  ],
26
27
  "dependencies": {
27
- "@totemsdk/core": "^1.4.0",
28
- "@totemsdk/omnia": "^2.2.0",
29
- "@totemsdk/wots-lease": "^1.0.1",
30
- "@totemsdk/tx-builder": "^0.2.1",
31
- "@totemsdk/txpow": "^1.1.0",
32
- "@totemsdk/chain-provider": "^0.3.0",
33
- "@totemsdk/storage": "^0.1.0"
28
+ "@totemsdk/core": "^1.4.2",
29
+ "@totemsdk/omnia": "^2.4.0",
30
+ "@totemsdk/wots-lease": "^1.0.2",
31
+ "@totemsdk/txpow": "^1.1.1",
32
+ "@totemsdk/tx-builder": "^0.2.2",
33
+ "@totemsdk/chain-provider": "^0.3.2",
34
+ "@totemsdk/storage": "^0.2.2"
34
35
  },
35
36
  "devDependencies": {
36
37
  "@types/jest": "^30.0.0",
@@ -45,7 +46,7 @@
45
46
  "publishConfig": {
46
47
  "access": "public"
47
48
  },
48
- "license": "MIT",
49
+ "license": "Apache-2.0",
49
50
  "author": "Totem SDK",
50
51
  "homepage": "https://docs.totem.ing",
51
52
  "bugs": {
@@ -6,7 +6,7 @@
6
6
  ],
7
7
  "description": "Channel factory commitment layer — N-of-N MULTISIG script building, state commitment hashing, balance conservation enforcement (Rust/WASM)",
8
8
  "version": "0.1.0",
9
- "license": "MIT",
9
+ "license": "Apache-2.0",
10
10
  "repository": {
11
11
  "type": "git",
12
12
  "url": "https://github.com/Totem-Edge/totem-sdk"
@@ -5,7 +5,7 @@
5
5
  ],
6
6
  "description": "Channel factory commitment layer — N-of-N MULTISIG script building, state commitment hashing, balance conservation enforcement (Rust/WASM)",
7
7
  "version": "0.1.0",
8
- "license": "MIT",
8
+ "license": "Apache-2.0",
9
9
  "repository": {
10
10
  "type": "git",
11
11
  "url": "https://github.com/Totem-Edge/totem-sdk"