@totemsdk/omnia-factory 0.6.0 → 0.7.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/factory.d.ts +2 -2
- package/dist/cjs/factory.js +63 -11
- package/dist/cjs/index.d.ts +3 -3
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/settlement.d.ts +5 -1
- package/dist/cjs/settlement.js +34 -11
- package/dist/cjs/types.d.ts +22 -0
- package/dist/cjs/virtual.d.ts +14 -0
- package/dist/cjs/virtual.js +83 -1
- package/dist/factory.d.ts +2 -2
- package/dist/factory.js +64 -12
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/settlement.d.ts +5 -1
- package/dist/settlement.js +35 -12
- package/dist/types.d.ts +22 -0
- package/dist/virtual.d.ts +14 -0
- package/dist/virtual.js +80 -1
- package/package.json +3 -3
package/dist/cjs/factory.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
2
|
-
import type { ChannelFactory, FactoryParticipant, WotsLeaseBundle } from './types.js';
|
|
2
|
+
import type { ChannelFactory, FactoryParticipant, FactoryFundingMaterial, WotsLeaseBundle } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Enforce the factory's balance conservation invariant:
|
|
5
5
|
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
@@ -38,7 +38,7 @@ export declare function enforceConservation(factory: ChannelFactory): void;
|
|
|
38
38
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
39
39
|
* Defaults to 0.
|
|
40
40
|
*/
|
|
41
|
-
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number): Promise<ChannelFactory>;
|
|
41
|
+
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
|
|
42
42
|
/**
|
|
43
43
|
* Counterparty co-signs the factory proposal.
|
|
44
44
|
*
|
package/dist/cjs/factory.js
CHANGED
|
@@ -9,6 +9,7 @@ exports.applyFactorySignature = applyFactorySignature;
|
|
|
9
9
|
exports.reallocate = reallocate;
|
|
10
10
|
const wasm_1 = require("@totemsdk/core/wasm");
|
|
11
11
|
const wasm_2 = require("@totemsdk/core/wasm");
|
|
12
|
+
const core_1 = require("@totemsdk/core");
|
|
12
13
|
const omnia_1 = require("@totemsdk/omnia");
|
|
13
14
|
const txpow_1 = require("@totemsdk/txpow");
|
|
14
15
|
const script_js_1 = require("./script.js");
|
|
@@ -118,7 +119,7 @@ function generateFactoryId(participants, tokenId, tokenScale) {
|
|
|
118
119
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
119
120
|
* Defaults to 0.
|
|
120
121
|
*/
|
|
121
|
-
async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
|
|
122
|
+
async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
|
|
122
123
|
if (participants.length < 2) {
|
|
123
124
|
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
124
125
|
}
|
|
@@ -140,19 +141,70 @@ async function createFactory(participants, tokenId, bundle, chainProvider, token
|
|
|
140
141
|
let pendingCommitment;
|
|
141
142
|
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
142
143
|
if (allHaveCoinId && chainProvider) {
|
|
144
|
+
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
145
|
+
// The transaction input address must be the *funding coin's* address, not
|
|
146
|
+
// the participant's settlement address. Callers supply it directly or via
|
|
147
|
+
// the funding coin script.
|
|
148
|
+
const inputAddresses = participants.map(p => {
|
|
149
|
+
const m = materialByParty.get(p.partyId);
|
|
150
|
+
return m?.coinAddress ?? (m?.script ? (0, core_1.computeScriptAddress)(m.script) : '');
|
|
151
|
+
});
|
|
152
|
+
if (inputAddresses.some(a => !a)) {
|
|
153
|
+
throw new Error('createFactory on-chain requires funding material (coinAddress or script) for every participant');
|
|
154
|
+
}
|
|
143
155
|
const tip = await chainProvider.getTip();
|
|
144
156
|
const escapeBlock = tip.block + script_js_1.FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
145
|
-
const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount),
|
|
146
|
-
//
|
|
147
|
-
pendingCommitment = (0, omnia_1.
|
|
157
|
+
const fundingDraft = (0, omnia_1.buildFundingTx)(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...(0, script_js_1.factoryBalanceStateVariables)(participants), (0, script_js_1.factoryEscapeStateVariable)(escapeBlock)]);
|
|
158
|
+
// Production signatures must cover the canonical Minima transaction ID.
|
|
159
|
+
pendingCommitment = (0, omnia_1.computeOmniaTxDigest)(fundingDraft);
|
|
160
|
+
// Assemble the real witness: one CoinProof + ScriptProof + signature per
|
|
161
|
+
// input coin (the factory's own MULTISIG script is the *output* script).
|
|
162
|
+
const signatures = [];
|
|
163
|
+
const coinProofs = [];
|
|
164
|
+
const scriptProofs = [];
|
|
165
|
+
for (const p of participants) {
|
|
166
|
+
const m = materialByParty.get(p.partyId);
|
|
167
|
+
if (!m)
|
|
168
|
+
throw new Error(`Missing funding material for factory party '${p.partyId}'`);
|
|
169
|
+
coinProofs.push(m.coinProof);
|
|
170
|
+
let scriptProof = m.scriptProof;
|
|
171
|
+
if (!scriptProof) {
|
|
172
|
+
if (!m.script)
|
|
173
|
+
throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
|
|
174
|
+
scriptProof = (0, core_1.buildScriptProof)(m.script);
|
|
175
|
+
}
|
|
176
|
+
scriptProofs.push(scriptProof);
|
|
177
|
+
if (m.signature) {
|
|
178
|
+
signatures.push(m.signature);
|
|
179
|
+
}
|
|
180
|
+
else if (m.signer) {
|
|
181
|
+
signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
148
187
|
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(fundingDraft);
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
188
|
+
const witnessBytes = (0, omnia_1.serializeOmniaWitness)({ signatures, coinProofs, scriptProofs });
|
|
189
|
+
if (chainProvider.submitTransaction) {
|
|
190
|
+
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
191
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
192
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
193
|
+
}
|
|
194
|
+
fundingTxId = submitted.txpowid;
|
|
195
|
+
}
|
|
196
|
+
else {
|
|
197
|
+
const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
|
|
198
|
+
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
|
|
199
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
|
|
200
|
+
const fullTxPoW = (0, wasm_2.concatBytes)((0, wasm_2.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
201
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
202
|
+
if (broadcast.success === false) {
|
|
203
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
204
|
+
}
|
|
205
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
206
|
+
}
|
|
207
|
+
fundingCoinId = (0, omnia_1.minimaOutputCoinIdsForDraft)(fundingDraft)[0];
|
|
156
208
|
}
|
|
157
209
|
else {
|
|
158
210
|
// In-memory / test path: sign the factory state commitment instead.
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
1
|
+
export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
2
2
|
export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
|
|
3
3
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
4
|
export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
|
|
5
5
|
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
6
|
export type { FactoryOpeningSignature } from './factory.js';
|
|
7
7
|
export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
|
|
8
|
-
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
9
|
-
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, } from './virtual.js';
|
|
8
|
+
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
9
|
+
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, VirtualChannelClosePlan, } from './virtual.js';
|
|
10
10
|
export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
11
11
|
export type { FactorySettlementDraft, FactorySettlementSignature, } from './settlement.js';
|
|
12
12
|
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
|
|
3
|
+
exports.createDurableFactoryStore = exports.assembleFactorySettlement = exports.verifyFactorySettlementSignature = exports.signFactorySettlement = exports.buildFactorySettlement = exports.buildDisputePayload = exports.closeFactory = exports.assembleVirtualChannelOpen = exports.verifyVirtualChannelOpenSignature = exports.assembleVirtualChannelClose = exports.signVirtualChannelClose = exports.buildVirtualChannelClose = exports.signVirtualChannelOpen = exports.buildVirtualChannelOpen = exports.closeVirtualChannel = exports.openVirtualChannel = exports.createFactoryCoordination = exports.applyFactorySignature = exports.verifyFactorySignature = exports.signFactoryOpening = exports.enforceConservation = exports.reallocate = exports.acceptFactory = exports.createFactory = exports.computeFactoryStateCommitment = exports.normalizeScript = exports.scriptAddress = exports.MSHS_PORT_FLOOR = exports.FACTORY_BALANCE_ROOT_PORT = exports.FACTORY_PARTY_ROOT_PORT = exports.FACTORY_MAX_PARTICIPANTS = exports.FACTORY_ESCAPE_DELAY_BLOCKS = exports.FACTORY_ESCAPE_PORT = exports.FACTORY_BALANCE_PORT_BASE = exports.buildFactoryDistributionScript = exports.factoryDistributionOutputs = exports.factoryBalanceProof = exports.factoryBalanceSetRoot = exports.factoryPartyProof = exports.factoryPartyRootStateVariable = exports.factoryPartySetRoot = exports.factoryEscapeStateVariable = exports.factoryBalanceStateVariables = exports.buildAndHashFactoryScript = exports.buildFactoryScript = void 0;
|
|
4
4
|
var script_js_1 = require("./script.js");
|
|
5
5
|
Object.defineProperty(exports, "buildFactoryScript", { enumerable: true, get: function () { return script_js_1.buildFactoryScript; } });
|
|
6
6
|
Object.defineProperty(exports, "buildAndHashFactoryScript", { enumerable: true, get: function () { return script_js_1.buildAndHashFactoryScript; } });
|
|
@@ -40,6 +40,9 @@ Object.defineProperty(exports, "openVirtualChannel", { enumerable: true, get: fu
|
|
|
40
40
|
Object.defineProperty(exports, "closeVirtualChannel", { enumerable: true, get: function () { return virtual_js_1.closeVirtualChannel; } });
|
|
41
41
|
Object.defineProperty(exports, "buildVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.buildVirtualChannelOpen; } });
|
|
42
42
|
Object.defineProperty(exports, "signVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.signVirtualChannelOpen; } });
|
|
43
|
+
Object.defineProperty(exports, "buildVirtualChannelClose", { enumerable: true, get: function () { return virtual_js_1.buildVirtualChannelClose; } });
|
|
44
|
+
Object.defineProperty(exports, "signVirtualChannelClose", { enumerable: true, get: function () { return virtual_js_1.signVirtualChannelClose; } });
|
|
45
|
+
Object.defineProperty(exports, "assembleVirtualChannelClose", { enumerable: true, get: function () { return virtual_js_1.assembleVirtualChannelClose; } });
|
|
43
46
|
Object.defineProperty(exports, "verifyVirtualChannelOpenSignature", { enumerable: true, get: function () { return virtual_js_1.verifyVirtualChannelOpenSignature; } });
|
|
44
47
|
Object.defineProperty(exports, "assembleVirtualChannelOpen", { enumerable: true, get: function () { return virtual_js_1.assembleVirtualChannelOpen; } });
|
|
45
48
|
var settlement_js_1 = require("./settlement.js");
|
package/dist/cjs/settlement.d.ts
CHANGED
|
@@ -31,6 +31,8 @@ export declare function verifyFactorySettlementSignature(factory: ChannelFactory
|
|
|
31
31
|
*/
|
|
32
32
|
export declare function assembleFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, signatures: Record<string, FactorySettlementSignature>, chainProvider?: ChainStateProvider, options?: {
|
|
33
33
|
verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean;
|
|
34
|
+
/** Serialized CoinProof for the factory's shared UTXO (coinexport `data`). */
|
|
35
|
+
coinProof?: Uint8Array;
|
|
34
36
|
}): Promise<FactorySettlementPayload>;
|
|
35
37
|
/**
|
|
36
38
|
* Cooperative N-of-N factory close (central/local path).
|
|
@@ -43,7 +45,9 @@ export declare function assembleFactorySettlement(factory: ChannelFactory, draft
|
|
|
43
45
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
44
46
|
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
45
47
|
*/
|
|
46
|
-
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider
|
|
48
|
+
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider, opts?: {
|
|
49
|
+
coinProof?: Uint8Array;
|
|
50
|
+
}): Promise<FactorySettlementPayload>;
|
|
47
51
|
/**
|
|
48
52
|
* Build a unilateral factory close (dispute) payload.
|
|
49
53
|
*
|
package/dist/cjs/settlement.js
CHANGED
|
@@ -7,6 +7,7 @@ exports.assembleFactorySettlement = assembleFactorySettlement;
|
|
|
7
7
|
exports.closeFactory = closeFactory;
|
|
8
8
|
exports.buildDisputePayload = buildDisputePayload;
|
|
9
9
|
const wasm_1 = require("@totemsdk/core/wasm");
|
|
10
|
+
const core_1 = require("@totemsdk/core");
|
|
10
11
|
const omnia_1 = require("@totemsdk/omnia");
|
|
11
12
|
const txpow_1 = require("@totemsdk/txpow");
|
|
12
13
|
/**
|
|
@@ -54,7 +55,7 @@ function buildFactorySettlement(factory) {
|
|
|
54
55
|
return {
|
|
55
56
|
settlementDraft,
|
|
56
57
|
settlementTxHex: (0, omnia_1.serializeTxDraft)(settlementDraft),
|
|
57
|
-
txDigest: (0, omnia_1.
|
|
58
|
+
txDigest: (0, omnia_1.computeOmniaTxDigest)(settlementDraft),
|
|
58
59
|
};
|
|
59
60
|
}
|
|
60
61
|
/**
|
|
@@ -104,7 +105,7 @@ function verifyFactorySettlementSignature(factory, txDigest, partyId, signature,
|
|
|
104
105
|
* (when a `chainProvider` is given) mine + broadcast the settlement TxPoW.
|
|
105
106
|
*/
|
|
106
107
|
async function assembleFactorySettlement(factory, draft, signatures, chainProvider, options) {
|
|
107
|
-
const
|
|
108
|
+
const signaturesOut = [];
|
|
108
109
|
for (const p of factory.participants) {
|
|
109
110
|
const s = signatures[p.partyId];
|
|
110
111
|
if (!s)
|
|
@@ -112,9 +113,8 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
112
113
|
if (!verifyFactorySettlementSignature(factory, draft.txDigest, p.partyId, s.signature, options?.verify)) {
|
|
113
114
|
throw new Error(`Settlement signature verification failed for party '${p.partyId}'`);
|
|
114
115
|
}
|
|
115
|
-
|
|
116
|
+
signaturesOut.push(s.signature);
|
|
116
117
|
}
|
|
117
|
-
const witnessBytes = witnessParts.reduce((a, b) => (0, wasm_1.concatBytes)(a, b));
|
|
118
118
|
const payload = {
|
|
119
119
|
factoryId: factory.factoryId,
|
|
120
120
|
sequence: factory.currentSequence,
|
|
@@ -122,13 +122,35 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
122
122
|
finalAllocations: { ...factory.allocations },
|
|
123
123
|
};
|
|
124
124
|
if (chainProvider) {
|
|
125
|
+
if (!options?.coinProof) {
|
|
126
|
+
throw new Error('closeFactory broadcast requires the factory coin proof (coinexport data)');
|
|
127
|
+
}
|
|
128
|
+
// The settlement input is the factory's N-of-N MULTISIG UTXO; the witness
|
|
129
|
+
// needs all N signatures + the coin proof + the funding-script proof.
|
|
130
|
+
const witnessBytes = (0, omnia_1.serializeOmniaWitness)({
|
|
131
|
+
signatures: signaturesOut,
|
|
132
|
+
coinProofs: [options.coinProof],
|
|
133
|
+
scriptProofs: [(0, core_1.buildScriptProof)(factory.fundingScript)],
|
|
134
|
+
});
|
|
125
135
|
const draftBytes = (0, omnia_1.omniaDraftToMinimaBytes)(draft.settlementDraft);
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
if (chainProvider.submitTransaction) {
|
|
137
|
+
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
138
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
139
|
+
throw new Error(`Factory settlement submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
140
|
+
}
|
|
141
|
+
payload.txpowId = submitted.txpowid;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
const txnDifficulty = await (0, txpow_1.resolveTxPowTarget)(chainProvider);
|
|
145
|
+
const txBody = (0, txpow_1.serializeTxBody)(draftBytes, witnessBytes, { txnDifficulty });
|
|
146
|
+
const mined = await (0, txpow_1.mineTxPoW)(txBody, txnDifficulty);
|
|
147
|
+
const fullTxPoW = (0, wasm_1.concatBytes)((0, wasm_1.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
148
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
149
|
+
if (broadcast.success === false) {
|
|
150
|
+
throw new Error(`Factory settlement broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
151
|
+
}
|
|
152
|
+
payload.txpowId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
153
|
+
}
|
|
132
154
|
}
|
|
133
155
|
return payload;
|
|
134
156
|
}
|
|
@@ -143,7 +165,7 @@ async function assembleFactorySettlement(factory, draft, signatures, chainProvid
|
|
|
143
165
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
144
166
|
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
145
167
|
*/
|
|
146
|
-
async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
168
|
+
async function closeFactory(factory, leaseProviders, chainProvider, opts) {
|
|
147
169
|
for (const p of factory.participants) {
|
|
148
170
|
if (!leaseProviders[p.partyId]) {
|
|
149
171
|
throw new Error(`Missing WotsLeaseBundle for party '${p.partyId}' — closeFactory requires all N`);
|
|
@@ -163,6 +185,7 @@ async function closeFactory(factory, leaseProviders, chainProvider) {
|
|
|
163
185
|
const fn = bundle?.verify ?? omnia_1.verifyChannelSignature;
|
|
164
186
|
return fn(sig, digest, pkd);
|
|
165
187
|
},
|
|
188
|
+
coinProof: opts?.coinProof,
|
|
166
189
|
});
|
|
167
190
|
}
|
|
168
191
|
// ─── buildDisputePayload ──────────────────────────────────────────────────────
|
package/dist/cjs/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/cjs/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/cjs/virtual.js
CHANGED
|
@@ -5,6 +5,9 @@ exports.signVirtualChannelOpen = signVirtualChannelOpen;
|
|
|
5
5
|
exports.verifyVirtualChannelOpenSignature = verifyVirtualChannelOpenSignature;
|
|
6
6
|
exports.assembleVirtualChannelOpen = assembleVirtualChannelOpen;
|
|
7
7
|
exports.openVirtualChannel = openVirtualChannel;
|
|
8
|
+
exports.buildVirtualChannelClose = buildVirtualChannelClose;
|
|
9
|
+
exports.signVirtualChannelClose = signVirtualChannelClose;
|
|
10
|
+
exports.assembleVirtualChannelClose = assembleVirtualChannelClose;
|
|
8
11
|
exports.closeVirtualChannel = closeVirtualChannel;
|
|
9
12
|
const omnia_1 = require("@totemsdk/omnia");
|
|
10
13
|
const factory_js_1 = require("./factory.js");
|
|
@@ -221,7 +224,86 @@ async function openVirtualChannel(factory, parties, amounts, leaseProviders, cha
|
|
|
221
224
|
return (bundle?.verify ?? omnia_1.verifyChannelSignature)(sig, digest, pkd);
|
|
222
225
|
});
|
|
223
226
|
}
|
|
224
|
-
|
|
227
|
+
function buildVirtualChannelClose(factory, channel) {
|
|
228
|
+
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
229
|
+
if (!existing)
|
|
230
|
+
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
231
|
+
const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
|
|
232
|
+
const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
|
|
233
|
+
if (finalSum !== channel.totalValue) {
|
|
234
|
+
throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
|
|
235
|
+
}
|
|
236
|
+
const newSequence = factory.currentSequence + 1;
|
|
237
|
+
const newAllocations = { ...factory.allocations };
|
|
238
|
+
for (const [partyId, amount] of Object.entries(finalAllocations)) {
|
|
239
|
+
newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
|
|
240
|
+
}
|
|
241
|
+
const newVcIds = factory.virtualChannels
|
|
242
|
+
.filter(c => c.channelId !== channel.channelId)
|
|
243
|
+
.map(c => c.channelId);
|
|
244
|
+
const commitment = (0, commitment_js_1.computeFactoryStateCommitment)(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
245
|
+
return {
|
|
246
|
+
vcId: channel.channelId,
|
|
247
|
+
finalAllocations,
|
|
248
|
+
newSequence,
|
|
249
|
+
newAllocations,
|
|
250
|
+
newVcIds,
|
|
251
|
+
commitment,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
/** Produce this party's VC-close signature without committing the lease. */
|
|
255
|
+
async function signVirtualChannelClose(factory, plan, bundle) {
|
|
256
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
257
|
+
if (!participant) {
|
|
258
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
259
|
+
}
|
|
260
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
261
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
262
|
+
purpose: 'factory-vc-close',
|
|
263
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
264
|
+
});
|
|
265
|
+
let sig;
|
|
266
|
+
try {
|
|
267
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
271
|
+
throw err;
|
|
272
|
+
}
|
|
273
|
+
const verifyFn = bundle.verify ?? omnia_1.verifyChannelSignature;
|
|
274
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
275
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
276
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${participant.partyId}'`);
|
|
277
|
+
}
|
|
278
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
279
|
+
}
|
|
280
|
+
/** Assemble N-of-N VC-close signatures into the updated factory. */
|
|
281
|
+
function assembleVirtualChannelClose(factory, plan, signatures, verify) {
|
|
282
|
+
for (const p of factory.participants) {
|
|
283
|
+
const s = signatures[p.partyId];
|
|
284
|
+
if (!s)
|
|
285
|
+
throw new Error(`Missing virtual-channel close signature for party '${p.partyId}' — close requires all N`);
|
|
286
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
287
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${p.partyId}'`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const logEntry = {
|
|
291
|
+
sequence: plan.newSequence,
|
|
292
|
+
timestamp: Date.now(),
|
|
293
|
+
event: 'virtual_close',
|
|
294
|
+
allocations: plan.newAllocations,
|
|
295
|
+
virtualChannelIds: plan.newVcIds,
|
|
296
|
+
};
|
|
297
|
+
const updated = {
|
|
298
|
+
...factory,
|
|
299
|
+
allocations: plan.newAllocations,
|
|
300
|
+
virtualChannels: factory.virtualChannels.filter(c => c.channelId !== plan.vcId),
|
|
301
|
+
currentSequence: plan.newSequence,
|
|
302
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
303
|
+
};
|
|
304
|
+
(0, factory_js_1.enforceConservation)(updated);
|
|
305
|
+
return updated;
|
|
306
|
+
}
|
|
225
307
|
/**
|
|
226
308
|
* Close a virtual channel and return its final balances to factory allocations.
|
|
227
309
|
*
|
package/dist/factory.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
2
|
-
import type { ChannelFactory, FactoryParticipant, WotsLeaseBundle } from './types.js';
|
|
2
|
+
import type { ChannelFactory, FactoryParticipant, FactoryFundingMaterial, WotsLeaseBundle } from './types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Enforce the factory's balance conservation invariant:
|
|
5
5
|
* sum(allocations) + sum(virtualChannel.totalValue) === totalValue
|
|
@@ -38,7 +38,7 @@ export declare function enforceConservation(factory: ChannelFactory): void;
|
|
|
38
38
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
39
39
|
* Defaults to 0.
|
|
40
40
|
*/
|
|
41
|
-
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number): Promise<ChannelFactory>;
|
|
41
|
+
export declare function createFactory(participants: FactoryParticipant[], tokenId: string, bundle: WotsLeaseBundle, chainProvider?: ChainStateProvider, tokenScale?: number, funding?: FactoryFundingMaterial[]): Promise<ChannelFactory>;
|
|
42
42
|
/**
|
|
43
43
|
* Counterparty co-signs the factory proposal.
|
|
44
44
|
*
|
package/dist/factory.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { sha3_256 } from '@totemsdk/core/wasm';
|
|
2
2
|
import { concatBytes } from '@totemsdk/core/wasm';
|
|
3
|
-
import {
|
|
3
|
+
import { buildScriptProof, computeScriptAddress } from '@totemsdk/core';
|
|
4
|
+
import { buildFundingTx, omniaDraftToMinimaBytes, computeOmniaTxDigest, minimaOutputCoinIdsForDraft, serializeOmniaWitness, verifyChannelSignature, } from '@totemsdk/omnia';
|
|
4
5
|
import { mineTxPoW, resolveTxPowTarget, serializeTxBody } from '@totemsdk/txpow';
|
|
5
6
|
import { buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, FACTORY_ESCAPE_DELAY_BLOCKS } from './script.js';
|
|
6
7
|
import { computeFactoryStateCommitment } from './commitment.js';
|
|
@@ -109,7 +110,7 @@ function generateFactoryId(participants, tokenId, tokenScale) {
|
|
|
109
110
|
* is 0; coloured coins use `tokenAmount = minimaRawAmount × 10^scale`.
|
|
110
111
|
* Defaults to 0.
|
|
111
112
|
*/
|
|
112
|
-
export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0) {
|
|
113
|
+
export async function createFactory(participants, tokenId, bundle, chainProvider, tokenScale = 0, funding) {
|
|
113
114
|
if (participants.length < 2) {
|
|
114
115
|
throw new Error(`Factory requires at least 2 participants, got ${participants.length}`);
|
|
115
116
|
}
|
|
@@ -131,19 +132,70 @@ export async function createFactory(participants, tokenId, bundle, chainProvider
|
|
|
131
132
|
let pendingCommitment;
|
|
132
133
|
const allHaveCoinId = participants.every(p => p.fundingCoinId);
|
|
133
134
|
if (allHaveCoinId && chainProvider) {
|
|
135
|
+
const materialByParty = new Map((funding ?? []).map(m => [m.partyId, m]));
|
|
136
|
+
// The transaction input address must be the *funding coin's* address, not
|
|
137
|
+
// the participant's settlement address. Callers supply it directly or via
|
|
138
|
+
// the funding coin script.
|
|
139
|
+
const inputAddresses = participants.map(p => {
|
|
140
|
+
const m = materialByParty.get(p.partyId);
|
|
141
|
+
return m?.coinAddress ?? (m?.script ? computeScriptAddress(m.script) : '');
|
|
142
|
+
});
|
|
143
|
+
if (inputAddresses.some(a => !a)) {
|
|
144
|
+
throw new Error('createFactory on-chain requires funding material (coinAddress or script) for every participant');
|
|
145
|
+
}
|
|
134
146
|
const tip = await chainProvider.getTip();
|
|
135
147
|
const escapeBlock = tip.block + FACTORY_ESCAPE_DELAY_BLOCKS;
|
|
136
|
-
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount),
|
|
137
|
-
//
|
|
138
|
-
pendingCommitment =
|
|
148
|
+
const fundingDraft = buildFundingTx(script, address, totalValue, tokenId, tokenScale, participants.map(p => p.fundingCoinId), participants.map(p => p.contributionAmount), inputAddresses, [...factoryBalanceStateVariables(participants), factoryEscapeStateVariable(escapeBlock)]);
|
|
149
|
+
// Production signatures must cover the canonical Minima transaction ID.
|
|
150
|
+
pendingCommitment = computeOmniaTxDigest(fundingDraft);
|
|
151
|
+
// Assemble the real witness: one CoinProof + ScriptProof + signature per
|
|
152
|
+
// input coin (the factory's own MULTISIG script is the *output* script).
|
|
153
|
+
const signatures = [];
|
|
154
|
+
const coinProofs = [];
|
|
155
|
+
const scriptProofs = [];
|
|
156
|
+
for (const p of participants) {
|
|
157
|
+
const m = materialByParty.get(p.partyId);
|
|
158
|
+
if (!m)
|
|
159
|
+
throw new Error(`Missing funding material for factory party '${p.partyId}'`);
|
|
160
|
+
coinProofs.push(m.coinProof);
|
|
161
|
+
let scriptProof = m.scriptProof;
|
|
162
|
+
if (!scriptProof) {
|
|
163
|
+
if (!m.script)
|
|
164
|
+
throw new Error(`Missing script or scriptProof for factory party '${p.partyId}'`);
|
|
165
|
+
scriptProof = buildScriptProof(m.script);
|
|
166
|
+
}
|
|
167
|
+
scriptProofs.push(scriptProof);
|
|
168
|
+
if (m.signature) {
|
|
169
|
+
signatures.push(m.signature);
|
|
170
|
+
}
|
|
171
|
+
else if (m.signer) {
|
|
172
|
+
signatures.push(Uint8Array.from(await m.signer(pendingCommitment)));
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
throw new Error(`Missing signature or signer for factory party '${p.partyId}'`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
139
178
|
const draftBytes = omniaDraftToMinimaBytes(fundingDraft);
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
179
|
+
const witnessBytes = serializeOmniaWitness({ signatures, coinProofs, scriptProofs });
|
|
180
|
+
if (chainProvider.submitTransaction) {
|
|
181
|
+
const submitted = await chainProvider.submitTransaction(draftBytes, witnessBytes);
|
|
182
|
+
if (submitted.success === false || !submitted.txpowid) {
|
|
183
|
+
throw new Error(`Factory funding submission failed: ${submitted.message ?? 'no txpowid'}`);
|
|
184
|
+
}
|
|
185
|
+
fundingTxId = submitted.txpowid;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
const txnDifficulty = await resolveTxPowTarget(chainProvider);
|
|
189
|
+
const txBody = serializeTxBody(draftBytes, witnessBytes, { txnDifficulty });
|
|
190
|
+
const mined = await mineTxPoW(txBody, txnDifficulty);
|
|
191
|
+
const fullTxPoW = concatBytes(concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
|
|
192
|
+
const broadcast = await chainProvider.broadcastTxPoW(Buffer.from(fullTxPoW).toString('hex'));
|
|
193
|
+
if (broadcast.success === false) {
|
|
194
|
+
throw new Error(`Factory funding broadcast failed: ${broadcast.message ?? 'unknown error'}`);
|
|
195
|
+
}
|
|
196
|
+
fundingTxId = broadcast.txpowid ?? Buffer.from(mined.txpowId).toString('hex');
|
|
197
|
+
}
|
|
198
|
+
fundingCoinId = minimaOutputCoinIdsForDraft(fundingDraft)[0];
|
|
147
199
|
}
|
|
148
200
|
else {
|
|
149
201
|
// In-memory / test path: sign the factory state commitment instead.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
export type { FactoryStatus, FactoryParticipant, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
1
|
+
export type { FactoryStatus, FactoryParticipant, FactoryFundingMaterial, FactorySignature, FactoryLogEntry, ChannelFactory, FactorySettlementPayload, FactoryDisputePayload, FactoryLeaseOps, WotsLeaseBundle, OmniaChannel, } from './types.js';
|
|
2
2
|
export { buildFactoryScript, buildAndHashFactoryScript, factoryBalanceStateVariables, factoryEscapeStateVariable, factoryPartySetRoot, factoryPartyRootStateVariable, factoryPartyProof, factoryBalanceSetRoot, factoryBalanceProof, factoryDistributionOutputs, buildFactoryDistributionScript, FACTORY_BALANCE_PORT_BASE, FACTORY_ESCAPE_PORT, FACTORY_ESCAPE_DELAY_BLOCKS, FACTORY_MAX_PARTICIPANTS, FACTORY_PARTY_ROOT_PORT, FACTORY_BALANCE_ROOT_PORT, MSHS_PORT_FLOOR, scriptAddress, normalizeScript, } from './script.js';
|
|
3
3
|
export { computeFactoryStateCommitment } from './commitment.js';
|
|
4
4
|
export type { FactoryDistributionOutput, FactoryDistributionScriptConfig } from './script.js';
|
|
5
5
|
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
6
6
|
export type { FactoryOpeningSignature } from './factory.js';
|
|
7
7
|
export { createFactoryCoordination, type FactoryCoordination, type FactoryCoordinationDeps, type FactoryApproval, type FactoryApprovalRequest, } from './coordination.js';
|
|
8
|
-
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
9
|
-
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, } from './virtual.js';
|
|
8
|
+
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
9
|
+
export type { VirtualChannelOpenPlan, VirtualChannelOpenSignature, VirtualChannelClosePlan, } from './virtual.js';
|
|
10
10
|
export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
11
11
|
export type { FactorySettlementDraft, FactorySettlementSignature, } from './settlement.js';
|
|
12
12
|
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,6 @@ export { computeFactoryStateCommitment } from './commitment.js';
|
|
|
3
3
|
export { createFactory, acceptFactory, reallocate, enforceConservation, signFactoryOpening, verifyFactorySignature, applyFactorySignature, } from './factory.js';
|
|
4
4
|
// RFC-035 B2 — factory opening round-trip over the coordination transport.
|
|
5
5
|
export { createFactoryCoordination, } from './coordination.js';
|
|
6
|
-
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
6
|
+
export { openVirtualChannel, closeVirtualChannel, buildVirtualChannelOpen, signVirtualChannelOpen, buildVirtualChannelClose, signVirtualChannelClose, assembleVirtualChannelClose, verifyVirtualChannelOpenSignature, assembleVirtualChannelOpen, } from './virtual.js';
|
|
7
7
|
export { closeFactory, buildDisputePayload, buildFactorySettlement, signFactorySettlement, verifyFactorySettlementSignature, assembleFactorySettlement, } from './settlement.js';
|
|
8
8
|
export { createDurableFactoryStore, } from './durable-factory-store.js';
|
package/dist/settlement.d.ts
CHANGED
|
@@ -31,6 +31,8 @@ export declare function verifyFactorySettlementSignature(factory: ChannelFactory
|
|
|
31
31
|
*/
|
|
32
32
|
export declare function assembleFactorySettlement(factory: ChannelFactory, draft: FactorySettlementDraft, signatures: Record<string, FactorySettlementSignature>, chainProvider?: ChainStateProvider, options?: {
|
|
33
33
|
verify?: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean;
|
|
34
|
+
/** Serialized CoinProof for the factory's shared UTXO (coinexport `data`). */
|
|
35
|
+
coinProof?: Uint8Array;
|
|
34
36
|
}): Promise<FactorySettlementPayload>;
|
|
35
37
|
/**
|
|
36
38
|
* Cooperative N-of-N factory close (central/local path).
|
|
@@ -43,7 +45,9 @@ export declare function assembleFactorySettlement(factory: ChannelFactory, draft
|
|
|
43
45
|
* @param leaseProviders - WOTS lease bundles for ALL N factory participants.
|
|
44
46
|
* @param chainProvider - Optional: mine + broadcast the settlement TX.
|
|
45
47
|
*/
|
|
46
|
-
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider
|
|
48
|
+
export declare function closeFactory(factory: ChannelFactory, leaseProviders: Record<string, WotsLeaseBundle>, chainProvider?: ChainStateProvider, opts?: {
|
|
49
|
+
coinProof?: Uint8Array;
|
|
50
|
+
}): Promise<FactorySettlementPayload>;
|
|
47
51
|
/**
|
|
48
52
|
* Build a unilateral factory close (dispute) payload.
|
|
49
53
|
*
|
package/dist/settlement.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { concatBytes } from '@totemsdk/core/wasm';
|
|
2
|
-
import {
|
|
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:
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
@@ -213,7 +213,86 @@ export async function openVirtualChannel(factory, parties, amounts, leaseProvide
|
|
|
213
213
|
return (bundle?.verify ?? verifyChannelSignature)(sig, digest, pkd);
|
|
214
214
|
});
|
|
215
215
|
}
|
|
216
|
-
|
|
216
|
+
export function buildVirtualChannelClose(factory, channel) {
|
|
217
|
+
const existing = factory.virtualChannels.find(c => c.channelId === channel.channelId);
|
|
218
|
+
if (!existing)
|
|
219
|
+
throw new Error(`Virtual channel '${channel.channelId}' not found in factory`);
|
|
220
|
+
const finalAllocations = channel.latestState?.balances ?? { ...channel.balances };
|
|
221
|
+
const finalSum = Object.values(finalAllocations).reduce((a, b) => a + b, 0n);
|
|
222
|
+
if (finalSum !== channel.totalValue) {
|
|
223
|
+
throw new Error(`Final balance sum (${finalSum}) !== channel totalValue (${channel.totalValue})`);
|
|
224
|
+
}
|
|
225
|
+
const newSequence = factory.currentSequence + 1;
|
|
226
|
+
const newAllocations = { ...factory.allocations };
|
|
227
|
+
for (const [partyId, amount] of Object.entries(finalAllocations)) {
|
|
228
|
+
newAllocations[partyId] = (newAllocations[partyId] ?? 0n) + amount;
|
|
229
|
+
}
|
|
230
|
+
const newVcIds = factory.virtualChannels
|
|
231
|
+
.filter(c => c.channelId !== channel.channelId)
|
|
232
|
+
.map(c => c.channelId);
|
|
233
|
+
const commitment = computeFactoryStateCommitment(factory.factoryId, newSequence, newAllocations, newVcIds);
|
|
234
|
+
return {
|
|
235
|
+
vcId: channel.channelId,
|
|
236
|
+
finalAllocations,
|
|
237
|
+
newSequence,
|
|
238
|
+
newAllocations,
|
|
239
|
+
newVcIds,
|
|
240
|
+
commitment,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/** Produce this party's VC-close signature without committing the lease. */
|
|
244
|
+
export async function signVirtualChannelClose(factory, plan, bundle) {
|
|
245
|
+
const participant = factory.participants.find(p => p.publicKeyDigest === bundle.signer.publicKeyDigest);
|
|
246
|
+
if (!participant) {
|
|
247
|
+
throw new Error('signer.publicKeyDigest does not match any registered factory participant');
|
|
248
|
+
}
|
|
249
|
+
const reservation = await bundle.leaseProvider.reserveKeyUse({
|
|
250
|
+
treeId: `omnia-factory-${factory.factoryId}`,
|
|
251
|
+
purpose: 'factory-vc-close',
|
|
252
|
+
payloadHash: Buffer.from(plan.commitment).toString('hex'),
|
|
253
|
+
});
|
|
254
|
+
let sig;
|
|
255
|
+
try {
|
|
256
|
+
sig = await bundle.signer.sign(plan.commitment, reservation.indices);
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'sign-failed').catch(() => { });
|
|
260
|
+
throw err;
|
|
261
|
+
}
|
|
262
|
+
const verifyFn = bundle.verify ?? verifyChannelSignature;
|
|
263
|
+
if (!verifyFn(sig, plan.commitment, participant.publicKeyDigest)) {
|
|
264
|
+
await bundle.leaseProvider.burnReservation(reservation.reservationId, 'verification-failed').catch(() => { });
|
|
265
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${participant.partyId}'`);
|
|
266
|
+
}
|
|
267
|
+
return { partyId: participant.partyId, signature: sig, reservationId: reservation.reservationId };
|
|
268
|
+
}
|
|
269
|
+
/** Assemble N-of-N VC-close signatures into the updated factory. */
|
|
270
|
+
export function assembleVirtualChannelClose(factory, plan, signatures, verify) {
|
|
271
|
+
for (const p of factory.participants) {
|
|
272
|
+
const s = signatures[p.partyId];
|
|
273
|
+
if (!s)
|
|
274
|
+
throw new Error(`Missing virtual-channel close signature for party '${p.partyId}' — close requires all N`);
|
|
275
|
+
if (!verifyVirtualChannelOpenSignature(factory, plan.commitment, p.partyId, s.signature, verify)) {
|
|
276
|
+
throw new Error(`Virtual-channel close signature verification failed for party '${p.partyId}'`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const logEntry = {
|
|
280
|
+
sequence: plan.newSequence,
|
|
281
|
+
timestamp: Date.now(),
|
|
282
|
+
event: 'virtual_close',
|
|
283
|
+
allocations: plan.newAllocations,
|
|
284
|
+
virtualChannelIds: plan.newVcIds,
|
|
285
|
+
};
|
|
286
|
+
const updated = {
|
|
287
|
+
...factory,
|
|
288
|
+
allocations: plan.newAllocations,
|
|
289
|
+
virtualChannels: factory.virtualChannels.filter(c => c.channelId !== plan.vcId),
|
|
290
|
+
currentSequence: plan.newSequence,
|
|
291
|
+
stateLog: [...factory.stateLog, logEntry],
|
|
292
|
+
};
|
|
293
|
+
enforceConservation(updated);
|
|
294
|
+
return updated;
|
|
295
|
+
}
|
|
217
296
|
/**
|
|
218
297
|
* Close a virtual channel and return its final balances to factory allocations.
|
|
219
298
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@totemsdk/omnia-factory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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",
|
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
"LICENSE"
|
|
25
25
|
],
|
|
26
26
|
"dependencies": {
|
|
27
|
+
"@totemsdk/tx-builder": "^0.2.1",
|
|
27
28
|
"@totemsdk/core": "^1.4.0",
|
|
28
|
-
"@totemsdk/omnia": "^2.2.0",
|
|
29
29
|
"@totemsdk/wots-lease": "^1.0.1",
|
|
30
|
-
"@totemsdk/
|
|
30
|
+
"@totemsdk/omnia": "^2.3.0",
|
|
31
31
|
"@totemsdk/txpow": "^1.1.0",
|
|
32
32
|
"@totemsdk/chain-provider": "^0.3.0",
|
|
33
33
|
"@totemsdk/storage": "^0.1.0"
|