@totemsdk/omnia-splice 0.3.1 → 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/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 +1 -0
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/splice-tx.js +23 -33
- 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 +1 -0
- package/dist/index.js +1 -0
- package/dist/splice-tx.js +24 -34
- package/dist/successor.d.ts +102 -0
- package/dist/successor.js +104 -0
- package/dist/types.d.ts +4 -0
- package/package.json +4 -7
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.
|
package/dist/cjs/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/cjs/finalize.js
CHANGED
|
@@ -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:
|
|
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,35 @@ 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
|
+
let spliceFundingCoinId = `${spliceFundingTxId}-0`;
|
|
205
|
+
let successorStatus = 'active';
|
|
206
|
+
if (options?.chainProvider) {
|
|
207
|
+
const observed = await (0, successor_js_1.observeSpliceSuccessor)(options.chainProvider, {
|
|
208
|
+
address: channel.fundingAddress,
|
|
209
|
+
tokenId: channel.tokenId,
|
|
210
|
+
amount: params.newTotalValue,
|
|
211
|
+
confirmations: options.confirmations ?? 1,
|
|
212
|
+
timeoutMs: options.successorTimeoutMs ?? 30000,
|
|
213
|
+
pollIntervalMs: options.successorPollMs ?? 1000,
|
|
214
|
+
});
|
|
215
|
+
if (observed) {
|
|
216
|
+
spliceFundingCoinId = observed.coinId;
|
|
217
|
+
successorStatus = observed.confirmed ? 'active' : 'funding_pending';
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
successorStatus = 'funding_pending';
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (successorStatus === 'active') {
|
|
224
|
+
await options?.pendingSpliceStore?.clear(proposal.spliceId);
|
|
225
|
+
}
|
|
192
226
|
const splicedChannel = {
|
|
193
227
|
...channel,
|
|
194
|
-
status:
|
|
228
|
+
status: successorStatus,
|
|
195
229
|
splicedFrom: channel.channelId,
|
|
196
230
|
spliceType: params.type,
|
|
197
231
|
spliceFundingTxId,
|
|
@@ -200,13 +234,13 @@ async function finalizeSplice(channel, proposal, acceptance, options) {
|
|
|
200
234
|
fundingCoinId: spliceFundingCoinId,
|
|
201
235
|
totalValue: params.newTotalValue,
|
|
202
236
|
balances: params.newBalances,
|
|
203
|
-
currentSequence:
|
|
237
|
+
currentSequence: proposal.spliceTxDraft.nextSequence,
|
|
204
238
|
latestState: null,
|
|
205
239
|
pendingHTLCs: [],
|
|
206
240
|
stateLog: [
|
|
207
241
|
...channel.stateLog,
|
|
208
242
|
{
|
|
209
|
-
sequence:
|
|
243
|
+
sequence: proposal.spliceTxDraft.nextSequence,
|
|
210
244
|
timestamp: Date.now(),
|
|
211
245
|
balances: { ...params.newBalances },
|
|
212
246
|
htlcCount: 0,
|
package/dist/cjs/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/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; } });
|
package/dist/cjs/splice-tx.js
CHANGED
|
@@ -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:
|
|
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,
|
|
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
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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,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
|
@@ -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:
|
|
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
|
}
|
|
@@ -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,104 @@
|
|
|
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 candidate = coins.find((coin) => !coin.spent
|
|
28
|
+
&& coin.address.toLowerCase() === options.address.toLowerCase()
|
|
29
|
+
&& coin.tokenid.toLowerCase() === options.tokenId.toLowerCase()
|
|
30
|
+
&& BigInt(coin.amount) === options.amount);
|
|
31
|
+
if (candidate) {
|
|
32
|
+
const tip = await chain.getTip();
|
|
33
|
+
const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
|
|
34
|
+
const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
|
|
35
|
+
if (confirmations >= required) {
|
|
36
|
+
return { coinId: candidate.coinid, confirmations, confirmed: true, coin: candidate };
|
|
37
|
+
}
|
|
38
|
+
// Found but not deep enough; keep polling until the deadline.
|
|
39
|
+
}
|
|
40
|
+
if (now() >= deadline) {
|
|
41
|
+
if (candidate) {
|
|
42
|
+
const tip = await chain.getTip();
|
|
43
|
+
const created = candidate.created !== undefined ? Number(candidate.created) : NaN;
|
|
44
|
+
const confirmations = Number.isFinite(created) && created > 0 ? Math.max(0, tip.block - created + 1) : 0;
|
|
45
|
+
return { coinId: candidate.coinid, confirmations, confirmed: confirmations >= required, coin: candidate };
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
await sleep(pollMs);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Reconcile interrupted broadcasts.
|
|
54
|
+
*
|
|
55
|
+
* - If the successor is already visible, record its coin id and clear the
|
|
56
|
+
* pending entry.
|
|
57
|
+
* - Otherwise rebroadcast the exact TxPoW (idempotent at the node by txpow id)
|
|
58
|
+
* and leave the entry pending for the next pass.
|
|
59
|
+
*/
|
|
60
|
+
export async function recoverInterruptedSplices(store, chain, observe, broadcast) {
|
|
61
|
+
const pending = await store.list();
|
|
62
|
+
const results = [];
|
|
63
|
+
for (const record of pending) {
|
|
64
|
+
try {
|
|
65
|
+
const observed = await observeSpliceSuccessor(chain, { ...observe, timeoutMs: observe.timeoutMs ?? 0 });
|
|
66
|
+
if (observed?.confirmed) {
|
|
67
|
+
await store.clear(record.spliceId);
|
|
68
|
+
results.push({
|
|
69
|
+
spliceId: record.spliceId,
|
|
70
|
+
status: 'active',
|
|
71
|
+
coinId: observed.coinId,
|
|
72
|
+
rebroadcast: false,
|
|
73
|
+
});
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const rebroadcast = await broadcast(record.txHex);
|
|
77
|
+
if (rebroadcast.success === false && !rebroadcast.txpowid) {
|
|
78
|
+
results.push({
|
|
79
|
+
spliceId: record.spliceId,
|
|
80
|
+
status: 'funding_pending',
|
|
81
|
+
rebroadcast: true,
|
|
82
|
+
error: 'rebroadcast rejected',
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
results.push({
|
|
87
|
+
spliceId: record.spliceId,
|
|
88
|
+
status: observed ? 'funding_pending' : 'funding_pending',
|
|
89
|
+
...(observed ? { coinId: observed.coinId } : {}),
|
|
90
|
+
rebroadcast: true,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
results.push({
|
|
96
|
+
spliceId: record.spliceId,
|
|
97
|
+
status: 'funding_pending',
|
|
98
|
+
rebroadcast: false,
|
|
99
|
+
error: String(error),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return results;
|
|
104
|
+
}
|
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.
|
|
3
|
+
"version": "0.3.2",
|
|
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/omnia": "^2.4.1",
|
|
28
29
|
"@totemsdk/core": "^1.4.2",
|
|
29
30
|
"@totemsdk/txpow": "^1.1.1",
|
|
30
31
|
"@totemsdk/wots-lease": "^1.0.2",
|
|
31
|
-
"@totemsdk/tx-builder": "^0.
|
|
32
|
-
"@totemsdk/omnia": "^2.4.0",
|
|
32
|
+
"@totemsdk/tx-builder": "^0.3.1",
|
|
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,7 @@
|
|
|
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",
|
|
76
|
+
"test": "jest --config ../../tests/jest/omnia-splice.cjs",
|
|
80
77
|
"build:wasm": "cd rust && wasm-pack build --target bundler --out-dir pkg && wasm-pack build --target nodejs --out-dir pkg-node"
|
|
81
78
|
}
|
|
82
79
|
}
|