@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.
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +44 -0
- package/dist/finalize.d.ts +92 -0
- package/dist/finalize.js +224 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/quiesce.d.ts +57 -0
- package/dist/quiesce.js +64 -0
- package/dist/splice-tx.d.ts +38 -0
- package/dist/splice-tx.js +177 -0
- package/dist/splice.d.ts +71 -0
- package/dist/splice.js +298 -0
- package/dist/types.d.ts +130 -0
- package/dist/types.js +1 -0
- package/package.json +45 -0
- package/src/__tests__/omnia-splice.test.ts +919 -0
- package/src/errors.ts +63 -0
- package/src/finalize.ts +344 -0
- package/src/index.ts +29 -0
- package/src/quiesce.ts +103 -0
- package/src/splice-tx.ts +208 -0
- package/src/splice.ts +385 -0
- package/src/types.ts +136 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
export class SpliceError extends Error {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
constructor(code: string, message: string) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'SpliceError';
|
|
6
|
+
this.code = code;
|
|
7
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export class PendingHTLCError extends SpliceError {
|
|
12
|
+
constructor(pendingCount: number) {
|
|
13
|
+
super(
|
|
14
|
+
'PENDING_HTLC',
|
|
15
|
+
`Cannot splice: ${pendingCount} HTLC(s) still pending. Fulfill or timeout all HTLCs before splicing.`,
|
|
16
|
+
);
|
|
17
|
+
this.name = 'PendingHTLCError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class SpliceChannelStatusError extends SpliceError {
|
|
22
|
+
constructor(required: string, actual: string) {
|
|
23
|
+
super(
|
|
24
|
+
'INVALID_CHANNEL_STATUS',
|
|
25
|
+
`Splice requires channel status '${required}', got '${actual}'.`,
|
|
26
|
+
);
|
|
27
|
+
this.name = 'SpliceChannelStatusError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class SpliceBalanceConservationError extends SpliceError {
|
|
32
|
+
constructor(expected: bigint, actual: bigint) {
|
|
33
|
+
super(
|
|
34
|
+
'BALANCE_CONSERVATION',
|
|
35
|
+
`Splice balance conservation failed: expected ${expected}, got ${actual}.`,
|
|
36
|
+
);
|
|
37
|
+
this.name = 'SpliceBalanceConservationError';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class SpliceSignatureMismatchError extends SpliceError {
|
|
42
|
+
constructor(detail: string) {
|
|
43
|
+
super('SIGNATURE_MISMATCH', `Splice signature mismatch: ${detail}`);
|
|
44
|
+
this.name = 'SpliceSignatureMismatchError';
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class SpliceMissingPartyError extends SpliceError {
|
|
49
|
+
constructor(partyId: string) {
|
|
50
|
+
super('MISSING_PARTY', `Party '${partyId}' not found in channel.`);
|
|
51
|
+
this.name = 'SpliceMissingPartyError';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export class SpliceInsufficientFundsError extends SpliceError {
|
|
56
|
+
constructor(available: bigint, requested: bigint) {
|
|
57
|
+
super(
|
|
58
|
+
'INSUFFICIENT_FUNDS',
|
|
59
|
+
`Splice-out withdraws ${requested} but channel only holds ${available}.`,
|
|
60
|
+
);
|
|
61
|
+
this.name = 'SpliceInsufficientFundsError';
|
|
62
|
+
}
|
|
63
|
+
}
|
package/src/finalize.ts
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { wotsVerifyDigest, fromHex } from '@totemsdk/core';
|
|
2
|
+
import { serializeTxBody, mineTxPoW, TX_POW_MIN_DIFFICULTY } from '@totemsdk/txpow';
|
|
3
|
+
import { concatBytes } from '@totemsdk/core';
|
|
4
|
+
import type { OmniaChannel } from '@totemsdk/omnia';
|
|
5
|
+
import type { WotsLeaseProvider } from '@totemsdk/wots-lease';
|
|
6
|
+
import type {
|
|
7
|
+
SpliceProposal,
|
|
8
|
+
SpliceAcceptance,
|
|
9
|
+
SplicedChannel,
|
|
10
|
+
QuiescedChannel,
|
|
11
|
+
} from './types.js';
|
|
12
|
+
import { buildSpliceTx, computeSpliceTxDigest, spliceDraftToMinimaBytes } from './splice-tx.js';
|
|
13
|
+
import {
|
|
14
|
+
SpliceSignatureMismatchError,
|
|
15
|
+
SpliceMissingPartyError,
|
|
16
|
+
SpliceChannelStatusError,
|
|
17
|
+
} from './errors.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Options for `finalizeSplice`.
|
|
21
|
+
*
|
|
22
|
+
* @property broadcast - Broadcast the mined TxPoW hex to the network.
|
|
23
|
+
* `finalizeSplice` throws if `broadcast` returns
|
|
24
|
+
* `{ success: false }` without a `txpowid`.
|
|
25
|
+
* @property mineDifficulty - Override PoW difficulty (pass `MAX_HASH` in tests).
|
|
26
|
+
* @property verifySignature - Custom signature verifier called for both the
|
|
27
|
+
* proposer and acceptor signatures before state
|
|
28
|
+
* transition. Defaults to `wotsVerifyDigest`.
|
|
29
|
+
* **Override in test environments** that use mock
|
|
30
|
+
* signers (mock signatures are not real WOTS sigs
|
|
31
|
+
* and will not pass the default verifier).
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* // Example test helper:
|
|
35
|
+
* verifySignature: (sig, digest, pkd) => {
|
|
36
|
+
* const expected = sha3_256(concatBytes(fromHex(pkd), digest));
|
|
37
|
+
* return expected.length === sig.length
|
|
38
|
+
* && expected.every((b, i) => b === sig[i]);
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* @property proposerLeaseProvider - Proposer's WOTS lease provider. If supplied,
|
|
43
|
+
* `finalizeSplice` will call `commitKeyUse` on the
|
|
44
|
+
* proposer's reservation after a confirmed splice TX,
|
|
45
|
+
* or `burnReservation` if finalization fails after
|
|
46
|
+
* security checks pass. Prevents one-time-key reuse.
|
|
47
|
+
*
|
|
48
|
+
* @property acceptorLeaseProvider - Acceptor's WOTS lease provider. Same commit/burn
|
|
49
|
+
* semantics as `proposerLeaseProvider`.
|
|
50
|
+
*/
|
|
51
|
+
export interface FinalizeSpliceOptions {
|
|
52
|
+
broadcast?: (txHex: string) => Promise<{ txpowid?: string; success?: boolean }>;
|
|
53
|
+
mineDifficulty?: Uint8Array;
|
|
54
|
+
verifySignature?: (
|
|
55
|
+
signature: Uint8Array,
|
|
56
|
+
digest: Uint8Array,
|
|
57
|
+
publicKeyDigest: string,
|
|
58
|
+
) => boolean;
|
|
59
|
+
proposerLeaseProvider?: WotsLeaseProvider;
|
|
60
|
+
acceptorLeaseProvider?: WotsLeaseProvider;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function defaultWotsVerify(sig: Uint8Array, digest: Uint8Array, pkd: string): boolean {
|
|
64
|
+
try {
|
|
65
|
+
return wotsVerifyDigest(sig, digest, fromHex(pkd));
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function assembleSpliceWitness(sig1: Uint8Array, sig2: Uint8Array): Uint8Array {
|
|
72
|
+
const encodeMiniNumber = (n: number): Uint8Array => {
|
|
73
|
+
const buf = new Uint8Array(4);
|
|
74
|
+
new DataView(buf.buffer).setInt32(0, n, false);
|
|
75
|
+
return buf;
|
|
76
|
+
};
|
|
77
|
+
const encodeVarBytes = (b: Uint8Array): Uint8Array => {
|
|
78
|
+
const lenBuf = new Uint8Array(4);
|
|
79
|
+
new DataView(lenBuf.buffer).setInt32(0, b.length, false);
|
|
80
|
+
return concatBytes(lenBuf, b);
|
|
81
|
+
};
|
|
82
|
+
return concatBytes(
|
|
83
|
+
encodeMiniNumber(2),
|
|
84
|
+
encodeVarBytes(sig1),
|
|
85
|
+
encodeVarBytes(sig2),
|
|
86
|
+
encodeMiniNumber(0),
|
|
87
|
+
encodeMiniNumber(0),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Structural authorization checks: both parties must be distinct channel
|
|
93
|
+
* members and both signatures must be non-empty Uint8Arrays.
|
|
94
|
+
* Cryptographic WOTS verification is performed separately by
|
|
95
|
+
* `verifySpliceSignatures`.
|
|
96
|
+
*/
|
|
97
|
+
function validateSpliceAuthorization(
|
|
98
|
+
channel: OmniaChannel | QuiescedChannel,
|
|
99
|
+
proposal: SpliceProposal,
|
|
100
|
+
acceptance: SpliceAcceptance,
|
|
101
|
+
): void {
|
|
102
|
+
const proposerParty = channel.parties.find(
|
|
103
|
+
p => p.publicKeyDigest === proposal.proposerPublicKeyDigest,
|
|
104
|
+
);
|
|
105
|
+
if (!proposerParty) throw new SpliceMissingPartyError(proposal.proposerPublicKeyDigest);
|
|
106
|
+
|
|
107
|
+
const acceptorParty = channel.parties.find(
|
|
108
|
+
p => p.publicKeyDigest === acceptance.acceptorPublicKeyDigest,
|
|
109
|
+
);
|
|
110
|
+
if (!acceptorParty) throw new SpliceMissingPartyError(acceptance.acceptorPublicKeyDigest);
|
|
111
|
+
|
|
112
|
+
if (proposal.proposerPublicKeyDigest === acceptance.acceptorPublicKeyDigest) {
|
|
113
|
+
throw new Error('Proposer and acceptor must be different channel parties');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (!proposal.proposerSignature || proposal.proposerSignature.length === 0) {
|
|
117
|
+
throw new SpliceSignatureMismatchError('Proposer signature is empty');
|
|
118
|
+
}
|
|
119
|
+
if (!acceptance.acceptorSignature || acceptance.acceptorSignature.length === 0) {
|
|
120
|
+
throw new SpliceSignatureMismatchError('Acceptor signature is empty');
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Cryptographically verify both parties' signatures against the splice TX
|
|
126
|
+
* digest. Called after structural checks; fails closed — throws on any
|
|
127
|
+
* invalid signature.
|
|
128
|
+
*
|
|
129
|
+
* The digest covers the full canonical TX structure AND `newBalances` (sorted
|
|
130
|
+
* by partyId), so signatures are bound to the exact per-party balance split.
|
|
131
|
+
*/
|
|
132
|
+
function verifySpliceSignatures(
|
|
133
|
+
proposal: SpliceProposal,
|
|
134
|
+
acceptance: SpliceAcceptance,
|
|
135
|
+
verifier: (sig: Uint8Array, digest: Uint8Array, pkd: string) => boolean,
|
|
136
|
+
): void {
|
|
137
|
+
const digest = computeSpliceTxDigest(proposal.spliceTxDraft);
|
|
138
|
+
|
|
139
|
+
if (!verifier(proposal.proposerSignature, digest, proposal.proposerPublicKeyDigest)) {
|
|
140
|
+
throw new SpliceSignatureMismatchError(
|
|
141
|
+
'Proposer signature failed cryptographic verification — digest or key mismatch',
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
if (!verifier(acceptance.acceptorSignature, digest, acceptance.acceptorPublicKeyDigest)) {
|
|
145
|
+
throw new SpliceSignatureMismatchError(
|
|
146
|
+
'Acceptor signature failed cryptographic verification — digest or key mismatch',
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Cryptographically bind the proposal's spliceTxDraft to its params by
|
|
153
|
+
* recomputing the draft deterministically and comparing digests.
|
|
154
|
+
*
|
|
155
|
+
* Prevents state divergence: finalizeSplice uses spliceTxDraft for the
|
|
156
|
+
* on-chain TX but applies channel state changes from params. If they are
|
|
157
|
+
* inconsistent, the new channel state would not match what was actually mined.
|
|
158
|
+
*/
|
|
159
|
+
function bindFinalizeParamsToDraft(
|
|
160
|
+
channel: OmniaChannel | QuiescedChannel,
|
|
161
|
+
proposal: SpliceProposal,
|
|
162
|
+
): void {
|
|
163
|
+
const recomputed = buildSpliceTx(channel as OmniaChannel, proposal.params);
|
|
164
|
+
const expected = computeSpliceTxDigest(recomputed);
|
|
165
|
+
const actual = computeSpliceTxDigest(proposal.spliceTxDraft);
|
|
166
|
+
if (!expected.every((b, i) => b === actual[i])) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
'finalizeSplice: proposal.spliceTxDraft is inconsistent with proposal.params — ' +
|
|
169
|
+
'rejecting to prevent on-chain/off-chain state divergence',
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Finalize a splice by assembling both parties' signatures, mining PoW,
|
|
176
|
+
* optionally broadcasting the TX, and returning the new active channel.
|
|
177
|
+
*
|
|
178
|
+
* **Quiesce gate**: the channel must be in `'quiesced'` state. Call
|
|
179
|
+
* `quiesceChannel` first to settle all HTLCs and sign the pre-splice state.
|
|
180
|
+
*
|
|
181
|
+
* **Security checks** (all verified before mining):
|
|
182
|
+
* 1. `channel.status === 'quiesced'`
|
|
183
|
+
* 2. `proposal.spliceId === acceptance.spliceId`
|
|
184
|
+
* 3. `proposal.channelId` and `acceptance.channelId` match `channel.channelId`
|
|
185
|
+
* 4. Proposer and acceptor are distinct, non-empty-keyed channel parties
|
|
186
|
+
* 5. Both signatures are non-empty byte arrays
|
|
187
|
+
* 6. Both signatures pass cryptographic verification against the splice TX
|
|
188
|
+
* digest (WOTS by default; override with `options.verifySignature` in tests)
|
|
189
|
+
* 7. `spliceTxDraft` digest matches what `buildSpliceTx(channel, params)` produces
|
|
190
|
+
*
|
|
191
|
+
* **WOTS lease lifecycle**:
|
|
192
|
+
* - If `options.proposerLeaseProvider` is supplied: `commitKeyUse` is called
|
|
193
|
+
* after a confirmed splice TX, or `burnReservation` on failure.
|
|
194
|
+
* - Same for `options.acceptorLeaseProvider`.
|
|
195
|
+
* - Reservations are tracked independently; only uncommitted ones are burned.
|
|
196
|
+
*
|
|
197
|
+
* **Broadcast failure**: if `broadcast()` returns `{ success: false }` without
|
|
198
|
+
* a `txpowid`, `finalizeSplice` throws and burns any open reservations.
|
|
199
|
+
*
|
|
200
|
+
* **Side effect**: the `channel` object passed in is mutated to
|
|
201
|
+
* `status: 'spliced'` after a successful finalize. This marks the old
|
|
202
|
+
* quiesced channel as invalid; only the returned `SplicedChannel` is live.
|
|
203
|
+
*
|
|
204
|
+
* **Returned SplicedChannel**:
|
|
205
|
+
* - `status: 'active'` — ready for new payments immediately
|
|
206
|
+
* - `totalValue` — updated to `proposal.params.newTotalValue`
|
|
207
|
+
* - `balances` — updated to `proposal.params.newBalances`
|
|
208
|
+
* - `currentSequence: 0` — fresh WOTS budget
|
|
209
|
+
* - `latestState: null` — no cosigned state yet
|
|
210
|
+
* - `splicedFrom` — old channel's `channelId`
|
|
211
|
+
* - `spliceFundingTxId` — mined (or broadcast) TX ID
|
|
212
|
+
* - `spliceFundingCoinId` — `<txId>-0`
|
|
213
|
+
*
|
|
214
|
+
* @param channel - Quiesced channel (mutated to 'spliced' on success).
|
|
215
|
+
* @param proposal - Splice proposal from the initiating party.
|
|
216
|
+
* @param acceptance - Co-signature from the accepting party.
|
|
217
|
+
* @param options - Broadcast, difficulty, verifier, and lease providers.
|
|
218
|
+
* @returns SplicedChannel (`status: 'active'`) with updated value and provenance.
|
|
219
|
+
*/
|
|
220
|
+
export async function finalizeSplice(
|
|
221
|
+
channel: OmniaChannel | QuiescedChannel,
|
|
222
|
+
proposal: SpliceProposal,
|
|
223
|
+
acceptance: SpliceAcceptance,
|
|
224
|
+
options?: FinalizeSpliceOptions,
|
|
225
|
+
): Promise<SplicedChannel> {
|
|
226
|
+
if (channel.status !== 'quiesced') {
|
|
227
|
+
throw new SpliceChannelStatusError('quiesced', channel.status);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (proposal.spliceId !== acceptance.spliceId) {
|
|
231
|
+
throw new SpliceSignatureMismatchError(
|
|
232
|
+
`proposal spliceId '${proposal.spliceId}' !== acceptance spliceId '${acceptance.spliceId}'`,
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
if (proposal.channelId !== channel.channelId) {
|
|
236
|
+
throw new Error(
|
|
237
|
+
`proposal.channelId '${proposal.channelId}' does not match channel '${channel.channelId}'`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
if (acceptance.channelId !== channel.channelId) {
|
|
241
|
+
throw new Error(
|
|
242
|
+
`acceptance.channelId '${acceptance.channelId}' does not match channel '${channel.channelId}'`,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
validateSpliceAuthorization(channel, proposal, acceptance);
|
|
247
|
+
|
|
248
|
+
const verifier = options?.verifySignature ?? defaultWotsVerify;
|
|
249
|
+
verifySpliceSignatures(proposal, acceptance, verifier);
|
|
250
|
+
|
|
251
|
+
bindFinalizeParamsToDraft(channel, proposal);
|
|
252
|
+
|
|
253
|
+
const proposerLease = options?.proposerLeaseProvider;
|
|
254
|
+
const acceptorLease = options?.acceptorLeaseProvider;
|
|
255
|
+
|
|
256
|
+
// Track which reservations have been committed so we know which to burn on failure.
|
|
257
|
+
const committed = new Set<string>();
|
|
258
|
+
|
|
259
|
+
const txBytes = spliceDraftToMinimaBytes(proposal.spliceTxDraft);
|
|
260
|
+
const witnessBytes = assembleSpliceWitness(
|
|
261
|
+
proposal.proposerSignature,
|
|
262
|
+
acceptance.acceptorSignature,
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
let spliceFundingTxId: string;
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
const difficulty = options?.mineDifficulty ?? TX_POW_MIN_DIFFICULTY;
|
|
269
|
+
const txBody = serializeTxBody(txBytes, witnessBytes);
|
|
270
|
+
const mined = await mineTxPoW(txBody, difficulty);
|
|
271
|
+
const fullTxPoW = concatBytes(mined.minedHeaderBytes, new Uint8Array([0x01]), txBody);
|
|
272
|
+
const txHex = Buffer.from(fullTxPoW).toString('hex');
|
|
273
|
+
|
|
274
|
+
spliceFundingTxId = Buffer.from(mined.txpowId).toString('hex');
|
|
275
|
+
|
|
276
|
+
if (options?.broadcast) {
|
|
277
|
+
const result = await options.broadcast(txHex);
|
|
278
|
+
if (result.txpowid) {
|
|
279
|
+
spliceFundingTxId = result.txpowid;
|
|
280
|
+
} else if (result.success === false) {
|
|
281
|
+
throw new Error(
|
|
282
|
+
'Splice TX broadcast rejected by the network — channel state not advanced',
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Commit leases on confirmed splice TX
|
|
288
|
+
if (proposerLease) {
|
|
289
|
+
await proposerLease.commitKeyUse(proposal.proposerReservationId, spliceFundingTxId);
|
|
290
|
+
committed.add(proposal.proposerReservationId);
|
|
291
|
+
}
|
|
292
|
+
if (acceptorLease) {
|
|
293
|
+
await acceptorLease.commitKeyUse(acceptance.acceptorReservationId, spliceFundingTxId);
|
|
294
|
+
committed.add(acceptance.acceptorReservationId);
|
|
295
|
+
}
|
|
296
|
+
} catch (err) {
|
|
297
|
+
// Burn any reservations that were not yet committed (fail-close lease accounting)
|
|
298
|
+
await Promise.allSettled([
|
|
299
|
+
proposerLease && !committed.has(proposal.proposerReservationId)
|
|
300
|
+
? proposerLease.burnReservation(proposal.proposerReservationId, 'finalize-failed')
|
|
301
|
+
: undefined,
|
|
302
|
+
acceptorLease && !committed.has(acceptance.acceptorReservationId)
|
|
303
|
+
? acceptorLease.burnReservation(acceptance.acceptorReservationId, 'finalize-failed')
|
|
304
|
+
: undefined,
|
|
305
|
+
].filter((x): x is Promise<void> => x !== undefined));
|
|
306
|
+
throw err;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const spliceFundingCoinId = `${spliceFundingTxId}-0`;
|
|
310
|
+
const params = proposal.params;
|
|
311
|
+
|
|
312
|
+
const splicedChannel: SplicedChannel = {
|
|
313
|
+
...(channel as unknown as OmniaChannel),
|
|
314
|
+
status: 'active',
|
|
315
|
+
splicedFrom: channel.channelId,
|
|
316
|
+
spliceType: params.type,
|
|
317
|
+
spliceFundingTxId,
|
|
318
|
+
spliceFundingCoinId,
|
|
319
|
+
fundingTxId: spliceFundingTxId,
|
|
320
|
+
fundingCoinId: spliceFundingCoinId,
|
|
321
|
+
totalValue: params.newTotalValue,
|
|
322
|
+
balances: params.newBalances,
|
|
323
|
+
currentSequence: 0,
|
|
324
|
+
latestState: null,
|
|
325
|
+
pendingHTLCs: [],
|
|
326
|
+
stateLog: [
|
|
327
|
+
...channel.stateLog,
|
|
328
|
+
{
|
|
329
|
+
sequence: 0,
|
|
330
|
+
timestamp: Date.now(),
|
|
331
|
+
balances: { ...params.newBalances },
|
|
332
|
+
htlcCount: 0,
|
|
333
|
+
event: 'update',
|
|
334
|
+
},
|
|
335
|
+
],
|
|
336
|
+
updatedAt: Date.now(),
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
// Mark the old (quiesced) channel as spliced — it is now invalidated.
|
|
340
|
+
// Any further operations on `channel` should be rejected by status checks.
|
|
341
|
+
(channel as unknown as OmniaChannel).status = 'spliced';
|
|
342
|
+
|
|
343
|
+
return splicedChannel;
|
|
344
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
|
|
6
|
+
export type {
|
|
7
|
+
SpliceType,
|
|
8
|
+
SpliceParams,
|
|
9
|
+
SpliceTxDraft,
|
|
10
|
+
SpliceTxInput,
|
|
11
|
+
SpliceTxOutput,
|
|
12
|
+
SpliceProposal,
|
|
13
|
+
SpliceAcceptance,
|
|
14
|
+
QuiescedChannel,
|
|
15
|
+
SplicedChannel,
|
|
16
|
+
SpliceLeaseProvider,
|
|
17
|
+
SpliceSigningIndices,
|
|
18
|
+
WotsSignature,
|
|
19
|
+
} from './types.js';
|
|
20
|
+
|
|
21
|
+
export {
|
|
22
|
+
SpliceError,
|
|
23
|
+
PendingHTLCError,
|
|
24
|
+
SpliceChannelStatusError,
|
|
25
|
+
SpliceBalanceConservationError,
|
|
26
|
+
SpliceSignatureMismatchError,
|
|
27
|
+
SpliceMissingPartyError,
|
|
28
|
+
SpliceInsufficientFundsError,
|
|
29
|
+
} from './errors.js';
|
package/src/quiesce.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { updateState } from '@totemsdk/omnia';
|
|
2
|
+
import type { OmniaChannel } from '@totemsdk/omnia';
|
|
3
|
+
import type { QuiescedChannel, SpliceLeaseProvider } from './types.js';
|
|
4
|
+
import { PendingHTLCError, SpliceChannelStatusError } from './errors.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Options for `quiesceChannel`.
|
|
8
|
+
*/
|
|
9
|
+
export interface QuiesceOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Called when the channel has pending HTLCs that have not yet reached a
|
|
12
|
+
* terminal state (`fulfilled` or `timed_out`). If provided, `quiesceChannel`
|
|
13
|
+
* invokes this callback with the still-pending HTLCs, giving the caller an
|
|
14
|
+
* opportunity to drive resolution — e.g. submit preimage reveals, wait for
|
|
15
|
+
* timeout blocks, or poll a Minima node — before the quiesce is retried.
|
|
16
|
+
*
|
|
17
|
+
* After the callback resolves, `channel.pendingHTLCs` is re-inspected. If
|
|
18
|
+
* all HTLCs have moved to a terminal state the quiesce proceeds; if any are
|
|
19
|
+
* still pending, `PendingHTLCError` is thrown.
|
|
20
|
+
*
|
|
21
|
+
* If this option is not provided, `PendingHTLCError` is thrown immediately
|
|
22
|
+
* when pending HTLCs are found.
|
|
23
|
+
*
|
|
24
|
+
* @param pending - The HTLCs that still need resolution.
|
|
25
|
+
*/
|
|
26
|
+
awaitResolution?: (pending: OmniaChannel['pendingHTLCs']) => Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Quiesce a channel before splicing.
|
|
31
|
+
*
|
|
32
|
+
* Quiescing is mandatory before a splice can be proposed or accepted. It:
|
|
33
|
+
* 1. Validates the channel is `'active'`.
|
|
34
|
+
* 2. Ensures all in-flight HTLCs have reached a terminal state
|
|
35
|
+
* (`fulfilled` or `timed_out`). If pending HTLCs exist and
|
|
36
|
+
* `options.awaitResolution` is provided, the callback is invoked so the
|
|
37
|
+
* caller can drive/await resolution (submit preimages, wait for timeouts,
|
|
38
|
+
* poll a node). After the callback the channel is re-checked. If HTLCs
|
|
39
|
+
* remain pending, `PendingHTLCError` is thrown. If the option is absent
|
|
40
|
+
* and pending HTLCs exist, `PendingHTLCError` is thrown immediately.
|
|
41
|
+
* 3. Signs a final state update (via `updateState`) that captures the settled
|
|
42
|
+
* balance split at `currentSequence + 1`. This produces a WOTS-signed
|
|
43
|
+
* `Partial<SignedChannelState>` binding both parties to the pre-splice
|
|
44
|
+
* balance before the splice TX resets the sequence to 0.
|
|
45
|
+
* 4. Returns a `QuiescedChannel` with `status: 'quiesced'`, `pendingHTLCs: []`
|
|
46
|
+
* (all resolved HTLCs cleared), and `quiesceSignedState` containing the
|
|
47
|
+
* local party's partial signature over the final balance state.
|
|
48
|
+
*
|
|
49
|
+
* The caller must exchange `quiesceSignedState` with the counterparty to obtain
|
|
50
|
+
* their co-signature, providing a fully signed record of the last pre-splice
|
|
51
|
+
* balance for any future dispute resolution.
|
|
52
|
+
*
|
|
53
|
+
* @param channel - The active channel to quiesce.
|
|
54
|
+
* @param leaseProvider - Provides the local party's signer and WOTS lease.
|
|
55
|
+
* @param options - Optional: `awaitResolution` callback for HTLC settlement.
|
|
56
|
+
* @returns A QuiescedChannel with `status: 'quiesced'`, cleared `pendingHTLCs`,
|
|
57
|
+
* and the local party's partial signature over the final balance state.
|
|
58
|
+
* @throws {SpliceChannelStatusError} If channel is not active.
|
|
59
|
+
* @throws {PendingHTLCError} If HTLCs remain pending after resolution.
|
|
60
|
+
*/
|
|
61
|
+
export async function quiesceChannel(
|
|
62
|
+
channel: OmniaChannel,
|
|
63
|
+
leaseProvider: SpliceLeaseProvider,
|
|
64
|
+
options?: QuiesceOptions,
|
|
65
|
+
): Promise<QuiescedChannel> {
|
|
66
|
+
if (channel.status !== 'active') {
|
|
67
|
+
throw new SpliceChannelStatusError('active', channel.status);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const pendingHTLCs = channel.pendingHTLCs.filter(h => h.status === 'pending');
|
|
71
|
+
if (pendingHTLCs.length > 0) {
|
|
72
|
+
if (options?.awaitResolution) {
|
|
73
|
+
await options.awaitResolution(pendingHTLCs);
|
|
74
|
+
const stillPending = channel.pendingHTLCs.filter(h => h.status === 'pending').length;
|
|
75
|
+
if (stillPending > 0) {
|
|
76
|
+
throw new PendingHTLCError(stillPending);
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
throw new PendingHTLCError(pendingHTLCs.length);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const { channel: updatedChannel, signedState, error } = await updateState(
|
|
84
|
+
channel,
|
|
85
|
+
{ newBalances: channel.balances },
|
|
86
|
+
leaseProvider.wotsLease,
|
|
87
|
+
leaseProvider.signer,
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
if (error) {
|
|
91
|
+
throw new Error(`quiesceChannel: updateState blocked — ${error}. Splice cannot proceed.`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const quiesced: QuiescedChannel = {
|
|
95
|
+
...(updatedChannel as Omit<OmniaChannel, 'status'>),
|
|
96
|
+
status: 'quiesced',
|
|
97
|
+
pendingHTLCs: [],
|
|
98
|
+
quiesceSignedState: signedState,
|
|
99
|
+
updatedAt: Date.now(),
|
|
100
|
+
} as QuiescedChannel;
|
|
101
|
+
|
|
102
|
+
return quiesced;
|
|
103
|
+
}
|