// This file is Copyright its original authors, visible in version control // history. // // This file is licensed under the Apache License, Version 2.0 or the MIT license // , at your option. // You may not use this file except in accordance with one or both of these // licenses. //! Various user-configurable channel limits and settings which ChannelManager //! applies for you. use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT}; #[cfg(fuzzing)] use crate::util::ser::Readable; /// Configuration we set when applicable. /// /// `Default::default()` provides sane defaults. #[derive(Copy, Clone, Debug)] pub struct ChannelHandshakeConfig { /// Confirmations we will wait for before considering the channel locked in. /// Applied only for inbound channels (see [`ChannelHandshakeLimits::max_minimum_depth`] for the /// equivalent limit applied to outbound channels). /// /// Also used when splicing the channel for the number of confirmations needed before sending a /// `splice_locked` message to the counterparty. The spliced funds are considered locked in when /// both parties have exchanged `splice_locked`. /// /// A lower-bound of `1` is applied, requiring all channels to have a confirmed commitment /// transaction before operation. If you wish to accept channels with zero confirmations, /// manually accept them via [`Event::OpenChannelRequest`] using /// [`ChannelManager::accept_inbound_channel_from_trusted_peer`]. /// /// Default value: `6` /// /// [`ChannelManager::accept_inbound_channel_from_trusted_peer`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel_from_trusted_peer /// [`Event::OpenChannelRequest`]: crate::events::Event::OpenChannelRequest pub minimum_depth: u32, /// Set to the number of blocks we require our counterparty to wait to claim their money (ie /// the number of blocks we have to punish our counterparty if they broadcast a revoked /// transaction). /// /// This is one of the main parameters of our security model. We (or one of our watchtowers) MUST /// be online to check for revoked transactions on-chain at least once every our_to_self_delay /// blocks (minus some margin to allow us enough time to broadcast and confirm a transaction, /// possibly with time in between to RBF the spending transaction). /// /// Meanwhile, asking for a too high delay, we bother peer to freeze funds for nothing in /// case of an honest unilateral channel close, which implicitly decrease the economic value of /// our channel. /// /// Default value: [`BREAKDOWN_TIMEOUT`] (We enforce it as a minimum at channel opening so you /// can tweak config to ask for more security, not less.) pub our_to_self_delay: u16, /// Set to the smallest value HTLC we will accept to process. /// /// This value is sent to our counterparty on channel-open and we close the channel any time /// our counterparty misbehaves by sending us an HTLC with a value smaller than this. /// /// Default value: `1` (If the value is less than `1`, it is ignored and set to `1`, as is /// required by the protocol. pub our_htlc_minimum_msat: u64, /// Sets the maximum percentage of the total channel value that can be allocated to inbound /// HTLCs in announced channels. /// /// This can be set to a value between 1-100, where the value corresponds to the percent of the /// channel value in whole percentages. /// /// Note that: /// * This caps the total value for inbound HTLCs in-flight only, and there's currently /// no way to configure the cap for the total value of outbound HTLCs in-flight. /// /// * The requirements for your node being online to ensure the safety of HTLC-encumbered funds /// are different from the non-HTLC-encumbered funds. This makes this an important knob to /// restrict exposure to loss due to being offline for too long. /// See [`ChannelHandshakeConfig::our_to_self_delay`] and [`ChannelConfig::cltv_expiry_delta`] /// for more information. /// /// Default value: `25` /// /// Minimum value: `1` (Any values less will be treated as `1` instead.) /// /// Maximum value: `100` (Any values larger will be treated as `100` instead.) pub announced_channel_max_inbound_htlc_value_in_flight_percentage: u8, /// Sets the maximum percentage of the total channel value that can be allocated to inbound /// HTLCs in unannounced channels. /// /// This can be set to a value between 1-100, where the value corresponds to the percent of the /// channel value in whole percentages. /// /// Note that: /// * This caps the total value for inbound HTLCs in-flight only, and there's currently /// no way to configure the cap for the total value of outbound HTLCs in-flight. /// /// * The requirements for your node being online to ensure the safety of HTLC-encumbered funds /// are different from the non-HTLC-encumbered funds. This makes this an important knob to /// restrict exposure to loss due to being offline for too long. /// See [`ChannelHandshakeConfig::our_to_self_delay`] and [`ChannelConfig::cltv_expiry_delta`] /// for more information. /// /// Default value: `100` /// /// Minimum value: `1` (Any values less will be treated as `1` instead.) /// /// Maximum value: `100` (Any values larger will be treated as `100` instead.) pub unannounced_channel_max_inbound_htlc_value_in_flight_percentage: u8, /// Set to announce the channel publicly and notify all nodes that they can route via this /// channel. /// /// This should only be set to true for nodes which expect to be online reliably. /// /// As the node which funds a channel picks this value this will only apply for new outbound /// channels unless [`ChannelHandshakeLimits::force_announced_channel_preference`] is set. /// /// Default value: `false` pub announce_for_forwarding: bool, /// When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty /// supports it, they will then enforce the mutual-close output to us matches what we provided /// at intialization, preventing us from closing to an alternate pubkey. /// /// This is set to true by default to provide a slight increase in security, though ultimately /// any attacker who is able to take control of a channel can just as easily send the funds via /// lightning payments, so we never require that our counterparties support this option. /// /// The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`]. /// /// Default value: `true` /// /// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::sign::SignerProvider::get_shutdown_scriptpubkey pub commit_upfront_shutdown_pubkey: bool, /// The Proportion of the channel value to configure as counterparty's channel reserve, /// i.e., `their_channel_reserve_satoshis` for both outbound and inbound channels. /// /// `their_channel_reserve_satoshis` is the minimum balance that the other node has to maintain /// on their side, at all times. /// This ensures that if our counterparty broadcasts a revoked state, we can punish them by /// claiming at least this value on chain. /// /// Channel reserve values greater than 30% could be considered highly unreasonable, since that /// amount can never be used for payments. /// Also, if our selected channel reserve for counterparty and counterparty's selected /// channel reserve for us sum up to equal or greater than channel value, channel negotiations /// will fail. /// /// Note: Versions of LDK earlier than v0.0.104 will fail to read channels with any channel reserve /// other than the default value. /// /// Default value: `10_000` millionths (i.e., 1% of channel value) /// /// Minimum value: If the calculated proportional value is less than `1000` sats, it will be /// treated as `1000` sats instead, which is a safe implementation-specific lower /// bound. /// /// Maximum value: `1_000_000` (i.e., 100% of channel value. Any values larger than one million /// will be treated as one million instead, although channel negotiations will /// fail in that case.) pub their_channel_reserve_proportional_millionths: u32, /// If set, we attempt to negotiate the `anchors_zero_fee_htlc_tx` option for all future /// channels. This feature requires having a reserve of onchain funds readily available to bump /// transactions in the event of a channel force close to avoid the possibility of losing funds. /// /// Upon receiving an [`Event::OpenChannelRequest`] for a channel of this type, you must /// check whether your reserve of onchain funds is enough to cover the fees for all existing /// and new channels featuring anchor outputs in the event of a force close. /// /// If this option is set, channels may be created that will not be readable by LDK versions /// prior to 0.0.116, causing [`ChannelManager`]'s read method to return a /// [`DecodeError::InvalidValue`]. /// /// Note that setting this to true does *not* prevent us from opening channels with /// counterparties that do not support the `anchors_zero_fee_htlc_tx` option; we will simply /// fall back to a `static_remote_key` channel. /// /// Default value: `true` /// /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel /// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue /// [`Event::OpenChannelRequest`]: crate::events::Event::OpenChannelRequest pub negotiate_anchors_zero_fee_htlc_tx: bool, /// If set, we attempt to negotiate the `zero_fee_commitments` option for all future channels. /// /// These channels operate very similarly to the `anchors_zero_fee_htlc` channels but rely on /// [TRUC] to assign zero fee to the commitment transactions themselves, avoiding many protocol /// edge-cases involving fee updates and greatly simplifying the concept of your "balance" in /// lightning. /// /// Like `anchors_zero_fee_htlc` channels, this feature requires having a reserve of onchain /// funds readily available to bump transactions in the event of a channel force close to avoid /// the possibility of losing funds. /// /// Upon receiving an [`Event::OpenChannelRequest`] for a channel of this type, you must /// check whether your reserve of onchain funds is enough to cover the fees for all existing /// and new channels featuring anchor outputs in the event of a force close. /// /// If this option is set, channels may be created that will not be readable by LDK versions /// prior to 0.2, causing [`ChannelManager`]'s read method to return a /// [`DecodeError::InvalidValue`]. /// /// Note that setting this to true does *not* prevent us from opening channels with /// counterparties that do not support the `zero_fee_commitments` option; we will simply fall /// back to a `anchors_zero_fee_htlc` (if [`Self::negotiate_anchors_zero_fee_htlc_tx`] /// is set) or `static_remote_key` channel. /// /// For a force-close transaction to reach miners and get confirmed, /// zero-fee commitment channels require a path from your Bitcoin node to miners that /// relays TRUC transactions (BIP 431), P2A outputs, and Ephemeral Dust. Currently, only /// nodes running Bitcoin Core v29 and above relay transactions with these features. /// /// Default value: `false` (This value is likely to change to `true` in the future.) /// /// [TRUC]: (https://bitcoinops.org/en/topics/version-3-transaction-relay/) /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel /// [`DecodeError::InvalidValue`]: crate::ln::msgs::DecodeError::InvalidValue /// [`Event::OpenChannelRequest`]: crate::events::Event::OpenChannelRequest pub negotiate_anchor_zero_fee_commitments: bool, /// The maximum number of HTLCs in-flight from our counterparty towards us at the same time. /// /// Increasing the value can help improve liquidity and stability in /// routing at the cost of higher long term disk / DB usage. /// /// Note: Versions of LDK earlier than v0.0.115 will fail to read channels with a configuration /// other than the default value. /// /// Default value: `50` /// /// Maximum value: depends on channel type, see docs on [`max_htlcs`] (any values over the /// maximum will be silently reduced to the maximum). /// /// [`max_htlcs`]: crate::ln::chan_utils::max_htlcs pub our_max_accepted_htlcs: u16, } impl Default for ChannelHandshakeConfig { fn default() -> ChannelHandshakeConfig { ChannelHandshakeConfig { minimum_depth: 6, our_to_self_delay: BREAKDOWN_TIMEOUT, our_htlc_minimum_msat: 1, announced_channel_max_inbound_htlc_value_in_flight_percentage: 25, unannounced_channel_max_inbound_htlc_value_in_flight_percentage: 100, announce_for_forwarding: false, commit_upfront_shutdown_pubkey: true, their_channel_reserve_proportional_millionths: 10_000, negotiate_anchors_zero_fee_htlc_tx: true, negotiate_anchor_zero_fee_commitments: false, our_max_accepted_htlcs: 50, } } } // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We // don't really want to ever expose this to users (if we did we'd want to use TLVs). #[cfg(fuzzing)] impl Readable for ChannelHandshakeConfig { fn read(reader: &mut R) -> Result { let minimum_depth = Readable::read(reader)?; let our_to_self_delay = Readable::read(reader)?; let our_htlc_minimum_msat = Readable::read(reader)?; // Apply the same byte to both the announced and the unannounced maximums so as to // not invalidate the existing fuzz corpus let max_inbound_htlc_value_in_flight_percentage = Readable::read(reader)?; // The fuzz corpus reserves a byte for SCID privacy negotiation. let _scid_privacy: bool = Readable::read(reader)?; Ok(Self { minimum_depth, our_to_self_delay, our_htlc_minimum_msat, announced_channel_max_inbound_htlc_value_in_flight_percentage: max_inbound_htlc_value_in_flight_percentage, unannounced_channel_max_inbound_htlc_value_in_flight_percentage: max_inbound_htlc_value_in_flight_percentage, announce_for_forwarding: Readable::read(reader)?, commit_upfront_shutdown_pubkey: Readable::read(reader)?, their_channel_reserve_proportional_millionths: Readable::read(reader)?, negotiate_anchors_zero_fee_htlc_tx: Readable::read(reader)?, negotiate_anchor_zero_fee_commitments: Readable::read(reader)?, our_max_accepted_htlcs: Readable::read(reader)?, }) } } /// Optional channel limits which are applied during channel creation. /// /// These limits are only applied to our counterparty's limits, not our own. /// /// Use `0` or `::MAX` as appropriate to skip checking. /// /// Provides sane defaults for most configurations. /// /// Most additional limits are disabled except those with which specify a default in individual /// field documentation. Note that this may result in barely-usable channels, but since they /// are applied mostly only to incoming channels that's not much of a problem. #[derive(Copy, Clone, Debug)] pub struct ChannelHandshakeLimits { /// Minimum allowed satoshis when a channel is funded. This is supplied by the sender and so /// only applies to inbound channels. It is also enforced for inbound channels on splices in /// which the counterparty's contribution is negative. /// /// Default value: `1000` /// /// Minimum value: `1000` (Any values less will be treated as `1000` instead.) pub min_funding_satoshis: u64, /// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows /// you to limit the maximum minimum-size they can require. /// /// Default value: `u64::MAX` pub max_htlc_minimum_msat: u64, /// The remote node sets a limit on the maximum value of pending HTLCs to them at any given /// time to limit their funds exposure to HTLCs. This allows you to set a minimum such value. /// /// Default value: `0` pub min_max_htlc_value_in_flight_msat: u64, /// The remote node will require we keep a certain amount in direct payment to ourselves at all /// time, ensuring that we are able to be punished if we broadcast an old state. This allows to /// you limit the amount which we will have to keep to ourselves (and cannot use for HTLCs). /// /// Default value: `u64::MAX`. pub max_channel_reserve_satoshis: u64, /// The remote node sets a limit on the maximum number of pending HTLCs to them at any given /// time. This allows you to set a minimum such value. /// /// Default value: `0` pub min_max_accepted_htlcs: u16, /// Before a channel is usable the funding transaction will need to be confirmed by at least a /// certain number of blocks, specified by the node which is not the funder (as the funder can /// assume they aren't going to double-spend themselves). /// This config allows you to set a limit on the maximum amount of time to wait. /// /// Default value: `144`, or roughly one day and only applies to outbound channels pub max_minimum_depth: u32, /// Whether we implicitly trust funding transactions generated by us for our own outbound /// channels to not be double-spent. /// /// If this is set, we assume that our own funding transactions are *never* double-spent, and /// thus we can trust them without any confirmations. This is generally a reasonable /// assumption, given we're the only ones who could ever double-spend it (assuming we have sole /// control of the signing keys). /// /// You may wish to un-set this if you allow the user to (or do in an automated fashion) /// double-spend the funding transaction to RBF with an alternative channel open. /// /// This only applies if our counterparty set their confirmations-required value to `0`, and we /// always trust our own funding transaction at `1` confirmation irrespective of this value. /// Thus, this effectively acts as a `min_minimum_depth`, with the only possible values being /// `true` (`0`) and `false` (`1`). /// /// Default value: `true` pub trust_own_funding_0conf: bool, /// Set to force an incoming channel to match our announced channel preference in /// [`ChannelHandshakeConfig::announce_for_forwarding`]. /// /// For a node which is not online reliably, this should be set to true and /// [`ChannelHandshakeConfig::announce_for_forwarding`] set to false, ensuring that no announced (aka public) /// channels will ever be opened. /// /// Default value: `true` pub force_announced_channel_preference: bool, /// Set to the amount of time we're willing to wait to claim money back to us. /// /// Not checking this value would be a security issue, as our peer would be able to set it to /// max relative lock-time (a year) and we would "lose" money as it would be locked for a long time. /// /// Default value: `2016`, which we also enforce as a maximum value so you can tweak config to /// reduce the loss of having useless locked funds (if your peer accepts) pub their_to_self_delay: u16, } impl Default for ChannelHandshakeLimits { fn default() -> Self { ChannelHandshakeLimits { min_funding_satoshis: 1000, max_htlc_minimum_msat: u64::MAX, min_max_htlc_value_in_flight_msat: 0, max_channel_reserve_satoshis: u64::MAX, min_max_accepted_htlcs: 0, trust_own_funding_0conf: true, max_minimum_depth: 144, force_announced_channel_preference: true, their_to_self_delay: MAX_LOCAL_BREAKDOWN_TIMEOUT, } } } // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We // don't really want to ever expose this to users (if we did we'd want to use TLVs). #[cfg(fuzzing)] impl Readable for ChannelHandshakeLimits { fn read(reader: &mut R) -> Result { Ok(Self { min_funding_satoshis: Readable::read(reader)?, max_htlc_minimum_msat: Readable::read(reader)?, min_max_htlc_value_in_flight_msat: Readable::read(reader)?, max_channel_reserve_satoshis: Readable::read(reader)?, min_max_accepted_htlcs: Readable::read(reader)?, trust_own_funding_0conf: Readable::read(reader)?, max_minimum_depth: Readable::read(reader)?, force_announced_channel_preference: Readable::read(reader)?, their_to_self_delay: Readable::read(reader)?, }) } } /// Options for how to set the max dust exposure allowed on a channel. See /// [`ChannelConfig::max_dust_htlc_exposure`] for details. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum MaxDustHTLCExposure { /// This sets a fixed limit on the total dust exposure in millisatoshis. Setting this too low /// may prevent the sending or receipt of low-value HTLCs on high-traffic nodes, however this /// limit is very important to prevent stealing of large amounts of dust HTLCs by miners /// through [fee griefing /// attacks](https://lists.linuxfoundation.org/pipermail/lightning-dev/2020-May/002714.html). /// /// Note that if the feerate increases significantly, without a manual increase /// to this maximum the channel may be unable to send/receive HTLCs between the maximum dust /// exposure and the new minimum value for HTLCs to be economically viable to claim. FixedLimitMsat(u64), /// This sets a multiplier on the [`ConfirmationTarget::MaximumFeeEstimate`] feerate (in /// sats/KW) to determine the maximum allowed dust exposure. If this variant is used then the /// maximum dust exposure in millisatoshis is calculated as: /// `feerate_per_kw * value`. For example, with our default value /// `FeeRateMultiplier(10_000)`: /// /// - For the minimum fee rate of 1 sat/vByte (250 sat/KW, although the minimum /// defaults to 253 sats/KW for rounding, see [`FeeEstimator`]), the max dust exposure would /// be 253 * 10_000 = 2,530,000 msats. /// - For a fee rate of 30 sat/vByte (7500 sat/KW), the max dust exposure would be /// 7500 * 50_000 = 75,000,000 msats (0.00075 BTC). /// /// Note, if you're using a third-party fee estimator, this may leave you more exposed to a /// fee griefing attack, where your fee estimator may purposely overestimate the fee rate, /// causing you to accept more dust HTLCs than you would otherwise. /// /// This variant is primarily meant to serve pre-anchor channels, as HTLC fees being included /// on HTLC outputs means your channel may be subject to more dust exposure in the event of /// increases in fee rate. /// /// Note that because zero-commitment-fee anchor channels do not allow for feerate updates (and /// thus never experience dust exposure changes due to feerate shifts, resulting in no /// force-closes due to dust exposure limits), such channels will calculate their maximum /// dust exposure using a constant feerate of 250 sat/KW when using this variant. /// See [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`] to enable such channels. /// /// # Backwards Compatibility /// This variant only became available in LDK 0.0.116, so if you downgrade to a prior version /// by default this will be set to a [`Self::FixedLimitMsat`] of 5,000,000 msat. /// /// [`FeeEstimator`]: crate::chain::chaininterface::FeeEstimator /// [`ConfirmationTarget::MaximumFeeEstimate`]: crate::chain::chaininterface::ConfirmationTarget::MaximumFeeEstimate /// [`ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments`]: ChannelHandshakeConfig::negotiate_anchor_zero_fee_commitments FeeRateMultiplier(u64), } impl_ser_tlv_based_enum_legacy!(MaxDustHTLCExposure, ; (1, FixedLimitMsat), (3, FeeRateMultiplier), ); /// Options which apply on a per-channel basis and may change at runtime or based on negotiation /// with our counterparty. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct ChannelConfig { /// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound /// over the channel. /// This may be allowed to change at runtime in a later update, however doing so must result in /// update messages sent to notify all nodes of our updated relay fee. /// /// Default value: `0` pub forwarding_fee_proportional_millionths: u32, /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in /// excess of [`forwarding_fee_proportional_millionths`]. /// This may be allowed to change at runtime in a later update, however doing so must result in /// update messages sent to notify all nodes of our updated relay fee. /// /// The default value of a single satoshi roughly matches the market rate on many routing nodes /// as of July 2021. Adjusting it upwards or downwards may change whether nodes route through /// this node. /// /// Default value: `1000` /// /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths pub forwarding_fee_base_msat: u32, /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over /// the channel this config applies to. /// /// This is analogous to [`ChannelHandshakeConfig::our_to_self_delay`] but applies to in-flight /// HTLC balance when a channel appears on-chain whereas /// [`ChannelHandshakeConfig::our_to_self_delay`] applies to the remaining /// (non-HTLC-encumbered) balance. /// /// Thus, for HTLC-encumbered balances to be enforced on-chain when a channel is force-closed, /// we (or one of our watchtowers) MUST be online to check for broadcast of the current /// commitment transaction at least once per this many blocks (minus some margin to allow us /// enough time to broadcast and confirm a transaction, possibly with time in between to RBF /// the spending transaction). /// /// Default value: `72` (12 hours at an average of 6 blocks/hour) /// /// Minimum value: [`MIN_CLTV_EXPIRY_DELTA`] (Any values less than this will be treated as /// [`MIN_CLTV_EXPIRY_DELTA`] instead.) /// /// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA pub cltv_expiry_delta: u16, /// Limit our total exposure to potential loss to on-chain fees on close, including in-flight /// HTLCs which are burned to fees as they are too small to claim on-chain and fees on /// commitment transaction(s) broadcasted by our counterparty in excess of our own fee estimate. /// /// # HTLC-based Dust Exposure /// /// When an HTLC present in one of our channels is below a "dust" threshold, the HTLC will /// not be claimable on-chain, instead being turned into additional miner fees if either /// party force-closes the channel. Because the threshold is per-HTLC, our total exposure /// to such payments may be substantial if there are many dust HTLCs present when the /// channel is force-closed. /// /// The dust threshold for each HTLC is based on the `dust_limit_satoshis` for each party in a /// channel negotiated throughout the channel open process, along with the fees required to have /// a broadcastable HTLC spending transaction. When a channel supports anchor outputs /// (specifically the zero fee HTLC transaction variant), this threshold no longer takes into /// account the HTLC transaction fee as it is zero. Because of this, you may want to set this /// value to a fixed limit for channels using anchor outputs, while the fee rate multiplier /// variant is primarily intended for use with pre-anchor channels. /// /// The selected limit is applied for sent, forwarded, and received HTLCs and limits the total /// exposure across all three types per-channel. /// /// # Transaction Fee Dust Exposure /// /// Further, counterparties broadcasting a commitment transaction in a force-close may result /// in other balance being burned to fees, and thus all fees on commitment and HTLC /// transactions in excess of our local fee estimates are included in the dust calculation. /// /// Because of this, another way to look at this limit is to divide it by 43,000 (or 218,750 /// for non-anchor channels) and see it as the maximum feerate disagreement (in sats/vB) per /// non-dust HTLC we're allowed to have with our peers before risking a force-closure for /// inbound channels. // This works because, for anchor channels the on-chain cost is 172 weight (172+703 for // non-anchors with an HTLC-Success transaction), i.e. // dust_exposure_limit_msat / 1000 = 172 * feerate_in_sat_per_vb / 4 * HTLC count // dust_exposure_limit_msat = 43,000 * feerate_in_sat_per_vb * HTLC count // dust_exposure_limit_msat / HTLC count / 43,000 = feerate_in_sat_per_vb /// /// Thus, for the default value of 10_000 * a current feerate estimate of 10 sat/vB (or 2,500 /// sat/KW), we risk force-closure if we disagree with our peer by: /// * `10_000 * 2_500 / 43_000 / (483*2)` = 0.6 sat/vB for anchor channels with 483 HTLCs in /// both directions (the maximum), /// * `10_000 * 2_500 / 43_000 / (50*2)` = 5.8 sat/vB for anchor channels with 50 HTLCs in both /// directions (the LDK default max from [`ChannelHandshakeConfig::our_max_accepted_htlcs`]) /// * `10_000 * 2_500 / 218_750 / (483*2)` = 0.1 sat/vB for non-anchor channels with 483 HTLCs /// in both directions (the maximum), /// * `10_000 * 2_500 / 218_750 / (50*2)` = 1.1 sat/vB for non-anchor channels with 50 HTLCs /// in both (the LDK default maximum from [`ChannelHandshakeConfig::our_max_accepted_htlcs`]) /// /// Note that when using [`MaxDustHTLCExposure::FeeRateMultiplier`] this maximum disagreement /// will scale linearly with increases (or decreases) in the our feerate estimates. Further, /// for anchor channels we expect our counterparty to use a relatively low feerate estimate /// while we use [`ConfirmationTarget::MaximumFeeEstimate`] (which should be relatively high) /// and feerate disagreement force-closures should only occur when theirs is higher than ours. /// /// Default value: [`MaxDustHTLCExposure::FeeRateMultiplier`] with a multiplier of `10_000` /// /// [`ConfirmationTarget::MaximumFeeEstimate`]: crate::chain::chaininterface::ConfirmationTarget::MaximumFeeEstimate pub max_dust_htlc_exposure: MaxDustHTLCExposure, /// The additional fee we're willing to pay to avoid waiting for the counterparty's /// `to_self_delay` to reclaim funds. /// /// When we close a channel cooperatively with our counterparty, we negotiate a fee for the /// closing transaction which both sides find acceptable, ultimately paid by the channel /// funder/initiator. /// /// When we are the funder, because we have to pay the channel closing fee, we bound the /// acceptable fee by our [`ChannelCloseMinimum`] and [`NonAnchorChannelFee`] fees, with the upper bound increased by /// this value. Because the on-chain fee we'd pay to force-close the channel is kept near our /// [`NonAnchorChannelFee`] feerate during normal operation, this value represents the additional fee we're /// willing to pay in order to avoid waiting for our counterparty's to_self_delay to reclaim our /// funds. /// /// When we are not the funder, we require the closing transaction fee pay at least our /// [`ChannelCloseMinimum`] fee estimate, but allow our counterparty to pay as much fee as they like. /// Thus, this value is ignored when we are not the funder. /// /// Default value: `1000` /// /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum pub force_close_avoidance_max_fee_satoshis: u64, /// If set, allows this channel's counterparty to skim an additional fee off this node's inbound /// HTLCs. Useful for liquidity providers to offload on-chain channel costs to end users. /// /// Usage: /// - The payee will set this option and set its invoice route hints to use [intercept scids] /// generated by this channel's counterparty. /// - The counterparty will get an [`HTLCIntercepted`] event upon payment forward, and call /// [`forward_intercepted_htlc`] with less than the amount provided in /// [`HTLCIntercepted::expected_outbound_amount_msat`]. The difference between the expected and /// actual forward amounts is their fee. See /// /// for how this feature may be used in the LSP use case. /// /// # Note /// It's important for payee wallet software to verify that [`PaymentClaimable::amount_msat`] is /// as-expected if this feature is activated, otherwise they may lose money! /// [`PaymentClaimable::counterparty_skimmed_fee_msat`] provides the fee taken by the /// counterparty. /// /// # Note /// Switching this config flag on may break compatibility with versions of LDK prior to 0.0.116. /// Unsetting this flag between restarts may lead to payment receive failures. /// /// Default value: `false` /// /// [intercept scids]: crate::ln::channelmanager::ChannelManager::get_intercept_scid /// [`forward_intercepted_htlc`]: crate::ln::channelmanager::ChannelManager::forward_intercepted_htlc /// [`HTLCIntercepted`]: crate::events::Event::HTLCIntercepted /// [`HTLCIntercepted::expected_outbound_amount_msat`]: crate::events::Event::HTLCIntercepted::expected_outbound_amount_msat /// [`PaymentClaimable::amount_msat`]: crate::events::Event::PaymentClaimable::amount_msat /// [`PaymentClaimable::counterparty_skimmed_fee_msat`]: crate::events::Event::PaymentClaimable::counterparty_skimmed_fee_msat // TODO: link to bLIP when it's merged pub accept_underpaying_htlcs: bool, /// The minimum number of confirmations we will wait for before sending `splice_locked` for a /// splice which we do not contribute any inputs or outputs to. /// /// Note that setting this to zero means the splice can be considered locked in before its /// funding transaction confirms, so RBFing splices will not be possible. /// /// Default value: `6` pub inbound_splice_min_depth: u32, /// The minimum number of confirmations we will wait for before sending `splice_locked` for a /// splice which we contribute inputs or outputs to. /// /// Note that setting this to zero means the splice can be considered locked in before its /// funding transaction confirms, so RBFing splices will not be possible. /// /// Default value: `6` pub outbound_splice_min_depth: u32, } impl ChannelConfig { /// Applies the given [`ChannelConfigUpdate`] as a partial update to the [`ChannelConfig`]. pub fn apply(&mut self, update: &ChannelConfigUpdate) { if let Some(forwarding_fee_proportional_millionths) = update.forwarding_fee_proportional_millionths { self.forwarding_fee_proportional_millionths = forwarding_fee_proportional_millionths; } if let Some(forwarding_fee_base_msat) = update.forwarding_fee_base_msat { self.forwarding_fee_base_msat = forwarding_fee_base_msat; } if let Some(cltv_expiry_delta) = update.cltv_expiry_delta { self.cltv_expiry_delta = cltv_expiry_delta; } if let Some(max_dust_htlc_exposure_msat) = update.max_dust_htlc_exposure_msat { self.max_dust_htlc_exposure = max_dust_htlc_exposure_msat; } if let Some(force_close_avoidance_max_fee_satoshis) = update.force_close_avoidance_max_fee_satoshis { self.force_close_avoidance_max_fee_satoshis = force_close_avoidance_max_fee_satoshis; } if let Some(accept_underpaying_htlcs) = update.accept_underpaying_htlcs { self.accept_underpaying_htlcs = accept_underpaying_htlcs; } if let Some(inbound_splice_min_depth) = update.inbound_splice_min_depth { self.inbound_splice_min_depth = inbound_splice_min_depth; } if let Some(outbound_splice_min_depth) = update.outbound_splice_min_depth { self.outbound_splice_min_depth = outbound_splice_min_depth; } } } impl Default for ChannelConfig { /// Provides sane defaults for most configurations (but with zero relay fees!). fn default() -> Self { ChannelConfig { forwarding_fee_proportional_millionths: 0, forwarding_fee_base_msat: 1000, cltv_expiry_delta: 6 * 12, // 6 blocks/hour * 12 hours max_dust_htlc_exposure: MaxDustHTLCExposure::FeeRateMultiplier(10000), force_close_avoidance_max_fee_satoshis: 1000, accept_underpaying_htlcs: false, inbound_splice_min_depth: 6, outbound_splice_min_depth: 6, } } } impl crate::util::ser::Writeable for ChannelConfig { fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { let max_dust_htlc_exposure_msat_fixed_limit = match self.max_dust_htlc_exposure { MaxDustHTLCExposure::FixedLimitMsat(limit) => limit, MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000, }; write_tlv_fields!(writer, { (0, self.forwarding_fee_proportional_millionths, required), (1, self.accept_underpaying_htlcs, (default_value, false)), (2, self.forwarding_fee_base_msat, required), (3, self.max_dust_htlc_exposure, required), (4, self.cltv_expiry_delta, required), (6, max_dust_htlc_exposure_msat_fixed_limit, required), (8, _forwarding_fee_base_msat, retired), // Used before LegacyChannelConfig's introduction // Even type 10 ensures readers of the old format, which used type 8, fail on this one. (10, self.force_close_avoidance_max_fee_satoshis, required), (13, self.inbound_splice_min_depth, required), (15, self.outbound_splice_min_depth, required), }); Ok(()) } } impl crate::util::ser::Readable for ChannelConfig { fn read(reader: &mut R) -> Result { let mut forwarding_fee_proportional_millionths = 0; let mut accept_underpaying_htlcs = false; let mut forwarding_fee_base_msat = 1000; let mut cltv_expiry_delta = 6 * 12; let mut max_dust_htlc_exposure_msat = None; let mut max_dust_htlc_exposure_enum = None; let mut force_close_avoidance_max_fee_satoshis = 1000; let mut inbound_splice_min_depth = 6; let mut outbound_splice_min_depth = 6; read_tlv_fields!(reader, { (0, forwarding_fee_proportional_millionths, required), (1, accept_underpaying_htlcs, (default_value, false)), (2, forwarding_fee_base_msat, required), (3, max_dust_htlc_exposure_enum, option), (4, cltv_expiry_delta, required), // Has always been written, but became optionally read in 0.0.116 (6, max_dust_htlc_exposure_msat, option), (8, _forwarding_fee_base_msat, retired), // Used before LegacyChannelConfig's introduction (10, force_close_avoidance_max_fee_satoshis, required), (13, inbound_splice_min_depth, (default_value, 6u32)), (15, outbound_splice_min_depth, (default_value, 6u32)), }); let max_dust_htlc_fixed_limit = max_dust_htlc_exposure_msat.unwrap_or(5_000_000); let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum .unwrap_or(MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_fixed_limit)); Ok(Self { forwarding_fee_proportional_millionths, accept_underpaying_htlcs, forwarding_fee_base_msat, cltv_expiry_delta, max_dust_htlc_exposure: max_dust_htlc_exposure_msat, force_close_avoidance_max_fee_satoshis, inbound_splice_min_depth, outbound_splice_min_depth, }) } } /// A parallel struct to [`ChannelConfig`] to define partial updates. #[derive(Default)] pub struct ChannelConfigUpdate { /// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound over the channel. See /// [`ChannelConfig::forwarding_fee_proportional_millionths`]. pub forwarding_fee_proportional_millionths: Option, /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel. See /// [`ChannelConfig::forwarding_fee_base_msat`]. pub forwarding_fee_base_msat: Option, /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over the channel this /// config applies to. See [`ChannelConfig::cltv_expiry_delta`]. pub cltv_expiry_delta: Option, /// The total exposure we are willing to allow to dust HTLCs. See [`ChannelConfig::max_dust_htlc_exposure`]. pub max_dust_htlc_exposure_msat: Option, /// The additional fee we're willing to pay to avoid waiting for the counterparty's `to_self_delay` to reclaim /// funds. See [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]. pub force_close_avoidance_max_fee_satoshis: Option, /// If set, allows this channel's counterparty to skim an additional fee off this node's inbound HTLCs. See /// [`ChannelConfig::accept_underpaying_htlcs`]. pub accept_underpaying_htlcs: Option, /// The minimum number of confirmations we will wait for before sending `splice_locked` for a /// splice which we do not contribute any inputs or outputs to. See /// [`ChannelConfig::inbound_splice_min_depth`]. pub inbound_splice_min_depth: Option, /// The minimum number of confirmations we will wait for before sending `splice_locked` for a /// splice which we contribute inputs or outputs to. See /// [`ChannelConfig::outbound_splice_min_depth`]. pub outbound_splice_min_depth: Option, } impl From for ChannelConfigUpdate { fn from(config: ChannelConfig) -> ChannelConfigUpdate { ChannelConfigUpdate { forwarding_fee_proportional_millionths: Some( config.forwarding_fee_proportional_millionths, ), forwarding_fee_base_msat: Some(config.forwarding_fee_base_msat), cltv_expiry_delta: Some(config.cltv_expiry_delta), max_dust_htlc_exposure_msat: Some(config.max_dust_htlc_exposure), force_close_avoidance_max_fee_satoshis: Some( config.force_close_avoidance_max_fee_satoshis, ), accept_underpaying_htlcs: Some(config.accept_underpaying_htlcs), inbound_splice_min_depth: Some(config.inbound_splice_min_depth), outbound_splice_min_depth: Some(config.outbound_splice_min_depth), } } } /// Legacy version of [`ChannelConfig`] that stored the static /// [`ChannelHandshakeConfig::announce_for_forwarding`] and /// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] fields. #[derive(Copy, Clone, Debug)] pub(crate) struct LegacyChannelConfig { pub(crate) options: ChannelConfig, /// Deprecated but may still be read from. See [`ChannelHandshakeConfig::announce_for_forwarding`] to /// set this when opening/accepting a channel. pub(crate) announce_for_forwarding: bool, /// Deprecated but may still be read from. See /// [`ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`] to set this when /// opening/accepting a channel. pub(crate) commit_upfront_shutdown_pubkey: bool, } impl Default for LegacyChannelConfig { fn default() -> Self { Self { options: ChannelConfig::default(), announce_for_forwarding: false, commit_upfront_shutdown_pubkey: true, } } } impl crate::util::ser::Writeable for LegacyChannelConfig { fn write(&self, writer: &mut W) -> Result<(), crate::io::Error> { let max_dust_htlc_exposure_msat_fixed_limit = match self.options.max_dust_htlc_exposure { MaxDustHTLCExposure::FixedLimitMsat(limit) => limit, MaxDustHTLCExposure::FeeRateMultiplier(_) => 5_000_000, }; write_tlv_fields!(writer, { (0, self.options.forwarding_fee_proportional_millionths, required), (1, max_dust_htlc_exposure_msat_fixed_limit, required), (2, self.options.cltv_expiry_delta, required), (3, self.options.force_close_avoidance_max_fee_satoshis, (default_value, 1000)), (4, self.announce_for_forwarding, required), (5, self.options.max_dust_htlc_exposure, required), (6, self.commit_upfront_shutdown_pubkey, required), (8, self.options.forwarding_fee_base_msat, required), (13, self.options.inbound_splice_min_depth, (default_value, 6u32)), (15, self.options.outbound_splice_min_depth, (default_value, 6u32)), }); Ok(()) } } impl crate::util::ser::Readable for LegacyChannelConfig { fn read(reader: &mut R) -> Result { let mut forwarding_fee_proportional_millionths = 0; let mut max_dust_htlc_exposure_msat_fixed_limit = None; let mut cltv_expiry_delta = 0; let mut force_close_avoidance_max_fee_satoshis = 1000; let mut announce_for_forwarding = false; let mut commit_upfront_shutdown_pubkey = false; let mut forwarding_fee_base_msat = 0; let mut max_dust_htlc_exposure_enum = None; let mut inbound_splice_min_depth = 6; let mut outbound_splice_min_depth = 6; read_tlv_fields!(reader, { (0, forwarding_fee_proportional_millionths, required), // Has always been written, but became optionally read in 0.0.116 (1, max_dust_htlc_exposure_msat_fixed_limit, option), (2, cltv_expiry_delta, required), (3, force_close_avoidance_max_fee_satoshis, (default_value, 1000u64)), (4, announce_for_forwarding, required), (5, max_dust_htlc_exposure_enum, option), (6, commit_upfront_shutdown_pubkey, required), (8, forwarding_fee_base_msat, required), (13, inbound_splice_min_depth, (default_value, 6u32)), (15, outbound_splice_min_depth, (default_value, 6u32)), }); let max_dust_htlc_exposure_msat_fixed_limit = max_dust_htlc_exposure_msat_fixed_limit.unwrap_or(5_000_000); let max_dust_htlc_exposure_msat = max_dust_htlc_exposure_enum.unwrap_or( MaxDustHTLCExposure::FixedLimitMsat(max_dust_htlc_exposure_msat_fixed_limit), ); Ok(Self { options: ChannelConfig { forwarding_fee_proportional_millionths, max_dust_htlc_exposure: max_dust_htlc_exposure_msat, cltv_expiry_delta, force_close_avoidance_max_fee_satoshis, forwarding_fee_base_msat, accept_underpaying_htlcs: false, inbound_splice_min_depth, outbound_splice_min_depth, }, announce_for_forwarding, commit_upfront_shutdown_pubkey, }) } } /// Flags which can be set on [`UserConfig::htlc_interception_flags`]. Each flag selects some set /// of HTLCs which are forwarded across this node to be intercepted instead, generating an /// [`Event::HTLCIntercepted`] instead of automatically forwarding the HTLC and allowing it to be /// forwarded or rejected manually. /// /// Note that which HTLCs are intercepted is determined based on the outbound channel named by the /// sender's onion, though the HTLC may be delivered over any usable channel to the same peer. /// Thus, if both public and private channels exist with a peer, HTLCs which name a public channel /// may be delivered over a private channel without being intercepted by the private-channel /// flags. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HTLCInterceptionFlags { /// If this flag is set, LDK will intercept HTLCs that are attempting to be forwarded over fake /// short channel ids generated via [`ChannelManager::get_intercept_scid`]. This allows you to /// only intercept HTLCs which are specifically marked for interception by the invoice being /// paid. /// /// Note that because LDK is not aware of which channel the HTLC will be forwarded over at the /// time of interception, only basic checks to ensure the fee the HTLC intends to pay is not /// negative and a minimum CLTV delta between the incoming and outgoing HTLC edge are performed /// before the [`Event::HTLCIntercepted`] is generated. You must validate the fee and CLTV /// delta meets your requirements before forwarding the HTLC. /// /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToInterceptSCIDs = 1 << 0, /// If this flag is set, any attempts to forward a payment to a private channel while the /// channel counterparty is offline will instead generate an [`Event::HTLCIntercepted`] which /// must be handled the same as any other intercepted HTLC. /// /// This is useful for LSPs that may need to wake the recipient node (e.g. via a mobile push /// notification). Note that in this case you must ensure that you set a quick timeout to fail /// the HTLC if the recipient node fails to come online (e.g. within 10 seconds). /// /// Before interception, the HTLC is validated against the forwarding config of the outbound /// channel to ensure it pays sufficient fee and meets the /// [`ChannelConfig::cltv_expiry_delta`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToOfflinePrivateChannels = 1 << 1, /// If this flag is set, any attempts to forward a payment to a private channel while the /// channel counterparty is online will instead generate an [`Event::HTLCIntercepted`] which /// must be handled the same as any other intercepted HTLC. /// /// This is the complement to [`Self::ToOfflinePrivateChannels`] and, together, they allow /// intercepting all HTLCs destined for private channels. This may be useful for LSPs that wish /// to take an additional fee paid by the recipient on all forwards to clients. /// /// Before interception, the HTLC is validated against the forwarding config of the outbound /// channel to ensure it pays sufficient fee and meets the /// [`ChannelConfig::cltv_expiry_delta`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToOnlinePrivateChannels = 1 << 2, /// If this flag is set, any attempts to forward a payment to a publicly announced channel will /// instead generate an [`Event::HTLCIntercepted`] which must be handled the same as any other /// intercepted HTLC. /// /// Before interception, the HTLC is validated against the forwarding config of the outbound /// channel to ensure it pays sufficient fee and meets the /// [`ChannelConfig::cltv_expiry_delta`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToPublicChannels = 1 << 3, /// If these flags are set, any attempts to forward a payment to a channel of ours or a fake /// short channel id generated via [`ChannelManager::get_intercept_scid`] will instead generate /// an [`Event::HTLCIntercepted`] which must be handled the same as any other intercepted HTLC. /// /// In the case of intercept SCIDs, only basic checks to ensure the fee the HTLC intends to pay /// is not negative and a minimum CLTV delta between the incoming and outgoing HTLC edge are /// performed before the [`Event::HTLCIntercepted`] is generated. You must validate the fee and /// CLTV delta meets your requirements before forwarding the HTLC. /// /// [`ChannelManager::get_intercept_scid`]: crate::ln::channelmanager::ChannelManager::get_intercept_scid /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToAllKnownSCIDs = Self::ToInterceptSCIDs as isize | Self::ToOfflinePrivateChannels as isize | Self::ToOnlinePrivateChannels as isize | Self::ToPublicChannels as isize, /// If this flag is set, any attempts to forward a payment from a private channel (to anywhere) /// will instead generate an [`Event::HTLCIntercepted`] which must be handled the same as any /// other intercepted HTLC. /// /// This is useful for an LSP that may wish to apply a higher fee policy on their channels when /// the HTLC comes from a private channel client. Note that HTLCs which do not pay the /// configured fee rate or do not meet the [`ChannelConfig::cltv_expiry_delta`] will fail. /// Thus, this cannot be used to allow forwarding for less than the public fees. /// /// Note that no HTLCs to unknown channels will be intercepted by this flag. For that, use /// [`Self::ToUnknownSCIDs`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted FromPrivateChannels = 1 << 4, /// If this flag is set, any attempts to forward a payment from a public channel to a private /// channel will instead generate an [`Event::HTLCIntercepted`] which must be handled the same /// as any other intercepted HTLC. /// /// This is useful for an LSP that may wish to take an additional fee on any HTLCs which are /// forwarded to a private channel client but wishes to avoid taking that fee when forwarding /// an HTLC from a private channel client to another private channel client. /// /// Note that HTLCs which do not pay the configured fee rate or do not meet the /// [`ChannelConfig::cltv_expiry_delta`] will fail and not be intercepted. /// /// Note that no HTLCs to unknown channels will be intercepted by this flag. For that, use /// [`Self::ToUnknownSCIDs`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted FromPublicToPrivateChannels = 1 << 5, /// If this flag is set, any attempts to forward a payment from a public channel to another /// public channel will instead generate an [`Event::HTLCIntercepted`] which must be handled /// the same as any other intercepted HTLC. /// /// This primarily exists for completeness, and generally interception of HTLCs between public /// channels is *strongly* discouraged. /// /// Note that HTLCs which do not pay the configured fee rate or do not meet the /// [`ChannelConfig::cltv_expiry_delta`] will fail and not be intercepted. /// /// Note that no HTLCs to unknown channels will be intercepted by this flag. For that, use /// [`Self::ToUnknownSCIDs`]. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted FromPublicToPublicChannels = 1 << 6, /// If this flag is set, any attempts to forward a payment to an unknown short channel id will /// instead generate an [`Event::HTLCIntercepted`] which must be handled the same as any other /// intercepted HTLC. /// /// Note that because LDK is not aware of which channel the HTLC will be forwarded over at the /// time of interception, only basic checks to ensure the fee the HTLC intends to pay is not /// negative and a minimum CLTV delta between the incoming and outgoing HTLC edge are performed /// before the [`Event::HTLCIntercepted`] is generated. You must validate the fee and CLTV /// delta meets your requirements before forwarding the HTLC. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted ToUnknownSCIDs = 1 << 7, /// If these flags are set, all HTLCs being forwarded over this node will instead generate an /// [`Event::HTLCIntercepted`] which must be handled the same as any other intercepted HTLC. /// /// In the case of intercept or unknown SCIDs, only basic checks to ensure the fee the HTLC /// intends to pay is not negative and a minimum CLTV delta between the incoming and outgoing /// HTLC edge are performed before the [`Event::HTLCIntercepted`] is generated. You must /// validate the fee and CLTV delta meets your requirements before forwarding the HTLC. /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted AllValidHTLCs = 0xff, } impl Into for HTLCInterceptionFlags { fn into(self) -> u8 { self as u8 } } /// Top-level config which holds ChannelHandshakeLimits and ChannelConfig. /// /// `Default::default()` provides sane defaults for most configurations /// (but currently with zero relay fees!) #[derive(Clone, Debug)] pub struct UserConfig { /// Channel handshake config that we propose to our counterparty. pub channel_handshake_config: ChannelHandshakeConfig, /// Limits applied to our counterparty's proposed channel handshake config settings. pub channel_handshake_limits: ChannelHandshakeLimits, /// Channel config which affects behavior during channel lifetime. pub channel_config: ChannelConfig, /// If this is set to `false`, we will reject any HTLCs which were to be forwarded over private /// channels. This prevents us from taking on HTLC-forwarding risk when we intend to run as a /// node which is not online reliably. /// /// Note that this policy is checked against the channel named by the sender's onion, though /// the HTLC may be delivered over any usable channel we have with the same peer. Thus, if we /// have both public and private channels with a peer, HTLCs which name a public channel may /// still be forwarded over a private channel, even with this set to `false`. To ensure HTLCs /// are never forwarded over private channels, do not maintain private channels with peers you /// also have public channels with. /// /// For nodes which are not online reliably, you should set all channels to *not* be announced /// (using [`ChannelHandshakeConfig::announce_for_forwarding`] and /// [`ChannelHandshakeLimits::force_announced_channel_preference`]) and set this to `false` to /// ensure you are not exposed to any forwarding risk. /// /// Note that because you cannot change a channel's announced state after creation, there is no /// way to disable forwarding on public channels retroactively. Thus, in order to change a node /// from a publicly-announced forwarding node to a private non-forwarding node you must close /// all your channels and open new ones. For privacy, you should also change your node_id /// (swapping all private and public key material for new ones) at that time. /// /// Note that this setting does not apply for intercepted payments that are surfaced via /// [`Event::HTLCIntercepted`] and manually forwarded. /// /// Default value: `false` /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted pub accept_forwards_to_priv_channels: bool, /// If this is set to `false`, we do not accept inbound requests to open a new channel. /// /// Default value: `true` pub accept_inbound_channels: bool, /// Flags consisting of OR'd values from [`HTLCInterceptionFlags`] which describe HTLCs /// forwarded over this node to intercept. Any HTLCs which are intercepted will generate an /// [`Event::HTLCIntercepted`] event which must be handled to forward or fail the HTLC. /// /// Do NOT hold on to intercepted HTLCs for more than a few seconds, they must always be /// forwarded or failed nearly immediately to avoid performing accidental denial of service /// attacks against other lightning nodes and being punished appropriately by other nodes. /// /// To ensure efficiency and reliable HTLC latency you should ensure you only intercept types /// of HTLCs which you need to manually forward or reject. /// /// Default value: `0` (indicating no HTLCs will be intercepted). /// /// [`Event::HTLCIntercepted`]: crate::events::Event::HTLCIntercepted pub htlc_interception_flags: u8, /// If this is set to `true`, the user needs to manually pay [`Bolt12Invoice`]s when received. /// /// When set to `true`, [`Event::InvoiceReceived`] will be generated for each received /// [`Bolt12Invoice`] instead of being automatically paid after verification. Use /// [`ChannelManager::send_payment_for_bolt12_invoice`] to pay the invoice or /// [`ChannelManager::abandon_payment`] to abandon the associated payment. /// /// Default value: `false` /// /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice /// [`Event::InvoiceReceived`]: crate::events::Event::InvoiceReceived /// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment #[deprecated( since = "0.3.0", note = "Instead, manually handle invoice messages at the OffersMessageHandler layer, \ delegating validation to an OffersMessageFlow where relevant, then pay using \ ChannelManager::pay_for_bolt12_invoice (being careful to avoid duplicative payments)." )] pub manually_handle_bolt12_invoices: bool, /// If this is set to `true`, dual-funded channels will be enabled. /// /// Default value: `false` pub enable_dual_funded_channels: bool, /// LDK supports a feature for always-online nodes such that these nodes can hold onto an HTLC /// from an often-offline channel peer until the often-offline payment recipient sends an onion /// message telling the always-online node to release the HTLC. If this is set to `true`, our node /// will carry out this feature for channel peers that request it. /// /// This should only be set to `true` for nodes which expect to be online reliably. /// /// Setting this to `true` may break backwards compatibility with LDK versions < 0.2. /// /// Default value: `false` pub enable_htlc_hold: bool, /// If this is set to true, then if we as an often-offline payer receive a [`StaticInvoice`] to /// pay, we will attempt to hold the corresponding outbound HTLCs with our next-hop channel /// counterparty(s) that support the `htlc_hold` feature. This allows our node to go offline once /// the HTLCs are locked in even though the recipient may not yet be online to receive them. /// /// This option is intended for usage by private nodes, and should NOT be set if we are an /// announced node that is expected to be online at all times. /// /// Setting this to `true` may lead to HTLC failures if downgrading to LDK versions < 0.2. /// /// Default value: `false` /// /// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice pub hold_outbound_htlcs_at_next_hop: bool, /// If this is set to `true`, then inbound channel splice requests will be rejected. This /// ensures backwards compatibility is not broken with LDK versions < 0.2 while a splice is /// pending. /// /// Outbound channel splice requests (via [`ChannelManager::splice_channel`], an opt-in API) are /// still allowed as users should be aware of the backwards compatibility risk prior to using /// the functionality. /// /// Default value: `true` /// /// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel pub reject_inbound_splices: bool, } #[allow(deprecated)] impl Default for UserConfig { fn default() -> Self { UserConfig { channel_handshake_config: ChannelHandshakeConfig::default(), channel_handshake_limits: ChannelHandshakeLimits::default(), channel_config: ChannelConfig::default(), accept_forwards_to_priv_channels: false, accept_inbound_channels: true, htlc_interception_flags: 0, manually_handle_bolt12_invoices: false, enable_dual_funded_channels: false, enable_htlc_hold: false, hold_outbound_htlcs_at_next_hop: false, reject_inbound_splices: true, } } } // When fuzzing, we want to allow the fuzzer to pick any configuration parameters. Thus, we // implement Readable here in a naive way (which is a bit easier for the fuzzer to handle). We // don't really want to ever expose this to users (if we did we'd want to use TLVs). #[cfg(fuzzing)] #[allow(deprecated)] impl Readable for UserConfig { fn read(reader: &mut R) -> Result { Ok(Self { channel_handshake_config: Readable::read(reader)?, channel_handshake_limits: Readable::read(reader)?, channel_config: Readable::read(reader)?, accept_forwards_to_priv_channels: Readable::read(reader)?, accept_inbound_channels: Readable::read(reader)?, htlc_interception_flags: Readable::read(reader)?, manually_handle_bolt12_invoices: Readable::read(reader)?, enable_dual_funded_channels: Readable::read(reader)?, hold_outbound_htlcs_at_next_hop: Readable::read(reader)?, enable_htlc_hold: Readable::read(reader)?, reject_inbound_splices: Readable::read(reader)?, }) } } /// Config structure for overriding channel parameters. #[derive(Default)] pub struct ChannelConfigOverrides { /// Overrides for channel handshake parameters. pub handshake_overrides: Option, /// Overrides for channel update parameters. pub update_overrides: Option, } impl UserConfig { /// Applies given channel config overrides to the user config. pub fn apply(&mut self, config: &ChannelConfigOverrides) { if let Some(handshake_overrides) = &config.handshake_overrides { self.channel_handshake_config.apply(&handshake_overrides); } if let Some(update_overrides) = &config.update_overrides { self.channel_config.apply(&update_overrides); } } } /// Config structure for overriding channel handshake parameters. #[derive(Default)] pub struct ChannelHandshakeConfigUpdate { /// Overrides the maximum percentage of the total channel value that can be allocated to inbound /// HTLCs in announced channels. See /// [`ChannelHandshakeConfig::announced_channel_max_inbound_htlc_value_in_flight_percentage`]. pub announced_channel_max_inbound_htlc_value_in_flight_percentage: Option, /// Overrides the maximum percentage of the total channel value that can be allocated to inbound /// HTLCs in unannounced channels. See /// [`ChannelHandshakeConfig::unannounced_channel_max_inbound_htlc_value_in_flight_percentage`]. pub unannounced_channel_max_inbound_htlc_value_in_flight_percentage: Option, /// Overrides the smallest value HTLC we will accept to process. See [`ChannelHandshakeConfig::our_htlc_minimum_msat`]. pub htlc_minimum_msat: Option, /// Overrides confirmations we will wait for before considering the channel locked in. See /// [`ChannelHandshakeConfig::minimum_depth`]. pub minimum_depth: Option, /// Overrides the number of blocks we require our counterparty to wait to claim their money. See /// [`ChannelHandshakeConfig::our_to_self_delay`]. pub to_self_delay: Option, /// The maximum number of HTLCs in-flight from our counterparty towards us at the same time. See /// [`ChannelHandshakeConfig::our_max_accepted_htlcs`]. pub max_accepted_htlcs: Option, /// The Proportion of the channel value to configure as counterparty's channel reserve. See /// [`ChannelHandshakeConfig::their_channel_reserve_proportional_millionths`]. pub channel_reserve_proportional_millionths: Option, } impl From for ChannelHandshakeConfigUpdate { fn from(config: ChannelHandshakeConfig) -> Self { Self { announced_channel_max_inbound_htlc_value_in_flight_percentage: Some( config.announced_channel_max_inbound_htlc_value_in_flight_percentage, ), unannounced_channel_max_inbound_htlc_value_in_flight_percentage: Some( config.unannounced_channel_max_inbound_htlc_value_in_flight_percentage, ), htlc_minimum_msat: Some(config.our_htlc_minimum_msat), minimum_depth: Some(config.minimum_depth), to_self_delay: Some(config.our_to_self_delay), max_accepted_htlcs: Some(config.our_max_accepted_htlcs), channel_reserve_proportional_millionths: Some( config.their_channel_reserve_proportional_millionths, ), } } } impl ChannelHandshakeConfig { /// Applies the provided handshake config update. pub fn apply(&mut self, config: &ChannelHandshakeConfigUpdate) { if let Some(max_in_flight_percent) = config.announced_channel_max_inbound_htlc_value_in_flight_percentage { self.announced_channel_max_inbound_htlc_value_in_flight_percentage = max_in_flight_percent; } if let Some(max_in_flight_percent) = config.unannounced_channel_max_inbound_htlc_value_in_flight_percentage { self.unannounced_channel_max_inbound_htlc_value_in_flight_percentage = max_in_flight_percent; } if let Some(htlc_minimum_msat) = config.htlc_minimum_msat { self.our_htlc_minimum_msat = htlc_minimum_msat; } if let Some(minimum_depth) = config.minimum_depth { self.minimum_depth = minimum_depth; } if let Some(to_self_delay) = config.to_self_delay { self.our_to_self_delay = to_self_delay; } if let Some(max_accepted_htlcs) = config.max_accepted_htlcs { self.our_max_accepted_htlcs = max_accepted_htlcs; } if let Some(channel_reserve) = config.channel_reserve_proportional_millionths { self.their_channel_reserve_proportional_millionths = channel_reserve; } } }