@@ -62,7 +62,7 @@ pub struct ChannelValueStat {
6262 pub counterparty_dust_limit_msat : u64 ,
6363}
6464
65- #[ derive( Clone , Copy , PartialEq ) ]
65+ #[ derive( Debug , Clone , Copy , PartialEq ) ]
6666enum FeeUpdateState {
6767 // Inbound states mirroring InboundHTLCState
6868 RemoteAnnounced ,
@@ -293,6 +293,7 @@ struct HTLCStats {
293293 pending_htlcs_value_msat : u64 ,
294294 on_counterparty_tx_dust_exposure_msat : u64 ,
295295 on_holder_tx_dust_exposure_msat : u64 ,
296+ holding_cell_msat : u64 ,
296297}
297298
298299/// Used when calculating whether we or the remote can afford an additional HTLC.
@@ -384,6 +385,17 @@ const FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE: u64 = 2;
384385/// This constant is the one suggested in BOLT 2.
385386pub ( crate ) const FUNDING_CONF_DEADLINE_BLOCKS : u32 = 2016 ;
386387
388+ /// In case of a concurrent update_add_htlc proposed by our counterparty, we might
389+ /// not have enough balance value remaining to cover the onchain cost of this new
390+ /// HTLC weight. If this happens, our counterparty fails the reception of our
391+ /// commitment_signed including this new HTLC due to infringement on the channel
392+ /// reserve.
393+ /// To prevent this case, we compute our outbound update_fee with an HTLC buffer of
394+ /// size 2. However, if the number of concurrent update_add_htlc is higher, this still
395+ /// leads to a channel force-close. Ultimately, this is an issue coming from the
396+ /// design of LN state machines, allowing asynchronous updates.
397+ const CONCURRENT_INBOUND_HTLC_FEE_BUFFER : u32 = 2 ;
398+
387399// TODO: We should refactor this to be an Inbound/OutboundChannel until initial setup handshaking
388400// has been completed, and then turn into a Channel to get compiler-time enforcement of things like
389401// calling channel_id() before we're set up or things like get_outbound_funding_signed on an
@@ -1110,8 +1122,10 @@ impl<Signer: Sign> Channel<Signer> {
11101122 /// transaction, the list of HTLCs which were not ignored when building the transaction).
11111123 /// Note that below-dust HTLCs are included in the fourth return value, but not the third, and
11121124 /// sources are provided only for outbound HTLCs in the fourth return value.
1125+ /// Note that fifth and sixth return values are respectively anticipated holder and counterparty
1126+ /// balance, not the value actually paid on-chain, which may be zero if it got rounded to dust.
11131127 #[ inline]
1114- fn build_commitment_transaction < L : Deref > ( & self , commitment_number : u64 , keys : & TxCreationKeys , local : bool , generated_by_local : bool , logger : & L ) -> ( CommitmentTransaction , u32 , usize , Vec < ( HTLCOutputInCommitment , Option < & HTLCSource > ) > ) where L :: Target : Logger {
1128+ fn build_commitment_transaction < L : Deref > ( & self , commitment_number : u64 , keys : & TxCreationKeys , local : bool , generated_by_local : bool , logger : & L ) -> ( CommitmentTransaction , u32 , usize , Vec < ( HTLCOutputInCommitment , Option < & HTLCSource > ) > , u64 , u64 ) where L :: Target : Logger {
11151129 let mut included_dust_htlcs: Vec < ( HTLCOutputInCommitment , Option < & HTLCSource > ) > = Vec :: new ( ) ;
11161130 let num_htlcs = self . pending_inbound_htlcs . len ( ) + self . pending_outbound_htlcs . len ( ) ;
11171131 let mut included_non_dust_htlcs: Vec < ( HTLCOutputInCommitment , Option < & HTLCSource > ) > = Vec :: with_capacity ( num_htlcs) ;
@@ -1302,7 +1316,7 @@ impl<Signer: Sign> Channel<Signer> {
13021316 htlcs_included. sort_unstable_by_key ( |h| h. 0 . transaction_output_index . unwrap ( ) ) ;
13031317 htlcs_included. append ( & mut included_dust_htlcs) ;
13041318
1305- ( tx, feerate_per_kw, num_nondust_htlcs, htlcs_included)
1319+ ( tx, feerate_per_kw, num_nondust_htlcs, htlcs_included, value_to_self_msat as u64 , value_to_remote_msat as u64 )
13061320 }
13071321
13081322 #[ inline]
@@ -1990,6 +2004,7 @@ impl<Signer: Sign> Channel<Signer> {
19902004 pending_htlcs_value_msat : 0 ,
19912005 on_counterparty_tx_dust_exposure_msat : 0 ,
19922006 on_holder_tx_dust_exposure_msat : 0 ,
2007+ holding_cell_msat : 0 ,
19932008 } ;
19942009
19952010 let counterparty_dust_limit_timeout_sat = ( self . get_dust_buffer_feerate ( ) as u64 * HTLC_TIMEOUT_TX_WEIGHT / 1000 ) + self . counterparty_dust_limit_satoshis ;
@@ -2013,6 +2028,7 @@ impl<Signer: Sign> Channel<Signer> {
20132028 pending_htlcs_value_msat : 0 ,
20142029 on_counterparty_tx_dust_exposure_msat : 0 ,
20152030 on_holder_tx_dust_exposure_msat : 0 ,
2031+ holding_cell_msat : 0 ,
20162032 } ;
20172033
20182034 let counterparty_dust_limit_success_sat = ( self . get_dust_buffer_feerate ( ) as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 ) + self . counterparty_dust_limit_satoshis ;
@@ -2031,6 +2047,7 @@ impl<Signer: Sign> Channel<Signer> {
20312047 if let & HTLCUpdateAwaitingACK :: AddHTLC { ref amount_msat, .. } = update {
20322048 stats. pending_htlcs += 1 ;
20332049 stats. pending_htlcs_value_msat += amount_msat;
2050+ stats. holding_cell_msat += amount_msat;
20342051 if * amount_msat / 1000 < counterparty_dust_limit_success_sat {
20352052 stats. on_counterparty_tx_dust_exposure_msat += amount_msat;
20362053 }
@@ -2478,7 +2495,7 @@ impl<Signer: Sign> Channel<Signer> {
24782495
24792496 let keys = self . build_holder_transaction_keys ( self . cur_holder_commitment_transaction_number ) . map_err ( |e| ( None , e) ) ?;
24802497
2481- let ( num_htlcs, mut htlcs_cloned, commitment_tx, commitment_txid, feerate_per_kw) = {
2498+ let ( num_htlcs, mut htlcs_cloned, commitment_tx, commitment_txid, feerate_per_kw, _ , counterparty_balance_msat ) = {
24822499 let commitment_tx = self . build_commitment_transaction ( self . cur_holder_commitment_transaction_number , & keys, true , false , logger) ;
24832500 let commitment_txid = {
24842501 let trusted_tx = commitment_tx. 0 . trust ( ) ;
@@ -2495,7 +2512,7 @@ impl<Signer: Sign> Channel<Signer> {
24952512 bitcoin_tx. txid
24962513 } ;
24972514 let htlcs_cloned: Vec < _ > = commitment_tx. 3 . iter ( ) . map ( |htlc| ( htlc. 0 . clone ( ) , htlc. 1 . map ( |h| h. clone ( ) ) ) ) . collect ( ) ;
2498- ( commitment_tx. 2 , htlcs_cloned, commitment_tx. 0 , commitment_txid, commitment_tx. 1 )
2515+ ( commitment_tx. 2 , htlcs_cloned, commitment_tx. 0 , commitment_txid, commitment_tx. 1 , commitment_tx . 4 , commitment_tx . 5 )
24992516 } ;
25002517
25012518 // If our counterparty updated the channel fee in this commitment transaction, check that
@@ -2507,7 +2524,7 @@ impl<Signer: Sign> Channel<Signer> {
25072524 let total_fee_sat = Channel :: < Signer > :: commit_tx_fee_sat ( feerate_per_kw, num_htlcs) ;
25082525 if update_fee {
25092526 let counterparty_reserve_we_require = Channel :: < Signer > :: get_holder_selected_channel_reserve_satoshis ( self . channel_value_satoshis ) ;
2510- if self . channel_value_satoshis - self . value_to_self_msat / 1000 < total_fee_sat + counterparty_reserve_we_require {
2527+ if counterparty_balance_msat < total_fee_sat * 1000 + counterparty_reserve_we_require * 1000 {
25112528 return Err ( ( None , ChannelError :: Close ( "Funding remote cannot afford proposed new fee" . to_owned ( ) ) ) ) ;
25122529 }
25132530 }
@@ -2692,7 +2709,7 @@ impl<Signer: Sign> Channel<Signer> {
26922709 // to rebalance channels.
26932710 match & htlc_update {
26942711 & HTLCUpdateAwaitingACK :: AddHTLC { amount_msat, cltv_expiry, ref payment_hash, ref source, ref onion_routing_packet, ..} => {
2695- match self . send_htlc ( amount_msat, * payment_hash, cltv_expiry, source. clone ( ) , onion_routing_packet. clone ( ) ) {
2712+ match self . send_htlc ( amount_msat, * payment_hash, cltv_expiry, source. clone ( ) , onion_routing_packet. clone ( ) , logger ) {
26962713 Ok ( update_add_msg_option) => update_add_htlcs. push ( update_add_msg_option. unwrap ( ) ) ,
26972714 Err ( e) => {
26982715 match e {
@@ -2751,12 +2768,7 @@ impl<Signer: Sign> Channel<Signer> {
27512768 return Ok ( ( None , htlcs_to_fail) ) ;
27522769 }
27532770 let update_fee = if let Some ( feerate) = self . holding_cell_update_fee . take ( ) {
2754- assert ! ( self . is_outbound( ) ) ;
2755- self . pending_update_fee = Some ( ( feerate, FeeUpdateState :: Outbound ) ) ;
2756- Some ( msgs:: UpdateFee {
2757- channel_id : self . channel_id ,
2758- feerate_per_kw : feerate as u32 ,
2759- } )
2771+ self . send_update_fee ( feerate, logger)
27602772 } else {
27612773 None
27622774 } ;
@@ -3053,8 +3065,10 @@ impl<Signer: Sign> Channel<Signer> {
30533065
30543066 /// Adds a pending update to this channel. See the doc for send_htlc for
30553067 /// further details on the optionness of the return value.
3068+ /// If our balance is too low to cover the cost of the next commitment transaction at the
3069+ /// new feerate, the update is cancelled.
30563070 /// You MUST call send_commitment prior to any other calls on this Channel
3057- fn send_update_fee ( & mut self , feerate_per_kw : u32 ) -> Option < msgs:: UpdateFee > {
3071+ fn send_update_fee < L : Deref > ( & mut self , feerate_per_kw : u32 , logger : & L ) -> Option < msgs:: UpdateFee > where L :: Target : Logger {
30583072 if !self . is_outbound ( ) {
30593073 panic ! ( "Cannot send fee from inbound channel" ) ;
30603074 }
@@ -3065,6 +3079,19 @@ impl<Signer: Sign> Channel<Signer> {
30653079 panic ! ( "Cannot update fee while peer is disconnected/we're awaiting a monitor update (ChannelManager should have caught this)" ) ;
30663080 }
30673081
3082+ // Before proposing a feerate update, check that we can actually afford the new fee.
3083+ let inbound_stats = self . get_inbound_pending_htlc_stats ( ) ;
3084+ let outbound_stats = self . get_outbound_pending_htlc_stats ( ) ;
3085+ let keys = if let Ok ( keys) = self . build_holder_transaction_keys ( self . cur_holder_commitment_transaction_number ) { keys } else { return None ; } ;
3086+ let ( _, _, num_htlcs, _, holder_balance_msat, _) = self . build_commitment_transaction ( self . cur_holder_commitment_transaction_number , & keys, true , true , logger) ;
3087+ let total_fee_sat = Channel :: < Signer > :: commit_tx_fee_sat ( feerate_per_kw, num_htlcs + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize ) ;
3088+ let holder_balance_msat = holder_balance_msat - outbound_stats. holding_cell_msat ;
3089+ if holder_balance_msat < total_fee_sat * 1000 + self . counterparty_selected_channel_reserve_satoshis . unwrap ( ) * 1000 {
3090+ //TODO: auto-close after a number of failures?
3091+ log_debug ! ( logger, "Cannot afford to send new feerate at {}" , feerate_per_kw) ;
3092+ return None ;
3093+ }
3094+
30683095 if ( self . channel_state & ( ChannelState :: AwaitingRemoteRevoke as u32 | ChannelState :: MonitorUpdateFailed as u32 ) ) != 0 {
30693096 self . holding_cell_update_fee = Some ( feerate_per_kw) ;
30703097 return None ;
@@ -3080,7 +3107,7 @@ impl<Signer: Sign> Channel<Signer> {
30803107 }
30813108
30823109 pub fn send_update_fee_and_commit < L : Deref > ( & mut self , feerate_per_kw : u32 , logger : & L ) -> Result < Option < ( msgs:: UpdateFee , msgs:: CommitmentSigned , ChannelMonitorUpdate ) > , ChannelError > where L :: Target : Logger {
3083- match self . send_update_fee ( feerate_per_kw) {
3110+ match self . send_update_fee ( feerate_per_kw, logger ) {
30843111 Some ( update_fee) => {
30853112 let ( commitment_signed, monitor_update) = self . send_commitment_no_status_check ( logger) ?;
30863113 Ok ( Some ( ( update_fee, commitment_signed, monitor_update) ) )
@@ -4601,7 +4628,7 @@ impl<Signer: Sign> Channel<Signer> {
46014628 /// You MUST call send_commitment prior to calling any other methods on this Channel!
46024629 ///
46034630 /// If an Err is returned, it's a ChannelError::Ignore!
4604- pub fn send_htlc ( & mut self , amount_msat : u64 , payment_hash : PaymentHash , cltv_expiry : u32 , source : HTLCSource , onion_routing_packet : msgs:: OnionPacket ) -> Result < Option < msgs:: UpdateAddHTLC > , ChannelError > {
4631+ pub fn send_htlc < L : Deref > ( & mut self , amount_msat : u64 , payment_hash : PaymentHash , cltv_expiry : u32 , source : HTLCSource , onion_routing_packet : msgs:: OnionPacket , logger : & L ) -> Result < Option < msgs:: UpdateAddHTLC > , ChannelError > where L :: Target : Logger {
46054632 if ( self . channel_state & ( ChannelState :: ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK ) ) != ( ChannelState :: ChannelFunded as u32 ) {
46064633 return Err ( ChannelError :: Ignore ( "Cannot send HTLC until channel is fully established and we haven't started shutting down" . to_owned ( ) ) ) ;
46074634 }
@@ -4638,13 +4665,14 @@ impl<Signer: Sign> Channel<Signer> {
46384665 return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would put us over the max HTLC value in flight our peer will accept ({})" , self . counterparty_max_htlc_value_in_flight_msat) ) ) ;
46394666 }
46404667
4668+ let keys = self . build_holder_transaction_keys ( self . cur_holder_commitment_transaction_number ) ?;
46414669 if !self . is_outbound ( ) {
46424670 // Check that we won't violate the remote channel reserve by adding this HTLC.
4643- let counterparty_balance_msat = self . channel_value_satoshis * 1000 - self . value_to_self_msat ;
4644- let holder_selected_chan_reserve_msat = Channel :: < Signer > :: get_holder_selected_channel_reserve_satoshis ( self . channel_value_satoshis ) * 1000 ;
4671+ let counterparty_balance_msat = self . build_commitment_transaction ( self . cur_holder_commitment_transaction_number , & keys, true , true , logger) . 5 ;
46454672 let htlc_candidate = HTLCCandidate :: new ( amount_msat, HTLCInitiator :: LocalOffered ) ;
46464673 let counterparty_commit_tx_fee_msat = self . next_remote_commit_tx_fee_msat ( htlc_candidate, None ) ;
4647- if counterparty_balance_msat < holder_selected_chan_reserve_msat + counterparty_commit_tx_fee_msat {
4674+ let holder_selected_chan_reserve_msat = Channel :: < Signer > :: get_holder_selected_channel_reserve_satoshis ( self . channel_value_satoshis ) * 1000 ;
4675+ if counterparty_balance_msat < counterparty_commit_tx_fee_msat + holder_selected_chan_reserve_msat {
46484676 return Err ( ChannelError :: Ignore ( "Cannot send value that would put counterparty balance under holder-announced channel reserve value" . to_owned ( ) ) ) ;
46494677 }
46504678 }
@@ -4667,24 +4695,24 @@ impl<Signer: Sign> Channel<Signer> {
46674695 }
46684696 }
46694697
4670- let pending_value_to_self_msat = self . value_to_self_msat - outbound_stats. pending_htlcs_value_msat ;
4671- if pending_value_to_self_msat < amount_msat {
4672- return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would overdraw remaining funds. Amount: {}, pending value to self {}" , amount_msat, pending_value_to_self_msat ) ) ) ;
4698+ let holder_balance_msat = self . build_commitment_transaction ( self . cur_holder_commitment_transaction_number , & keys , true , true , logger ) . 4 as u64 - outbound_stats. holding_cell_msat ;
4699+ if holder_balance_msat < amount_msat {
4700+ return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would overdraw remaining funds. Amount: {}, pending value to self {}" , amount_msat, holder_balance_msat ) ) ) ;
46734701 }
46744702
46754703 // `2 *` and extra HTLC are for the fee spike buffer.
46764704 let commit_tx_fee_msat = if self . is_outbound ( ) {
46774705 let htlc_candidate = HTLCCandidate :: new ( amount_msat, HTLCInitiator :: LocalOffered ) ;
46784706 FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * self . next_local_commit_tx_fee_msat ( htlc_candidate, Some ( ( ) ) )
46794707 } else { 0 } ;
4680- if pending_value_to_self_msat - amount_msat < commit_tx_fee_msat {
4681- return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would not leave enough to pay for fees. Pending value to self: {}. local_commit_tx_fee {}" , pending_value_to_self_msat , commit_tx_fee_msat) ) ) ;
4708+ if holder_balance_msat - amount_msat < commit_tx_fee_msat {
4709+ return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would not leave enough to pay for fees. Pending value to self: {}. local_commit_tx_fee {}" , holder_balance_msat , commit_tx_fee_msat) ) ) ;
46824710 }
46834711
46844712 // Check self.counterparty_selected_channel_reserve_satoshis (the amount we must keep as
46854713 // reserve for the remote to have something to claim if we misbehave)
46864714 let chan_reserve_msat = self . counterparty_selected_channel_reserve_satoshis . unwrap ( ) * 1000 ;
4687- if pending_value_to_self_msat - amount_msat - commit_tx_fee_msat < chan_reserve_msat {
4715+ if holder_balance_msat - amount_msat - commit_tx_fee_msat < chan_reserve_msat {
46884716 return Err ( ChannelError :: Ignore ( format ! ( "Cannot send value that would put our balance under counterparty-announced channel reserve value ({})" , chan_reserve_msat) ) ) ;
46894717 }
46904718
@@ -4878,7 +4906,7 @@ impl<Signer: Sign> Channel<Signer> {
48784906 /// Shorthand for calling send_htlc() followed by send_commitment(), see docs on those for
48794907 /// more info.
48804908 pub fn send_htlc_and_commit < L : Deref > ( & mut self , amount_msat : u64 , payment_hash : PaymentHash , cltv_expiry : u32 , source : HTLCSource , onion_routing_packet : msgs:: OnionPacket , logger : & L ) -> Result < Option < ( msgs:: UpdateAddHTLC , msgs:: CommitmentSigned , ChannelMonitorUpdate ) > , ChannelError > where L :: Target : Logger {
4881- match self . send_htlc ( amount_msat, payment_hash, cltv_expiry, source, onion_routing_packet) ? {
4909+ match self . send_htlc ( amount_msat, payment_hash, cltv_expiry, source, onion_routing_packet, logger ) ? {
48824910 Some ( update_add_htlc) => {
48834911 let ( commitment_signed, monitor_update) = self . send_commitment_no_status_check ( logger) ?;
48844912 Ok ( Some ( ( update_add_htlc, commitment_signed, monitor_update) ) )
0 commit comments