Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@

---

# Channel management

Open a channel's details to set a private label, copy its counterparty's advertised connection addresses, or review a splice. Labels are stored in the node's `cln-application/channel-labels` datastore namespace; they are not sent to peers. A credential without datastore access can still list channels, with a label-lookup warning.

Splice in adds on-chain funds and splice out withdraws local channel funds without closing the channel. Both peers must support splicing, and the channel must be connected and active with no pending funding transaction. Enter whole sats, review the direction and amount, then confirm. CLN selects the fee using its normal safety checks. Splice RPCs are available through REST or Commando; the application's current gRPC schema does not expose them.

An unresolved submission is retained in the browser so closing and reopening channel details does not submit it again. A lost reply is not proof of failure: check the channel and wallet before dismissing a record or attempting another splice. Pending splice amounts and confirmations come from the node, not the browser's saved record. Confirmation lookup requires CLN's SQL plugin and RPC permission; failures are shown as unavailable instead of an invented count. CLN does not report the peer's required confirmation count, so the UI does not guess it.

# Getting started

- ## Standalone
Expand Down
120 changes: 117 additions & 3 deletions apps/backend/source/controllers/lightning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,23 @@ const ALLOWED_METHODS = new Set([
'listfunds',
'listpeers',
'listpeerchannels',
'setchannellabel',
'listnodes',
'sql',
'listsqlschemas',
'feerates',
'fundchannel',
'splicein',
'spliceout',
'close',
'withdraw',
'newaddr',
'pay',
'keysend',
'invoice',
'offer',
'decode',
'fetchinvoice',
'decode',
'createrune',
]);

