1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Various user-configurable channel limits and settings which ChannelManager
13 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
14 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
17 use crate::util::ser::Readable;
19 /// Configuration we set when applicable.
21 /// `Default::default()` provides sane defaults.
22 #[derive(Copy, Clone, Debug)]
23 pub struct ChannelHandshakeConfig {
24 /// Confirmations we will wait for before considering the channel locked in.
25 /// Applied only for inbound channels (see [`ChannelHandshakeLimits::max_minimum_depth`] for the
26 /// equivalent limit applied to outbound channels).
28 /// A lower-bound of `1` is applied, requiring all channels to have a confirmed commitment
29 /// transaction before operation. If you wish to accept channels with zero confirmations, see
30 /// [`UserConfig::manually_accept_inbound_channels`] and
31 /// [`ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`].
33 /// Default value: `6`
35 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
36 /// [`ChannelManager::accept_inbound_channel_from_trusted_peer_0conf`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer_0conf
37 pub minimum_depth: u32,
38 /// Set to the number of blocks we require our counterparty to wait to claim their money (ie
39 /// the number of blocks we have to punish our counterparty if they broadcast a revoked
42 /// This is one of the main parameters of our security model. We (or one of our watchtowers) MUST
43 /// be online to check for revoked transactions on-chain at least once every our_to_self_delay
44 /// blocks (minus some margin to allow us enough time to broadcast and confirm a transaction,
45 /// possibly with time in between to RBF the spending transaction).
47 /// Meanwhile, asking for a too high delay, we bother peer to freeze funds for nothing in
48 /// case of an honest unilateral channel close, which implicitly decrease the economic value of
51 /// Default value: [`BREAKDOWN_TIMEOUT`] (We enforce it as a minimum at channel opening so you
52 /// can tweak config to ask for more security, not less.)
53 pub our_to_self_delay: u16,
54 /// Set to the smallest value HTLC we will accept to process.
56 /// This value is sent to our counterparty on channel-open and we close the channel any time
57 /// our counterparty misbehaves by sending us an HTLC with a value smaller than this.
59 /// Default value: `1` (If the value is less than `1`, it is ignored and set to `1`, as is
60 /// required by the protocol.
61 pub our_htlc_minimum_msat: u64,
62 /// Sets the percentage of the channel value we will cap the total value of outstanding inbound
65 /// This can be set to a value between 1-100, where the value corresponds to the percent of the
66 /// channel value in whole percentages.
69 /// * If configured to another value than the default value `10`, any new channels created with
70 /// the non default value will cause versions of LDK prior to 0.0.104 to refuse to read the
73 /// * This caps the total value for inbound HTLCs in-flight only, and there's currently
74 /// no way to configure the cap for the total value of outbound HTLCs in-flight.
76 /// * The requirements for your node being online to ensure the safety of HTLC-encumbered funds
77 /// are different from the non-HTLC-encumbered funds. This makes this an important knob to
78 /// restrict exposure to loss due to being offline for too long.
79 /// See [`ChannelHandshakeConfig::our_to_self_delay`] and [`ChannelConfig::cltv_expiry_delta`]
80 /// for more information.
82 /// Default value: `10`
84 /// Minimum value: `1` (Any values less will be treated as `1` instead.)
86 /// Maximum value: `100` (Any values larger will be treated as `100` instead.)
87 pub max_inbound_htlc_value_in_flight_percent_of_channel: u8,
88 /// If set, we attempt to negotiate the `scid_privacy` (referred to as `scid_alias` in the
89 /// BOLTs) option for outbound private channels. This provides better privacy by not including
90 /// our real on-chain channel UTXO in each invoice and requiring that our counterparty only
91 /// relay HTLCs to us using the channel's SCID alias.
93 /// If this option is set, channels may be created that will not be readable by LDK versions
94 /// prior to 0.0.106, causing [`ChannelManager`]'s read method to return a
95 /// [`DecodeError::InvalidValue`].
97 /// Note that setting this to true does *not* prevent us from opening channels with
98 /// counterparties that do not support the `scid_alias` option; we will simply fall back to a
99 /// private channel without that option.
101 /// Ignored if the channel is negotiated to be announced, see
102 /// [`ChannelHandshakeConfig::announced_channel`] and
103 /// [`ChannelHandshakeLimits::force_announced_channel_preference`] for more.
105 /// Default value: `false` (This value is likely to change to `true` in the future.)
107 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
108 /// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue
109 pub negotiate_scid_privacy: bool,
110 /// Set to announce the channel publicly and notify all nodes that they can route via this
113 /// This should only be set to true for nodes which expect to be online reliably.
115 /// As the node which funds a channel picks this value this will only apply for new outbound
116 /// channels unless [`ChannelHandshakeLimits::force_announced_channel_preference`] is set.
118 /// Default value: `false`
119 pub announced_channel: bool,
120 /// When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty
121 /// supports it, they will then enforce the mutual-close output to us matches what we provided
122 /// at intialization, preventing us from closing to an alternate pubkey.
124 /// This is set to true by default to provide a slight increase in security, though ultimately
125 /// any attacker who is able to take control of a channel can just as easily send the funds via
126 /// lightning payments, so we never require that our counterparties support this option.
128 /// The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`].
130 /// Default value: `true`
132 /// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::sign::SignerProvider::get_shutdown_scriptpubkey
133 pub commit_upfront_shutdown_pubkey: bool,
134 /// The Proportion of the channel value to configure as counterparty's channel reserve,
135 /// i.e., `their_channel_reserve_satoshis` for both outbound and inbound channels.
137 /// `their_channel_reserve_satoshis` is the minimum balance that the other node has to maintain
138 /// on their side, at all times.
139 /// This ensures that if our counterparty broadcasts a revoked state, we can punish them by
140 /// claiming at least this value on chain.
142 /// Channel reserve values greater than 30% could be considered highly unreasonable, since that
143 /// amount can never be used for payments.
144 /// Also, if our selected channel reserve for counterparty and counterparty's selected
145 /// channel reserve for us sum up to equal or greater than channel value, channel negotiations
148 /// Note: Versions of LDK earlier than v0.0.104 will fail to read channels with any channel reserve
149 /// other than the default value.
151 /// Default value: `10_000` millionths (i.e., 1% of channel value)
153 /// Minimum value: If the calculated proportional value is less than `1000` sats, it will be
154 /// treated as `1000` sats instead, which is a safe implementation-specific lower
157 /// Maximum value: `1_000_000` (i.e., 100% of channel value. Any values larger than one million
158 /// will be treated as one million instead, although channel negotiations will
159 /// fail in that case.)
160 pub their_channel_reserve_proportional_millionths: u32,
161 /// If set, we attempt to negotiate the `anchors_zero_fee_htlc_tx`option for all future
162 /// channels. This feature requires having a reserve of onchain funds readily available to bump
163 /// transactions in the event of a channel force close to avoid the possibility of losing funds.
165 /// Note that if you wish accept inbound channels with anchor outputs, you must enable
166 /// [`UserConfig::manually_accept_inbound_channels`] and manually accept them with
167 /// [`ChannelManager::accept_inbound_channel`]. This is done to give you the chance to check
168 /// whether your reserve of onchain funds is enough to cover the fees for all existing and new
169 /// channels featuring anchor outputs in the event of a force close.
171 /// If this option is set, channels may be created that will not be readable by LDK versions
172 /// prior to 0.0.116, causing [`ChannelManager`]'s read method to return a
173 /// [`DecodeError::InvalidValue`].
175 /// Note that setting this to true does *not* prevent us from opening channels with
176 /// counterparties that do not support the `anchors_zero_fee_htlc_tx` option; we will simply
177 /// fall back to a `static_remote_key` channel.
179 /// LDK will not support the legacy `option_anchors` commitment version due to a discovered
180 /// vulnerability after its deployment. For more context, see the [`SIGHASH_SINGLE + update_fee
181 /// Considered Harmful`] mailing list post.
183 /// Default value: `false` (This value is likely to change to `true` in the future.)
185 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
186 /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
187 /// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue
188 /// [`SIGHASH_SINGLE + update_fee Considered Harmful`]: https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-September/002796.html
189 pub negotiate_anchors_zero_fee_htlc_tx: bool,
191 /// The maximum number of HTLCs in-flight from our counterparty towards us at the same time.
193 /// Increasing the value can help improve liquidity and stability in
194 /// routing at the cost of higher long term disk / DB usage.
196 /// Note: Versions of LDK earlier than v0.0.115 will fail to read channels with a configuration
197 /// other than the default value.
199 /// Default value: `50`
201 /// Maximum value: `483` (Any values larger will be treated as `483`. This is the BOLT #2 spec
202 /// limit on `max_accepted_htlcs`.)
203 pub our_max_accepted_htlcs: u16,
206 impl Default for ChannelHandshakeConfig {
207 fn default() -> ChannelHandshakeConfig {
208 ChannelHandshakeConfig {
210 our_to_self_delay: BREAKDOWN_TIMEOUT,
211 our_htlc_minimum_msat: 1,
212 max_inbound_htlc_value_in_flight_percent_of_channel: 10,
213 negotiate_scid_privacy: false,
214 announced_channel: false,
215 commit_upfront_shutdown_pubkey: true,
216 their_channel_reserve_proportional_millionths: 10_000,
217 negotiate_anchors_zero_fee_htlc_tx: false,
218 our_max_accepted_htlcs: 50,
223 // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
224 // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
225 // don't really want to ever expose this to users (if we did we'd want to use TLVs).
227 impl Readable for ChannelHandshakeConfig {
228 fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
230 minimum_depth: Readable::read(reader)?,
231 our_to_self_delay: Readable::read(reader)?,
232 our_htlc_minimum_msat: Readable::read(reader)?,
233 max_inbound_htlc_value_in_flight_percent_of_channel: Readable::read(reader)?,
234 negotiate_scid_privacy: Readable::read(reader)?,
235 announced_channel: Readable::read(reader)?,
236 commit_upfront_shutdown_pubkey: Readable::read(reader)?,
237 their_channel_reserve_proportional_millionths: Readable::read(reader)?,
238 negotiate_anchors_zero_fee_htlc_tx: Readable::read(reader)?,
239 our_max_accepted_htlcs: Readable::read(reader)?,
244 /// Optional channel limits which are applied during channel creation.
246 /// These limits are only applied to our counterparty's limits, not our own.
248 /// Use `0` or `<type>::max_value()` as appropriate to skip checking.
250 /// Provides sane defaults for most configurations.
252 /// Most additional limits are disabled except those with which specify a default in individual
253 /// field documentation. Note that this may result in barely-usable channels, but since they
254 /// are applied mostly only to incoming channels that's not much of a problem.
255 #[derive(Copy, Clone, Debug)]
256 pub struct ChannelHandshakeLimits {
257 /// Minimum allowed satoshis when a channel is funded. This is supplied by the sender and so
258 /// only applies to inbound channels.
260 /// Default value: `0`
261 pub min_funding_satoshis: u64,
262 /// Maximum allowed satoshis when a channel is funded. This is supplied by the sender and so
263 /// only applies to inbound channels.
265 /// Default value: `2^24 - 1`
266 pub max_funding_satoshis: u64,
267 /// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows
268 /// you to limit the maximum minimum-size they can require.
270 /// Default value: `u64::max_value`
271 pub max_htlc_minimum_msat: u64,
272 /// The remote node sets a limit on the maximum value of pending HTLCs to them at any given
273 /// time to limit their funds exposure to HTLCs. This allows you to set a minimum such value.
275 /// Default value: `0`
276 pub min_max_htlc_value_in_flight_msat: u64,
277 /// The remote node will require we keep a certain amount in direct payment to ourselves at all
278 /// time, ensuring that we are able to be punished if we broadcast an old state. This allows to
279 /// you limit the amount which we will have to keep to ourselves (and cannot use for HTLCs).
281 /// Default value: `u64::max_value`.
282 pub max_channel_reserve_satoshis: u64,
283 /// The remote node sets a limit on the maximum number of pending HTLCs to them at any given
284 /// time. This allows you to set a minimum such value.
286 /// Default value: `0`
287 pub min_max_accepted_htlcs: u16,
288 /// Before a channel is usable the funding transaction will need to be confirmed by at least a
289 /// certain number of blocks, specified by the node which is not the funder (as the funder can
290 /// assume they aren't going to double-spend themselves).
291 /// This config allows you to set a limit on the maximum amount of time to wait.
293 /// Default value: `144`, or roughly one day and only applies to outbound channels
294 pub max_minimum_depth: u32,
295 /// Whether we implicitly trust funding transactions generated by us for our own outbound
296 /// channels to not be double-spent.
298 /// If this is set, we assume that our own funding transactions are *never* double-spent, and
299 /// thus we can trust them without any confirmations. This is generally a reasonable
300 /// assumption, given we're the only ones who could ever double-spend it (assuming we have sole
301 /// control of the signing keys).
303 /// You may wish to un-set this if you allow the user to (or do in an automated fashion)
304 /// double-spend the funding transaction to RBF with an alternative channel open.
306 /// This only applies if our counterparty set their confirmations-required value to `0`, and we
307 /// always trust our own funding transaction at `1` confirmation irrespective of this value.
308 /// Thus, this effectively acts as a `min_minimum_depth`, with the only possible values being
309 /// `true` (`0`) and `false` (`1`).
311 /// Default value: `true`
312 pub trust_own_funding_0conf: bool,
313 /// Set to force an incoming channel to match our announced channel preference in
314 /// [`ChannelHandshakeConfig::announced_channel`].
316 /// For a node which is not online reliably, this should be set to true and
317 /// [`ChannelHandshakeConfig::announced_channel`] set to false, ensuring that no announced (aka public)
318 /// channels will ever be opened.
320 /// Default value: `true`
321 pub force_announced_channel_preference: bool,
322 /// Set to the amount of time we're willing to wait to claim money back to us.
324 /// Not checking this value would be a security issue, as our peer would be able to set it to
325 /// max relative lock-time (a year) and we would "lose" money as it would be locked for a long time.
327 /// Default value: `2016`, which we also enforce as a maximum value so you can tweak config to
328 /// reduce the loss of having useless locked funds (if your peer accepts)
329 pub their_to_self_delay: u16
332 impl Default for ChannelHandshakeLimits {
333 fn default() -> Self {
334 ChannelHandshakeLimits {
335 min_funding_satoshis: 0,
336 max_funding_satoshis: MAX_FUNDING_SATOSHIS_NO_WUMBO,
337 max_htlc_minimum_msat: <u64>::max_value(),
338 min_max_htlc_value_in_flight_msat: 0,
339 max_channel_reserve_satoshis: <u64>::max_value(),
340 min_max_accepted_htlcs: 0,
341 trust_own_funding_0conf: true,
342 max_minimum_depth: 144,
343 force_announced_channel_preference: true,
344 their_to_self_delay: MAX_LOCAL_BREAKDOWN_TIMEOUT,
349 // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
350 // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
351 // don't really want to ever expose this to users (if we did we'd want to use TLVs).
353 impl Readable for ChannelHandshakeLimits {
354 fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
356 min_funding_satoshis: Readable::read(reader)?,
357 max_funding_satoshis: Readable::read(reader)?,
358 max_htlc_minimum_msat: Readable::read(reader)?,
359 min_max_htlc_value_in_flight_msat: Readable::read(reader)?,
360 max_channel_reserve_satoshis: Readable::read(reader)?,
361 min_max_accepted_htlcs: Readable::read(reader)?,
362 trust_own_funding_0conf: Readable::read(reader)?,
363 max_minimum_depth: Readable::read(reader)?,
364 force_announced_channel_preference: Readable::read(reader)?,
365 their_to_self_delay: Readable::read(reader)?,
370 /// Options for how to set the max dust exposure allowed on a channel. See
371 /// [`ChannelConfig::max_dust_htlc_exposure`] for details.
372 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
373 pub enum MaxDustHTLCExposure {
374 /// This sets a fixed limit on the total dust exposure in millisatoshis. Setting this too low
375 /// may prevent the sending or receipt of low-value HTLCs on high-traffic nodes, however this
376 /// limit is very important to prevent stealing of large amounts of dust HTLCs by miners
377 /// through [fee griefing
378 /// attacks](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-May/002714.html).
380 /// Note that if the feerate increases significantly, without a manual increase
381 /// to this maximum the channel may be unable to send/receive HTLCs between the maximum dust
382 /// exposure and the new minimum value for HTLCs to be economically viable to claim.
384 /// This sets a multiplier on the [`ConfirmationTarget::OnChainSweep`] feerate (in sats/KW) to
385 /// determine the maximum allowed dust exposure. If this variant is used then the maximum dust
386 /// exposure in millisatoshis is calculated as:
387 /// `feerate_per_kw * value`. For example, with our default value
388 /// `FeeRateMultiplier(10_000)`:
390 /// - For the minimum fee rate of 1 sat/vByte (250 sat/KW, although the minimum
391 /// defaults to 253 sats/KW for rounding, see [`FeeEstimator`]), the max dust exposure would
392 /// be 253 * 10_000 = 2,530,000 msats.
393 /// - For a fee rate of 30 sat/vByte (7500 sat/KW), the max dust exposure would be
394 /// 7500 * 50_000 = 75,000,000 msats (0.00075 BTC).
396 /// Note, if you're using a third-party fee estimator, this may leave you more exposed to a
397 /// fee griefing attack, where your fee estimator may purposely overestimate the fee rate,
398 /// causing you to accept more dust HTLCs than you would otherwise.
400 /// This variant is primarily meant to serve pre-anchor channels, as HTLC fees being included
401 /// on HTLC outputs means your channel may be subject to more dust exposure in the event of
402 /// increases in fee rate.
404 /// # Backwards Compatibility
405 /// This variant only became available in LDK 0.0.116, so if you downgrade to a prior version
406 /// by default this will be set to a [`Self::FixedLimitMsat`] of 5,000,000 msat.
408 /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator
409 /// [`ConfirmationTarget::OnChainSweep`]: crate::chain::chaininterface::ConfirmationTarget::OnChainSweep
410 FeeRateMultiplier(u64),
413 impl_writeable_tlv_based_enum!(MaxDustHTLCExposure, ;
415 (3, FeeRateMultiplier),
418 /// Options which apply on a per-channel basis and may change at runtime or based on negotiation
419 /// with our counterparty.
420 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
421 pub struct ChannelConfig {
422 /// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound
423 /// over the channel.
424 /// This may be allowed to change at runtime in a later update, however doing so must result in
425 /// update messages sent to notify all nodes of our updated relay fee.
427 /// Default value: `0`
428 pub forwarding_fee_proportional_millionths: u32,
429 /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in
430 /// excess of [`forwarding_fee_proportional_millionths`].
431 /// This may be allowed to change at runtime in a later update, however doing so must result in
432 /// update messages sent to notify all nodes of our updated relay fee.
434 /// The default value of a single satoshi roughly matches the market rate on many routing nodes
435 /// as of July 2021. Adjusting it upwards or downwards may change whether nodes route through
438 /// Default value: `1000`
440 /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
441 pub forwarding_fee_base_msat: u32,
442 /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over
443 /// the channel this config applies to.
445 /// This is analogous to [`ChannelHandshakeConfig::our_to_self_delay`] but applies to in-flight
446 /// HTLC balance when a channel appears on-chain whereas
447 /// [`ChannelHandshakeConfig::our_to_self_delay`] applies to the remaining
448 /// (non-HTLC-encumbered) balance.
450 /// Thus, for HTLC-encumbered balances to be enforced on-chain when a channel is force-closed,
451 /// we (or one of our watchtowers) MUST be online to check for broadcast of the current
452 /// commitment transaction at least once per this many blocks (minus some margin to allow us
453 /// enough time to broadcast and confirm a transaction, possibly with time in between to RBF
454 /// the spending transaction).
456 /// Default value: `72` (12 hours at an average of 6 blocks/hour)
458 /// Minimum value: [`MIN_CLTV_EXPIRY_DELTA`] (Any values less than this will be treated as
459 /// [`MIN_CLTV_EXPIRY_DELTA`] instead.)
461 /// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA
462 pub cltv_expiry_delta: u16,
463 /// Limit our total exposure to potential loss to on-chain fees on close, including in-flight
464 /// HTLCs which are burned to fees as they are too small to claim on-chain and fees on
465 /// commitment transaction(s) broadcasted by our counterparty in excess of our own fee estimate.
467 /// # HTLC-based Dust Exposure
469 /// When an HTLC present in one of our channels is below a "dust" threshold, the HTLC will
470 /// not be claimable on-chain, instead being turned into additional miner fees if either
471 /// party force-closes the channel. Because the threshold is per-HTLC, our total exposure
472 /// to such payments may be substantial if there are many dust HTLCs present when the
473 /// channel is force-closed.
475 /// The dust threshold for each HTLC is based on the `dust_limit_satoshis` for each party in a
476 /// channel negotiated throughout the channel open process, along with the fees required to have
477 /// a broadcastable HTLC spending transaction. When a channel supports anchor outputs
478 /// (specifically the zero fee HTLC transaction variant), this threshold no longer takes into
479 /// account the HTLC transaction fee as it is zero. Because of this, you may want to set this
480 /// value to a fixed limit for channels using anchor outputs, while the fee rate multiplier
481 /// variant is primarily intended for use with pre-anchor channels.
483 /// The selected limit is applied for sent, forwarded, and received HTLCs and limits the total
484 /// exposure across all three types per-channel.
486 /// # Transaction Fee Dust Exposure
488 /// Further, counterparties broadcasting a commitment transaction in a force-close may result
489 /// in other balance being burned to fees, and thus all fees on commitment and HTLC
490 /// transactions in excess of our local fee estimates are included in the dust calculation.
492 /// Because of this, another way to look at this limit is to divide it by 43,000 (or 218,750
493 /// for non-anchor channels) and see it as the maximum feerate disagreement (in sats/vB) per
494 /// non-dust HTLC we're allowed to have with our peers before risking a force-closure for
495 /// inbound channels.
496 // This works because, for anchor channels the on-chain cost is 172 weight (172+703 for
497 // non-anchors with an HTLC-Success transaction), i.e.
498 // dust_exposure_limit_msat / 1000 = 172 * feerate_in_sat_per_vb / 4 * HTLC count
499 // dust_exposure_limit_msat = 43,000 * feerate_in_sat_per_vb * HTLC count
500 // dust_exposure_limit_msat / HTLC count / 43,000 = feerate_in_sat_per_vb
502 /// Thus, for the default value of 10_000 * a current feerate estimate of 10 sat/vB (or 2,500
503 /// sat/KW), we risk force-closure if we disagree with our peer by:
504 /// * `10_000 * 2_500 / 43_000 / (483*2)` = 0.6 sat/vB for anchor channels with 483 HTLCs in
505 /// both directions (the maximum),
506 /// * `10_000 * 2_500 / 43_000 / (50*2)` = 5.8 sat/vB for anchor channels with 50 HTLCs in both
507 /// directions (the LDK default max from [`ChannelHandshakeConfig::our_max_accepted_htlcs`])
508 /// * `10_000 * 2_500 / 218_750 / (483*2)` = 0.1 sat/vB for non-anchor channels with 483 HTLCs
509 /// in both directions (the maximum),
510 /// * `10_000 * 2_500 / 218_750 / (50*2)` = 1.1 sat/vB for non-anchor channels with 50 HTLCs
511 /// in both (the LDK default maximum from [`ChannelHandshakeConfig::our_max_accepted_htlcs`])
513 /// Note that when using [`MaxDustHTLCExposure::FeeRateMultiplier`] this maximum disagreement
514 /// will scale linearly with increases (or decreases) in the our feerate estimates. Further,
515 /// for anchor channels we expect our counterparty to use a relatively low feerate estimate
516 /// while we use [`ConfirmationTarget::OnChainSweep`] (which should be relatively high) and
517 /// feerate disagreement force-closures should only occur when theirs is higher than ours.
519 /// Default value: [`MaxDustHTLCExposure::FeeRateMultiplier`] with a multiplier of `10_000`
521 /// [`ConfirmationTarget::OnChainSweep`]: crate::chain::chaininterface::ConfirmationTarget::OnChainSweep
522 pub max_dust_htlc_exposure: MaxDustHTLCExposure,
523 /// The additional fee we're willing to pay to avoid waiting for the counterparty's
524 /// `to_self_delay` to reclaim funds.
526 /// When we close a channel cooperatively with our counterparty, we negotiate a fee for the
527 /// closing transaction which both sides find acceptable, ultimately paid by the channel
528 /// funder/initiator.
530 /// When we are the funder, because we have to pay the channel closing fee, we bound the
531 /// acceptable fee by our [`ChannelCloseMinimum`] and [`NonAnchorChannelFee`] fees, with the upper bound increased by
532 /// this value. Because the on-chain fee we'd pay to force-close the channel is kept near our
533 /// [`NonAnchorChannelFee`] feerate during normal operation, this value represents the additional fee we're
534 /// willing to pay in order to avoid waiting for our counterparty's to_self_delay to reclaim our
537 /// When we are not the funder, we require the closing transaction fee pay at least our
538 /// [`ChannelCloseMinimum`] fee estimate, but allow our counterparty to pay as much fee as they like.
539 /// Thus, this value is ignored when we are not the funder.
541 /// Default value: `1000`
543 /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
544 /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
545 pub force_close_avoidance_max_fee_satoshis: u64,
546 /// If set, allows this channel's counterparty to skim an additional fee off this node's inbound
547 /// HTLCs. Useful for liquidity providers to offload on-chain channel costs to end users.
550 /// - The payee will set this option and set its invoice route hints to use [intercept scids]
551 /// generated by this channel's counterparty.
552 /// - The counterparty will get an [`HTLCIntercepted`] event upon payment forward, and call
553 /// [`forward_intercepted_htlc`] with less than the amount provided in
554 /// [`HTLCIntercepted::expected_outbound_amount_msat`]. The difference between the expected and
555 /// actual forward amounts is their fee. See
556 /// <https://github.com/BitcoinAndLightningLayerSpecs/lsp/tree/main/LSPS2#flow-lsp-trusts-client-model>
557 /// for how this feature may be used in the LSP use case.
560 /// It's important for payee wallet software to verify that [`PaymentClaimable::amount_msat`] is
561 /// as-expected if this feature is activated, otherwise they may lose money!
562 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`] provides the fee taken by the
566 /// Switching this config flag on may break compatibility with versions of LDK prior to 0.0.116.
567 /// Unsetting this flag between restarts may lead to payment receive failures.
569 /// Default value: `false`
571 /// [intercept scids]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
572 /// [`forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc
573 /// [`HTLCIntercepted`]: crate::events::Event::HTLCIntercepted
574 /// [`HTLCIntercepted::expected_outbound_amount_msat`]: crate::events::Event::HTLCIntercepted::expected_outbound_amount_msat
575 /// [`PaymentClaimable::amount_msat`]: crate::events::Event::PaymentClaimable::amount_msat
576 /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: crate::events::Event::PaymentClaimable::counterparty_skimmed_fee_msat
577 // TODO: link to bLIP when it's merged
578 pub accept_underpaying_htlcs: bool,
582 /// Applies the given [`ChannelConfigUpdate`] as a partial update to the [`ChannelConfig`].
583 pub fn apply(&mut self, update: &ChannelConfigUpdate) {
584 if let Some(forwarding_fee_proportional_millionths) = update.forwarding_fee_proportional_millionths {
585 self.forwarding_fee_proportional_millionths = forwarding_fee_proportional_millionths;
587 if let Some(forwarding_fee_base_msat) = update.forwarding_fee_base_msat {
588 self.forwarding_fee_base_msat = forwarding_fee_base_msat;
590 if let Some(cltv_expiry_delta) = update.cltv_expiry_delta {
591 self.cltv_expiry_delta = cltv_expiry_delta;
593 if let Some(max_dust_htlc_exposure_msat) = update.max_dust_htlc_exposure_msat {
594 self.max_dust_htlc_exposure = max_dust_htlc_exposure_msat;
596 if let Some(force_close_avoidance_max_fee_satoshis) = update.force_close_avoidance_max_fee_satoshis {
597 self.force_close_avoidance_max_fee_satoshis = force_close_avoidance_max_fee_satoshis;
602 impl Default for ChannelConfig {
603 /// Provides sane defaults for most configurations (but with zero relay fees!).
604 fn default() -> Self {
606 forwarding_fee_proportional_millionths: 0,
607 forwarding_fee_base_msat: 1000,
608 cltv_expiry_delta: 6 * 12, // 6 blocks/hour * 12 hours
609 max_dust_htlc_exposure: MaxDustHTLCExposure::FeeRateMultiplier(10000),
610 force_close_avoidance_max_fee_satoshis: 1000,
611 accept_underpaying_htlcs: false,
616 impl crate::util::ser::Writeable for ChannelConfig {
617 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
618 let max_dust_htlc_exposure_msat_fixed_limit = match self.max_dust_htlc_exposure {
619 MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
620 MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000,
622 write_tlv_fields!(writer, {
623 (0, self.forwarding_fee_proportional_millionths, required),
624 (1, self.accept_underpaying_htlcs, (default_value, false)),
625 (2, self.forwarding_fee_base_msat, required),
626 (3, self.max_dust_htlc_exposure, required),
627 (4, self.cltv_expiry_delta, required),
628 (6, max_dust_htlc_exposure_msat_fixed_limit, required),
629 // ChannelConfig serialized this field with a required type of 8 prior to the introduction of
630 // LegacyChannelConfig. To make sure that serialization is not compatible with this one, we use
631 // the next required type of 10, which if seen by the old serialization will always fail.
632 (10, self.force_close_avoidance_max_fee_satoshis, required),
638 impl crate::util::ser::Readable for ChannelConfig {
639 fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
640 let mut forwarding_fee_proportional_millionths = 0;
641 let mut accept_underpaying_htlcs = false;
642 let mut forwarding_fee_base_msat = 1000;
643 let mut cltv_expiry_delta = 6 * 12;
644 let mut max_dust_htlc_exposure_msat = None;
645 let mut max_dust_htlc_exposure_enum = None;
646 let mut force_close_avoidance_max_fee_satoshis = 1000;
647 read_tlv_fields!(reader, {
648 (0, forwarding_fee_proportional_millionths, required),
649 (1, accept_underpaying_htlcs, (default_value, false)),
650 (2, forwarding_fee_base_msat, required),
651 (3, max_dust_htlc_exposure_enum, option),
652 (4, cltv_expiry_delta, required),
653 // Has always been written, but became optionally read in 0.0.116
654 (6, max_dust_htlc_exposure_msat, option),
655 (10, force_close_avoidance_max_fee_satoshis, required),
657 let max_dust_htlc_fixed_limit = max_dust_htlc_exposure_msat.unwrap_or(5_000_000);
658 let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum
659 .unwrap_or(MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_fixed_limit));
661 forwarding_fee_proportional_millionths,
662 accept_underpaying_htlcs,
663 forwarding_fee_base_msat,
665 max_dust_htlc_exposure: max_dust_htlc_exposure_msat,
666 force_close_avoidance_max_fee_satoshis,
671 /// A parallel struct to [`ChannelConfig`] to define partial updates.
672 #[allow(missing_docs)]
673 pub struct ChannelConfigUpdate {
674 pub forwarding_fee_proportional_millionths: Option<u32>,
675 pub forwarding_fee_base_msat: Option<u32>,
676 pub cltv_expiry_delta: Option<u16>,
677 pub max_dust_htlc_exposure_msat: Option<MaxDustHTLCExposure>,
678 pub force_close_avoidance_max_fee_satoshis: Option<u64>,
681 impl Default for ChannelConfigUpdate {
682 fn default() -> ChannelConfigUpdate {
683 ChannelConfigUpdate {
684 forwarding_fee_proportional_millionths: None,
685 forwarding_fee_base_msat: None,
686 cltv_expiry_delta: None,
687 max_dust_htlc_exposure_msat: None,
688 force_close_avoidance_max_fee_satoshis: None,
693 impl From<ChannelConfig> for ChannelConfigUpdate {
694 fn from(config: ChannelConfig) -> ChannelConfigUpdate {
695 ChannelConfigUpdate {
696 forwarding_fee_proportional_millionths: Some(config.forwarding_fee_proportional_millionths),
697 forwarding_fee_base_msat: Some(config.forwarding_fee_base_msat),
698 cltv_expiry_delta: Some(config.cltv_expiry_delta),
699 max_dust_htlc_exposure_msat: Some(config.max_dust_htlc_exposure),
700 force_close_avoidance_max_fee_satoshis: Some(config.force_close_avoidance_max_fee_satoshis),
705 /// Legacy version of [`ChannelConfig`] that stored the static
706 /// [`ChannelHandshakeConfig::announced_channel`] and
707 /// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] fields.
708 #[derive(Copy, Clone, Debug)]
709 pub(crate) struct LegacyChannelConfig {
710 pub(crate) options: ChannelConfig,
711 /// Deprecated but may still be read from. See [`ChannelHandshakeConfig::announced_channel`] to
712 /// set this when opening/accepting a channel.
713 pub(crate) announced_channel: bool,
714 /// Deprecated but may still be read from. See
715 /// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] to set this when
716 /// opening/accepting a channel.
717 pub(crate) commit_upfront_shutdown_pubkey: bool,
720 impl Default for LegacyChannelConfig {
721 fn default() -> Self {
723 options: ChannelConfig::default(),
724 announced_channel: false,
725 commit_upfront_shutdown_pubkey: true,
730 impl crate::util::ser::Writeable for LegacyChannelConfig {
731 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
732 let max_dust_htlc_exposure_msat_fixed_limit = match self.options.max_dust_htlc_exposure {
733 MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
734 MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000,
736 write_tlv_fields!(writer, {
737 (0, self.options.forwarding_fee_proportional_millionths, required),
738 (1, max_dust_htlc_exposure_msat_fixed_limit, required),
739 (2, self.options.cltv_expiry_delta, required),
740 (3, self.options.force_close_avoidance_max_fee_satoshis, (default_value, 1000)),
741 (4, self.announced_channel, required),
742 (5, self.options.max_dust_htlc_exposure, required),
743 (6, self.commit_upfront_shutdown_pubkey, required),
744 (8, self.options.forwarding_fee_base_msat, required),
750 impl crate::util::ser::Readable for LegacyChannelConfig {
751 fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
752 let mut forwarding_fee_proportional_millionths = 0;
753 let mut max_dust_htlc_exposure_msat_fixed_limit = None;
754 let mut cltv_expiry_delta = 0;
755 let mut force_close_avoidance_max_fee_satoshis = 1000;
756 let mut announced_channel = false;
757 let mut commit_upfront_shutdown_pubkey = false;
758 let mut forwarding_fee_base_msat = 0;
759 let mut max_dust_htlc_exposure_enum = None;
760 read_tlv_fields!(reader, {
761 (0, forwarding_fee_proportional_millionths, required),
762 // Has always been written, but became optionally read in 0.0.116
763 (1, max_dust_htlc_exposure_msat_fixed_limit, option),
764 (2, cltv_expiry_delta, required),
765 (3, force_close_avoidance_max_fee_satoshis, (default_value, 1000u64)),
766 (4, announced_channel, required),
767 (5, max_dust_htlc_exposure_enum, option),
768 (6, commit_upfront_shutdown_pubkey, required),
769 (8, forwarding_fee_base_msat, required),
771 let max_dust_htlc_exposure_msat_fixed_limit =
772 max_dust_htlc_exposure_msat_fixed_limit.unwrap_or(5_000_000);
773 let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum
774 .unwrap_or(MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_exposure_msat_fixed_limit));
776 options: ChannelConfig {
777 forwarding_fee_proportional_millionths,
778 max_dust_htlc_exposure: max_dust_htlc_exposure_msat,
780 force_close_avoidance_max_fee_satoshis,
781 forwarding_fee_base_msat,
782 accept_underpaying_htlcs: false,
785 commit_upfront_shutdown_pubkey,
790 /// Top-level config which holds ChannelHandshakeLimits and ChannelConfig.
792 /// `Default::default()` provides sane defaults for most configurations
793 /// (but currently with zero relay fees!)
794 #[derive(Copy, Clone, Debug)]
795 pub struct UserConfig {
796 /// Channel handshake config that we propose to our counterparty.
797 pub channel_handshake_config: ChannelHandshakeConfig,
798 /// Limits applied to our counterparty's proposed channel handshake config settings.
799 pub channel_handshake_limits: ChannelHandshakeLimits,
800 /// Channel config which affects behavior during channel lifetime.
801 pub channel_config: ChannelConfig,
802 /// If this is set to `false`, we will reject any HTLCs which were to be forwarded over private
803 /// channels. This prevents us from taking on HTLC-forwarding risk when we intend to run as a
804 /// node which is not online reliably.
806 /// For nodes which are not online reliably, you should set all channels to *not* be announced
807 /// (using [`ChannelHandshakeConfig::announced_channel`] and
808 /// [`ChannelHandshakeLimits::force_announced_channel_preference`]) and set this to `false` to
809 /// ensure you are not exposed to any forwarding risk.
811 /// Note that because you cannot change a channel's announced state after creation, there is no
812 /// way to disable forwarding on public channels retroactively. Thus, in order to change a node
813 /// from a publicly-announced forwarding node to a private non-forwarding node you must close
814 /// all your channels and open new ones. For privacy, you should also change your node_id
815 /// (swapping all private and public key material for new ones) at that time.
817 /// Default value: `false`
818 pub accept_forwards_to_priv_channels: bool,
819 /// If this is set to `false`, we do not accept inbound requests to open a new channel.
821 /// Default value: `true`
822 pub accept_inbound_channels: bool,
823 /// If this is set to `true`, the user needs to manually accept inbound requests to open a new
826 /// When set to `true`, [`Event::OpenChannelRequest`] will be triggered once a request to open a
827 /// new inbound channel is received through a [`msgs::OpenChannel`] message. In that case, a
828 /// [`msgs::AcceptChannel`] message will not be sent back to the counterparty node unless the
829 /// user explicitly chooses to accept the request.
831 /// Default value: `false`
833 /// [`Event::OpenChannelRequest`]: crate::events::Event::OpenChannelRequest
834 /// [`msgs::OpenChannel`]: crate::ln::msgs::OpenChannel
835 /// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
836 pub manually_accept_inbound_channels: bool,
837 /// If this is set to `true`, LDK will intercept HTLCs that are attempting to be forwarded over
838 /// fake short channel ids generated via [`ChannelManager::get_intercept_scid`]. Upon HTLC
839 /// intercept, LDK will generate an [`Event::HTLCIntercepted`] which MUST be handled by the user.
841 /// Setting this to `true` may break backwards compatibility with LDK versions < 0.0.113.
843 /// Default value: `false`
845 /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid
846 /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted
847 pub accept_intercept_htlcs: bool,
848 /// If this is set to `false`, when receiving a keysend payment we'll fail it if it has multiple
849 /// parts. If this is set to `true`, we'll accept the payment.
851 /// Setting this to `true` will break backwards compatibility upon downgrading to an LDK
852 /// version prior to 0.0.116 while receiving an MPP keysend. If we have already received an MPP
853 /// keysend, downgrading will cause us to fail to deserialize [`ChannelManager`].
855 /// Default value: `false`
857 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
858 pub accept_mpp_keysend: bool,
859 /// If this is set to `true`, the user needs to manually pay [`Bolt12Invoice`]s when received.
861 /// When set to `true`, [`Event::InvoiceReceived`] will be generated for each received
862 /// [`Bolt12Invoice`] instead of being automatically paid after verification. Use
863 /// [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or
864 /// [`ChannelManager::abandon_payment`] to abandon the associated payment.
866 /// Default value: `false`
868 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
869 /// [`Event::InvoiceReceived`]: crate::events::Event::InvoiceReceived
870 /// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
871 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
872 pub manually_handle_bolt12_invoices: bool,
875 impl Default for UserConfig {
876 fn default() -> Self {
878 channel_handshake_config: ChannelHandshakeConfig::default(),
879 channel_handshake_limits: ChannelHandshakeLimits::default(),
880 channel_config: ChannelConfig::default(),
881 accept_forwards_to_priv_channels: false,
882 accept_inbound_channels: true,
883 manually_accept_inbound_channels: false,
884 accept_intercept_htlcs: false,
885 accept_mpp_keysend: false,
886 manually_handle_bolt12_invoices: false,
891 // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we
892 // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We
893 // don't really want to ever expose this to users (if we did we'd want to use TLVs).
895 impl Readable for UserConfig {
896 fn read<R: crate::io::Read>(reader: &mut R) -> Result<Self, crate::ln::msgs::DecodeError> {
898 channel_handshake_config: Readable::read(reader)?,
899 channel_handshake_limits: Readable::read(reader)?,
900 channel_config: Readable::read(reader)?,
901 accept_forwards_to_priv_channels: Readable::read(reader)?,
902 accept_inbound_channels: Readable::read(reader)?,
903 manually_accept_inbound_channels: Readable::read(reader)?,
904 accept_intercept_htlcs: Readable::read(reader)?,
905 accept_mpp_keysend: Readable::read(reader)?,
906 manually_handle_bolt12_invoices: Readable::read(reader)?,