Skip to content
Merged
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
174 changes: 144 additions & 30 deletions channeld/channeld.c
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <channeld/watchtower.h>
#include <common/billboard.h>
#include <common/ecdh_hsmd.h>
#include <common/initial_commit_tx.h>
#include <common/interactivetx.h>
#include <common/key_derive.h>
#include <common/memleak.h>
Expand Down Expand Up @@ -3669,6 +3670,80 @@ static struct amount_sat calc_balance(struct peer *peer)
return funding_amount_res;
}

/* The reserve lightningd sets once a splice to this capacity locks. */
static struct amount_sat reserve_for_capacity(const struct peer *peer,
struct amount_sat capacity)
{
return channel_reserve_for_capacity(capacity,
peer->channel->opener == LOCAL
? chainparams->dust_limit
: peer->channel->config[REMOTE].dust_limit);
}

/* BOLT-191462825ae341f0a27098765c075f01ca9bc6c2 #2:
* The receiving node:
* - MUST compute the channel balance for each side by adding their respective
* `funding_contribution_satoshis` to their previous channel balance.
* - MUST fail the negotiation by sending `tx_abort` if:
*...
* - Either side has added an output other than the channel funding output
* and the balance for that side is less than the channel reserve that
* matches the new channel capacity.
*/
static void check_splice_reserves(struct peer *peer,
bool we_initiated,
const struct wally_psbt *psbt,
int chan_output_index,
struct amount_sat capacity)
{
s64 relative[NUM_TX_ROLES];
bool binds[NUM_TX_ROLES];
struct amount_sat reserve;

relative[TX_INITIATOR] = peer->splicing->opener_relative;
relative[TX_ACCEPTER] = peer->splicing->accepter_relative;

/* Funds a side takes out of the channel by any route, fees
* included, bind it as an added output does. */
for (enum tx_role r = 0; r < NUM_TX_ROLES; r++)
binds[r] = relative[r] < 0;
for (size_t i = 0; i < psbt->num_outputs; i++) {
if (i == chan_output_index)
continue;
if (is_initiators_serial(&psbt->outputs[i].unknowns))
binds[TX_INITIATOR] = true;
else
binds[TX_ACCEPTER] = true;
}

reserve = reserve_for_capacity(peer, capacity);

for (enum tx_role r = 0; r < NUM_TX_ROLES; r++) {
enum side side = (r == TX_INITIATOR) == we_initiated
? LOCAL : REMOTE;
struct amount_msat balance;

if (!binds[r])
continue;
if (!amount_msat_add_sat_s64(&balance,
peer->channel->view->owed[side],
relative[r]))
splice_abort(peer, NULL, "%s takes %"PRId64"sat out of"
" a balance of %s",
r == TX_INITIATOR ? "Initiator" : "Accepter",
-relative[r],
fmt_amount_msat(tmpctx,
peer->channel->view->owed[side]));
if (amount_msat_less_sat(balance, reserve))
splice_abort(peer, NULL, "%s would keep %s, below the"
" reserve of %s for a channel of %s",
r == TX_INITIATOR ? "Initiator" : "Accepter",
fmt_amount_msat(tmpctx, balance),
fmt_amount_sat(tmpctx, reserve),
fmt_amount_sat(tmpctx, capacity));
}
}

/* Returns the total channel funding output amount if all checks pass.
* Otherwise, exits via peer_failed_warn.
* Note: Should only be called before adding splice to inflights. */
Expand Down Expand Up @@ -3963,34 +4038,6 @@ static struct amount_sat check_balances(struct peer *peer,
fmt_amount_sat(tmpctx, max_accepter_fee));
}

/* BOLT-??? #2:
* - if either side has added an output other than the new channel
* funding output:
* - MUST fail the negotiation if the balance for that side is less
* than 1% of the total channel capacity. */
/* DTODO: Spec out reserve requirements for splices!! Lets gooo */
/* DTODO: If we were at or over the reserve at start of splice,
* then we must ensure the reserve is preserved through splice.
* It should only to 1% of the old balance
* 1: The channel is growing
* --- your balnce was underneath reserve req
* Valid: YES
* 2: The node's balance is shrinking
* --- and it shrinks below the reserve
* Valid: NO
*
* The reserve requirement should only matter if someone is withdrawing
* from.
*
* Node A Node B
* 1000 sat <-> 1000 sat
* reserve: 20sat
*
* Node B desires withdraw 990 sats
* Can I?
* New reserve req = 1010 * 0.01 = 10 (round down from 10.1)
* */

if (!amount_msat_to_sat(&funding_amount_res, funding_amount)) {
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"splice error: msat of total funding %s should"
Expand All @@ -4003,6 +4050,9 @@ static struct amount_sat check_balances(struct peer *peer,
peer->channel->view->owed[REMOTE]));
}

check_splice_reserves(peer, opener, psbt, chan_output_index,
funding_amount_res);

return funding_amount_res;
}