Expand All @@ -36,6 +39,35 @@ export function validateCallRequest(method: unknown, params: unknown): string |
if (params !== undefined && (typeof params !== 'object' || params === null)) {
return 'Invalid params for ' + method;
}
if (method === 'setchannellabel') {
const p = params as any;
if (
!p ||
Object.keys(p).some(k => !['channel_id', 'label'].includes(k)) ||
typeof p.channel_id !== 'string' ||
!/^[0-9a-f]{64}$/.test(p.channel_id) ||
typeof p.label !== 'string' ||
p.label.length > 80 ||
/[\u0000-\u001f\u007f]/.test(p.label)
) {
return 'Channel labels require a valid channel ID and at most 80 characters, without control characters';
}
}
if (method === 'splicein' || method === 'spliceout') {
const p = params as any;
if (
!p ||
Array.isArray(p) ||
Object.keys(p).some(k => !['channel', 'amount'].includes(k)) ||
typeof p.channel !== 'string' ||
!/^[0-9a-f]{64}$/.test(p.channel) ||
typeof p.amount !== 'string' ||
!/^[1-9][0-9]{0,15}$/.test(p.amount) ||
!Number.isSafeInteger(Number(p.amount))
) {
return 'Splicing requires one channel ID and a positive whole-satoshi amount; fee overrides and scripts are not accepted';
}
}
if (method === 'createrune') {
const restrictions = (params as any)?.restrictions;
const valid =
Expand Down Expand Up @@ -70,11 +102,93 @@ export class LightningController {
logger.warn('Refused lightning call: ' + validationError);
return handleError(new APIError(HttpStatusCode.FORBIDDEN, validationError), req, res, next);
}
if (req.body.method === 'setchannellabel') {
const { channel_id, label } = req.body.params;
const channels = await this.clnService.call('listpeerchannels', {});
if (!channels.channels?.some((c: any) => c.channel_id === channel_id)) {
throw new APIError(
HttpStatusCode.INVALID_DATA,
'This channel is no longer available. Refresh the channel list.',
);
}
await this.clnService.call('datastore', {
key: ['cln-application', 'channel-labels', channel_id],
string: label.trim(),
mode: 'create-or-replace',
});
return res.status(200).json({ channel_id, label: label.trim() });
}
if (req.body.method === 'splicein' || req.body.method === 'spliceout') {
if (APP_CONSTANTS.APP_CONNECT === AppConnect.GRPC) {
throw new APIError(
HttpStatusCode.INVALID_DATA,
'Splicing requires a REST or Commando connection; this application’s gRPC schema does not expose splicein/spliceout.',
);
}
const channels = await this.clnService.call('listpeerchannels', {});
const channel = channels.channels.find(
(c: any) => c.channel_id === req.body.params.channel,
);
if (
!channel ||
channel.state !== 'CHANNELD_NORMAL' ||
!channel.peer_connected ||
channel.inflight?.length
) {
throw new APIError(
HttpStatusCode.INVALID_DATA,
'Splice requires a connected, active channel with no pending funding transaction. Inspect channel status before retrying.',
);
}
const peers = await this.clnService.call('listpeers', { id: channel.peer_id });
const features = peers.peers?.[0]?.features;
if (
typeof features !== 'string' ||
!/^[0-9a-fA-F]+$/.test(features) ||
!(BigInt('0x' + features) & (3n << 62n))
) {
throw new APIError(
HttpStatusCode.INVALID_DATA,
'The peer has not negotiated splice support (feature 62/63). Enable splicing on the peer and reconnect.',
);
}
}
logger.info('Calling method: ' + req.body.method);
this.clnService
return this.clnService
.call(req.body.method, req.body.params)
.then((commandRes: any) => {
.then(async (commandRes: any) => {
logger.info('Controller received response for ' + req.body.method);
if (req.body.method === 'listpeerchannels') {
try {
const stored = await this.clnService.call('listdatastore', {
key: ['cln-application', 'channel-labels'],
});
const labels = new Map(
(stored.datastore || [])
.filter(
(v: any) =>
v.key?.length === 3 &&
v.key[0] === 'cln-application' &&
v.key[1] === 'channel-labels' &&
typeof v.string === 'string',
)
.map((v: any) => [v.key[2], v.string]),
);
commandRes.channels = commandRes.channels.map((c: any) => ({
...c,
channel_label: labels.get(c.channel_id) || '',
}));
} catch (error) {
commandRes.channels = commandRes.channels.map((c: any) => ({
...c,
channel_label_error: 'Could not load channel labels: ' + String(error),
}));
}
commandRes.channels = commandRes.channels.map((c: any) => ({
...c,
splice_supported: APP_CONSTANTS.APP_CONNECT !== AppConnect.GRPC,
}));
}
if (
APP_CONSTANTS.APP_CONNECT == AppConnect.COMMANDO &&
req.body.method &&
Expand Down
14 changes: 14 additions & 0 deletions apps/backend/source/service/grpc.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,20 @@ export class GRPCService {
payload.amount_msat = this.transformTypes('Amount', payload.amount_msat);
}

// CLN JSON-RPC uses hyphenated names; protobuf expects the numeric enum.
if (method?.toLowerCase() === 'datastore' && typeof payload.mode === 'string') {
const modes: Record<string, number> = {
'must-create': 0,
'must-replace': 1,
'create-or-replace': 2,
'must-append': 3,
'create-or-append': 4,
};
if (!Object.prototype.hasOwnProperty.call(modes, payload.mode))
throw new Error('Invalid datastore mode');
payload.mode = modes[payload.mode];
}

// Map values with their Enums
const enumsMapping: Record<string, string[]> = {
Feerates: ['style'],
Expand Down
144 changes: 144 additions & 0 deletions apps/backend/test/channel-management.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
process.env.APP_LOG_FILE = join(mkdtempSync(join(tmpdir(), 'channel-test-')), 'app.log');
const { LightningController, validateCallRequest } = await import(
'../dist/controllers/lightning.js'
);
const { APP_CONSTANTS, AppConnect } = await import('../dist/shared/consts.js');
const id = 'ab'.repeat(32);
const peer = '02' + 'cd'.repeat(32);
const channel = { channel_id: id, peer_id: peer, state: 'CHANNELD_NORMAL', peer_connected: true };
async function request(method, params, call, connection = AppConnect.REST) {
APP_CONSTANTS.APP_CONNECT = connection;
const controller = new LightningController({ call });
const res = {
statusCode: 200,
status(value) {
this.statusCode = value;
return this;
},
json(value) {
this.body = value;
return this;
},
};
await controller.callMethod({ body: { method, params } }, res, () => {});
return res;
}
test('splice input accepts only a channel and positive whole-satoshi amount', () => {
for (const method of ['splicein', 'spliceout']) {
assert.equal(validateCallRequest(method, { channel: id, amount: '1000000' }), null);
for (const amount of ['0', '-1', '1.5', '1sat', '9007199254740992'])
assert.ok(validateCallRequest(method, { channel: id, amount }));
assert.ok(validateCallRequest(method, { channel: id, amount: '1', force_feerate: true }));
assert.ok(validateCallRequest(method, { channel: 'not a channel', amount: '1' }));
}
assert.equal(validateCallRequest('offer', {}), null);
assert.equal(validateCallRequest('fetchinvoice', {}), null);
});
test('splice checks connection, pending funding and peer features before mutation', async () => {
for (const changed of [{ peer_connected: false }, { state: 'ONCHAIN' }, { inflight: [{}] }]) {
const calls = [];
const res = await request('splicein', { channel: id, amount: '1' }, async method => {
calls.push(method);
return { channels: [{ ...channel, ...changed }] };
});
assert.notEqual(res.statusCode, 200);
assert.deepEqual(calls, ['listpeerchannels']);
}
for (const features of ['00', 'invalid']) {
const calls = [];
const res = await request('spliceout', { channel: id, amount: '1' }, async method => {
calls.push(method);
return method === 'listpeerchannels' ? { channels: [channel] } : { peers: [{ features }] };
});
assert.notEqual(res.statusCode, 200);
assert.deepEqual(calls, ['listpeerchannels', 'listpeers']);
}
const calls = [];
const res = await request(
'splicein',
{ channel: id, amount: '1000000' },
async (method, params) => {
calls.push([method, params]);
return method === 'listpeerchannels'
? { channels: [channel] }
: method === 'listpeers'
? { peers: [{ features: (1n << 63n).toString(16) }] }
: { txid: id };
},
);
assert.equal(res.statusCode, 200);
assert.deepEqual(calls.at(-1), ['splicein', { channel: id, amount: '1000000' }]);
});
test('gRPC splice refusal happens before any node operation', async () => {
const res = await request(
'splicein',
{ channel: id, amount: '1' },
() => {
throw Error('must not call');
},
AppConnect.GRPC,
);
assert.match(res.body, /gRPC/);
});
test('labels are limited to the application namespace and existing channels', async () => {
assert.ok(validateCallRequest('setchannellabel', { channel_id: id, label: 'x'.repeat(81) }));
assert.ok(validateCallRequest('setchannellabel', { channel_id: id, label: 'bad\nlabel' }));
const calls = [];
const res = await request(
'setchannellabel',
{ channel_id: id, label: ' Savings ' },
async (method, params) => {
calls.push([method, params]);
return { channels: [channel] };
},
);
assert.deepEqual(res.body, { channel_id: id, label: 'Savings' });
assert.deepEqual(calls[1], [
'datastore',
{
key: ['cln-application', 'channel-labels', id],
string: 'Savings',
mode: 'create-or-replace',
},
]);
const missing = await request(
'setchannellabel',
{ channel_id: id, label: 'test' },
async method => {
assert.equal(method, 'listpeerchannels');
return { channels: [] };
},
);
assert.notEqual(missing.statusCode, 200);
});
test('label lookup failure retains channels and exposes the failure', async () => {
const res = await request('listpeerchannels', {}, async method => {
if (method === 'listdatastore') throw Error('permission denied');
return { channels: [channel] };
});
assert.equal(res.statusCode, 200);
assert.equal(res.body.channels[0].channel_id, id);
assert.match(res.body.channels[0].channel_label_error, /permission denied/);
});

test('gRPC encodes JSON-RPC datastore modes as the protobuf enum', async () => {
const { GRPCService } = await import('../dist/service/grpc.service.js');
const service = Object.create(GRPCService.prototype);
assert.equal(
service.transformPayload('Datastore', {
key: ['app'],
string: 'label',
mode: 'create-or-replace',
}).mode,
2,
);
assert.throws(
() => service.transformPayload('Datastore', { mode: 'unknown' }),
/Invalid datastore mode/,
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@

.channel-scroll-container {
max-height: 53vh;
min-width: 0;
& .channel-balance-summary, & .channel-peer-heading, & .channel-peer-name {
min-width: 0;
max-width: 100%;
}
& .channel-peer-name {
overflow-wrap: anywhere;
white-space: normal;
}
& .channel-peer-heading .dot {
flex-shrink: 0;
margin-top: 0.45em;
}
& .progress {
height: 6px;
}
Expand Down
Loading