diff --git a/channeld/channeld.c b/channeld/channeld.c index b62fea92b0e7..5fcf19059579 100644 --- a/channeld/channeld.c +++ b/channeld/channeld.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -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. */ @@ -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" @@ -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; } @@ -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, diff --git a/common/channel_config.c b/common/channel_config.c index 55e32ae6dc66..d61983596175 100644 --- a/common/channel_config.c +++ b/common/channel_config.c @@ -2,6 +2,16 @@ #include #include +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); diff --git a/common/channel_config.h b/common/channel_config.h index 9f38573c0b51..49f748edb100 100644 --- a/common/channel_config.h +++ b/common/channel_config.h @@ -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); diff --git a/contrib/msggen/msggen/schema.json b/contrib/msggen/msggen/schema.json index 722d0367bd42..84aac6c3f71b 100644 --- a/contrib/msggen/msggen/schema.json +++ b/contrib/msggen/msggen/schema.json @@ -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%", diff --git a/doc/schemas/dev-splice.json b/doc/schemas/dev-splice.json index 507041b85d7f..a6f0a97649e6 100644 --- a/doc/schemas/dev-splice.json +++ b/doc/schemas/dev-splice.json @@ -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%", diff --git a/lightningd/dual_open_control.c b/lightningd/dual_open_control.c index 884da9778d18..f5b844437257 100644 --- a/lightningd/dual_open_control.c +++ b/lightningd/dual_open_control.c @@ -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: * @@ -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, diff --git a/tests/test_splice.py b/tests/test_splice.py index 00d1817667de..b46efbe7164e 100644 --- a/tests/test_splice.py +++ b/tests/test_splice.py @@ -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') @@ -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) @@ -736,7 +743,7 @@ 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') @@ -744,7 +751,7 @@ def test_script_two_chan_splice_n(node_factory, bitcoind): @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') @@ -752,7 +759,7 @@ def test_script_two_chan_splice_oo(node_factory, bitcoind): @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') diff --git a/tests/test_splicing.py b/tests/test_splicing.py index e80a2a31a78a..2acc86534b78 100644 --- a/tests/test_splicing.py +++ b/tests/test_splicing.py @@ -3016,3 +3016,121 @@ def test_splice_ack_contribution_above_max_supply(node_factory, bitcoind, contri assert l1.db_query("SELECT count(*) as c FROM channel_funding_inflights;")[0]['c'] == 0 wait_for(lambda: only_one(l1.rpc.listpeerchannels()['channels'])['peer_connected']) assert only_one(l1.rpc.listpeerchannels()['channels'])['state'] == 'CHANNELD_NORMAL' + + +def _splice_out_keeping(l2, chan_id, keep_sat): + """l2 splices its 500,000 sat out to its wallet, keeping keep_sat; the + 5,801 sat fee comes out of the channel too.""" + funds_result = l2.rpc.addpsbtoutput(500000 - keep_sat - 5801) + result = l2.rpc.splice_init(chan_id, -(500000 - keep_sat), funds_result['psbt']) + result = l2.rpc.splice_update(chan_id, result['psbt']) + result = l2.rpc.splice_update(chan_id, result['psbt']) + return l2.rpc.splice_signed(chan_id, result['psbt']) + + +@pytest.mark.openchannel('v1') +@pytest.mark.openchannel('v2') +@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need') +def test_splice_out_below_reserve(node_factory, bitcoind): + l1, l2 = node_factory.line_graph(2, fundamount=1000000, wait_for_announce=True, + opts={'may_reconnect': True, + 'allow_warning': True}) + chan_id = l1.get_channel_id(l2) + l1.rpc.xpay(l2.rpc.invoice(500000000, 'push', 'push')['bolt11']) + wait_for(lambda: only_one(l2.rpc.listpeerchannels()['channels'])['to_us_msat'] == 500000000) + + # Keeping 5,049 sat of a 505,049 sat channel is one below its 5,050 sat + # reserve. Each of l1 and l2 refuses it on its own check. + with pytest.raises(RpcError, match='below the reserve of 5050sat'): + _splice_out_keeping(l2, chan_id, 5049) + for n in (l1, l2): + n.daemon.wait_for_log(r'We are initiating tx_abort for reason: Initiator' + r' would keep 5049000msat, below the reserve of' + r' 5050sat for a channel of 505049sat') + for n in (l1, l2): + n.daemon.wait_for_log(r'Restarting channeld after tx_abort on CHANNELD_NORMAL channel') + assert n.db_query("SELECT count(*) as c FROM channel_funding_inflights;")[0]['c'] == 0 + wait_for(lambda: only_one(l2.rpc.listpeerchannels()['channels'])['peer_connected']) + + # Keeping exactly the reserve is enough. + result = _splice_out_keeping(l2, chan_id, 5050) + bitcoind.generate_block(6, wait_for_mempool=result['txid']) + for n in (l1, l2): + n.daemon.wait_for_log(r'CHANNELD_AWAITING_SPLICE to CHANNELD_NORMAL') + channel = only_one(l2.rpc.listpeerchannels()['channels']) + assert channel['to_us_msat'] == 5050000 + assert channel['total_msat'] == 505050000 + + +@pytest.mark.openchannel('v1') +@pytest.mark.openchannel('v2') +@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need') +def test_splice_out_all_keeps_reserve(node_factory, bitcoind): + l1, l2 = node_factory.line_graph(2, fundamount=1000000, wait_for_announce=True) + chan_id = l1.get_channel_id(l2) + l1.rpc.xpay(l2.rpc.invoice(500000000, 'push', 'push')['bolt11']) + wait_for(lambda: only_one(l2.rpc.listpeerchannels()['channels'])['to_us_msat'] == 500000000) + + # All of l2's available funds leave it 5,050 sat, exactly the reserve + # for the 505,050 sat channel that leaves. + result = l2.rpc.splice(f"{chan_id} -> 100%") + bitcoind.generate_block(6, wait_for_mempool=result['txid']) + for n in (l1, l2): + n.daemon.wait_for_log(r'CHANNELD_AWAITING_SPLICE to CHANNELD_NORMAL') + channel = only_one(l2.rpc.listpeerchannels()['channels']) + assert channel['to_us_msat'] == 5050000 + assert channel['total_msat'] == 505050000 + + +@pytest.mark.openchannel('v1') +@pytest.mark.openchannel('v2') +@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need') +def test_splice_in_with_change_below_reserve(node_factory, bitcoind): + l1, l2 = node_factory.line_graph(2, fundamount=1000000, wait_for_announce=True, + opts={'may_reconnect': True, + 'allow_warning': True}) + chan_id = l1.get_channel_id(l2) + assert only_one(l2.rpc.listpeerchannels()['channels'])['to_us_msat'] == 0 + l2.fundwallet(100000) + + def splice_in(amount, funds): + result = l2.rpc.splice_init(chan_id, amount, funds['psbt']) + result = l2.rpc.splice_update(chan_id, result['psbt']) + result = l2.rpc.splice_update(chan_id, result['psbt']) + result = l2.rpc.signpsbt(result['psbt']) + return l2.rpc.splice_signed(chan_id, result['signed_psbt']) + + # l2 adds its change output, so it must keep the 10,050 sat reserve for + # the new 1,005,000 sat channel, and 5,000 sat does not. + funds = l2.rpc.fundpsbt("16722sat", 0, 0, excess_as_change=True) + with pytest.raises(RpcError, match='below the reserve of 10050sat'): + splice_in(5000, funds) + l2.rpc.unreserveinputs(funds['psbt']) + for n in (l1, l2): + n.daemon.wait_for_log(r'Restarting channeld after tx_abort on CHANNELD_NORMAL channel') + wait_for(lambda: only_one(l2.rpc.listpeerchannels()['channels'])['peer_connected']) + + # 20,000 sat is above the 10,200 sat reserve for 1,020,000 sat. + result = splice_in(20000, l2.rpc.fundpsbt("31722sat", 0, 0, excess_as_change=True)) + bitcoind.generate_block(6, wait_for_mempool=result['txid']) + for n in (l1, l2): + n.daemon.wait_for_log(r'CHANNELD_AWAITING_SPLICE to CHANNELD_NORMAL') + assert only_one(l2.rpc.listpeerchannels()['channels'])['to_us_msat'] == 20000000 + + +@pytest.mark.openchannel('v1') +@pytest.mark.openchannel('v2') +@unittest.skipIf(TEST_NETWORK != 'regtest', 'elementsd doesnt yet support PSBT features we need') +def test_splice_out_all_opener_keeps_fee(node_factory, bitcoind): + l1, l2 = node_factory.line_graph(2, fundamount=1000000, wait_for_announce=True) + chan_id = l1.get_channel_id(l2) + result = l1.rpc.splice(f"{chan_id} -> 100%") + bitcoind.generate_block(6, wait_for_mempool=result['txid']) + for n in (l1, l2): + n.daemon.wait_for_log(r'CHANNELD_AWAITING_SPLICE to CHANNELD_NORMAL') + # As opener l1 keeps the 546 sat dust-limit reserve, plus the anchors' + # 660 sat and the 9,377 sat commitment fee with one more HTLC at the + # 7,236 perkw marginal feerate for 3,750, as channel_add_htlc asks. + channel = only_one(l1.rpc.listpeerchannels()['channels']) + assert channel['to_us_msat'] == 10583000 + assert channel['total_msat'] == 10583000