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