@totemsdk/omnia-splice 0.3.0 → 0.3.2
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/LICENSE +202 -21
- package/NOTICE +60 -0
- package/README.md +5 -0
- package/dist/cjs/finalize.d.ts +16 -1
- package/dist/cjs/finalize.js +39 -5
- package/dist/cjs/index.d.ts +3 -1
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/splice-tx.js +23 -33
- package/dist/cjs/splice.d.ts +25 -1
- package/dist/cjs/splice.js +74 -0
- package/dist/cjs/successor.d.ts +102 -0
- package/dist/cjs/successor.js +108 -0
- package/dist/cjs/types.d.ts +4 -0
- package/dist/finalize.d.ts +16 -1
- package/dist/finalize.js +39 -5
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/splice-tx.js +24 -34
- package/dist/splice.d.ts +25 -1
- package/dist/splice.js +71 -0
- package/dist/successor.d.ts +102 -0
- package/dist/successor.js +104 -0
- package/dist/types.d.ts +4 -0
- package/package.json +11 -13
- package/rust/pkg/package.json +1 -1
- package/rust/pkg-node/package.json +1 -1
package/dist/cjs/splice.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildSpliceProposal = buildSpliceProposal;
|
|
4
|
+
exports.buildSpliceInProposal = buildSpliceInProposal;
|
|
5
|
+
exports.buildSpliceOutProposal = buildSpliceOutProposal;
|
|
3
6
|
exports.proposeSpliceIn = proposeSpliceIn;
|
|
4
7
|
exports.proposeSpliceOut = proposeSpliceOut;
|
|
5
8
|
exports.acceptSplice = acceptSplice;
|
|
@@ -104,6 +107,77 @@ function bindDraftToParams(channel, proposal) {
|
|
|
104
107
|
'the TX draft may have been tampered with');
|
|
105
108
|
}
|
|
106
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Build the deterministic splice draft/digest without signing. Used by the
|
|
112
|
+
* wallet/coordinator flow: the caller signs `digest` and attaches the
|
|
113
|
+
* signature before finalization.
|
|
114
|
+
*/
|
|
115
|
+
function buildSpliceProposal(channel, params, proposerPublicKeyDigest) {
|
|
116
|
+
validateChannelQuiesced(channel);
|
|
117
|
+
validateProposalParams(channel, params);
|
|
118
|
+
const proposerInChannel = channel.parties.find(p => p.publicKeyDigest === proposerPublicKeyDigest);
|
|
119
|
+
if (!proposerInChannel)
|
|
120
|
+
throw new errors_js_1.SpliceMissingPartyError(proposerPublicKeyDigest);
|
|
121
|
+
const draft = (0, splice_tx_js_1.buildSpliceTx)(channel, params);
|
|
122
|
+
return {
|
|
123
|
+
spliceId: generateSpliceId(),
|
|
124
|
+
channelId: channel.channelId,
|
|
125
|
+
params,
|
|
126
|
+
spliceTxHex: Buffer.from((0, splice_tx_js_1.spliceDraftToMinimaBytes)(draft)).toString('hex'),
|
|
127
|
+
spliceTxDraft: draft,
|
|
128
|
+
proposerPublicKeyDigest,
|
|
129
|
+
digest: (0, splice_tx_js_1.computeSpliceTxDigest)(draft),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Build an unsigned splice-in proposal (see `buildSpliceProposal`). */
|
|
133
|
+
function buildSpliceInProposal(channel, additionalCoinId, additionalAmount, proposerPublicKeyDigest, newBalances) {
|
|
134
|
+
validateChannelQuiesced(channel);
|
|
135
|
+
const newTotal = channel.totalValue + additionalAmount;
|
|
136
|
+
const effectiveNewBalances = newBalances ?? scaleBalances(channel.balances, channel.totalValue, newTotal);
|
|
137
|
+
return buildSpliceProposal(channel, {
|
|
138
|
+
type: 'splice_in',
|
|
139
|
+
newTotalValue: newTotal,
|
|
140
|
+
newBalances: effectiveNewBalances,
|
|
141
|
+
additionalCoinId,
|
|
142
|
+
additionalAmount,
|
|
143
|
+
}, proposerPublicKeyDigest);
|
|
144
|
+
}
|
|
145
|
+
/** Build an unsigned splice-out proposal (see `buildSpliceProposal`). */
|
|
146
|
+
function buildSpliceOutProposal(channel, withdrawAmount, withdrawAddress, proposerPublicKeyDigest, newBalances, extraOutputs) {
|
|
147
|
+
validateChannelQuiesced(channel);
|
|
148
|
+
const extraSum = (extraOutputs ?? []).reduce((a, o) => a + o.amount, 0n);
|
|
149
|
+
const totalOutflow = withdrawAmount + extraSum;
|
|
150
|
+
if (totalOutflow > channel.totalValue) {
|
|
151
|
+
throw new Error(`buildSpliceOutProposal: total outflow (withdraw ${withdrawAmount} + extra outputs ${extraSum} = ${totalOutflow}) ` +
|
|
152
|
+
`exceeds channel totalValue (${channel.totalValue})`);
|
|
153
|
+
}
|
|
154
|
+
const remainingTotal = channel.totalValue - totalOutflow;
|
|
155
|
+
const effectiveNewBalances = newBalances ?? (() => {
|
|
156
|
+
const ratio = channel.totalValue > 0n ? remainingTotal * 1000n / channel.totalValue : 0n;
|
|
157
|
+
const adjusted = {};
|
|
158
|
+
let assigned = 0n;
|
|
159
|
+
const partyIds = Object.keys(channel.balances);
|
|
160
|
+
for (let i = 0; i < partyIds.length - 1; i++) {
|
|
161
|
+
const pid = partyIds[i];
|
|
162
|
+
const prev = channel.balances[pid] ?? 0n;
|
|
163
|
+
const scaled = (prev * ratio) / 1000n;
|
|
164
|
+
adjusted[pid] = scaled;
|
|
165
|
+
assigned += scaled;
|
|
166
|
+
}
|
|
167
|
+
const lastId = partyIds[partyIds.length - 1];
|
|
168
|
+
if (lastId)
|
|
169
|
+
adjusted[lastId] = remainingTotal - assigned;
|
|
170
|
+
return adjusted;
|
|
171
|
+
})();
|
|
172
|
+
return buildSpliceProposal(channel, {
|
|
173
|
+
type: 'splice_out',
|
|
174
|
+
newTotalValue: remainingTotal,
|
|
175
|
+
newBalances: effectiveNewBalances,
|
|
176
|
+
withdrawAmount,
|
|
177
|
+
withdrawAddress,
|
|
178
|
+
extraOutputs,
|
|
179
|
+
}, proposerPublicKeyDigest);
|
|
180
|
+
}
|
|
107
181
|
/**
|
|
108
182
|
* Initiating party proposes a splice-in: add external funds to the channel.
|
|
109
183
|
*
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splice successor observation and interrupted-broadcast recovery (RFC-078 §3.5).
|
|
3
|
+
*
|
|
4
|
+
* A splice spends the old channel coin and creates a successor at the same
|
|
5
|
+
* eltoo address. The successor coin id is not known from the transaction alone
|
|
6
|
+
* because the channel input floats (`COINID_ELTOO`). The only trustworthy
|
|
7
|
+
* answer comes from observing the funding address after broadcast. This module
|
|
8
|
+
* provides that observation plus a small journal seam so a process that dies
|
|
9
|
+
* between broadcast and confirmation can finish or retry safely.
|
|
10
|
+
*/
|
|
11
|
+
import type { ChannelStatus } from '@totemsdk/omnia';
|
|
12
|
+
/** Minimal chain surface needed by splice observation. */
|
|
13
|
+
export interface SpliceChainObserver {
|
|
14
|
+
getCoins(query: {
|
|
15
|
+
address?: string;
|
|
16
|
+
tokenId?: string;
|
|
17
|
+
coinId?: string;
|
|
18
|
+
relevant?: boolean;
|
|
19
|
+
}): Promise<Array<{
|
|
20
|
+
coinid: string;
|
|
21
|
+
amount: string;
|
|
22
|
+
address: string;
|
|
23
|
+
tokenid: string;
|
|
24
|
+
spent?: boolean;
|
|
25
|
+
created?: string;
|
|
26
|
+
mmrentry?: string;
|
|
27
|
+
}>>;
|
|
28
|
+
getTip(): Promise<{
|
|
29
|
+
block: number;
|
|
30
|
+
}>;
|
|
31
|
+
}
|
|
32
|
+
export interface SpliceSuccessorOptions {
|
|
33
|
+
/** Channel funding address the successor must pay to. */
|
|
34
|
+
address: string;
|
|
35
|
+
/** Token id of the channel coin. */
|
|
36
|
+
tokenId: string;
|
|
37
|
+
/** Exact successor amount. */
|
|
38
|
+
amount: bigint;
|
|
39
|
+
/** Confirmations required before the channel is active. Default 1. */
|
|
40
|
+
confirmations?: number;
|
|
41
|
+
/** Give up after this long and leave the channel funding-pending. Default 30s. */
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
/** Poll interval. Default 1s. */
|
|
44
|
+
pollIntervalMs?: number;
|
|
45
|
+
/** Absolute deadline override (used by recovery paths). */
|
|
46
|
+
now?: () => number;
|
|
47
|
+
/** Injected sleep (tests). */
|
|
48
|
+
sleep?: (ms: number) => Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
export interface ObservedSuccessor {
|
|
51
|
+
coinId: string;
|
|
52
|
+
confirmations: number;
|
|
53
|
+
confirmed: boolean;
|
|
54
|
+
coin: {
|
|
55
|
+
coinid: string;
|
|
56
|
+
amount: string;
|
|
57
|
+
address: string;
|
|
58
|
+
tokenid: string;
|
|
59
|
+
created?: string;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Find the successor coin at the channel address, excluding the spent old
|
|
64
|
+
* coin. A coin with `spent: true` is never a valid successor. Confirmation
|
|
65
|
+
* depth is derived from the coin's creation height when the provider supplies
|
|
66
|
+
* it; otherwise it is treated as unconfirmed.
|
|
67
|
+
*/
|
|
68
|
+
export declare function observeSpliceSuccessor(chain: SpliceChainObserver, options: SpliceSuccessorOptions): Promise<ObservedSuccessor | null>;
|
|
69
|
+
/** Durable record written before broadcast so a restart can reconcile. */
|
|
70
|
+
export interface PendingSpliceRecord {
|
|
71
|
+
spliceId: string;
|
|
72
|
+
channelId: string;
|
|
73
|
+
txHex: string;
|
|
74
|
+
txpowId: string;
|
|
75
|
+
coinId?: string;
|
|
76
|
+
broadcastAt: number;
|
|
77
|
+
}
|
|
78
|
+
export interface PendingSpliceStore {
|
|
79
|
+
save(record: PendingSpliceRecord): Promise<void> | void;
|
|
80
|
+
clear(spliceId: string): Promise<void> | void;
|
|
81
|
+
list(): Promise<PendingSpliceRecord[]> | PendingSpliceRecord[];
|
|
82
|
+
}
|
|
83
|
+
/** Outcome of reconciling one interrupted splice. */
|
|
84
|
+
export interface SpliceRecoveryResult {
|
|
85
|
+
spliceId: string;
|
|
86
|
+
status: ChannelStatus;
|
|
87
|
+
coinId?: string;
|
|
88
|
+
rebroadcast: boolean;
|
|
89
|
+
error?: string;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Reconcile interrupted broadcasts.
|
|
93
|
+
*
|
|
94
|
+
* - If the successor is already visible, record its coin id and clear the
|
|
95
|
+
* pending entry.
|
|
96
|
+
* - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
|
|
97
|
+
* and leave the entry pending for the next pass.
|
|
98
|
+
*/
|
|
99
|
+
export declare function recoverInterruptedSplices(store: PendingSpliceStore, chain: SpliceChainObserver, observe: Omit<SpliceSuccessorOptions, 'now'>, broadcast: (txHex: string) => Promise<{
|
|
100
|
+
txpowid?: string;
|
|
101
|
+
success?: boolean;
|
|
102
|
+
}>): Promise<SpliceRecoveryResult[]>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Splice successor observation and interrupted-broadcast recovery (RFC-078 §3.5).
|
|
4
|
+
*
|
|
5
|
+
* A splice spends the old channel coin and creates a successor at the same
|
|
6
|
+
* eltoo address. The successor coin id is not known from the transaction alone
|
|
7
|
+
* because the channel input floats (`COINID_ELTOO`). The only trustworthy
|
|
8
|
+
* answer comes from observing the funding address after broadcast. This module
|
|
9
|
+
* provides that observation plus a small journal seam so a process that dies
|
|
10
|
+
* between broadcast and confirmation can finish or retry safely.
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.observeSpliceSuccessor = observeSpliceSuccessor;
|
|
14
|
+
exports.recoverInterruptedSplices = recoverInterruptedSplices;
|
|
15
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
16
|
+
/**
|
|
17
|
+
* Find the successor coin at the channel address, excluding the spent old
|
|
18
|
+
* coin. A coin with `spent: true` is never a valid successor. Confirmation
|
|
19
|
+
* depth is derived from the coin's creation height when the provider supplies
|
|
20
|
+
* it; otherwise it is treated as unconfirmed.
|
|
21
|
+
*/
|
|
22
|
+
async function observeSpliceSuccessor(chain, options) {
|
|
23
|
+
const required = options.confirmations ?? 1;
|
|
24
|
+
const timeoutMs = options.timeoutMs ?? 30000;
|
|
25
|
+
const pollMs = options.pollIntervalMs ?? 1000;
|
|
26
|
+
const now = options.now ?? (() => Date.now());
|
|
27
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
28
|
+
const deadline = now() + timeoutMs;
|
|
29
|
+
for (;;) {
|
|
30
|
+
const coins = await chain.getCoins({ address: options.address, tokenId: options.tokenId });
|
|
31
|
+
const candidate = coins.find((coin) => !coin.spent
|
|
32
|
+
&& coin.address.toLowerCase() === options.address.toLowerCase()
|
|
33
|
+
&& coin.tokenid.toLowerCase() === options.tokenId.toLowerCase()
|
|
34
|
+
&& BigInt(coin.amount) === options.amount);
|
|
35
|
+
if (candidate) {
|
|
36
|
+
const tip = await chain.getTip();
|
|
37
|
+
const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
|
|
38
|
+
const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
|
|
39
|
+
if (confirmations >= required) {
|
|
40
|
+
return { coinId: candidate.coinid, confirmations, confirmed: true, coin: candidate };
|
|
41
|
+
}
|
|
42
|
+
// Found but not deep enough; keep polling until the deadline.
|
|
43
|
+
}
|
|
44
|
+
if (now() >= deadline) {
|
|
45
|
+
if (candidate) {
|
|
46
|
+
const tip = await chain.getTip();
|
|
47
|
+
const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
|
|
48
|
+
const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
|
|
49
|
+
return { coinId: candidate.coinid, confirmations, confirmed: confirmations >= required, coin: candidate };
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
await sleep(pollMs);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Reconcile interrupted broadcasts.
|
|
58
|
+
*
|
|
59
|
+
* - If the successor is already visible, record its coin id and clear the
|
|
60
|
+
* pending entry.
|
|
61
|
+
* - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
|
|
62
|
+
* and leave the entry pending for the next pass.
|
|
63
|
+
*/
|
|
64
|
+
async function recoverInterruptedSplices(store, chain, observe, broadcast) {
|
|
65
|
+
const pending = await store.list();
|
|
66
|
+
const results = [];
|
|
67
|
+
for (const record of pending) {
|
|
68
|
+
try {
|
|
69
|
+
const observed = await observeSpliceSuccessor(chain, { ...observe, timeoutMs: observe.timeoutMs ?? 0 });
|
|
70
|
+
if (observed?.confirmed) {
|
|
71
|
+
await store.clear(record.spliceId);
|
|
72
|
+
results.push({
|
|
73
|
+
spliceId: record.spliceId,
|
|
74
|
+
status: 'active',
|
|
75
|
+
coinId: observed.coinId,
|
|
76
|
+
rebroadcast: false,
|
|
77
|
+
});
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const rebroadcast = await broadcast(record.txHex);
|
|
81
|
+
if (rebroadcast.success === false && !rebroadcast.txpowid) {
|
|
82
|
+
results.push({
|
|
83
|
+
spliceId: record.spliceId,
|
|
84
|
+
status: 'funding_pending',
|
|
85
|
+
rebroadcast: true,
|
|
86
|
+
error: 'rebroadcast rejected',
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
results.push({
|
|
91
|
+
spliceId: record.spliceId,
|
|
92
|
+
status: observed ? 'funding_pending' : 'funding_pending',
|
|
93
|
+
...(observed ? { coinId: observed.coinId } : {}),
|
|
94
|
+
rebroadcast: true,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
results.push({
|
|
100
|
+
spliceId: record.spliceId,
|
|
101
|
+
status: 'funding_pending',
|
|
102
|
+
rebroadcast: false,
|
|
103
|
+
error: String(error),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return results;
|
|
108
|
+
}
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -32,11 +32,15 @@ export interface SpliceTxOutput {
|
|
|
32
32
|
storeState: boolean;
|
|
33
33
|
stateVarSettlement: boolean;
|
|
34
34
|
stateVarSequence: number;
|
|
35
|
+
/** Optional V2 state commitment (binds off-chain balances to the splice TX). */
|
|
36
|
+
stateVarCommitment?: string;
|
|
35
37
|
}
|
|
36
38
|
export interface SpliceTxDraft {
|
|
37
39
|
inputs: SpliceTxInput[];
|
|
38
40
|
outputs: SpliceTxOutput[];
|
|
39
41
|
channelId: string;
|
|
42
|
+
/** Sequence the new channel coin commits to (must exceed the old channel). */
|
|
43
|
+
nextSequence: number;
|
|
40
44
|
params: SpliceParams;
|
|
41
45
|
}
|
|
42
46
|
/**
|
package/dist/finalize.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { OmniaChannel } from '@totemsdk/omnia';
|
|
2
2
|
import type { WotsLeaseProvider } from '@totemsdk/wots-lease';
|
|
3
3
|
import type { SpliceProposal, SpliceAcceptance, SplicedChannel, QuiescedChannel } from './types.js';
|
|
4
|
+
import { type PendingSpliceStore, type SpliceChainObserver } from './successor.js';
|
|
4
5
|
/**
|
|
5
6
|
* Options for `finalizeSplice`.
|
|
6
7
|
*
|
|
@@ -42,6 +43,20 @@ export interface FinalizeSpliceOptions {
|
|
|
42
43
|
verifySignature?: (signature: Uint8Array, digest: Uint8Array, publicKeyDigest: string) => boolean;
|
|
43
44
|
proposerLeaseProvider?: WotsLeaseProvider;
|
|
44
45
|
acceptorLeaseProvider?: WotsLeaseProvider;
|
|
46
|
+
/**
|
|
47
|
+
* Chain surface used to observe the successor coin. When supplied the
|
|
48
|
+
* returned channel is only `active` after the successor is visible with the
|
|
49
|
+
* required confirmation depth; otherwise it is `funding_pending`.
|
|
50
|
+
*/
|
|
51
|
+
chainProvider?: SpliceChainObserver;
|
|
52
|
+
/** Confirmations required before activation. Default 1. */
|
|
53
|
+
confirmations?: number;
|
|
54
|
+
/** Successor observation timeout. Default 30s. */
|
|
55
|
+
successorTimeoutMs?: number;
|
|
56
|
+
/** Observation poll interval. Default 1s. */
|
|
57
|
+
successorPollMs?: number;
|
|
58
|
+
/** Durable journal written before broadcast, cleared after confirmation. */
|
|
59
|
+
pendingSpliceStore?: PendingSpliceStore;
|
|
45
60
|
}
|
|
46
61
|
/**
|
|
47
62
|
* Finalize a splice by assembling both parties' signatures, mining PoW,
|
|
@@ -77,7 +92,7 @@ export interface FinalizeSpliceOptions {
|
|
|
77
92
|
* - `status: 'active'` — ready for new payments immediately
|
|
78
93
|
* - `totalValue` — updated to `proposal.params.newTotalValue`
|
|
79
94
|
* - `balances` — updated to `proposal.params.newBalances`
|
|
80
|
-
* - `currentSequence:
|
|
95
|
+
* - `currentSequence: nextSequence` — successor state (must exceed the old channel)
|
|
81
96
|
* - `latestState: null` — no cosigned state yet
|
|
82
97
|
* - `splicedFrom` — old channel's `channelId`
|
|
83
98
|
* - `spliceFundingTxId` — mined (or broadcast) TX ID
|
package/dist/finalize.js
CHANGED
|
@@ -2,6 +2,7 @@ import { concatBytes } from '@totemsdk/core';
|
|
|
2
2
|
import { serializeTxBody, mineTxPoW, TX_POW_MIN_DIFFICULTY } from '@totemsdk/txpow';
|
|
3
3
|
import { verifyChannelSignature } from '@totemsdk/omnia';
|
|
4
4
|
import { buildSpliceTx, computeSpliceTxDigest, spliceDraftToMinimaBytes } from './splice-tx.js';
|
|
5
|
+
import { observeSpliceSuccessor, } from './successor.js';
|
|
5
6
|
import { SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceChannelStatusError, } from './errors.js';
|
|
6
7
|
function defaultWotsVerify(sig, digest, pkd) {
|
|
7
8
|
return verifyChannelSignature(sig, digest, pkd);
|
|
@@ -110,7 +111,7 @@ function bindFinalizeParamsToDraft(channel, proposal) {
|
|
|
110
111
|
* - `status: 'active'` — ready for new payments immediately
|
|
111
112
|
* - `totalValue` — updated to `proposal.params.newTotalValue`
|
|
112
113
|
* - `balances` — updated to `proposal.params.newBalances`
|
|
113
|
-
* - `currentSequence:
|
|
114
|
+
* - `currentSequence: nextSequence` — successor state (must exceed the old channel)
|
|
114
115
|
* - `latestState: null` — no cosigned state yet
|
|
115
116
|
* - `splicedFrom` — old channel's `channelId`
|
|
116
117
|
* - `spliceFundingTxId` — mined (or broadcast) TX ID
|
|
@@ -154,9 +155,18 @@ export async function finalizeSplice(channel, proposal, acceptance, options) {
|
|
|
154
155
|
const txHex = Buffer.from(fullTxPoW).toString('hex');
|
|
155
156
|
spliceFundingTxId = Buffer.from(mined.txpowId).toString('hex');
|
|
156
157
|
if (options?.broadcast) {
|
|
158
|
+
const record = {
|
|
159
|
+
spliceId: proposal.spliceId,
|
|
160
|
+
channelId: channel.channelId,
|
|
161
|
+
txHex,
|
|
162
|
+
txpowId: spliceFundingTxId,
|
|
163
|
+
broadcastAt: Date.now(),
|
|
164
|
+
};
|
|
165
|
+
await options.pendingSpliceStore?.save(record);
|
|
157
166
|
const result = await options.broadcast(txHex);
|
|
158
167
|
if (result.txpowid) {
|
|
159
168
|
spliceFundingTxId = result.txpowid;
|
|
169
|
+
await options.pendingSpliceStore?.save({ ...record, txpowId: result.txpowid });
|
|
160
170
|
}
|
|
161
171
|
else if (result.success === false) {
|
|
162
172
|
throw new Error('Splice TX broadcast rejected by the network — channel state not advanced');
|
|
@@ -184,11 +194,35 @@ export async function finalizeSplice(channel, proposal, acceptance, options) {
|
|
|
184
194
|
].filter((x) => x !== undefined));
|
|
185
195
|
throw err;
|
|
186
196
|
}
|
|
187
|
-
const spliceFundingCoinId = `${spliceFundingTxId}-0`;
|
|
188
197
|
const params = proposal.params;
|
|
198
|
+
// Observe the actual successor. The old channel coin is spent by the splice,
|
|
199
|
+
// so `txid-0` is only a placeholder; the live coin id comes from the funding
|
|
200
|
+
// address. Until it is confirmed the channel must not be reported active.
|
|
201
|
+
let spliceFundingCoinId = `${spliceFundingTxId}-0`;
|
|
202
|
+
let successorStatus = 'active';
|
|
203
|
+
if (options?.chainProvider) {
|
|
204
|
+
const observed = await observeSpliceSuccessor(options.chainProvider, {
|
|
205
|
+
address: channel.fundingAddress,
|
|
206
|
+
tokenId: channel.tokenId,
|
|
207
|
+
amount: params.newTotalValue,
|
|
208
|
+
confirmations: options.confirmations ?? 1,
|
|
209
|
+
timeoutMs: options.successorTimeoutMs ?? 30000,
|
|
210
|
+
pollIntervalMs: options.successorPollMs ?? 1000,
|
|
211
|
+
});
|
|
212
|
+
if (observed) {
|
|
213
|
+
spliceFundingCoinId = observed.coinId;
|
|
214
|
+
successorStatus = observed.confirmed ? 'active' : 'funding_pending';
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
successorStatus = 'funding_pending';
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (successorStatus === 'active') {
|
|
221
|
+
await options?.pendingSpliceStore?.clear(proposal.spliceId);
|
|
222
|
+
}
|
|
189
223
|
const splicedChannel = {
|
|
190
224
|
...channel,
|
|
191
|
-
status:
|
|
225
|
+
status: successorStatus,
|
|
192
226
|
splicedFrom: channel.channelId,
|
|
193
227
|
spliceType: params.type,
|
|
194
228
|
spliceFundingTxId,
|
|
@@ -197,13 +231,13 @@ export async function finalizeSplice(channel, proposal, acceptance, options) {
|
|
|
197
231
|
fundingCoinId: spliceFundingCoinId,
|
|
198
232
|
totalValue: params.newTotalValue,
|
|
199
233
|
balances: params.newBalances,
|
|
200
|
-
currentSequence:
|
|
234
|
+
currentSequence: proposal.spliceTxDraft.nextSequence,
|
|
201
235
|
latestState: null,
|
|
202
236
|
pendingHTLCs: [],
|
|
203
237
|
stateLog: [
|
|
204
238
|
...channel.stateLog,
|
|
205
239
|
{
|
|
206
|
-
sequence:
|
|
240
|
+
sequence: proposal.spliceTxDraft.nextSequence,
|
|
207
241
|
timestamp: Date.now(),
|
|
208
242
|
balances: { ...params.newBalances },
|
|
209
243
|
htlcCount: 0,
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { quiesceChannel, type QuiesceOptions } from './quiesce.js';
|
|
2
2
|
export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
|
|
3
|
-
export { proposeSpliceIn, proposeSpliceOut, acceptSplice } from './splice.js';
|
|
3
|
+
export { proposeSpliceIn, proposeSpliceOut, acceptSplice, buildSpliceProposal, buildSpliceInProposal, buildSpliceOutProposal, } from './splice.js';
|
|
4
|
+
export type { UnsignedSpliceProposal } from './splice.js';
|
|
4
5
|
export { finalizeSplice, type FinalizeSpliceOptions } from './finalize.js';
|
|
6
|
+
export { observeSpliceSuccessor, recoverInterruptedSplices, type SpliceChainObserver, type SpliceSuccessorOptions, type ObservedSuccessor, type PendingSpliceRecord, type PendingSpliceStore, type SpliceRecoveryResult, } from './successor.js';
|
|
5
7
|
export type { SpliceType, SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput, SpliceProposal, SpliceAcceptance, QuiescedChannel, SplicedChannel, SpliceLeaseProvider, SpliceSigningIndices, WotsSignature, } from './types.js';
|
|
6
8
|
export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
|
|
7
9
|
export { createDurableSpliceStore, } from './durable-splice-store.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export { quiesceChannel } from './quiesce.js';
|
|
2
2
|
export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
|
|
3
|
-
export { proposeSpliceIn, proposeSpliceOut, acceptSplice } from './splice.js';
|
|
3
|
+
export { proposeSpliceIn, proposeSpliceOut, acceptSplice, buildSpliceProposal, buildSpliceInProposal, buildSpliceOutProposal, } from './splice.js';
|
|
4
4
|
export { finalizeSplice } from './finalize.js';
|
|
5
|
+
export { observeSpliceSuccessor, recoverInterruptedSplices, } from './successor.js';
|
|
5
6
|
export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
|
|
6
7
|
export { createDurableSpliceStore, } from './durable-splice-store.js';
|
|
7
8
|
// RFC-035 B1 — splice peer round-trip over the coordination transport.
|
package/dist/splice-tx.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { sha3_256 } from '@totemsdk/core';
|
|
2
2
|
import { serializeTransaction, } from '@totemsdk/core';
|
|
3
|
-
import { COINID_ELTOO } from '@totemsdk/omnia';
|
|
3
|
+
import { COINID_ELTOO, computeStateCommitmentV2 } from '@totemsdk/omnia';
|
|
4
|
+
import { bytesToHex } from '@totemsdk/core';
|
|
4
5
|
import { SpliceBalanceConservationError, SpliceInsufficientFundsError } from './errors.js';
|
|
5
6
|
const STATE_SETTLEMENT_PORT = 100;
|
|
6
7
|
const STATE_SEQUENCE_PORT = 101;
|
|
8
|
+
const STATE_COMMITMENT_V2_PORT = 102;
|
|
7
9
|
/**
|
|
8
10
|
* Build a validated SpliceTxDraft from channel + splice params.
|
|
9
11
|
*
|
|
@@ -63,6 +65,17 @@ export function buildSpliceTx(channel, params) {
|
|
|
63
65
|
tokenId,
|
|
64
66
|
});
|
|
65
67
|
}
|
|
68
|
+
// A splice spends the old channel coin and creates a successor at the same
|
|
69
|
+
// script. The channel script requires STATE(101) GT PREVSTATE(101) for a
|
|
70
|
+
// non-settlement update, so the successor must advance the sequence. Resetting
|
|
71
|
+
// to zero is not a WOTS-capacity reset and is rejected by the script.
|
|
72
|
+
const nextSequence = channel.currentSequence + 1;
|
|
73
|
+
const postSpliceChannel = {
|
|
74
|
+
...channel,
|
|
75
|
+
totalValue: params.newTotalValue,
|
|
76
|
+
balances: { ...params.newBalances },
|
|
77
|
+
};
|
|
78
|
+
const stateCommitment = bytesToHex(computeStateCommitmentV2(postSpliceChannel, nextSequence, params.newBalances, [], { settlement: false }));
|
|
66
79
|
const outputs = [
|
|
67
80
|
{
|
|
68
81
|
address: channel.fundingAddress,
|
|
@@ -70,7 +83,8 @@ export function buildSpliceTx(channel, params) {
|
|
|
70
83
|
tokenId,
|
|
71
84
|
storeState: true,
|
|
72
85
|
stateVarSettlement: false,
|
|
73
|
-
stateVarSequence:
|
|
86
|
+
stateVarSequence: nextSequence,
|
|
87
|
+
stateVarCommitment: stateCommitment,
|
|
74
88
|
},
|
|
75
89
|
];
|
|
76
90
|
if (params.type === 'splice_out' && params.withdrawAmount && params.withdrawAmount > 0n && params.withdrawAddress) {
|
|
@@ -97,6 +111,7 @@ export function buildSpliceTx(channel, params) {
|
|
|
97
111
|
inputs,
|
|
98
112
|
outputs,
|
|
99
113
|
channelId: channel.channelId,
|
|
114
|
+
nextSequence,
|
|
100
115
|
params,
|
|
101
116
|
};
|
|
102
117
|
}
|
|
@@ -157,12 +172,15 @@ export function spliceDraftToMinimaBytes(draft) {
|
|
|
157
172
|
? [
|
|
158
173
|
svToJson(STATE_SETTLEMENT_PORT, out.stateVarSettlement, 'bool'),
|
|
159
174
|
svToJson(STATE_SEQUENCE_PORT, out.stateVarSequence, 'number'),
|
|
175
|
+
...(out.stateVarCommitment !== undefined
|
|
176
|
+
? [svToJson(STATE_COMMITMENT_V2_PORT, out.stateVarCommitment, 'hex')]
|
|
177
|
+
: []),
|
|
160
178
|
]
|
|
161
179
|
: [],
|
|
162
180
|
}));
|
|
163
181
|
const state = [
|
|
164
182
|
svToJson(STATE_SETTLEMENT_PORT, false, 'bool'),
|
|
165
|
-
svToJson(STATE_SEQUENCE_PORT,
|
|
183
|
+
svToJson(STATE_SEQUENCE_PORT, BigInt(draft.nextSequence), 'number'),
|
|
166
184
|
];
|
|
167
185
|
return serializeTransaction(JSON.stringify({ inputs, outputs, state, linkhash: '0x00' }));
|
|
168
186
|
}
|
|
@@ -171,35 +189,7 @@ export function spliceDraftToMinimaBytes(draft) {
|
|
|
171
189
|
* This is the canonical message both parties sign to authorize the splice.
|
|
172
190
|
*/
|
|
173
191
|
export function computeSpliceTxDigest(draft) {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
coinId: i.coinId,
|
|
178
|
-
address: i.address,
|
|
179
|
-
amount: i.amount.toString(),
|
|
180
|
-
tokenId: i.tokenId,
|
|
181
|
-
})),
|
|
182
|
-
outputs: draft.outputs.map(o => ({
|
|
183
|
-
address: o.address,
|
|
184
|
-
amount: o.amount.toString(),
|
|
185
|
-
tokenId: o.tokenId,
|
|
186
|
-
storeState: o.storeState,
|
|
187
|
-
stateVarSettlement: o.storeState ? o.stateVarSettlement : undefined,
|
|
188
|
-
stateVarSequence: o.storeState ? o.stateVarSequence : undefined,
|
|
189
|
-
})),
|
|
190
|
-
params: {
|
|
191
|
-
type: draft.params.type,
|
|
192
|
-
newTotalValue: draft.params.newTotalValue.toString(),
|
|
193
|
-
/**
|
|
194
|
-
* newBalances is sorted by partyId for determinism and included in the
|
|
195
|
-
* digest so that signatures cryptographically bind to the exact per-party
|
|
196
|
-
* balance split. Different allocations with the same sum produce different
|
|
197
|
-
* digests and therefore require new signatures.
|
|
198
|
-
*/
|
|
199
|
-
newBalances: Object.entries(draft.params.newBalances)
|
|
200
|
-
.sort(([a], [b]) => a.localeCompare(b))
|
|
201
|
-
.map(([k, v]) => [k, v.toString()]),
|
|
202
|
-
},
|
|
203
|
-
});
|
|
204
|
-
return sha3_256(new TextEncoder().encode(canonical));
|
|
192
|
+
// Sign the same canonical Minima bytes the chain will execute. A JSON draft
|
|
193
|
+
// digest is not the transaction digest and cannot be verified on-chain.
|
|
194
|
+
return sha3_256(spliceDraftToMinimaBytes(draft));
|
|
205
195
|
}
|
package/dist/splice.d.ts
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
import type { OmniaChannel } from '@totemsdk/omnia';
|
|
2
|
-
import type { SpliceProposal, SpliceAcceptance, SpliceLeaseProvider, QuiescedChannel } from './types.js';
|
|
2
|
+
import type { SpliceParams, SpliceProposal, SpliceAcceptance, SpliceLeaseProvider, QuiescedChannel } from './types.js';
|
|
3
|
+
/** A splice proposal whose proposer signature has not been applied yet. */
|
|
4
|
+
export interface UnsignedSpliceProposal {
|
|
5
|
+
spliceId: string;
|
|
6
|
+
channelId: string;
|
|
7
|
+
params: SpliceParams;
|
|
8
|
+
spliceTxHex: string;
|
|
9
|
+
spliceTxDraft: SpliceProposal['spliceTxDraft'];
|
|
10
|
+
proposerPublicKeyDigest: string;
|
|
11
|
+
digest: Uint8Array;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Build the deterministic splice draft/digest without signing. Used by the
|
|
15
|
+
* wallet/coordinator flow: the caller signs `digest` and attaches the
|
|
16
|
+
* signature before finalization.
|
|
17
|
+
*/
|
|
18
|
+
export declare function buildSpliceProposal(channel: OmniaChannel | QuiescedChannel, params: SpliceParams, proposerPublicKeyDigest: string): UnsignedSpliceProposal;
|
|
19
|
+
/** Build an unsigned splice-in proposal (see `buildSpliceProposal`). */
|
|
20
|
+
export declare function buildSpliceInProposal(channel: OmniaChannel | QuiescedChannel, additionalCoinId: string, additionalAmount: bigint, proposerPublicKeyDigest: string, newBalances?: Record<string, bigint>): UnsignedSpliceProposal;
|
|
21
|
+
/** Build an unsigned splice-out proposal (see `buildSpliceProposal`). */
|
|
22
|
+
export declare function buildSpliceOutProposal(channel: OmniaChannel | QuiescedChannel, withdrawAmount: bigint, withdrawAddress: string, proposerPublicKeyDigest: string, newBalances?: Record<string, bigint>, extraOutputs?: Array<{
|
|
23
|
+
address: string;
|
|
24
|
+
amount: bigint;
|
|
25
|
+
tokenId?: string;
|
|
26
|
+
}>): UnsignedSpliceProposal;
|
|
3
27
|
/**
|
|
4
28
|
* Initiating party proposes a splice-in: add external funds to the channel.
|
|
5
29
|
*
|