@totemsdk/omnia-splice 0.2.1 → 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.
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.finalizeSplice = finalizeSplice;
4
+ const core_1 = require("@totemsdk/core");
5
+ const txpow_1 = require("@totemsdk/txpow");
6
+ const omnia_1 = require("@totemsdk/omnia");
7
+ const splice_tx_js_1 = require("./splice-tx.js");
8
+ const errors_js_1 = require("./errors.js");
9
+ function defaultWotsVerify(sig, digest, pkd) {
10
+ return (0, omnia_1.verifyChannelSignature)(sig, digest, pkd);
11
+ }
12
+ function assembleSpliceWitness(sig1, sig2) {
13
+ const encodeMiniNumber = (n) => {
14
+ const buf = new Uint8Array(4);
15
+ new DataView(buf.buffer).setInt32(0, n, false);
16
+ return buf;
17
+ };
18
+ const encodeVarBytes = (b) => {
19
+ const lenBuf = new Uint8Array(4);
20
+ new DataView(lenBuf.buffer).setInt32(0, b.length, false);
21
+ return (0, core_1.concatBytes)(lenBuf, b);
22
+ };
23
+ return (0, core_1.concatBytes)((0, core_1.concatBytes)((0, core_1.concatBytes)((0, core_1.concatBytes)(encodeMiniNumber(2), encodeVarBytes(sig1)), encodeVarBytes(sig2)), encodeMiniNumber(0)), encodeMiniNumber(0));
24
+ }
25
+ /**
26
+ * Structural authorization checks: both parties must be distinct channel
27
+ * members and both signatures must be non-empty Uint8Arrays.
28
+ * Cryptographic WOTS verification is performed separately by
29
+ * `verifySpliceSignatures`.
30
+ */
31
+ function validateSpliceAuthorization(channel, proposal, acceptance) {
32
+ const proposerParty = channel.parties.find(p => p.publicKeyDigest === proposal.proposerPublicKeyDigest);
33
+ if (!proposerParty)
34
+ throw new errors_js_1.SpliceMissingPartyError(proposal.proposerPublicKeyDigest);
35
+ const acceptorParty = channel.parties.find(p => p.publicKeyDigest === acceptance.acceptorPublicKeyDigest);
36
+ if (!acceptorParty)
37
+ throw new errors_js_1.SpliceMissingPartyError(acceptance.acceptorPublicKeyDigest);
38
+ if (proposal.proposerPublicKeyDigest === acceptance.acceptorPublicKeyDigest) {
39
+ throw new Error('Proposer and acceptor must be different channel parties');
40
+ }
41
+ if (!proposal.proposerSignature || proposal.proposerSignature.length === 0) {
42
+ throw new errors_js_1.SpliceSignatureMismatchError('Proposer signature is empty');
43
+ }
44
+ if (!acceptance.acceptorSignature || acceptance.acceptorSignature.length === 0) {
45
+ throw new errors_js_1.SpliceSignatureMismatchError('Acceptor signature is empty');
46
+ }
47
+ }
48
+ /**
49
+ * Cryptographically verify both parties' signatures against the splice TX
50
+ * digest. Called after structural checks; fails closed — throws on any
51
+ * invalid signature.
52
+ *
53
+ * The digest covers the full canonical TX structure AND `newBalances` (sorted
54
+ * by partyId), so signatures are bound to the exact per-party balance split.
55
+ */
56
+ function verifySpliceSignatures(proposal, acceptance, verifier) {
57
+ const digest = (0, splice_tx_js_1.computeSpliceTxDigest)(proposal.spliceTxDraft);
58
+ if (!verifier(proposal.proposerSignature, digest, proposal.proposerPublicKeyDigest)) {
59
+ throw new errors_js_1.SpliceSignatureMismatchError('Proposer signature failed cryptographic verification — digest or key mismatch');
60
+ }
61
+ if (!verifier(acceptance.acceptorSignature, digest, acceptance.acceptorPublicKeyDigest)) {
62
+ throw new errors_js_1.SpliceSignatureMismatchError('Acceptor signature failed cryptographic verification — digest or key mismatch');
63
+ }
64
+ }
65
+ /**
66
+ * Cryptographically bind the proposal's spliceTxDraft to its params by
67
+ * recomputing the draft deterministically and comparing digests.
68
+ *
69
+ * Prevents state divergence: finalizeSplice uses spliceTxDraft for the
70
+ * on-chain TX but applies channel state changes from params. If they are
71
+ * inconsistent, the new channel state would not match what was actually mined.
72
+ */
73
+ function bindFinalizeParamsToDraft(channel, proposal) {
74
+ const recomputed = (0, splice_tx_js_1.buildSpliceTx)(channel, proposal.params);
75
+ const expected = (0, splice_tx_js_1.computeSpliceTxDigest)(recomputed);
76
+ const actual = (0, splice_tx_js_1.computeSpliceTxDigest)(proposal.spliceTxDraft);
77
+ if (!expected.every((b, i) => b === actual[i])) {
78
+ throw new Error('finalizeSplice: proposal.spliceTxDraft is inconsistent with proposal.params — ' +
79
+ 'rejecting to prevent on-chain/off-chain state divergence');
80
+ }
81
+ }
82
+ /**
83
+ * Finalize a splice by assembling both parties' signatures, mining PoW,
84
+ * optionally broadcasting the TX, and returning the new active channel.
85
+ *
86
+ * **Quiesce gate**: the channel must be in `'quiesced'` state. Call
87
+ * `quiesceChannel` first to settle all HTLCs and sign the pre-splice state.
88
+ *
89
+ * **Security checks** (all verified before mining):
90
+ * 1. `channel.status === 'quiesced'`
91
+ * 2. `proposal.spliceId === acceptance.spliceId`
92
+ * 3. `proposal.channelId` and `acceptance.channelId` match `channel.channelId`
93
+ * 4. Proposer and acceptor are distinct, non-empty-keyed channel parties
94
+ * 5. Both signatures are non-empty byte arrays
95
+ * 6. Both signatures pass cryptographic verification against the splice TX
96
+ * digest (WOTS by default; override with `options.verifySignature` in tests)
97
+ * 7. `spliceTxDraft` digest matches what `buildSpliceTx(channel, params)` produces
98
+ *
99
+ * **WOTS lease lifecycle**:
100
+ * - If `options.proposerLeaseProvider` is supplied: `commitKeyUse` is called
101
+ * after a confirmed splice TX, or `burnReservation` on failure.
102
+ * - Same for `options.acceptorLeaseProvider`.
103
+ * - Reservations are tracked independently; only uncommitted ones are burned.
104
+ *
105
+ * **Broadcast failure**: if `broadcast()` returns `{ success: false }` without
106
+ * a `txpowid`, `finalizeSplice` throws and burns any open reservations.
107
+ *
108
+ * **Side effect**: the `channel` object passed in is mutated to
109
+ * `status: 'spliced'` after a successful finalize. This marks the old
110
+ * quiesced channel as invalid; only the returned `SplicedChannel` is live.
111
+ *
112
+ * **Returned SplicedChannel**:
113
+ * - `status: 'active'` — ready for new payments immediately
114
+ * - `totalValue` — updated to `proposal.params.newTotalValue`
115
+ * - `balances` — updated to `proposal.params.newBalances`
116
+ * - `currentSequence: 0` — fresh WOTS budget
117
+ * - `latestState: null` — no cosigned state yet
118
+ * - `splicedFrom` — old channel's `channelId`
119
+ * - `spliceFundingTxId` — mined (or broadcast) TX ID
120
+ * - `spliceFundingCoinId` — `<txId>-0`
121
+ *
122
+ * @param channel - Quiesced channel (mutated to 'spliced' on success).
123
+ * @param proposal - Splice proposal from the initiating party.
124
+ * @param acceptance - Co-signature from the accepting party.
125
+ * @param options - Broadcast, difficulty, verifier, and lease providers.
126
+ * @returns SplicedChannel (`status: 'active'`) with updated value and provenance.
127
+ */
128
+ async function finalizeSplice(channel, proposal, acceptance, options) {
129
+ if (channel.status !== 'quiesced') {
130
+ throw new errors_js_1.SpliceChannelStatusError('quiesced', channel.status);
131
+ }
132
+ if (proposal.spliceId !== acceptance.spliceId) {
133
+ throw new errors_js_1.SpliceSignatureMismatchError(`proposal spliceId '${proposal.spliceId}' !== acceptance spliceId '${acceptance.spliceId}'`);
134
+ }
135
+ if (proposal.channelId !== channel.channelId) {
136
+ throw new Error(`proposal.channelId '${proposal.channelId}' does not match channel '${channel.channelId}'`);
137
+ }
138
+ if (acceptance.channelId !== channel.channelId) {
139
+ throw new Error(`acceptance.channelId '${acceptance.channelId}' does not match channel '${channel.channelId}'`);
140
+ }
141
+ validateSpliceAuthorization(channel, proposal, acceptance);
142
+ const verifier = options?.verifySignature ?? defaultWotsVerify;
143
+ verifySpliceSignatures(proposal, acceptance, verifier);
144
+ bindFinalizeParamsToDraft(channel, proposal);
145
+ const proposerLease = options?.proposerLeaseProvider;
146
+ const acceptorLease = options?.acceptorLeaseProvider;
147
+ // Track which reservations have been committed so we know which to burn on failure.
148
+ const committed = new Set();
149
+ const txBytes = (0, splice_tx_js_1.spliceDraftToMinimaBytes)(proposal.spliceTxDraft);
150
+ const witnessBytes = assembleSpliceWitness(proposal.proposerSignature, acceptance.acceptorSignature);
151
+ let spliceFundingTxId;
152
+ try {
153
+ const difficulty = options?.mineDifficulty ?? txpow_1.TX_POW_MIN_DIFFICULTY;
154
+ const txBody = (0, txpow_1.serializeTxBody)(txBytes, witnessBytes);
155
+ const mined = await (0, txpow_1.mineTxPoW)(txBody, difficulty);
156
+ const fullTxPoW = (0, core_1.concatBytes)((0, core_1.concatBytes)(mined.minedHeaderBytes, new Uint8Array([0x01])), txBody);
157
+ const txHex = Buffer.from(fullTxPoW).toString('hex');
158
+ spliceFundingTxId = Buffer.from(mined.txpowId).toString('hex');
159
+ if (options?.broadcast) {
160
+ const result = await options.broadcast(txHex);
161
+ if (result.txpowid) {
162
+ spliceFundingTxId = result.txpowid;
163
+ }
164
+ else if (result.success === false) {
165
+ throw new Error('Splice TX broadcast rejected by the network — channel state not advanced');
166
+ }
167
+ }
168
+ // Commit leases on confirmed splice TX
169
+ if (proposerLease) {
170
+ await proposerLease.commitKeyUse(proposal.proposerReservationId, spliceFundingTxId);
171
+ committed.add(proposal.proposerReservationId);
172
+ }
173
+ if (acceptorLease) {
174
+ await acceptorLease.commitKeyUse(acceptance.acceptorReservationId, spliceFundingTxId);
175
+ committed.add(acceptance.acceptorReservationId);
176
+ }
177
+ }
178
+ catch (err) {
179
+ // Burn any reservations that were not yet committed (fail-close lease accounting)
180
+ await Promise.allSettled([
181
+ proposerLease && !committed.has(proposal.proposerReservationId)
182
+ ? proposerLease.burnReservation(proposal.proposerReservationId, 'finalize-failed')
183
+ : undefined,
184
+ acceptorLease && !committed.has(acceptance.acceptorReservationId)
185
+ ? acceptorLease.burnReservation(acceptance.acceptorReservationId, 'finalize-failed')
186
+ : undefined,
187
+ ].filter((x) => x !== undefined));
188
+ throw err;
189
+ }
190
+ const spliceFundingCoinId = `${spliceFundingTxId}-0`;
191
+ const params = proposal.params;
192
+ const splicedChannel = {
193
+ ...channel,
194
+ status: 'active',
195
+ splicedFrom: channel.channelId,
196
+ spliceType: params.type,
197
+ spliceFundingTxId,
198
+ spliceFundingCoinId,
199
+ fundingTxId: spliceFundingTxId,
200
+ fundingCoinId: spliceFundingCoinId,
201
+ totalValue: params.newTotalValue,
202
+ balances: params.newBalances,
203
+ currentSequence: 0,
204
+ latestState: null,
205
+ pendingHTLCs: [],
206
+ stateLog: [
207
+ ...channel.stateLog,
208
+ {
209
+ sequence: 0,
210
+ timestamp: Date.now(),
211
+ balances: { ...params.newBalances },
212
+ htlcCount: 0,
213
+ event: 'update',
214
+ },
215
+ ],
216
+ updatedAt: Date.now(),
217
+ };
218
+ // Mark the old (quiesced) channel as spliced — it is now invalidated.
219
+ // Any further operations on `channel` should be rejected by status checks.
220
+ channel.status = 'spliced';
221
+ return splicedChannel;
222
+ }
@@ -0,0 +1,9 @@
1
+ export { quiesceChannel, type QuiesceOptions } from './quiesce.js';
2
+ export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
3
+ export { proposeSpliceIn, proposeSpliceOut, acceptSplice } from './splice.js';
4
+ export { finalizeSplice, type FinalizeSpliceOptions } from './finalize.js';
5
+ export type { SpliceType, SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput, SpliceProposal, SpliceAcceptance, QuiescedChannel, SplicedChannel, SpliceLeaseProvider, SpliceSigningIndices, WotsSignature, } from './types.js';
6
+ export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
7
+ export { createDurableSpliceStore, } from './durable-splice-store.js';
8
+ export type { SpliceRecord, SpliceRecordStatus, SpliceStoreState, DurableSpliceStore, DurableSpliceStoreOptions, } from './durable-splice-store.js';
9
+ export { createSpliceCoordination, type SpliceCoordination, type SpliceCoordinationDeps, type SpliceProposeParams, type SpliceApproval, type SpliceApprovalRequest, type VerifySignature, } from './coordination.js';
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSpliceCoordination = exports.createDurableSpliceStore = exports.SpliceInsufficientFundsError = exports.SpliceMissingPartyError = exports.SpliceSignatureMismatchError = exports.SpliceBalanceConservationError = exports.SpliceChannelStatusError = exports.PendingHTLCError = exports.SpliceError = exports.finalizeSplice = exports.acceptSplice = exports.proposeSpliceOut = exports.proposeSpliceIn = exports.computeSpliceTxDigest = exports.spliceDraftToMinimaBytes = exports.buildSpliceTx = exports.quiesceChannel = void 0;
4
+ var quiesce_js_1 = require("./quiesce.js");
5
+ Object.defineProperty(exports, "quiesceChannel", { enumerable: true, get: function () { return quiesce_js_1.quiesceChannel; } });
6
+ var splice_tx_js_1 = require("./splice-tx.js");
7
+ Object.defineProperty(exports, "buildSpliceTx", { enumerable: true, get: function () { return splice_tx_js_1.buildSpliceTx; } });
8
+ Object.defineProperty(exports, "spliceDraftToMinimaBytes", { enumerable: true, get: function () { return splice_tx_js_1.spliceDraftToMinimaBytes; } });
9
+ Object.defineProperty(exports, "computeSpliceTxDigest", { enumerable: true, get: function () { return splice_tx_js_1.computeSpliceTxDigest; } });
10
+ var splice_js_1 = require("./splice.js");
11
+ Object.defineProperty(exports, "proposeSpliceIn", { enumerable: true, get: function () { return splice_js_1.proposeSpliceIn; } });
12
+ Object.defineProperty(exports, "proposeSpliceOut", { enumerable: true, get: function () { return splice_js_1.proposeSpliceOut; } });
13
+ Object.defineProperty(exports, "acceptSplice", { enumerable: true, get: function () { return splice_js_1.acceptSplice; } });
14
+ var finalize_js_1 = require("./finalize.js");
15
+ Object.defineProperty(exports, "finalizeSplice", { enumerable: true, get: function () { return finalize_js_1.finalizeSplice; } });
16
+ var errors_js_1 = require("./errors.js");
17
+ Object.defineProperty(exports, "SpliceError", { enumerable: true, get: function () { return errors_js_1.SpliceError; } });
18
+ Object.defineProperty(exports, "PendingHTLCError", { enumerable: true, get: function () { return errors_js_1.PendingHTLCError; } });
19
+ Object.defineProperty(exports, "SpliceChannelStatusError", { enumerable: true, get: function () { return errors_js_1.SpliceChannelStatusError; } });
20
+ Object.defineProperty(exports, "SpliceBalanceConservationError", { enumerable: true, get: function () { return errors_js_1.SpliceBalanceConservationError; } });
21
+ Object.defineProperty(exports, "SpliceSignatureMismatchError", { enumerable: true, get: function () { return errors_js_1.SpliceSignatureMismatchError; } });
22
+ Object.defineProperty(exports, "SpliceMissingPartyError", { enumerable: true, get: function () { return errors_js_1.SpliceMissingPartyError; } });
23
+ Object.defineProperty(exports, "SpliceInsufficientFundsError", { enumerable: true, get: function () { return errors_js_1.SpliceInsufficientFundsError; } });
24
+ var durable_splice_store_js_1 = require("./durable-splice-store.js");
25
+ Object.defineProperty(exports, "createDurableSpliceStore", { enumerable: true, get: function () { return durable_splice_store_js_1.createDurableSpliceStore; } });
26
+ // RFC-035 B1 — splice peer round-trip over the coordination transport.
27
+ var coordination_js_1 = require("./coordination.js");
28
+ Object.defineProperty(exports, "createSpliceCoordination", { enumerable: true, get: function () { return coordination_js_1.createSpliceCoordination; } });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,57 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { QuiescedChannel, SpliceLeaseProvider } from './types.js';
3
+ /**
4
+ * Options for `quiesceChannel`.
5
+ */
6
+ export interface QuiesceOptions {
7
+ /**
8
+ * Called when the channel has pending HTLCs that have not yet reached a
9
+ * terminal state (`fulfilled` or `timed_out`). If provided, `quiesceChannel`
10
+ * invokes this callback with the still-pending HTLCs, giving the caller an
11
+ * opportunity to drive resolution — e.g. submit preimage reveals, wait for
12
+ * timeout blocks, or poll a Minima node — before the quiesce is retried.
13
+ *
14
+ * After the callback resolves, `channel.pendingHTLCs` is re-inspected. If
15
+ * all HTLCs have moved to a terminal state the quiesce proceeds; if any are
16
+ * still pending, `PendingHTLCError` is thrown.
17
+ *
18
+ * If this option is not provided, `PendingHTLCError` is thrown immediately
19
+ * when pending HTLCs are found.
20
+ *
21
+ * @param pending - The HTLCs that still need resolution.
22
+ */
23
+ awaitResolution?: (pending: OmniaChannel['pendingHTLCs']) => Promise<void>;
24
+ }
25
+ /**
26
+ * Quiesce a channel before splicing.
27
+ *
28
+ * Quiescing is mandatory before a splice can be proposed or accepted. It:
29
+ * 1. Validates the channel is `'active'`.
30
+ * 2. Ensures all in-flight HTLCs have reached a terminal state
31
+ * (`fulfilled` or `timed_out`). If pending HTLCs exist and
32
+ * `options.awaitResolution` is provided, the callback is invoked so the
33
+ * caller can drive/await resolution (submit preimages, wait for timeouts,
34
+ * poll a node). After the callback the channel is re-checked. If HTLCs
35
+ * remain pending, `PendingHTLCError` is thrown. If the option is absent
36
+ * and pending HTLCs exist, `PendingHTLCError` is thrown immediately.
37
+ * 3. Signs a final state update (via `updateState`) that captures the settled
38
+ * balance split at `currentSequence + 1`. This produces a WOTS-signed
39
+ * `Partial<SignedChannelState>` binding both parties to the pre-splice
40
+ * balance before the splice TX resets the sequence to 0.
41
+ * 4. Returns a `QuiescedChannel` with `status: 'quiesced'`, `pendingHTLCs: []`
42
+ * (all resolved HTLCs cleared), and `quiesceSignedState` containing the
43
+ * local party's partial signature over the final balance state.
44
+ *
45
+ * The caller must exchange `quiesceSignedState` with the counterparty to obtain
46
+ * their co-signature, providing a fully signed record of the last pre-splice
47
+ * balance for any future dispute resolution.
48
+ *
49
+ * @param channel - The active channel to quiesce.
50
+ * @param leaseProvider - Provides the local party's signer and WOTS lease.
51
+ * @param options - Optional: `awaitResolution` callback for HTLC settlement.
52
+ * @returns A QuiescedChannel with `status: 'quiesced'`, cleared `pendingHTLCs`,
53
+ * and the local party's partial signature over the final balance state.
54
+ * @throws {SpliceChannelStatusError} If channel is not active.
55
+ * @throws {PendingHTLCError} If HTLCs remain pending after resolution.
56
+ */
57
+ export declare function quiesceChannel(channel: OmniaChannel, leaseProvider: SpliceLeaseProvider, options?: QuiesceOptions): Promise<QuiescedChannel>;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.quiesceChannel = quiesceChannel;
4
+ const omnia_1 = require("@totemsdk/omnia");
5
+ const errors_js_1 = require("./errors.js");
6
+ /**
7
+ * Quiesce a channel before splicing.
8
+ *
9
+ * Quiescing is mandatory before a splice can be proposed or accepted. It:
10
+ * 1. Validates the channel is `'active'`.
11
+ * 2. Ensures all in-flight HTLCs have reached a terminal state
12
+ * (`fulfilled` or `timed_out`). If pending HTLCs exist and
13
+ * `options.awaitResolution` is provided, the callback is invoked so the
14
+ * caller can drive/await resolution (submit preimages, wait for timeouts,
15
+ * poll a node). After the callback the channel is re-checked. If HTLCs
16
+ * remain pending, `PendingHTLCError` is thrown. If the option is absent
17
+ * and pending HTLCs exist, `PendingHTLCError` is thrown immediately.
18
+ * 3. Signs a final state update (via `updateState`) that captures the settled
19
+ * balance split at `currentSequence + 1`. This produces a WOTS-signed
20
+ * `Partial<SignedChannelState>` binding both parties to the pre-splice
21
+ * balance before the splice TX resets the sequence to 0.
22
+ * 4. Returns a `QuiescedChannel` with `status: 'quiesced'`, `pendingHTLCs: []`
23
+ * (all resolved HTLCs cleared), and `quiesceSignedState` containing the
24
+ * local party's partial signature over the final balance state.
25
+ *
26
+ * The caller must exchange `quiesceSignedState` with the counterparty to obtain
27
+ * their co-signature, providing a fully signed record of the last pre-splice
28
+ * balance for any future dispute resolution.
29
+ *
30
+ * @param channel - The active channel to quiesce.
31
+ * @param leaseProvider - Provides the local party's signer and WOTS lease.
32
+ * @param options - Optional: `awaitResolution` callback for HTLC settlement.
33
+ * @returns A QuiescedChannel with `status: 'quiesced'`, cleared `pendingHTLCs`,
34
+ * and the local party's partial signature over the final balance state.
35
+ * @throws {SpliceChannelStatusError} If channel is not active.
36
+ * @throws {PendingHTLCError} If HTLCs remain pending after resolution.
37
+ */
38
+ async function quiesceChannel(channel, leaseProvider, options) {
39
+ if (channel.status !== 'active') {
40
+ throw new errors_js_1.SpliceChannelStatusError('active', channel.status);
41
+ }
42
+ const pendingHTLCs = channel.pendingHTLCs.filter(h => h.status === 'pending');
43
+ if (pendingHTLCs.length > 0) {
44
+ if (options?.awaitResolution) {
45
+ await options.awaitResolution(pendingHTLCs);
46
+ const stillPending = channel.pendingHTLCs.filter(h => h.status === 'pending').length;
47
+ if (stillPending > 0) {
48
+ throw new errors_js_1.PendingHTLCError(stillPending);
49
+ }
50
+ }
51
+ else {
52
+ throw new errors_js_1.PendingHTLCError(pendingHTLCs.length);
53
+ }
54
+ }
55
+ const { channel: updatedChannel, signedState, error } = await (0, omnia_1.updateState)(channel, { newBalances: channel.balances }, leaseProvider.wotsLease, leaseProvider.signer);
56
+ if (error) {
57
+ throw new Error(`quiesceChannel: updateState blocked — ${error}. Splice cannot proceed.`);
58
+ }
59
+ const quiesced = {
60
+ ...updatedChannel,
61
+ status: 'quiesced',
62
+ pendingHTLCs: [],
63
+ quiesceSignedState: signedState,
64
+ updatedAt: Date.now(),
65
+ };
66
+ return quiesced;
67
+ }
@@ -0,0 +1,38 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type { SpliceParams, SpliceTxDraft } from './types.js';
3
+ /**
4
+ * Build a validated SpliceTxDraft from channel + splice params.
5
+ *
6
+ * For splice-in:
7
+ * inputs = [channel coin (latestCoinId), additional coin]
8
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
9
+ *
10
+ * For splice-out:
11
+ * inputs = [channel coin (latestCoinId)]
12
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
13
+ * [withdrawal coin at withdrawAddress]
14
+ * [any extra outputs]
15
+ *
16
+ * The output channel coin always resets STATE(101)=0 so the new channel starts
17
+ * from sequence 0 with a full WOTS signing budget.
18
+ *
19
+ * @param channel - Quiesced or active channel to splice.
20
+ * @param params - Splice parameters (type, amounts, addresses).
21
+ * @returns Validated SpliceTxDraft.
22
+ * @throws {SpliceBalanceConservationError} If output amounts do not sum to newTotalValue.
23
+ * @throws {SpliceInsufficientFundsError} If splice-out exceeds channel holdings.
24
+ */
25
+ export declare function buildSpliceTx(channel: OmniaChannel, params: SpliceParams): SpliceTxDraft;
26
+ /**
27
+ * Convert a SpliceTxDraft to canonical Minima binary TX bytes.
28
+ *
29
+ * The resulting bytes cover inputs, outputs, and state variables and are
30
+ * suitable for WOTS signing. Both parties sign the same bytes independently;
31
+ * the final splice TX assembles both signatures into the witness.
32
+ */
33
+ export declare function spliceDraftToMinimaBytes(draft: SpliceTxDraft): Uint8Array;
34
+ /**
35
+ * Compute a 32-byte digest over the splice TX draft for WOTS signing.
36
+ * This is the canonical message both parties sign to authorize the splice.
37
+ */
38
+ export declare function computeSpliceTxDigest(draft: SpliceTxDraft): Uint8Array;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSpliceTx = buildSpliceTx;
4
+ exports.spliceDraftToMinimaBytes = spliceDraftToMinimaBytes;
5
+ exports.computeSpliceTxDigest = computeSpliceTxDigest;
6
+ const core_1 = require("@totemsdk/core");
7
+ const core_2 = require("@totemsdk/core");
8
+ const omnia_1 = require("@totemsdk/omnia");
9
+ const errors_js_1 = require("./errors.js");
10
+ const STATE_SETTLEMENT_PORT = 100;
11
+ const STATE_SEQUENCE_PORT = 101;
12
+ /**
13
+ * Build a validated SpliceTxDraft from channel + splice params.
14
+ *
15
+ * For splice-in:
16
+ * inputs = [channel coin (latestCoinId), additional coin]
17
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
18
+ *
19
+ * For splice-out:
20
+ * inputs = [channel coin (latestCoinId)]
21
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
22
+ * [withdrawal coin at withdrawAddress]
23
+ * [any extra outputs]
24
+ *
25
+ * The output channel coin always resets STATE(101)=0 so the new channel starts
26
+ * from sequence 0 with a full WOTS signing budget.
27
+ *
28
+ * @param channel - Quiesced or active channel to splice.
29
+ * @param params - Splice parameters (type, amounts, addresses).
30
+ * @returns Validated SpliceTxDraft.
31
+ * @throws {SpliceBalanceConservationError} If output amounts do not sum to newTotalValue.
32
+ * @throws {SpliceInsufficientFundsError} If splice-out exceeds channel holdings.
33
+ */
34
+ function buildSpliceTx(channel, params) {
35
+ const tokenId = channel.tokenId ?? '0x00';
36
+ if (params.type === 'splice_out') {
37
+ const withdrawAmount = params.withdrawAmount ?? 0n;
38
+ const extraSum = (params.extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
39
+ const totalOutflow = withdrawAmount + extraSum;
40
+ if (totalOutflow > channel.totalValue) {
41
+ throw new errors_js_1.SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
42
+ }
43
+ if (params.newTotalValue < 0n) {
44
+ throw new errors_js_1.SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
45
+ }
46
+ }
47
+ const balanceSum = Object.values(params.newBalances).reduce((a, b) => a + b, 0n);
48
+ // `params.newTotalValue` is the amount that will remain locked in the new channel coin
49
+ // after the splice. `newBalances` must sum exactly to that value.
50
+ // Withdrawals and extra outputs are separate outputs, already factored out by the
51
+ // caller when computing `newTotalValue`.
52
+ if (balanceSum !== params.newTotalValue) {
53
+ throw new errors_js_1.SpliceBalanceConservationError(params.newTotalValue, balanceSum);
54
+ }
55
+ const inputs = [
56
+ {
57
+ coinId: omnia_1.COINID_ELTOO,
58
+ address: channel.fundingAddress,
59
+ amount: channel.totalValue,
60
+ tokenId,
61
+ },
62
+ ];
63
+ if (params.type === 'splice_in' && params.additionalCoinId && params.additionalAmount) {
64
+ inputs.push({
65
+ coinId: params.additionalCoinId,
66
+ address: params.additionalCoinAddress ?? '',
67
+ amount: params.additionalAmount,
68
+ tokenId,
69
+ });
70
+ }
71
+ const outputs = [
72
+ {
73
+ address: channel.fundingAddress,
74
+ amount: balanceSum,
75
+ tokenId,
76
+ storeState: true,
77
+ stateVarSettlement: false,
78
+ stateVarSequence: 0,
79
+ },
80
+ ];
81
+ if (params.type === 'splice_out' && params.withdrawAmount && params.withdrawAmount > 0n && params.withdrawAddress) {
82
+ outputs.push({
83
+ address: params.withdrawAddress,
84
+ amount: params.withdrawAmount,
85
+ tokenId,
86
+ storeState: false,
87
+ stateVarSettlement: false,
88
+ stateVarSequence: 0,
89
+ });
90
+ }
91
+ for (const extra of params.extraOutputs ?? []) {
92
+ outputs.push({
93
+ address: extra.address,
94
+ amount: extra.amount,
95
+ tokenId: extra.tokenId ?? tokenId,
96
+ storeState: false,
97
+ stateVarSettlement: false,
98
+ stateVarSequence: 0,
99
+ });
100
+ }
101
+ return {
102
+ inputs,
103
+ outputs,
104
+ channelId: channel.channelId,
105
+ params,
106
+ };
107
+ }
108
+ /**
109
+ * Convert a SpliceTxDraft to canonical Minima binary TX bytes.
110
+ *
111
+ * The resulting bytes cover inputs, outputs, and state variables and are
112
+ * suitable for WOTS signing. Both parties sign the same bytes independently;
113
+ * the final splice TX assembles both signatures into the witness.
114
+ */
115
+ function spliceDraftToMinimaBytes(draft) {
116
+ const toHex = (b) => Buffer.from(b).toString('hex');
117
+ const svToJson = (port, value, type) => {
118
+ let data;
119
+ let svtype;
120
+ if (typeof value === 'bigint') {
121
+ data = value.toString();
122
+ svtype = 'number';
123
+ }
124
+ else if (typeof value === 'boolean') {
125
+ data = value ? 'true' : 'false';
126
+ svtype = 'bool';
127
+ }
128
+ else if (value instanceof Uint8Array) {
129
+ data = '0x' + toHex(value);
130
+ svtype = 'hex';
131
+ }
132
+ else if (typeof value === 'number') {
133
+ data = value.toString();
134
+ svtype = 'number';
135
+ }
136
+ else {
137
+ data = String(value);
138
+ svtype = type;
139
+ }
140
+ return { port, svtype, data };
141
+ };
142
+ const inputs = draft.inputs.map(inp => ({
143
+ coinid: inp.coinId,
144
+ amount: inp.amount.toString(),
145
+ address: inp.address,
146
+ tokenid: inp.tokenId,
147
+ storestate: false,
148
+ mmrentry: '0',
149
+ spent: false,
150
+ created: '0',
151
+ state: [],
152
+ }));
153
+ const outputs = draft.outputs.map(out => ({
154
+ amount: out.amount.toString(),
155
+ address: out.address,
156
+ tokenid: out.tokenId,
157
+ storestate: out.storeState ?? false,
158
+ mmrentry: '0',
159
+ spent: false,
160
+ created: '0',
161
+ state: out.storeState
162
+ ? [
163
+ svToJson(STATE_SETTLEMENT_PORT, out.stateVarSettlement, 'bool'),
164
+ svToJson(STATE_SEQUENCE_PORT, out.stateVarSequence, 'number'),
165
+ ]
166
+ : [],
167
+ }));
168
+ const state = [
169
+ svToJson(STATE_SETTLEMENT_PORT, false, 'bool'),
170
+ svToJson(STATE_SEQUENCE_PORT, 0n, 'number'),
171
+ ];
172
+ return (0, core_2.serializeTransaction)(JSON.stringify({ inputs, outputs, state, linkhash: '0x00' }));
173
+ }
174
+ /**
175
+ * Compute a 32-byte digest over the splice TX draft for WOTS signing.
176
+ * This is the canonical message both parties sign to authorize the splice.
177
+ */
178
+ function computeSpliceTxDigest(draft) {
179
+ const canonical = JSON.stringify({
180
+ channelId: draft.channelId,
181
+ inputs: draft.inputs.map(i => ({
182
+ coinId: i.coinId,
183
+ address: i.address,
184
+ amount: i.amount.toString(),
185
+ tokenId: i.tokenId,
186
+ })),
187
+ outputs: draft.outputs.map(o => ({
188
+ address: o.address,
189
+ amount: o.amount.toString(),
190
+ tokenId: o.tokenId,
191
+ storeState: o.storeState,
192
+ stateVarSettlement: o.storeState ? o.stateVarSettlement : undefined,
193
+ stateVarSequence: o.storeState ? o.stateVarSequence : undefined,
194
+ })),
195
+ params: {
196
+ type: draft.params.type,
197
+ newTotalValue: draft.params.newTotalValue.toString(),
198
+ /**
199
+ * newBalances is sorted by partyId for determinism and included in the
200
+ * digest so that signatures cryptographically bind to the exact per-party
201
+ * balance split. Different allocations with the same sum produce different
202
+ * digests and therefore require new signatures.
203
+ */
204
+ newBalances: Object.entries(draft.params.newBalances)
205
+ .sort(([a], [b]) => a.localeCompare(b))
206
+ .map(([k, v]) => [k, v.toString()]),
207
+ },
208
+ });
209
+ return (0, core_1.sha3_256)(new TextEncoder().encode(canonical));
210
+ }