@totemsdk/omnia-splice 0.1.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,208 @@
1
+ import { sha3_256 } from '@noble/hashes/sha3';
2
+ import {
3
+ serializeTransaction,
4
+ createDefaultTransaction,
5
+ buildMinimaCoin,
6
+ fromHex,
7
+ type StateVariable as CoreStateVariable,
8
+ } from '@totemsdk/core';
9
+ import type { OmniaChannel } from '@totemsdk/omnia';
10
+ import { COINID_ELTOO } from '@totemsdk/omnia';
11
+ import type { SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput } from './types.js';
12
+ import { SpliceBalanceConservationError, SpliceInsufficientFundsError } from './errors.js';
13
+
14
+ const STATE_SETTLEMENT_PORT = 100;
15
+ const STATE_SEQUENCE_PORT = 101;
16
+
17
+ /**
18
+ * Build a validated SpliceTxDraft from channel + splice params.
19
+ *
20
+ * For splice-in:
21
+ * inputs = [channel coin (latestCoinId), additional coin]
22
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
23
+ *
24
+ * For splice-out:
25
+ * inputs = [channel coin (latestCoinId)]
26
+ * outputs = [new channel coin at fundingAddress, sequence=0, settlement=false]
27
+ * [withdrawal coin at withdrawAddress]
28
+ * [any extra outputs]
29
+ *
30
+ * The output channel coin always resets STATE(101)=0 so the new channel starts
31
+ * from sequence 0 with a full WOTS signing budget.
32
+ *
33
+ * @param channel - Quiesced or active channel to splice.
34
+ * @param params - Splice parameters (type, amounts, addresses).
35
+ * @returns Validated SpliceTxDraft.
36
+ * @throws {SpliceBalanceConservationError} If output amounts do not sum to newTotalValue.
37
+ * @throws {SpliceInsufficientFundsError} If splice-out exceeds channel holdings.
38
+ */
39
+ export function buildSpliceTx(
40
+ channel: OmniaChannel,
41
+ params: SpliceParams,
42
+ ): SpliceTxDraft {
43
+ const tokenId = channel.tokenId ?? '0x00';
44
+
45
+ if (params.type === 'splice_out') {
46
+ const withdrawAmount = params.withdrawAmount ?? 0n;
47
+ const extraSum = (params.extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
48
+ const totalOutflow = withdrawAmount + extraSum;
49
+ if (totalOutflow > channel.totalValue) {
50
+ throw new SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
51
+ }
52
+ if (params.newTotalValue < 0n) {
53
+ throw new SpliceInsufficientFundsError(channel.totalValue, totalOutflow);
54
+ }
55
+ }
56
+
57
+ const balanceSum = Object.values(params.newBalances).reduce((a, b) => a + b, 0n);
58
+
59
+ // `params.newTotalValue` is the amount that will remain locked in the new channel coin
60
+ // after the splice. `newBalances` must sum exactly to that value.
61
+ // Withdrawals and extra outputs are separate outputs, already factored out by the
62
+ // caller when computing `newTotalValue`.
63
+ if (balanceSum !== params.newTotalValue) {
64
+ throw new SpliceBalanceConservationError(params.newTotalValue, balanceSum);
65
+ }
66
+
67
+ const inputs: SpliceTxInput[] = [
68
+ {
69
+ coinId: COINID_ELTOO,
70
+ address: channel.fundingAddress,
71
+ amount: channel.totalValue,
72
+ tokenId,
73
+ },
74
+ ];
75
+
76
+ if (params.type === 'splice_in' && params.additionalCoinId && params.additionalAmount) {
77
+ inputs.push({
78
+ coinId: params.additionalCoinId,
79
+ address: params.additionalCoinAddress ?? '',
80
+ amount: params.additionalAmount,
81
+ tokenId,
82
+ });
83
+ }
84
+
85
+ const outputs: SpliceTxOutput[] = [
86
+ {
87
+ address: channel.fundingAddress,
88
+ amount: balanceSum,
89
+ tokenId,
90
+ storeState: true,
91
+ stateVarSettlement: false,
92
+ stateVarSequence: 0,
93
+ },
94
+ ];
95
+
96
+ if (params.type === 'splice_out' && params.withdrawAmount && params.withdrawAmount > 0n && params.withdrawAddress) {
97
+ outputs.push({
98
+ address: params.withdrawAddress,
99
+ amount: params.withdrawAmount,
100
+ tokenId,
101
+ storeState: false,
102
+ stateVarSettlement: false,
103
+ stateVarSequence: 0,
104
+ });
105
+ }
106
+
107
+ for (const extra of params.extraOutputs ?? []) {
108
+ outputs.push({
109
+ address: extra.address,
110
+ amount: extra.amount,
111
+ tokenId: extra.tokenId ?? tokenId,
112
+ storeState: false,
113
+ stateVarSettlement: false,
114
+ stateVarSequence: 0,
115
+ });
116
+ }
117
+
118
+ return {
119
+ inputs,
120
+ outputs,
121
+ channelId: channel.channelId,
122
+ params,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Convert a SpliceTxDraft to canonical Minima binary TX bytes.
128
+ *
129
+ * The resulting bytes cover inputs, outputs, and state variables and are
130
+ * suitable for WOTS signing. Both parties sign the same bytes independently;
131
+ * the final splice TX assembles both signatures into the witness.
132
+ */
133
+ export function spliceDraftToMinimaBytes(draft: SpliceTxDraft): Uint8Array {
134
+ const tx = createDefaultTransaction();
135
+
136
+ for (const inp of draft.inputs) {
137
+ tx.inputs.push(buildMinimaCoin({
138
+ coinId: fromHex(inp.coinId),
139
+ address: fromHex(inp.address),
140
+ amount: inp.amount.toString(),
141
+ tokenId: fromHex(inp.tokenId),
142
+ }));
143
+ }
144
+
145
+ for (const out of draft.outputs) {
146
+ const state: CoreStateVariable[] = out.storeState
147
+ ? [
148
+ { port: STATE_SETTLEMENT_PORT, value: out.stateVarSettlement, type: 'bool' },
149
+ { port: STATE_SEQUENCE_PORT, value: BigInt(out.stateVarSequence), type: 'number' },
150
+ ]
151
+ : [];
152
+
153
+ tx.outputs.push(buildMinimaCoin({
154
+ address: fromHex(out.address),
155
+ amount: out.amount.toString(),
156
+ tokenId: fromHex(out.tokenId),
157
+ storeState: out.storeState,
158
+ state,
159
+ }));
160
+ }
161
+
162
+ tx.state = [
163
+ { port: STATE_SETTLEMENT_PORT, value: false, type: 'bool' },
164
+ { port: STATE_SEQUENCE_PORT, value: 0n, type: 'number' },
165
+ ];
166
+
167
+ return serializeTransaction(tx);
168
+ }
169
+
170
+ /**
171
+ * Compute a 32-byte digest over the splice TX draft for WOTS signing.
172
+ * This is the canonical message both parties sign to authorize the splice.
173
+ */
174
+ export function computeSpliceTxDigest(draft: SpliceTxDraft): Uint8Array {
175
+ const canonical = JSON.stringify(
176
+ {
177
+ channelId: draft.channelId,
178
+ inputs: draft.inputs.map(i => ({
179
+ coinId: i.coinId,
180
+ address: i.address,
181
+ amount: i.amount.toString(),
182
+ tokenId: i.tokenId,
183
+ })),
184
+ outputs: draft.outputs.map(o => ({
185
+ address: o.address,
186
+ amount: o.amount.toString(),
187
+ tokenId: o.tokenId,
188
+ storeState: o.storeState,
189
+ stateVarSettlement: o.storeState ? o.stateVarSettlement : undefined,
190
+ stateVarSequence: o.storeState ? o.stateVarSequence : undefined,
191
+ })),
192
+ params: {
193
+ type: draft.params.type,
194
+ newTotalValue: draft.params.newTotalValue.toString(),
195
+ /**
196
+ * newBalances is sorted by partyId for determinism and included in the
197
+ * digest so that signatures cryptographically bind to the exact per-party
198
+ * balance split. Different allocations with the same sum produce different
199
+ * digests and therefore require new signatures.
200
+ */
201
+ newBalances: Object.entries(draft.params.newBalances)
202
+ .sort(([a], [b]) => a.localeCompare(b))
203
+ .map(([k, v]) => [k, v.toString()]),
204
+ },
205
+ },
206
+ );
207
+ return sha3_256(new TextEncoder().encode(canonical));
208
+ }
package/src/splice.ts ADDED
@@ -0,0 +1,385 @@
1
+ import type { OmniaChannel } from '@totemsdk/omnia';
2
+ import type {
3
+ SpliceParams,
4
+ SpliceProposal,
5
+ SpliceAcceptance,
6
+ SpliceLeaseProvider,
7
+ QuiescedChannel,
8
+ } from './types.js';
9
+ import { buildSpliceTx, computeSpliceTxDigest, spliceDraftToMinimaBytes } from './splice-tx.js';
10
+ import {
11
+ PendingHTLCError,
12
+ SpliceChannelStatusError,
13
+ SpliceMissingPartyError,
14
+ } from './errors.js';
15
+
16
+ /**
17
+ * Scale existing balances proportionally to a new total, preserving relative
18
+ * ratios. The last party absorbs rounding so that sum(result) === newTotal
19
+ * exactly. Used as the default newBalances when a caller omits the argument.
20
+ */
21
+ function scaleBalances(
22
+ balances: Record<string, bigint>,
23
+ oldTotal: bigint,
24
+ newTotal: bigint,
25
+ ): Record<string, bigint> {
26
+ if (oldTotal === 0n) {
27
+ const partyIds = Object.keys(balances);
28
+ const each = partyIds.length > 0 ? newTotal / BigInt(partyIds.length) : 0n;
29
+ const result: Record<string, bigint> = {};
30
+ let assigned = 0n;
31
+ for (let i = 0; i < partyIds.length - 1; i++) {
32
+ result[partyIds[i]] = each;
33
+ assigned += each;
34
+ }
35
+ const last = partyIds[partyIds.length - 1];
36
+ if (last !== undefined) result[last] = newTotal - assigned;
37
+ return result;
38
+ }
39
+ const partyIds = Object.keys(balances);
40
+ const scaled: Record<string, bigint> = {};
41
+ let assigned = 0n;
42
+ for (let i = 0; i < partyIds.length - 1; i++) {
43
+ const pid = partyIds[i];
44
+ const prev = balances[pid] ?? 0n;
45
+ scaled[pid] = (prev * newTotal) / oldTotal;
46
+ assigned += scaled[pid];
47
+ }
48
+ const last = partyIds[partyIds.length - 1];
49
+ if (last !== undefined) scaled[last] = newTotal - assigned;
50
+ return scaled;
51
+ }
52
+
53
+ function generateSpliceId(): string {
54
+ const buf = new Uint8Array(16);
55
+ crypto.getRandomValues(buf);
56
+ return '0x' + buf.reduce((hex, b) => hex + b.toString(16).padStart(2, '0'), '');
57
+ }
58
+
59
+ /**
60
+ * Gate: all splice operations (propose, accept, finalize) require the channel
61
+ * to be in 'quiesced' state. Quiescing ensures all in-flight HTLCs are settled
62
+ * and the pre-splice balance split is mutually signed before any splice TX is built.
63
+ */
64
+ function validateChannelQuiesced(channel: OmniaChannel | QuiescedChannel): void {
65
+ if (channel.status !== 'quiesced') {
66
+ throw new SpliceChannelStatusError('quiesced', channel.status);
67
+ }
68
+ const pending = channel.pendingHTLCs.filter(h => h.status === 'pending').length;
69
+ if (pending > 0) {
70
+ throw new PendingHTLCError(pending);
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Validate proposal balance conservation and amount constraints.
76
+ * Called by acceptSplice before signing to independently verify inbound params.
77
+ */
78
+ function validateProposalParams(
79
+ channel: OmniaChannel | QuiescedChannel,
80
+ params: SpliceParams,
81
+ ): void {
82
+ const balanceSum = Object.values(params.newBalances).reduce((a, b) => a + b, 0n);
83
+ if (balanceSum !== params.newTotalValue) {
84
+ throw new Error(
85
+ `Proposal integrity check failed: newBalances sum (${balanceSum}) !== newTotalValue (${params.newTotalValue})`,
86
+ );
87
+ }
88
+
89
+ if (params.type === 'splice_out' && (params.withdrawAmount ?? 0n) > channel.totalValue) {
90
+ throw new Error(
91
+ `Proposal integrity check failed: withdrawAmount (${params.withdrawAmount}) exceeds channel totalValue (${channel.totalValue})`,
92
+ );
93
+ }
94
+
95
+ const channelOutput = params.newTotalValue;
96
+ const withdrawSum = params.withdrawAmount ?? 0n;
97
+ const extraSum = (params.extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
98
+
99
+ if (params.type === 'splice_in') {
100
+ const expectedExistingInput = channelOutput + withdrawSum + extraSum - (params.additionalAmount ?? 0n);
101
+ if (expectedExistingInput !== channel.totalValue) {
102
+ throw new Error(
103
+ `Proposal integrity check failed: splice-in amounts inconsistent ` +
104
+ `(expected existing channel input ${channel.totalValue}, derived ${expectedExistingInput})`,
105
+ );
106
+ }
107
+ } else {
108
+ if (channelOutput + withdrawSum + extraSum !== channel.totalValue) {
109
+ throw new Error(
110
+ `Proposal integrity check failed: splice-out amounts do not sum to channel total ` +
111
+ `(${channelOutput} + ${withdrawSum} + ${extraSum} !== ${channel.totalValue})`,
112
+ );
113
+ }
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Verify that `spliceTxDraft` is exactly what the params would produce by
119
+ * rebuilding the draft deterministically and comparing digests.
120
+ *
121
+ * Prevents a tampered proposal where params.newBalances is modified but
122
+ * spliceTxDraft is left unchanged (or vice versa), causing channel state
123
+ * to diverge from the actual on-chain TX outputs.
124
+ */
125
+ function bindDraftToParams(
126
+ channel: OmniaChannel | QuiescedChannel,
127
+ proposal: SpliceProposal,
128
+ ): void {
129
+ const recomputed = buildSpliceTx(channel as OmniaChannel, proposal.params);
130
+ const expected = computeSpliceTxDigest(recomputed);
131
+ const actual = computeSpliceTxDigest(proposal.spliceTxDraft);
132
+ if (!expected.every((b, i) => b === actual[i])) {
133
+ throw new Error(
134
+ 'Proposal spliceTxDraft is inconsistent with proposal.params — ' +
135
+ 'the TX draft may have been tampered with',
136
+ );
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Initiating party proposes a splice-in: add external funds to the channel.
142
+ *
143
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
144
+ *
145
+ * WOTS lease safety: a key slot is reserved via `leaseProvider.wotsLease`
146
+ * before signing. The returned `proposerReservationId` and
147
+ * `proposerSigningIndices` must be passed through to `finalizeSplice`
148
+ * (embedded in the `SpliceProposal`) so the reservation is committed on
149
+ * success or burned on failure, preventing one-time-key reuse.
150
+ *
151
+ * @param channel - Quiesced channel to splice.
152
+ * @param additionalCoinId - CoinId of the external coin being spliced in.
153
+ * @param additionalAmount - Amount of the additional coin.
154
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
155
+ * @param newBalances - How the new total should be split after splice.
156
+ * When omitted, existing balances are scaled
157
+ * proportionally to the new total value so that
158
+ * `sum(newBalances) === newTotalValue` is preserved.
159
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
160
+ */
161
+ export async function proposeSpliceIn(
162
+ channel: OmniaChannel | QuiescedChannel,
163
+ additionalCoinId: string,
164
+ additionalAmount: bigint,
165
+ leaseProvider: SpliceLeaseProvider,
166
+ newBalances?: Record<string, bigint>,
167
+ ): Promise<SpliceProposal> {
168
+ validateChannelQuiesced(channel);
169
+
170
+ const newTotal = channel.totalValue + additionalAmount;
171
+
172
+ const effectiveNewBalances = newBalances ?? scaleBalances(channel.balances, channel.totalValue, newTotal);
173
+
174
+ const params: SpliceParams = {
175
+ type: 'splice_in',
176
+ newTotalValue: newTotal,
177
+ newBalances: effectiveNewBalances,
178
+ additionalCoinId,
179
+ additionalAmount,
180
+ };
181
+
182
+ const draft = buildSpliceTx(channel as OmniaChannel, params);
183
+ const digest = computeSpliceTxDigest(draft);
184
+ const spliceTxHex = Buffer.from(spliceDraftToMinimaBytes(draft)).toString('hex');
185
+
186
+ const { signer, wotsLease } = leaseProvider;
187
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
188
+ if (!partyInChannel) {
189
+ throw new SpliceMissingPartyError(signer.publicKeyDigest);
190
+ }
191
+
192
+ const reservation = await wotsLease.reserveKeyUse({
193
+ treeId: signer.publicKeyDigest,
194
+ purpose: 'omnia-splice-propose',
195
+ payloadHash: Buffer.from(digest).toString('hex'),
196
+ });
197
+
198
+ const signature = await signer.sign(digest, reservation.indices);
199
+
200
+ return {
201
+ spliceId: generateSpliceId(),
202
+ channelId: channel.channelId,
203
+ params,
204
+ spliceTxHex,
205
+ spliceTxDraft: draft,
206
+ proposerPublicKeyDigest: signer.publicKeyDigest,
207
+ proposerSignature: signature,
208
+ proposerReservationId: reservation.reservationId,
209
+ proposerSigningIndices: reservation.indices,
210
+ proposedAt: Date.now(),
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Initiating party proposes a splice-out: withdraw funds from the channel on-chain.
216
+ *
217
+ * Requires the channel to be in 'quiesced' state (see quiesceChannel).
218
+ *
219
+ * WOTS lease safety: reserves a key slot before signing (same semantics as
220
+ * proposeSpliceIn). The `proposerReservationId` in the returned `SpliceProposal`
221
+ * must be committed/burned by `finalizeSplice`.
222
+ *
223
+ * @param channel - Quiesced channel.
224
+ * @param withdrawAmount - Amount to remove from the channel.
225
+ * @param withdrawAddress - On-chain destination for the withdrawn funds.
226
+ * @param leaseProvider - Provides the proposer signer and WOTS lease.
227
+ * @param newBalances - How the remaining total should be split after splice.
228
+ * @param extraOutputs - Optional additional on-chain outputs (third-party payments).
229
+ * @returns SpliceProposal signed by the proposer with lease reservation data.
230
+ */
231
+ export async function proposeSpliceOut(
232
+ channel: OmniaChannel | QuiescedChannel,
233
+ withdrawAmount: bigint,
234
+ withdrawAddress: string,
235
+ leaseProvider: SpliceLeaseProvider,
236
+ newBalances?: Record<string, bigint>,
237
+ extraOutputs?: Array<{ address: string; amount: bigint; tokenId?: string }>,
238
+ ): Promise<SpliceProposal> {
239
+ validateChannelQuiesced(channel);
240
+
241
+ const extraSum = (extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
242
+ const totalOutflow = withdrawAmount + extraSum;
243
+ if (totalOutflow > channel.totalValue) {
244
+ throw new Error(
245
+ `proposeSpliceOut: total outflow (withdraw ${withdrawAmount} + extra outputs ${extraSum} = ${totalOutflow}) ` +
246
+ `exceeds channel totalValue (${channel.totalValue})`,
247
+ );
248
+ }
249
+ const remainingTotal = channel.totalValue - totalOutflow;
250
+
251
+ const effectiveNewBalances = newBalances ?? (() => {
252
+ const ratio = channel.totalValue > 0n ? remainingTotal * 1000n / channel.totalValue : 0n;
253
+ const adjusted: Record<string, bigint> = {};
254
+ let assigned = 0n;
255
+ const partyIds = Object.keys(channel.balances);
256
+ for (let i = 0; i < partyIds.length - 1; i++) {
257
+ const pid = partyIds[i];
258
+ const prev = channel.balances[pid] ?? 0n;
259
+ const scaled = (prev * ratio) / 1000n;
260
+ adjusted[pid] = scaled;
261
+ assigned += scaled;
262
+ }
263
+ const lastId = partyIds[partyIds.length - 1];
264
+ if (lastId) adjusted[lastId] = remainingTotal - assigned;
265
+ return adjusted;
266
+ })();
267
+
268
+ const params: SpliceParams = {
269
+ type: 'splice_out',
270
+ newTotalValue: remainingTotal,
271
+ newBalances: effectiveNewBalances,
272
+ withdrawAmount,
273
+ withdrawAddress,
274
+ extraOutputs,
275
+ };
276
+
277
+ const draft = buildSpliceTx(channel as OmniaChannel, params);
278
+ const digest = computeSpliceTxDigest(draft);
279
+ const spliceTxHex = Buffer.from(spliceDraftToMinimaBytes(draft)).toString('hex');
280
+
281
+ const { signer, wotsLease } = leaseProvider;
282
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
283
+ if (!partyInChannel) {
284
+ throw new SpliceMissingPartyError(signer.publicKeyDigest);
285
+ }
286
+
287
+ const reservation = await wotsLease.reserveKeyUse({
288
+ treeId: signer.publicKeyDigest,
289
+ purpose: 'omnia-splice-propose',
290
+ payloadHash: Buffer.from(digest).toString('hex'),
291
+ });
292
+
293
+ const signature = await signer.sign(digest, reservation.indices);
294
+
295
+ return {
296
+ spliceId: generateSpliceId(),
297
+ channelId: channel.channelId,
298
+ params,
299
+ spliceTxHex,
300
+ spliceTxDraft: draft,
301
+ proposerPublicKeyDigest: signer.publicKeyDigest,
302
+ proposerSignature: signature,
303
+ proposerReservationId: reservation.reservationId,
304
+ proposerSigningIndices: reservation.indices,
305
+ proposedAt: Date.now(),
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Counterparty accepts a splice proposal by co-signing the splice TX digest.
311
+ *
312
+ * Requires the channel to be in 'quiesced' state.
313
+ *
314
+ * WOTS lease safety: reserves a key slot before signing. The returned
315
+ * `acceptorReservationId` and `acceptorSigningIndices` are embedded in the
316
+ * `SpliceAcceptance` and consumed by `finalizeSplice` to commit or burn the
317
+ * acceptor's key-slot reservation.
318
+ *
319
+ * The acceptor independently:
320
+ * 1. Validates party membership (proposer and acceptor both in channel).
321
+ * 2. Validates proposal balance conservation and amount constraints.
322
+ * 3. Cryptographically binds the signed draft to the proposal params by
323
+ * recomputing the expected draft from `params + channel` and comparing
324
+ * digests — rejects if they differ (tamper detection).
325
+ * 4. Reserves a WOTS key slot via `leaseProvider.wotsLease`.
326
+ * 5. Signs the splice TX digest with reserved indices.
327
+ *
328
+ * @param channel - Quiesced channel.
329
+ * @param proposal - Splice proposal from the initiating party.
330
+ * @param leaseProvider - Provides the acceptor signer and WOTS lease.
331
+ * @returns SpliceAcceptance containing acceptor co-signature and lease data.
332
+ */
333
+ export async function acceptSplice(
334
+ channel: OmniaChannel | QuiescedChannel,
335
+ proposal: SpliceProposal,
336
+ leaseProvider: SpliceLeaseProvider,
337
+ ): Promise<SpliceAcceptance> {
338
+ validateChannelQuiesced(channel);
339
+
340
+ if (proposal.channelId !== channel.channelId) {
341
+ throw new Error(
342
+ `Proposal channelId '${proposal.channelId}' does not match channel '${channel.channelId}'`,
343
+ );
344
+ }
345
+
346
+ const proposerInChannel = channel.parties.find(
347
+ p => p.publicKeyDigest === proposal.proposerPublicKeyDigest,
348
+ );
349
+ if (!proposerInChannel) {
350
+ throw new SpliceMissingPartyError(proposal.proposerPublicKeyDigest);
351
+ }
352
+
353
+ const { signer, wotsLease } = leaseProvider;
354
+ const partyInChannel = channel.parties.find(p => p.publicKeyDigest === signer.publicKeyDigest);
355
+ if (!partyInChannel) {
356
+ throw new SpliceMissingPartyError(signer.publicKeyDigest);
357
+ }
358
+
359
+ if (signer.publicKeyDigest === proposal.proposerPublicKeyDigest) {
360
+ throw new Error('Acceptor and proposer cannot be the same party');
361
+ }
362
+
363
+ validateProposalParams(channel, proposal.params);
364
+ bindDraftToParams(channel, proposal);
365
+
366
+ const digest = computeSpliceTxDigest(proposal.spliceTxDraft);
367
+
368
+ const reservation = await wotsLease.reserveKeyUse({
369
+ treeId: signer.publicKeyDigest,
370
+ purpose: 'omnia-splice-accept',
371
+ payloadHash: Buffer.from(digest).toString('hex'),
372
+ });
373
+
374
+ const signature = await signer.sign(digest, reservation.indices);
375
+
376
+ return {
377
+ spliceId: proposal.spliceId,
378
+ channelId: channel.channelId,
379
+ acceptorPublicKeyDigest: signer.publicKeyDigest,
380
+ acceptorSignature: signature,
381
+ acceptorReservationId: reservation.reservationId,
382
+ acceptorSigningIndices: reservation.indices,
383
+ acceptedAt: Date.now(),
384
+ };
385
+ }