Expand Down Expand Up @@ -5594,10 +5644,74 @@ static void handle_splice_init(struct peer *peer, const u8 *inmsg)
}
}

/* What we must keep above the reserve as opener: the commitment fee
* channel_add_htlc makes us able to pay (feerate rising, one more HTLC),
* plus the anchors. Counting every HTLC as untrimmed only adds margin. */
static struct amount_sat opener_fee_headroom(const struct peer *peer)
{
const struct channel *channel = peer->channel;
bool anchors = channel_has(channel, OPT_ANCHOR_OUTPUTS_DEPRECATED);
bool zero_fee = channel_has(channel, OPT_ANCHORS_ZERO_FEE_HTLC_TX);
struct amount_sat fee;

fee = commit_tx_base_fee(marginal_feerate(channel_feerate(channel, LOCAL)),
num_channel_htlcs(channel) + 1,
anchors, zero_fee);
if ((anchors || zero_fee) && !amount_sat_add(&fee, fee, AMOUNT_SAT(660)))
status_failed(STATUS_FAIL_INTERNAL_ERROR,
"Cannot add 660 sats to %s for anchor",
fmt_amount_sat(tmpctx, fee));
return fee;
}

/* Whether we keep the reserve after splicing out `out`, the peer adding
* nothing, and as opener can still pay the commitment fee. */
static bool keeps_reserve_after(const struct peer *peer, struct amount_sat out)
{
struct amount_msat balance;
struct amount_sat capacity, keep;

if (!amount_msat_sub_sat(&balance, peer->channel->view->owed[LOCAL], out)
|| !amount_sat_sub(&capacity, peer->channel->funding_sats, out))
return false;
keep = reserve_for_capacity(peer, capacity);
if (peer->channel->opener == LOCAL
&& !amount_sat_add(&keep, keep, opener_fee_headroom(peer)))
return false;
return !amount_msat_less_sat(balance, keep);
}

/* The most we can splice out and still keep the reserve that
* check_splice_reserves applies, if the peer adds nothing. If it adds
* funds, the reserve can rise and the splice is refused there. */
static struct amount_msat splice_out_max(const struct peer *peer)
{
struct amount_msat max;
u64 lo = 0, hi;

if (!keeps_reserve_after(peer, AMOUNT_SAT(0)))
return AMOUNT_MSAT(0);

/* Keeping the reserve only gets harder the more we take out. */
hi = amount_msat_to_sat_round_down(peer->channel->view->owed[LOCAL])
.satoshis; /* Raw: binary search */
while (lo < hi) {
u64 mid = lo + (hi - lo + 1) / 2;

if (keeps_reserve_after(peer, amount_sat(mid)))
lo = mid;
else
hi = mid - 1;
}
if (!amount_sat_to_msat(&max, amount_sat(lo)))
return AMOUNT_MSAT(0);
return max;
}

