@@ -37,7 +37,7 @@ use crate::ln::{PaymentHash, PaymentPreimage};
37
37
use crate :: ln:: msgs:: DecodeError ;
38
38
use crate :: ln:: chan_utils;
39
39
use crate :: ln:: chan_utils:: { CounterpartyCommitmentSecrets , HTLCOutputInCommitment , HTLCClaim , ChannelTransactionParameters , HolderCommitmentTransaction } ;
40
- use crate :: ln:: channelmanager:: HTLCSource ;
40
+ use crate :: ln:: channelmanager:: { HTLCSource , SentHTLCId } ;
41
41
use crate :: chain;
42
42
use crate :: chain:: { BestBlock , WatchedOutput } ;
43
43
use crate :: chain:: chaininterface:: { BroadcasterInterface , FeeEstimator , LowerBoundedFeeEstimator } ;
@@ -494,6 +494,7 @@ pub(crate) enum ChannelMonitorUpdateStep {
494
494
LatestHolderCommitmentTXInfo {
495
495
commitment_tx : HolderCommitmentTransaction ,
496
496
htlc_outputs : Vec < ( HTLCOutputInCommitment , Option < Signature > , Option < HTLCSource > ) > ,
497
+ claimed_htlcs : Vec < ( SentHTLCId , PaymentPreimage ) > ,
497
498
} ,
498
499
LatestCounterpartyCommitmentTXInfo {
499
500
commitment_txid : Txid ,
@@ -536,6 +537,7 @@ impl ChannelMonitorUpdateStep {
536
537
impl_writeable_tlv_based_enum_upgradable ! ( ChannelMonitorUpdateStep ,
537
538
( 0 , LatestHolderCommitmentTXInfo ) => {
538
539
( 0 , commitment_tx, required) ,
540
+ ( 1 , claimed_htlcs, vec_type) ,
539
541
( 2 , htlc_outputs, vec_type) ,
540
542
} ,
541
543
( 1 , LatestCounterpartyCommitmentTXInfo ) => {
@@ -750,6 +752,8 @@ pub(crate) struct ChannelMonitorImpl<Signer: WriteableEcdsaChannelSigner> {
750
752
/// Serialized to disk but should generally not be sent to Watchtowers.
751
753
counterparty_hash_commitment_number : HashMap < PaymentHash , u64 > ,
752
754
755
+ counterparty_fulfilled_htlcs : HashMap < SentHTLCId , PaymentPreimage > ,
756
+
753
757
// We store two holder commitment transactions to avoid any race conditions where we may update
754
758
// some monitors (potentially on watchtowers) but then fail to update others, resulting in the
755
759
// various monitors for one channel being out of sync, and us broadcasting a holder
@@ -1033,6 +1037,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signe
1033
1037
( 9 , self . counterparty_node_id, option) ,
1034
1038
( 11 , self . confirmed_commitment_tx_counterparty_output, option) ,
1035
1039
( 13 , self . spendable_txids_confirmed, vec_type) ,
1040
+ ( 15 , self . counterparty_fulfilled_htlcs, required) ,
1036
1041
} ) ;
1037
1042
1038
1043
Ok ( ( ) )
@@ -1120,6 +1125,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1120
1125
counterparty_claimable_outpoints : HashMap :: new ( ) ,
1121
1126
counterparty_commitment_txn_on_chain : HashMap :: new ( ) ,
1122
1127
counterparty_hash_commitment_number : HashMap :: new ( ) ,
1128
+ counterparty_fulfilled_htlcs : HashMap :: new ( ) ,
1123
1129
1124
1130
prev_holder_signed_commitment_tx : None ,
1125
1131
current_holder_commitment_tx : holder_commitment_tx,
@@ -1174,7 +1180,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1174
1180
& self , holder_commitment_tx : HolderCommitmentTransaction ,
1175
1181
htlc_outputs : Vec < ( HTLCOutputInCommitment , Option < Signature > , Option < HTLCSource > ) > ,
1176
1182
) -> Result < ( ) , ( ) > {
1177
- self . inner . lock ( ) . unwrap ( ) . provide_latest_holder_commitment_tx ( holder_commitment_tx, htlc_outputs) . map_err ( |_| ( ) )
1183
+ self . inner . lock ( ) . unwrap ( ) . provide_latest_holder_commitment_tx ( holder_commitment_tx, htlc_outputs, & Vec :: new ( ) ) . map_err ( |_| ( ) )
1178
1184
}
1179
1185
1180
1186
/// This is used to provide payment preimage(s) out-of-band during startup without updating the
@@ -1810,9 +1816,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1810
1816
/// `ChannelMonitor`. This is used to determine if an HTLC was removed from the channel prior
1811
1817
/// to the `ChannelManager` having been persisted.
1812
1818
///
1813
- /// This is similar to [`Self::get_pending_outbound_htlcs`] except it includes HTLCs which were
1814
- /// resolved by this `ChannelMonitor`.
1815
- pub ( crate ) fn get_all_current_outbound_htlcs ( & self ) -> HashMap < HTLCSource , HTLCOutputInCommitment > {
1819
+ /// This is similar to [`Self::get_pending_or_resolved_outbound_htlcs`] except it includes
1820
+ /// HTLCs which were resolved on-chain (i.e. where the final HTLC resolution was done by an
1821
+ /// event from this `ChannelMonitor`).
1822
+ pub ( crate ) fn get_all_current_outbound_htlcs ( & self ) -> HashMap < HTLCSource , ( HTLCOutputInCommitment , Option < PaymentPreimage > ) > {
1816
1823
let mut res = HashMap :: new ( ) ;
1817
1824
// Just examine the available counterparty commitment transactions. See docs on
1818
1825
// `fail_unbroadcast_htlcs`, below, for justification.
@@ -1822,7 +1829,8 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1822
1829
if let Some ( ref latest_outpoints) = us. counterparty_claimable_outpoints. get( $txid) {
1823
1830
for & ( ref htlc, ref source_option) in latest_outpoints. iter( ) {
1824
1831
if let & Some ( ref source) = source_option {
1825
- res. insert( ( * * source) . clone( ) , htlc. clone( ) ) ;
1832
+ res. insert( ( * * source) . clone( ) , ( htlc. clone( ) ,
1833
+ us. counterparty_fulfilled_htlcs. get( & SentHTLCId :: from_source( source) ) . cloned( ) ) ) ;
1826
1834
}
1827
1835
}
1828
1836
}
@@ -1837,9 +1845,14 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1837
1845
res
1838
1846
}
1839
1847
1840
- /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1848
+ /// Gets the set of outbound HTLCs which are pending resolution in this channel or which were
1849
+ /// resolved with a preimage from our counterparty.
1850
+ ///
1841
1851
/// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1842
- pub ( crate ) fn get_pending_outbound_htlcs ( & self ) -> HashMap < HTLCSource , HTLCOutputInCommitment > {
1852
+ ///
1853
+ /// Currently, the preimage is unused, however if it is present in the relevant internal state
1854
+ /// an HTLC is always included even if it has been resolved.
1855
+ pub ( crate ) fn get_pending_or_resolved_outbound_htlcs ( & self ) -> HashMap < HTLCSource , ( HTLCOutputInCommitment , Option < PaymentPreimage > ) > {
1843
1856
let us = self . inner . lock ( ) . unwrap ( ) ;
1844
1857
// We're only concerned with the confirmation count of HTLC transactions, and don't
1845
1858
// actually care how many confirmations a commitment transaction may or may not have. Thus,
@@ -1887,8 +1900,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
1887
1900
Some ( commitment_tx_output_idx) == htlc. transaction_output_index
1888
1901
} else { false }
1889
1902
} ) ;
1890
- if !htlc_update_confd {
1891
- res. insert( source. clone( ) , htlc. clone( ) ) ;
1903
+ let counterparty_resolved_preimage_opt =
1904
+ us. counterparty_fulfilled_htlcs. get( & SentHTLCId :: from_source( source) ) . cloned( ) ;
1905
+ if !htlc_update_confd || counterparty_resolved_preimage_opt. is_some( ) {
1906
+ res. insert( source. clone( ) , ( htlc. clone( ) , counterparty_resolved_preimage_opt) ) ;
1892
1907
}
1893
1908
}
1894
1909
}
@@ -1970,6 +1985,9 @@ macro_rules! fail_unbroadcast_htlcs {
1970
1985
}
1971
1986
}
1972
1987
if matched_htlc { continue ; }
1988
+ if $self. counterparty_fulfilled_htlcs. get( & SentHTLCId :: from_source( source) ) . is_some( ) {
1989
+ continue ;
1990
+ }
1973
1991
$self. onchain_events_awaiting_threshold_conf. retain( |ref entry| {
1974
1992
if entry. height != $commitment_tx_conf_height { return true ; }
1975
1993
match entry. event {
@@ -2041,8 +2059,23 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2041
2059
// Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
2042
2060
// events for now-revoked/fulfilled HTLCs.
2043
2061
if let Some ( txid) = self . prev_counterparty_commitment_txid . take ( ) {
2044
- for & mut ( _, ref mut source) in self . counterparty_claimable_outpoints . get_mut ( & txid) . unwrap ( ) {
2045
- * source = None ;
2062
+ if self . current_counterparty_commitment_txid . unwrap ( ) != txid {
2063
+ let cur_claimables = self . counterparty_claimable_outpoints . get (
2064
+ & self . current_counterparty_commitment_txid . unwrap ( ) ) . unwrap ( ) ;
2065
+ for ( _, ref source_opt) in self . counterparty_claimable_outpoints . get ( & txid) . unwrap ( ) {
2066
+ if let Some ( source) = source_opt {
2067
+ if !cur_claimables. iter ( )
2068
+ . any ( |( _, cur_source_opt) | cur_source_opt == source_opt)
2069
+ {
2070
+ self . counterparty_fulfilled_htlcs . remove ( & SentHTLCId :: from_source ( source) ) ;
2071
+ }
2072
+ }
2073
+ }
2074
+ for & mut ( _, ref mut source_opt) in self . counterparty_claimable_outpoints . get_mut ( & txid) . unwrap ( ) {
2075
+ * source_opt = None ;
2076
+ }
2077
+ } else {
2078
+ assert ! ( cfg!( fuzzing) , "Commitment txids are unique outside of fuzzing, where hashes can collide" ) ;
2046
2079
}
2047
2080
}
2048
2081
@@ -2127,28 +2160,37 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2127
2160
/// is important that any clones of this channel monitor (including remote clones) by kept
2128
2161
/// up-to-date as our holder commitment transaction is updated.
2129
2162
/// Panics if set_on_holder_tx_csv has never been called.
2130
- fn provide_latest_holder_commitment_tx ( & mut self , holder_commitment_tx : HolderCommitmentTransaction , htlc_outputs : Vec < ( HTLCOutputInCommitment , Option < Signature > , Option < HTLCSource > ) > ) -> Result < ( ) , & ' static str > {
2131
- // block for Rust 1.34 compat
2132
- let mut new_holder_commitment_tx = {
2133
- let trusted_tx = holder_commitment_tx. trust ( ) ;
2134
- let txid = trusted_tx. txid ( ) ;
2135
- let tx_keys = trusted_tx. keys ( ) ;
2136
- self . current_holder_commitment_number = trusted_tx. commitment_number ( ) ;
2137
- HolderSignedTx {
2138
- txid,
2139
- revocation_key : tx_keys. revocation_key ,
2140
- a_htlc_key : tx_keys. broadcaster_htlc_key ,
2141
- b_htlc_key : tx_keys. countersignatory_htlc_key ,
2142
- delayed_payment_key : tx_keys. broadcaster_delayed_payment_key ,
2143
- per_commitment_point : tx_keys. per_commitment_point ,
2144
- htlc_outputs,
2145
- to_self_value_sat : holder_commitment_tx. to_broadcaster_value_sat ( ) ,
2146
- feerate_per_kw : trusted_tx. feerate_per_kw ( ) ,
2147
- }
2163
+ fn provide_latest_holder_commitment_tx ( & mut self , holder_commitment_tx : HolderCommitmentTransaction , htlc_outputs : Vec < ( HTLCOutputInCommitment , Option < Signature > , Option < HTLCSource > ) > , claimed_htlcs : & [ ( SentHTLCId , PaymentPreimage ) ] ) -> Result < ( ) , & ' static str > {
2164
+ let trusted_tx = holder_commitment_tx. trust ( ) ;
2165
+ let txid = trusted_tx. txid ( ) ;
2166
+ let tx_keys = trusted_tx. keys ( ) ;
2167
+ self . current_holder_commitment_number = trusted_tx. commitment_number ( ) ;
2168
+ let mut new_holder_commitment_tx = HolderSignedTx {
2169
+ txid,
2170
+ revocation_key : tx_keys. revocation_key ,
2171
+ a_htlc_key : tx_keys. broadcaster_htlc_key ,
2172
+ b_htlc_key : tx_keys. countersignatory_htlc_key ,
2173
+ delayed_payment_key : tx_keys. broadcaster_delayed_payment_key ,
2174
+ per_commitment_point : tx_keys. per_commitment_point ,
2175
+ htlc_outputs,
2176
+ to_self_value_sat : holder_commitment_tx. to_broadcaster_value_sat ( ) ,
2177
+ feerate_per_kw : trusted_tx. feerate_per_kw ( ) ,
2148
2178
} ;
2149
2179
self . onchain_tx_handler . provide_latest_holder_tx ( holder_commitment_tx) ;
2150
2180
mem:: swap ( & mut new_holder_commitment_tx, & mut self . current_holder_commitment_tx ) ;
2151
2181
self . prev_holder_signed_commitment_tx = Some ( new_holder_commitment_tx) ;
2182
+ for ( claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2183
+ #[ cfg( debug_assertions) ] {
2184
+ let cur_counterparty_htlcs = self . counterparty_claimable_outpoints . get (
2185
+ & self . current_counterparty_commitment_txid . unwrap ( ) ) . unwrap ( ) ;
2186
+ assert ! ( cur_counterparty_htlcs. iter( ) . any( |( _, source_opt) | {
2187
+ if let Some ( source) = source_opt {
2188
+ SentHTLCId :: from_source( source) == * claimed_htlc_id
2189
+ } else { false }
2190
+ } ) ) ;
2191
+ }
2192
+ self . counterparty_fulfilled_htlcs . insert ( * claimed_htlc_id, * claimed_preimage) ;
2193
+ }
2152
2194
if self . holder_tx_signed {
2153
2195
return Err ( "Latest holder commitment signed has already been signed, update is rejected" ) ;
2154
2196
}
@@ -2243,10 +2285,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2243
2285
let bounded_fee_estimator = LowerBoundedFeeEstimator :: new ( & * fee_estimator) ;
2244
2286
for update in updates. updates . iter ( ) {
2245
2287
match update {
2246
- ChannelMonitorUpdateStep :: LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
2288
+ ChannelMonitorUpdateStep :: LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs } => {
2247
2289
log_trace ! ( logger, "Updating ChannelMonitor with latest holder commitment transaction info" ) ;
2248
2290
if self . lockdown_from_offchain { panic ! ( ) ; }
2249
- if let Err ( e) = self . provide_latest_holder_commitment_tx ( commitment_tx. clone ( ) , htlc_outputs. clone ( ) ) {
2291
+ if let Err ( e) = self . provide_latest_holder_commitment_tx ( commitment_tx. clone ( ) , htlc_outputs. clone ( ) , & claimed_htlcs ) {
2250
2292
log_error ! ( logger, "Providing latest holder commitment transaction failed/was refused:" ) ;
2251
2293
log_error ! ( logger, " {}" , e) ;
2252
2294
ret = Err ( ( ) ) ;
@@ -3868,6 +3910,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
3868
3910
let mut counterparty_node_id = None ;
3869
3911
let mut confirmed_commitment_tx_counterparty_output = None ;
3870
3912
let mut spendable_txids_confirmed = Some ( Vec :: new ( ) ) ;
3913
+ let mut counterparty_fulfilled_htlcs = Some ( HashMap :: new ( ) ) ;
3871
3914
read_tlv_fields ! ( reader, {
3872
3915
( 1 , funding_spend_confirmed, option) ,
3873
3916
( 3 , htlcs_resolved_on_chain, vec_type) ,
@@ -3876,6 +3919,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
3876
3919
( 9 , counterparty_node_id, option) ,
3877
3920
( 11 , confirmed_commitment_tx_counterparty_output, option) ,
3878
3921
( 13 , spendable_txids_confirmed, vec_type) ,
3922
+ ( 15 , counterparty_fulfilled_htlcs, option) ,
3879
3923
} ) ;
3880
3924
3881
3925
Ok ( ( best_block. block_hash ( ) , ChannelMonitor :: from_impl ( ChannelMonitorImpl {
@@ -3904,6 +3948,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
3904
3948
counterparty_claimable_outpoints,
3905
3949
counterparty_commitment_txn_on_chain,
3906
3950
counterparty_hash_commitment_number,
3951
+ counterparty_fulfilled_htlcs : counterparty_fulfilled_htlcs. unwrap ( ) ,
3907
3952
3908
3953
prev_holder_signed_commitment_tx,
3909
3954
current_holder_commitment_tx,
@@ -4077,7 +4122,6 @@ mod tests {
4077
4122
let fee_estimator = TestFeeEstimator { sat_per_kw : Mutex :: new ( 253 ) } ;
4078
4123
4079
4124
let dummy_key = PublicKey :: from_secret_key ( & secp_ctx, & SecretKey :: from_slice ( & [ 42 ; 32 ] ) . unwrap ( ) ) ;
4080
- let dummy_tx = Transaction { version : 0 , lock_time : PackedLockTime :: ZERO , input : Vec :: new ( ) , output : Vec :: new ( ) } ;
4081
4125
4082
4126
let mut preimages = Vec :: new ( ) ;
4083
4127
{
@@ -4167,11 +4211,10 @@ mod tests {
4167
4211
HolderCommitmentTransaction :: dummy ( ) , best_block, dummy_key) ;
4168
4212
4169
4213
monitor. provide_latest_holder_commitment_tx ( HolderCommitmentTransaction :: dummy ( ) , preimages_to_holder_htlcs ! ( preimages[ 0 ..10 ] ) ) . unwrap ( ) ;
4170
- let dummy_txid = dummy_tx. txid ( ) ;
4171
- monitor. provide_latest_counterparty_commitment_tx ( dummy_txid, preimages_slice_to_htlc_outputs ! ( preimages[ 5 ..15 ] ) , 281474976710655 , dummy_key, & logger) ;
4172
- monitor. provide_latest_counterparty_commitment_tx ( dummy_txid, preimages_slice_to_htlc_outputs ! ( preimages[ 15 ..20 ] ) , 281474976710654 , dummy_key, & logger) ;
4173
- monitor. provide_latest_counterparty_commitment_tx ( dummy_txid, preimages_slice_to_htlc_outputs ! ( preimages[ 17 ..20 ] ) , 281474976710653 , dummy_key, & logger) ;
4174
- monitor. provide_latest_counterparty_commitment_tx ( dummy_txid, preimages_slice_to_htlc_outputs ! ( preimages[ 18 ..20 ] ) , 281474976710652 , dummy_key, & logger) ;
4214
+ monitor. provide_latest_counterparty_commitment_tx ( Txid :: from_inner ( Sha256 :: hash ( b"1" ) . into_inner ( ) ) ,
4215
+ preimages_slice_to_htlc_outputs ! ( preimages[ 5 ..15 ] ) , 281474976710655 , dummy_key, & logger) ;
4216
+ monitor. provide_latest_counterparty_commitment_tx ( Txid :: from_inner ( Sha256 :: hash ( b"2" ) . into_inner ( ) ) ,
4217
+ preimages_slice_to_htlc_outputs ! ( preimages[ 15 ..20 ] ) , 281474976710654 , dummy_key, & logger) ;
4175
4218
for & ( ref preimage, ref hash) in preimages. iter ( ) {
4176
4219
let bounded_fee_estimator = LowerBoundedFeeEstimator :: new ( & fee_estimator) ;
4177
4220
monitor. provide_payment_preimage ( hash, preimage, & broadcaster, & bounded_fee_estimator, & logger) ;
@@ -4185,13 +4228,19 @@ mod tests {
4185
4228
test_preimages_exist ! ( & preimages[ 0 ..10 ] , monitor) ;
4186
4229
test_preimages_exist ! ( & preimages[ 15 ..20 ] , monitor) ;
4187
4230
4231
+ monitor. provide_latest_counterparty_commitment_tx ( Txid :: from_inner ( Sha256 :: hash ( b"3" ) . into_inner ( ) ) ,
4232
+ preimages_slice_to_htlc_outputs ! ( preimages[ 17 ..20 ] ) , 281474976710653 , dummy_key, & logger) ;
4233
+
4188
4234
// Now provide a further secret, pruning preimages 15-17
4189
4235
secret[ 0 ..32 ] . clone_from_slice ( & hex:: decode ( "c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964" ) . unwrap ( ) ) ;
4190
4236
monitor. provide_secret ( 281474976710654 , secret. clone ( ) ) . unwrap ( ) ;
4191
4237
assert_eq ! ( monitor. inner. lock( ) . unwrap( ) . payment_preimages. len( ) , 13 ) ;
4192
4238
test_preimages_exist ! ( & preimages[ 0 ..10 ] , monitor) ;
4193
4239
test_preimages_exist ! ( & preimages[ 17 ..20 ] , monitor) ;
4194
4240
4241
+ monitor. provide_latest_counterparty_commitment_tx ( Txid :: from_inner ( Sha256 :: hash ( b"4" ) . into_inner ( ) ) ,
4242
+ preimages_slice_to_htlc_outputs ! ( preimages[ 18 ..20 ] ) , 281474976710652 , dummy_key, & logger) ;
4243
+
4195
4244
// Now update holder commitment tx info, pruning only element 18 as we still care about the
4196
4245
// previous commitment tx's preimages too
4197
4246
monitor. provide_latest_holder_commitment_tx ( HolderCommitmentTransaction :: dummy ( ) , preimages_to_holder_htlcs ! ( preimages[ 0 ..5 ] ) ) . unwrap ( ) ;
0 commit comments