@totemsdk/omnia-splice 0.3.1 → 0.3.3

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/README.md CHANGED
@@ -88,3 +88,8 @@ try {
88
88
  - [`@totemsdk/omnia`](https://www.npmjs.com/package/@totemsdk/omnia) — the channel state machine being spliced
89
89
  - [`@totemsdk/tx-builder`](https://www.npmjs.com/package/@totemsdk/tx-builder) — used internally by `buildSpliceTx`
90
90
  - [`@totemsdk/wots-lease`](https://www.npmjs.com/package/@totemsdk/wots-lease) — signing slots managed during splice
91
+
92
+
93
+ ## Testing
94
+
95
+ Tests live outside the published package in `tests/unit/omnia-splice/`. Package `test:*` scripts are repository delegates; tests are not shipped.
@@ -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: 0` — fresh WOTS budget
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
@@ -5,6 +5,7 @@ const core_1 = require("@totemsdk/core");
5
5
  const txpow_1 = require("@totemsdk/txpow");
6
6
  const omnia_1 = require("@totemsdk/omnia");
7
7
  const splice_tx_js_1 = require("./splice-tx.js");
8
+ const successor_js_1 = require("./successor.js");
8
9
  const errors_js_1 = require("./errors.js");
9
10
  function defaultWotsVerify(sig, digest, pkd) {
10
11
  return (0, omnia_1.verifyChannelSignature)(sig, digest, pkd);
@@ -113,7 +114,7 @@ function bindFinalizeParamsToDraft(channel, proposal) {
113
114
  * - `status: 'active'` — ready for new payments immediately
114
115
  * - `totalValue` — updated to `proposal.params.newTotalValue`
115
116
  * - `balances` — updated to `proposal.params.newBalances`
116
- * - `currentSequence: 0` — fresh WOTS budget
117
+ * - `currentSequence: nextSequence` — successor state (must exceed the old channel)
117
118
  * - `latestState: null` — no cosigned state yet
118
119
  * - `splicedFrom` — old channel's `channelId`
119
120
  * - `spliceFundingTxId` — mined (or broadcast) TX ID
@@ -157,9 +158,18 @@ async function finalizeSplice(channel, proposal, acceptance, options) {
157
158
  const txHex = Buffer.from(fullTxPoW).toString('hex');
158
159
  spliceFundingTxId = Buffer.from(mined.txpowId).toString('hex');
159
160
  if (options?.broadcast) {
161
+ const record = {
162
+ spliceId: proposal.spliceId,
163
+ channelId: channel.channelId,
164
+ txHex,
165
+ txpowId: spliceFundingTxId,
166
+ broadcastAt: Date.now(),
167
+ };
168
+ await options.pendingSpliceStore?.save(record);
160
169
  const result = await options.broadcast(txHex);
161
170
  if (result.txpowid) {
162
171
  spliceFundingTxId = result.txpowid;
172
+ await options.pendingSpliceStore?.save({ ...record, txpowId: result.txpowid });
163
173
  }
164
174
  else if (result.success === false) {
165
175
  throw new Error('Splice TX broadcast rejected by the network — channel state not advanced');
@@ -187,11 +197,36 @@ async function finalizeSplice(channel, proposal, acceptance, options) {
187
197
  ].filter((x) => x !== undefined));
188
198
  throw err;
189
199
  }
190
- const spliceFundingCoinId = `${spliceFundingTxId}-0`;
191
200
  const params = proposal.params;
201
+ // Observe the actual successor. The old channel coin is spent by the splice,
202
+ // so `txid-0` is only a placeholder; the live coin id comes from the funding
203
+ // address. Until it is confirmed the channel must not be reported active —
204
+ // with no observer we cannot know, so it stays funding_pending (CAN-011).
205
+ let spliceFundingCoinId = `${spliceFundingTxId}-0`;
206
+ let successorStatus = 'funding_pending';
207
+ if (options?.chainProvider) {
208
+ const observed = await (0, successor_js_1.observeSpliceSuccessor)(options.chainProvider, {
209
+ address: channel.fundingAddress,
210
+ tokenId: channel.tokenId,
211
+ amount: params.newTotalValue,
212
+ confirmations: options.confirmations ?? 1,
213
+ timeoutMs: options.successorTimeoutMs ?? 30000,
214
+ pollIntervalMs: options.successorPollMs ?? 1000,
215
+ });
216
+ if (observed) {
217
+ spliceFundingCoinId = observed.coinId;
218
+ successorStatus = observed.confirmed ? 'active' : 'funding_pending';
219
+ }
220
+ else {
221
+ successorStatus = 'funding_pending';
222
+ }
223
+ }
224
+ if (successorStatus === 'active') {
225
+ await options?.pendingSpliceStore?.clear(proposal.spliceId);
226
+ }
192
227
  const splicedChannel = {
193
228
  ...channel,
194
- status: 'active',
229
+ status: successorStatus,
195
230
  splicedFrom: channel.channelId,
196
231
  spliceType: params.type,
197
232
  spliceFundingTxId,
@@ -200,13 +235,13 @@ async function finalizeSplice(channel, proposal, acceptance, options) {
200
235
  fundingCoinId: spliceFundingCoinId,
201
236
  totalValue: params.newTotalValue,
202
237
  balances: params.newBalances,
203
- currentSequence: 0,
238
+ currentSequence: proposal.spliceTxDraft.nextSequence,
204
239
  latestState: null,
205
240
  pendingHTLCs: [],
206
241
  stateLog: [
207
242
  ...channel.stateLog,
208
243
  {
209
- sequence: 0,
244
+ sequence: proposal.spliceTxDraft.nextSequence,
210
245
  timestamp: Date.now(),
211
246
  balances: { ...params.newBalances },
212
247
  htlcCount: 0,
@@ -3,6 +3,7 @@ export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from '
3
3
  export { proposeSpliceIn, proposeSpliceOut, acceptSplice, buildSpliceProposal, buildSpliceInProposal, buildSpliceOutProposal, } from './splice.js';
4
4
  export type { UnsignedSpliceProposal } from './splice.js';
5
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';
6
7
  export type { SpliceType, SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput, SpliceProposal, SpliceAcceptance, QuiescedChannel, SplicedChannel, SpliceLeaseProvider, SpliceSigningIndices, WotsSignature, } from './types.js';
7
8
  export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
8
9
  export { createDurableSpliceStore, } from './durable-splice-store.js';
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createSpliceCoordination = exports.createDurableSpliceStore = exports.SpliceInsufficientFundsError = exports.SpliceMissingPartyError = exports.SpliceSignatureMismatchError = exports.SpliceBalanceConservationError = exports.SpliceChannelStatusError = exports.PendingHTLCError = exports.SpliceError = exports.finalizeSplice = exports.buildSpliceOutProposal = exports.buildSpliceInProposal = exports.buildSpliceProposal = exports.acceptSplice = exports.proposeSpliceOut = exports.proposeSpliceIn = exports.computeSpliceTxDigest = exports.spliceDraftToMinimaBytes = exports.buildSpliceTx = exports.quiesceChannel = void 0;
3
+ exports.createSpliceCoordination = exports.createDurableSpliceStore = exports.SpliceInsufficientFundsError = exports.SpliceMissingPartyError = exports.SpliceSignatureMismatchError = exports.SpliceBalanceConservationError = exports.SpliceChannelStatusError = exports.PendingHTLCError = exports.SpliceError = exports.recoverInterruptedSplices = exports.observeSpliceSuccessor = exports.finalizeSplice = exports.buildSpliceOutProposal = exports.buildSpliceInProposal = exports.buildSpliceProposal = exports.acceptSplice = exports.proposeSpliceOut = exports.proposeSpliceIn = exports.computeSpliceTxDigest = exports.spliceDraftToMinimaBytes = exports.buildSpliceTx = exports.quiesceChannel = void 0;
4
4
  var quiesce_js_1 = require("./quiesce.js");
5
5
  Object.defineProperty(exports, "quiesceChannel", { enumerable: true, get: function () { return quiesce_js_1.quiesceChannel; } });
6
6
  var splice_tx_js_1 = require("./splice-tx.js");
@@ -16,6 +16,9 @@ Object.defineProperty(exports, "buildSpliceInProposal", { enumerable: true, get:
16
16
  Object.defineProperty(exports, "buildSpliceOutProposal", { enumerable: true, get: function () { return splice_js_1.buildSpliceOutProposal; } });
17
17
  var finalize_js_1 = require("./finalize.js");
18
18
  Object.defineProperty(exports, "finalizeSplice", { enumerable: true, get: function () { return finalize_js_1.finalizeSplice; } });
19
+ var successor_js_1 = require("./successor.js");
20
+ Object.defineProperty(exports, "observeSpliceSuccessor", { enumerable: true, get: function () { return successor_js_1.observeSpliceSuccessor; } });
21
+ Object.defineProperty(exports, "recoverInterruptedSplices", { enumerable: true, get: function () { return successor_js_1.recoverInterruptedSplices; } });
19
22
  var errors_js_1 = require("./errors.js");
20
23
  Object.defineProperty(exports, "SpliceError", { enumerable: true, get: function () { return errors_js_1.SpliceError; } });
21
24
  Object.defineProperty(exports, "PendingHTLCError", { enumerable: true, get: function () { return errors_js_1.PendingHTLCError; } });
@@ -6,9 +6,11 @@ exports.computeSpliceTxDigest = computeSpliceTxDigest;
6
6
  const core_1 = require("@totemsdk/core");
7
7
  const core_2 = require("@totemsdk/core");
8
8
  const omnia_1 = require("@totemsdk/omnia");
9
+ const core_3 = require("@totemsdk/core");
9
10
  const errors_js_1 = require("./errors.js");
10
11
  const STATE_SETTLEMENT_PORT = 100;
11
12
  const STATE_SEQUENCE_PORT = 101;
13
+ const STATE_COMMITMENT_V2_PORT = 102;
12
14
  /**
13
15
  * Build a validated SpliceTxDraft from channel + splice params.
14
16
  *
@@ -68,6 +70,17 @@ function buildSpliceTx(channel, params) {
68
70
  tokenId,
69
71
  });
70
72
  }
73
+ // A splice spends the old channel coin and creates a successor at the same
74
+ // script. The channel script requires STATE(101) GT PREVSTATE(101) for a
75
+ // non-settlement update, so the successor must advance the sequence. Resetting
76
+ // to zero is not a WOTS-capacity reset and is rejected by the script.
77
+ const nextSequence = channel.currentSequence + 1;
78
+ const postSpliceChannel = {
79
+ ...channel,
80
+ totalValue: params.newTotalValue,
81
+ balances: { ...params.newBalances },
82
+ };
83
+ const stateCommitment = (0, core_3.bytesToHex)((0, omnia_1.computeStateCommitmentV2)(postSpliceChannel, nextSequence, params.newBalances, [], { settlement: false }));
71
84
  const outputs = [
72
85
  {
73
86
  address: channel.fundingAddress,
@@ -75,7 +88,8 @@ function buildSpliceTx(channel, params) {
75
88
  tokenId,
76
89
  storeState: true,
77
90
  stateVarSettlement: false,
78
- stateVarSequence: 0,
91
+ stateVarSequence: nextSequence,
92
+ stateVarCommitment: stateCommitment,
79
93
  },
80
94
  ];
81
95
  if (params.type === 'splice_out' && params.withdrawAmount && params.withdrawAmount > 0n && params.withdrawAddress) {
@@ -102,6 +116,7 @@ function buildSpliceTx(channel, params) {
102
116
  inputs,
103
117
  outputs,
104
118
  channelId: channel.channelId,
119
+ nextSequence,
105
120
  params,
106
121
  };
107
122
  }
@@ -162,12 +177,15 @@ function spliceDraftToMinimaBytes(draft) {
162
177
  ? [
163
178
  svToJson(STATE_SETTLEMENT_PORT, out.stateVarSettlement, 'bool'),
164
179
  svToJson(STATE_SEQUENCE_PORT, out.stateVarSequence, 'number'),
180
+ ...(out.stateVarCommitment !== undefined
181
+ ? [svToJson(STATE_COMMITMENT_V2_PORT, out.stateVarCommitment, 'hex')]
182
+ : []),
165
183
  ]
166
184
  : [],
167
185
  }));
168
186
  const state = [
169
187
  svToJson(STATE_SETTLEMENT_PORT, false, 'bool'),
170
- svToJson(STATE_SEQUENCE_PORT, 0n, 'number'),
188
+ svToJson(STATE_SEQUENCE_PORT, BigInt(draft.nextSequence), 'number'),
171
189
  ];
172
190
  return (0, core_2.serializeTransaction)(JSON.stringify({ inputs, outputs, state, linkhash: '0x00' }));
173
191
  }
@@ -176,35 +194,7 @@ function spliceDraftToMinimaBytes(draft) {
176
194
  * This is the canonical message both parties sign to authorize the splice.
177
195
  */
178
196
  function computeSpliceTxDigest(draft) {
179
- const canonical = JSON.stringify({
180
- channelId: draft.channelId,
181
- inputs: draft.inputs.map(i => ({
182
- coinId: i.coinId,
183
- address: i.address,
184
- amount: i.amount.toString(),
185
- tokenId: i.tokenId,
186
- })),
187
- outputs: draft.outputs.map(o => ({
188
- address: o.address,
189
- amount: o.amount.toString(),
190
- tokenId: o.tokenId,
191
- storeState: o.storeState,
192
- stateVarSettlement: o.storeState ? o.stateVarSettlement : undefined,
193
- stateVarSequence: o.storeState ? o.stateVarSequence : undefined,
194
- })),
195
- params: {
196
- type: draft.params.type,
197
- newTotalValue: draft.params.newTotalValue.toString(),
198
- /**
199
- * newBalances is sorted by partyId for determinism and included in the
200
- * digest so that signatures cryptographically bind to the exact per-party
201
- * balance split. Different allocations with the same sum produce different
202
- * digests and therefore require new signatures.
203
- */
204
- newBalances: Object.entries(draft.params.newBalances)
205
- .sort(([a], [b]) => a.localeCompare(b))
206
- .map(([k, v]) => [k, v.toString()]),
207
- },
208
- });
209
- return (0, core_1.sha3_256)(new TextEncoder().encode(canonical));
197
+ // Sign the same canonical Minima bytes the chain will execute. A JSON draft
198
+ // digest is not the transaction digest and cannot be verified on-chain.
199
+ return (0, core_1.sha3_256)(spliceDraftToMinimaBytes(draft));
210
200
  }
@@ -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,117 @@
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 candidates = coins.filter((coin) => !coin.spent
32
+ && coin.address.toLowerCase() === options.address.toLowerCase()
33
+ && coin.tokenid.toLowerCase() === options.tokenId.toLowerCase()
34
+ && BigInt(coin.amount) === options.amount);
35
+ // CAN-012: the channel input floats (COINID_ELTOO), so the coin id cannot be
36
+ // predicted from the transaction. Two coins matching the same address, token
37
+ // and amount are indistinguishable here; picking the first would silently
38
+ // adopt a coin the channel does not control.
39
+ if (candidates.length > 1) {
40
+ throw new Error(`Ambiguous splice successor: ${candidates.length} unspent coins match `
41
+ + `${options.address} token ${options.tokenId} amount ${options.amount}`);
42
+ }
43
+ const candidate = candidates[0];
44
+ if (candidate) {
45
+ const tip = await chain.getTip();
46
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
47
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
48
+ if (confirmations >= required) {
49
+ return { coinId: candidate.coinid, confirmations, confirmed: true, coin: candidate };
50
+ }
51
+ // Found but not deep enough; keep polling until the deadline.
52
+ }
53
+ if (now() >= deadline) {
54
+ if (candidate) {
55
+ const tip = await chain.getTip();
56
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
57
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
58
+ return { coinId: candidate.coinid, confirmations, confirmed: confirmations >= required, coin: candidate };
59
+ }
60
+ return null;
61
+ }
62
+ await sleep(pollMs);
63
+ }
64
+ }
65
+ /**
66
+ * Reconcile interrupted broadcasts.
67
+ *
68
+ * - If the successor is already visible, record its coin id and clear the
69
+ * pending entry.
70
+ * - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
71
+ * and leave the entry pending for the next pass.
72
+ */
73
+ async function recoverInterruptedSplices(store, chain, observe, broadcast) {
74
+ const pending = await store.list();
75
+ const results = [];
76
+ for (const record of pending) {
77
+ try {
78
+ const observed = await observeSpliceSuccessor(chain, { ...observe, timeoutMs: observe.timeoutMs ?? 0 });
79
+ if (observed?.confirmed) {
80
+ await store.clear(record.spliceId);
81
+ results.push({
82
+ spliceId: record.spliceId,
83
+ status: 'active',
84
+ coinId: observed.coinId,
85
+ rebroadcast: false,
86
+ });
87
+ continue;
88
+ }
89
+ const rebroadcast = await broadcast(record.txHex);
90
+ if (rebroadcast.success === false && !rebroadcast.txpowid) {
91
+ results.push({
92
+ spliceId: record.spliceId,
93
+ status: 'funding_pending',
94
+ rebroadcast: true,
95
+ error: 'rebroadcast rejected',
96
+ });
97
+ }
98
+ else {
99
+ results.push({
100
+ spliceId: record.spliceId,
101
+ status: observed ? 'funding_pending' : 'funding_pending',
102
+ ...(observed ? { coinId: observed.coinId } : {}),
103
+ rebroadcast: true,
104
+ });
105
+ }
106
+ }
107
+ catch (error) {
108
+ results.push({
109
+ spliceId: record.spliceId,
110
+ status: 'funding_pending',
111
+ rebroadcast: false,
112
+ error: String(error),
113
+ });
114
+ }
115
+ }
116
+ return results;
117
+ }
@@ -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
  /**
@@ -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: 0` — fresh WOTS budget
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: 0` — fresh WOTS budget
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,36 @@ 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
+ // with no observer we cannot know, so it stays funding_pending (CAN-011).
202
+ let spliceFundingCoinId = `${spliceFundingTxId}-0`;
203
+ let successorStatus = 'funding_pending';
204
+ if (options?.chainProvider) {
205
+ const observed = await observeSpliceSuccessor(options.chainProvider, {
206
+ address: channel.fundingAddress,
207
+ tokenId: channel.tokenId,
208
+ amount: params.newTotalValue,
209
+ confirmations: options.confirmations ?? 1,
210
+ timeoutMs: options.successorTimeoutMs ?? 30000,
211
+ pollIntervalMs: options.successorPollMs ?? 1000,
212
+ });
213
+ if (observed) {
214
+ spliceFundingCoinId = observed.coinId;
215
+ successorStatus = observed.confirmed ? 'active' : 'funding_pending';
216
+ }
217
+ else {
218
+ successorStatus = 'funding_pending';
219
+ }
220
+ }
221
+ if (successorStatus === 'active') {
222
+ await options?.pendingSpliceStore?.clear(proposal.spliceId);
223
+ }
189
224
  const splicedChannel = {
190
225
  ...channel,
191
- status: 'active',
226
+ status: successorStatus,
192
227
  splicedFrom: channel.channelId,
193
228
  spliceType: params.type,
194
229
  spliceFundingTxId,
@@ -197,13 +232,13 @@ export async function finalizeSplice(channel, proposal, acceptance, options) {
197
232
  fundingCoinId: spliceFundingCoinId,
198
233
  totalValue: params.newTotalValue,
199
234
  balances: params.newBalances,
200
- currentSequence: 0,
235
+ currentSequence: proposal.spliceTxDraft.nextSequence,
201
236
  latestState: null,
202
237
  pendingHTLCs: [],
203
238
  stateLog: [
204
239
  ...channel.stateLog,
205
240
  {
206
- sequence: 0,
241
+ sequence: proposal.spliceTxDraft.nextSequence,
207
242
  timestamp: Date.now(),
208
243
  balances: { ...params.newBalances },
209
244
  htlcCount: 0,
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from '
3
3
  export { proposeSpliceIn, proposeSpliceOut, acceptSplice, buildSpliceProposal, buildSpliceInProposal, buildSpliceOutProposal, } from './splice.js';
4
4
  export type { UnsignedSpliceProposal } from './splice.js';
5
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';
6
7
  export type { SpliceType, SpliceParams, SpliceTxDraft, SpliceTxInput, SpliceTxOutput, SpliceProposal, SpliceAcceptance, QuiescedChannel, SplicedChannel, SpliceLeaseProvider, SpliceSigningIndices, WotsSignature, } from './types.js';
7
8
  export { SpliceError, PendingHTLCError, SpliceChannelStatusError, SpliceBalanceConservationError, SpliceSignatureMismatchError, SpliceMissingPartyError, SpliceInsufficientFundsError, } from './errors.js';
8
9
  export { createDurableSpliceStore, } from './durable-splice-store.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ export { quiesceChannel } from './quiesce.js';
2
2
  export { buildSpliceTx, spliceDraftToMinimaBytes, computeSpliceTxDigest } from './splice-tx.js';
3
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: 0,
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, 0n, 'number'),
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
- const canonical = JSON.stringify({
175
- channelId: draft.channelId,
176
- inputs: draft.inputs.map(i => ({
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
  }
@@ -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,113 @@
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
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+ /**
13
+ * Find the successor coin at the channel address, excluding the spent old
14
+ * coin. A coin with `spent: true` is never a valid successor. Confirmation
15
+ * depth is derived from the coin's creation height when the provider supplies
16
+ * it; otherwise it is treated as unconfirmed.
17
+ */
18
+ export async function observeSpliceSuccessor(chain, options) {
19
+ const required = options.confirmations ?? 1;
20
+ const timeoutMs = options.timeoutMs ?? 30000;
21
+ const pollMs = options.pollIntervalMs ?? 1000;
22
+ const now = options.now ?? (() => Date.now());
23
+ const sleep = options.sleep ?? defaultSleep;
24
+ const deadline = now() + timeoutMs;
25
+ for (;;) {
26
+ const coins = await chain.getCoins({ address: options.address, tokenId: options.tokenId });
27
+ const candidates = coins.filter((coin) => !coin.spent
28
+ && coin.address.toLowerCase() === options.address.toLowerCase()
29
+ && coin.tokenid.toLowerCase() === options.tokenId.toLowerCase()
30
+ && BigInt(coin.amount) === options.amount);
31
+ // CAN-012: the channel input floats (COINID_ELTOO), so the coin id cannot be
32
+ // predicted from the transaction. Two coins matching the same address, token
33
+ // and amount are indistinguishable here; picking the first would silently
34
+ // adopt a coin the channel does not control.
35
+ if (candidates.length > 1) {
36
+ throw new Error(`Ambiguous splice successor: ${candidates.length} unspent coins match `
37
+ + `${options.address} token ${options.tokenId} amount ${options.amount}`);
38
+ }
39
+ const candidate = candidates[0];
40
+ if (candidate) {
41
+ const tip = await chain.getTip();
42
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
43
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
44
+ if (confirmations >= required) {
45
+ return { coinId: candidate.coinid, confirmations, confirmed: true, coin: candidate };
46
+ }
47
+ // Found but not deep enough; keep polling until the deadline.
48
+ }
49
+ if (now() >= deadline) {
50
+ if (candidate) {
51
+ const tip = await chain.getTip();
52
+ const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
53
+ const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
54
+ return { coinId: candidate.coinid, confirmations, confirmed: confirmations >= required, coin: candidate };
55
+ }
56
+ return null;
57
+ }
58
+ await sleep(pollMs);
59
+ }
60
+ }
61
+ /**
62
+ * Reconcile interrupted broadcasts.
63
+ *
64
+ * - If the successor is already visible, record its coin id and clear the
65
+ * pending entry.
66
+ * - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
67
+ * and leave the entry pending for the next pass.
68
+ */
69
+ export async function recoverInterruptedSplices(store, chain, observe, broadcast) {
70
+ const pending = await store.list();
71
+ const results = [];
72
+ for (const record of pending) {
73
+ try {
74
+ const observed = await observeSpliceSuccessor(chain, { ...observe, timeoutMs: observe.timeoutMs ?? 0 });
75
+ if (observed?.confirmed) {
76
+ await store.clear(record.spliceId);
77
+ results.push({
78
+ spliceId: record.spliceId,
79
+ status: 'active',
80
+ coinId: observed.coinId,
81
+ rebroadcast: false,
82
+ });
83
+ continue;
84
+ }
85
+ const rebroadcast = await broadcast(record.txHex);
86
+ if (rebroadcast.success === false && !rebroadcast.txpowid) {
87
+ results.push({
88
+ spliceId: record.spliceId,
89
+ status: 'funding_pending',
90
+ rebroadcast: true,
91
+ error: 'rebroadcast rejected',
92
+ });
93
+ }
94
+ else {
95
+ results.push({
96
+ spliceId: record.spliceId,
97
+ status: observed ? 'funding_pending' : 'funding_pending',
98
+ ...(observed ? { coinId: observed.coinId } : {}),
99
+ rebroadcast: true,
100
+ });
101
+ }
102
+ }
103
+ catch (error) {
104
+ results.push({
105
+ spliceId: record.spliceId,
106
+ status: 'funding_pending',
107
+ rebroadcast: false,
108
+ error: String(error),
109
+ });
110
+ }
111
+ }
112
+ return results;
113
+ }
package/dist/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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/omnia-splice",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Channel splicing for @totemsdk/omnia — resize Minima eltoo channels without a close+reopen cycle",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",
@@ -25,18 +25,15 @@
25
25
  "NOTICE"
26
26
  ],
27
27
  "dependencies": {
28
- "@totemsdk/core": "^1.4.2",
28
+ "@totemsdk/omnia": "^2.4.4",
29
+ "@totemsdk/core": "^1.5.0",
30
+ "@totemsdk/wots-lease": "^1.0.3",
29
31
  "@totemsdk/txpow": "^1.1.1",
30
- "@totemsdk/wots-lease": "^1.0.2",
31
- "@totemsdk/tx-builder": "^0.2.2",
32
- "@totemsdk/omnia": "^2.4.0",
32
+ "@totemsdk/tx-builder": "^0.3.3",
33
33
  "@totemsdk/storage": "^0.2.2"
34
34
  },
35
35
  "devDependencies": {
36
- "@types/jest": "^30.0.0",
37
36
  "@types/node": "^20.0.0",
38
- "jest": "^30.4.2",
39
- "ts-jest": "^29.0.0",
40
37
  "typescript": "^7.0.2"
41
38
  },
42
39
  "engines": {
@@ -76,7 +73,8 @@
76
73
  "scripts": {
77
74
  "build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
78
75
  "clean": "rm -rf dist rust/pkg rust/pkg-node rust/target",
79
- "test": "jest",
80
- "build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
76
+ "test": "jest --config ../../tests/jest/omnia-splice.cjs",
77
+ "build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node",
78
+ "test:integration": "node --test ../../tests/qualification/security-train/test/omnia-splice-sequence.test.mjs"
81
79
  }
82
80
  }