static void handle_stfu_req_success(struct peer *peer)
{
struct amount_msat available_funds = peer->channel->view->owed[LOCAL];
/* DTODO: Subtract reserve requirment from available_funds? */
struct amount_msat available_funds = splice_out_max(peer);

if (peer->dev_delay_confirmed_stfu)
sleep(peer->dev_delay_confirmed_stfu);
wire_sync_write(MASTER_FD,
Expand Down
10 changes: 10 additions & 0 deletions common/channel_config.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@
#include <common/channel_config.h>
#include <wire/wire.h>

struct amount_sat channel_reserve_for_capacity(struct amount_sat capacity,
struct amount_sat opener_dust_limit)
{
struct amount_sat reserve = amount_sat_div(capacity, 100);

if (amount_sat_greater(opener_dust_limit, reserve))
return opener_dust_limit;
return reserve;
}

void towire_channel_config(u8 **pptr, const struct channel_config *config)
{
towire_amount_sat(pptr, config->dust_limit);
Expand Down
4 changes: 4 additions & 0 deletions common/channel_config.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ struct channel_config {

#define MAX_REMOTE_DUST_LIMIT AMOUNT_SAT(5000)

/* 1% of the capacity, rounded down, or the opener's dust limit if greater. */
struct amount_sat channel_reserve_for_capacity(struct amount_sat capacity,
struct amount_sat opener_dust_limit);

void towire_channel_config(u8 **pptr, const struct channel_config *config);
void fromwire_channel_config(const u8 **ptr, size_t *max,
struct channel_config *config);
Expand Down
6 changes: 4 additions & 2 deletions contrib/msggen/msggen/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -12479,8 +12479,10 @@
"```",
"",
"This takes all available funds out of channel 8338aef0 and puts them into the",
"onchain wallet. Note that available funds is restricted by pending HTLCs and",
"the 1% reserve requirement. To get all the funds you need to close the channel.",
"onchain wallet. Note that available funds is restricted by pending HTLCs, the",
"1% reserve for the channel that remains and, if you opened the channel, the",
"commitment transaction fee for one more HTLC at a higher feerate. To get all the",
"funds you need to close the channel.",
"More useful would be something like this:",
"```shell",
"8338aef0 -> 50%",
Expand Down
6 changes: 4 additions & 2 deletions doc/schemas/dev-splice.json
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,10 @@
"```",
"",
"This takes all available funds out of channel 8338aef0 and puts them into the",
"onchain wallet. Note that available funds is restricted by pending HTLCs and",
"the 1% reserve requirement. To get all the funds you need to close the channel.",
"onchain wallet. Note that available funds is restricted by pending HTLCs, the",
"1% reserve for the channel that remains and, if you opened the channel, the",
"commitment transaction fee for one more HTLC at a higher feerate. To get all the",
"funds you need to close the channel.",
"More useful would be something like this:",
"```shell",
"8338aef0 -> 50%",
Expand Down
8 changes: 2 additions & 6 deletions lightningd/dual_open_control.c
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,7 @@ static struct amount_sat calculate_reserve(struct channel_config *their_config,
struct amount_sat funding_total,
enum side opener)
{
struct amount_sat reserve, dust_limit;
struct amount_sat dust_limit;

/* BOLT #2:
*
Expand All @@ -1303,15 +1303,11 @@ static struct amount_sat calculate_reserve(struct channel_config *their_config,
* rounded down to the nearest whole satoshi or the `dust_limit_satoshis`,
* whichever is greater.
*/
reserve = amount_sat_div(funding_total, 100);
dust_limit = opener == LOCAL ?
chainparams->dust_limit :
their_config->dust_limit;

if (amount_sat_greater(dust_limit, reserve))
return dust_limit;

return reserve;
return channel_reserve_for_capacity(funding_total, dust_limit);
}

void channel_update_reserve(struct channel *channel,
Expand Down
17 changes: 12 additions & 5 deletions tests/test_splice.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,8 +454,9 @@ def test_script_two_chan_splice_out(node_factory, bitcoind):
chan_id2 = l2.get_channel_id(l3)

# l2 will splice funds out of the channels with l1 and l3 at the same time
# By default extra funds get sent to wallet
result = l2.rpc.splice(f"{chan_id1} -> 100000; {chan_id2} -> 100000")
# By default extra funds get sent to wallet. l2 keeps 10,000 sat with l1,
# above the 9,100 sat reserve for the 910,000 sat channel left.
result = l2.rpc.splice(f"{chan_id1} -> 90000; {chan_id2} -> 100000")

l3.daemon.wait_for_log(r'CHANNELD_NORMAL to CHANNELD_AWAITING_SPLICE')
l2.daemon.wait_for_log(r'CHANNELD_NORMAL to CHANNELD_AWAITING_SPLICE')
Expand Down Expand Up @@ -618,6 +619,12 @@ def verify_chans(nodes, bitcoind, txid, chanids, fee, expected_balances=None, fe
# * fee_multiplier is an array of ints. The coorisponding channel balance expectation is adjusted
# by the fee * fee_multiplier. For example [0, -1] reduces the second channels expected balance
# by the fee value
# Splicing out everything leaves the opener the 5,152 sat reserve plus 10,049 sat
# of fee headroom, which is 9,389 sat of commitment fee with another HTLC at the
# 7,245 perkw marginal feerate and 660 sat for the anchors.
OPENER_KEEPS = 15201


def execute_script(node_factory, bitcoind, script, expected_balances=None, fee_multiplier=None):
nodes, chanids = make_chans(node_factory, script.count("{}"))
result = nodes[1].rpc.splice(script.format(*chanids), debug_log=True)
Expand Down Expand Up @@ -736,23 +743,23 @@ def test_script_two_chan_splice_m(node_factory, bitcoind):
@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need')
def test_script_two_chan_splice_n(node_factory, bitcoind):
execute_script(node_factory, bitcoind, "wallet -> 100%+fee; {} -> 50%; 100000 -> {}",
[500000 // 2, 500000 + 100000])
[500000 - (500000 - OPENER_KEEPS) // 2, 500000 + 100000])


@pytest.mark.openchannel('v1')
@pytest.mark.openchannel('v2')
@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need')
def test_script_two_chan_splice_oo(node_factory, bitcoind):
execute_script(node_factory, bitcoind, "wallet -> *+fee; {} -> 50%; 100000 -> {}",
[500000 // 2, 500000 + 100000])
[500000 - (500000 - OPENER_KEEPS) // 2, 500000 + 100000])


@pytest.mark.openchannel('v1')
@pytest.mark.openchannel('v2')
@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need')
def test_script_two_chan_splice_p(node_factory, bitcoind):
execute_script(node_factory, bitcoind, "wallet -> *; {} -> 50%+fee; 100000 -> {}",
[500000 // 2, 500000 + 100000], [-1, 0])
[500000 - (500000 - OPENER_KEEPS) // 2, 500000 + 100000], [-1, 0])


@pytest.mark.openchannel('v1')
Expand Down
Loading
Loading