@@ -424,14 +424,36 @@ pub(super) enum RAACommitmentOrder {
424
424
RevokeAndACKFirst ,
425
425
}
426
426
427
+ /// Information about a payment which is currently being claimed.
428
+ struct ClaimingPayment {
429
+ amount_msat : u64 ,
430
+ payment_purpose : events:: PaymentPurpose ,
431
+ receiver_node_id : PublicKey ,
432
+ }
433
+ impl_writeable_tlv_based ! ( ClaimingPayment , {
434
+ ( 0 , amount_msat, required) ,
435
+ ( 2 , payment_purpose, required) ,
436
+ ( 4 , receiver_node_id, required) ,
437
+ } ) ;
438
+
427
439
/// Information about claimable or being-claimed payments
428
440
struct ClaimablePayments {
429
441
/// Map from payment hash to the payment data and any HTLCs which are to us and can be
430
442
/// failed/claimed by the user.
431
443
///
432
444
/// Note that, no consistency guarantees are made about the channels given here actually
433
445
/// existing anymore by the time you go to read them!
446
+ ///
447
+ /// When adding to the map, [`Self::pending_claimed_payments`] must also be checked to ensure
448
+ /// we don't get a duplicate payment.
434
449
claimable_htlcs : HashMap < PaymentHash , ( events:: PaymentPurpose , Vec < ClaimableHTLC > ) > ,
450
+
451
+ /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
452
+ /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
453
+ /// as an [`events::Event::PaymentClaimed`].
454
+ ///
455
+ /// See `ChannelManager` struct-level documentation for lock order requirements.
456
+ pending_claimed_payments : HashMap < PaymentHash , ClaimingPayment > ,
435
457
}
436
458
437
459
// Note this is only exposed in cfg(test):
@@ -800,6 +822,9 @@ pub struct ChannelManager<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
800
822
/// The sets of payments which are claimable or currently being claimed. See
801
823
/// [`ClaimablePayments`]' individual field docs for more info.
802
824
///
825
+ /// When adding to the map, [`Self::pending_claimed_payments`] must also be checked (under the
826
+ /// same lock) to ensure we don't get a duplicate payment.
827
+ ///
803
828
/// See `ChannelManager` struct-level documentation for lock order requirements.
804
829
claimable_payments : Mutex < ClaimablePayments > ,
805
830
@@ -1607,7 +1632,7 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
1607
1632
pending_inbound_payments : Mutex :: new ( HashMap :: new ( ) ) ,
1608
1633
pending_outbound_payments : Mutex :: new ( HashMap :: new ( ) ) ,
1609
1634
forward_htlcs : Mutex :: new ( HashMap :: new ( ) ) ,
1610
- claimable_payments : Mutex :: new ( ClaimablePayments { claimable_htlcs : HashMap :: new ( ) } ) ,
1635
+ claimable_payments : Mutex :: new ( ClaimablePayments { claimable_htlcs : HashMap :: new ( ) , pending_claimed_payments : HashMap :: new ( ) } ) ,
1611
1636
pending_intercepted_htlcs : Mutex :: new ( HashMap :: new ( ) ) ,
1612
1637
id_to_peer : Mutex :: new ( HashMap :: new ( ) ) ,
1613
1638
short_to_chan_info : FairRwLock :: new ( HashMap :: new ( ) ) ,
@@ -3491,6 +3516,10 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
3491
3516
}
3492
3517
} ;
3493
3518
let mut claimable_payments = self . claimable_payments. lock( ) . unwrap( ) ;
3519
+ if claimable_payments. pending_claimed_payments. contains_key( & payment_hash) {
3520
+ fail_htlc!( claimable_htlc, payment_hash) ;
3521
+ continue
3522
+ }
3494
3523
let ( _, htlcs) = claimable_payments. claimable_htlcs. entry( payment_hash)
3495
3524
. or_insert_with( || ( purpose( ) , Vec :: new( ) ) ) ;
3496
3525
if htlcs. len( ) == 1 {
@@ -3563,7 +3592,12 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
3563
3592
check_total_value ! ( payment_data, payment_preimage) ;
3564
3593
} ,
3565
3594
OnionPayload :: Spontaneous ( preimage) => {
3566
- match self . claimable_payments . lock ( ) . unwrap ( ) . claimable_htlcs . entry ( payment_hash) {
3595
+ let mut claimable_payments = self . claimable_payments . lock ( ) . unwrap ( ) ;
3596
+ if claimable_payments. pending_claimed_payments . contains_key ( & payment_hash) {
3597
+ fail_htlc ! ( claimable_htlc, payment_hash) ;
3598
+ continue
3599
+ }
3600
+ match claimable_payments. claimable_htlcs . entry ( payment_hash) {
3567
3601
hash_map:: Entry :: Vacant ( e) => {
3568
3602
let purpose = events:: PaymentPurpose :: SpontaneousPayment ( preimage) ;
3569
3603
e. insert ( ( purpose. clone ( ) , vec ! [ claimable_htlc] ) ) ;
@@ -4215,126 +4249,142 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
4215
4249
4216
4250
let _persistence_guard = PersistenceNotifierGuard :: notify_on_drop ( & self . total_consistency_lock , & self . persistence_notifier ) ;
4217
4251
4218
- let removed_source = self . claimable_payments . lock ( ) . unwrap ( ) . claimable_htlcs . remove ( & payment_hash) ;
4219
- if let Some ( ( payment_purpose, mut sources) ) = removed_source {
4220
- assert ! ( !sources. is_empty( ) ) ;
4221
-
4222
- // If we are claiming an MPP payment, we have to take special care to ensure that each
4223
- // channel exists before claiming all of the payments (inside one lock).
4224
- // Note that channel existance is sufficient as we should always get a monitor update
4225
- // which will take care of the real HTLC claim enforcement.
4226
- //
4227
- // If we find an HTLC which we would need to claim but for which we do not have a
4228
- // channel, we will fail all parts of the MPP payment. While we could wait and see if
4229
- // the sender retries the already-failed path(s), it should be a pretty rare case where
4230
- // we got all the HTLCs and then a channel closed while we were waiting for the user to
4231
- // provide the preimage, so worrying too much about the optimal handling isn't worth
4232
- // it.
4233
- let mut claimable_amt_msat = 0 ;
4234
- let mut expected_amt_msat = None ;
4235
- let mut valid_mpp = true ;
4236
- let mut errs = Vec :: new ( ) ;
4237
- let mut claimed_any_htlcs = false ;
4238
- let mut channel_state_lock = self . channel_state . lock ( ) . unwrap ( ) ;
4239
- let channel_state = & mut * channel_state_lock;
4240
- let mut receiver_node_id = Some ( self . our_network_pubkey ) ;
4241
- for htlc in sources. iter ( ) {
4242
- let chan_id = match self . short_to_chan_info . read ( ) . unwrap ( ) . get ( & htlc. prev_hop . short_channel_id ) {
4243
- Some ( ( _cp_id, chan_id) ) => chan_id. clone ( ) ,
4244
- None => {
4245
- valid_mpp = false ;
4252
+ let mut sources = {
4253
+ let mut claimable_payments = self . claimable_payments . lock ( ) . unwrap ( ) ;
4254
+ if let Some ( ( payment_purpose, sources) ) = claimable_payments. claimable_htlcs . remove ( & payment_hash) {
4255
+ let mut receiver_node_id = self . our_network_pubkey ;
4256
+ for htlc in sources. iter ( ) {
4257
+ if htlc. prev_hop . phantom_shared_secret . is_some ( ) {
4258
+ let phantom_pubkey = self . keys_manager . get_node_id ( Recipient :: PhantomNode )
4259
+ . expect ( "Failed to get node_id for phantom node recipient" ) ;
4260
+ receiver_node_id = phantom_pubkey;
4246
4261
break ;
4247
4262
}
4248
- } ;
4263
+ }
4249
4264
4250
- if let None = channel_state. by_id . get ( & chan_id) {
4251
- valid_mpp = false ;
4252
- break ;
4265
+ let dup_purpose = claimable_payments. pending_claimed_payments . insert ( payment_hash,
4266
+ ClaimingPayment { amount_msat : sources. iter ( ) . map ( |source| source. value ) . sum ( ) ,
4267
+ payment_purpose, receiver_node_id,
4268
+ } ) ;
4269
+ if dup_purpose. is_some ( ) {
4270
+ debug_assert ! ( false , "Shouldn't get a duplicate pending claim event ever" ) ;
4271
+ log_error ! ( self . logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug" ,
4272
+ log_bytes!( payment_hash. 0 ) ) ;
4253
4273
}
4274
+ sources
4275
+ } else { return ; }
4276
+ } ;
4277
+ debug_assert ! ( !sources. is_empty( ) ) ;
4254
4278
4255
- if expected_amt_msat. is_some ( ) && expected_amt_msat != Some ( htlc. total_msat ) {
4256
- log_error ! ( self . logger, "Somehow ended up with an MPP payment with different total amounts - this should not be reachable!" ) ;
4257
- debug_assert ! ( false ) ;
4279
+ // If we are claiming an MPP payment, we have to take special care to ensure that each
4280
+ // channel exists before claiming all of the payments (inside one lock).
4281
+ // Note that channel existance is sufficient as we should always get a monitor update
4282
+ // which will take care of the real HTLC claim enforcement.
4283
+ //
4284
+ // If we find an HTLC which we would need to claim but for which we do not have a
4285
+ // channel, we will fail all parts of the MPP payment. While we could wait and see if
4286
+ // the sender retries the already-failed path(s), it should be a pretty rare case where
4287
+ // we got all the HTLCs and then a channel closed while we were waiting for the user to
4288
+ // provide the preimage, so worrying too much about the optimal handling isn't worth
4289
+ // it.
4290
+ let mut claimable_amt_msat = 0 ;
4291
+ let mut expected_amt_msat = None ;
4292
+ let mut valid_mpp = true ;
4293
+ let mut errs = Vec :: new ( ) ;
4294
+ let mut claimed_any_htlcs = false ;
4295
+ let mut channel_state_lock = self . channel_state . lock ( ) . unwrap ( ) ;
4296
+ let channel_state = & mut * channel_state_lock;
4297
+ for htlc in sources. iter ( ) {
4298
+ let chan_id = match self . short_to_chan_info . read ( ) . unwrap ( ) . get ( & htlc. prev_hop . short_channel_id ) {
4299
+ Some ( ( _cp_id, chan_id) ) => chan_id. clone ( ) ,
4300
+ None => {
4258
4301
valid_mpp = false ;
4259
4302
break ;
4260
4303
}
4261
- expected_amt_msat = Some ( htlc. total_msat ) ;
4262
- if let OnionPayload :: Spontaneous ( _) = & htlc. onion_payload {
4263
- // We don't currently support MPP for spontaneous payments, so just check
4264
- // that there's one payment here and move on.
4265
- if sources. len ( ) != 1 {
4266
- log_error ! ( self . logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!" ) ;
4267
- debug_assert ! ( false ) ;
4268
- valid_mpp = false ;
4269
- break ;
4270
- }
4271
- }
4272
- let phantom_shared_secret = htlc. prev_hop . phantom_shared_secret ;
4273
- if phantom_shared_secret. is_some ( ) {
4274
- let phantom_pubkey = self . keys_manager . get_node_id ( Recipient :: PhantomNode )
4275
- . expect ( "Failed to get node_id for phantom node recipient" ) ;
4276
- receiver_node_id = Some ( phantom_pubkey)
4277
- }
4304
+ } ;
4278
4305
4279
- claimable_amt_msat += htlc. value ;
4280
- }
4281
- if sources. is_empty ( ) || expected_amt_msat. is_none ( ) {
4282
- log_info ! ( self . logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!" ) ;
4283
- return ;
4306
+ if let None = channel_state. by_id . get ( & chan_id) {
4307
+ valid_mpp = false ;
4308
+ break ;
4284
4309
}
4285
- if claimable_amt_msat != expected_amt_msat. unwrap ( ) {
4286
- log_info ! ( self . logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim." ,
4287
- expected_amt_msat. unwrap( ) , claimable_amt_msat) ;
4288
- return ;
4310
+
4311
+ if expected_amt_msat. is_some ( ) && expected_amt_msat != Some ( htlc. total_msat ) {
4312
+ log_error ! ( self . logger, "Somehow ended up with an MPP payment with different total amounts - this should not be reachable!" ) ;
4313
+ debug_assert ! ( false ) ;
4314
+ valid_mpp = false ;
4315
+ break ;
4289
4316
}
4290
- if valid_mpp {
4291
- for htlc in sources. drain ( ..) {
4292
- match self . claim_funds_from_hop ( & mut channel_state_lock, htlc. prev_hop , payment_preimage) {
4293
- ClaimFundsFromHop :: MonitorUpdateFail ( pk, err, _) => {
4294
- if let msgs:: ErrorAction :: IgnoreError = err. err . action {
4295
- // We got a temporary failure updating monitor, but will claim the
4296
- // HTLC when the monitor updating is restored (or on chain).
4297
- log_error ! ( self . logger, "Temporary failure claiming HTLC, treating as success: {}" , err. err. err) ;
4298
- claimed_any_htlcs = true ;
4299
- } else { errs. push ( ( pk, err) ) ; }
4300
- } ,
4301
- ClaimFundsFromHop :: PrevHopForceClosed => unreachable ! ( "We already checked for channel existence, we can't fail here!" ) ,
4302
- ClaimFundsFromHop :: DuplicateClaim => {
4303
- // While we should never get here in most cases, if we do, it likely
4304
- // indicates that the HTLC was timed out some time ago and is no longer
4305
- // available to be claimed. Thus, it does not make sense to set
4306
- // `claimed_any_htlcs`.
4307
- } ,
4308
- ClaimFundsFromHop :: Success ( _) => claimed_any_htlcs = true ,
4309
- }
4317
+ expected_amt_msat = Some ( htlc. total_msat ) ;
4318
+ if let OnionPayload :: Spontaneous ( _) = & htlc. onion_payload {
4319
+ // We don't currently support MPP for spontaneous payments, so just check
4320
+ // that there's one payment here and move on.
4321
+ if sources. len ( ) != 1 {
4322
+ log_error ! ( self . logger, "Somehow ended up with an MPP spontaneous payment - this should not be reachable!" ) ;
4323
+ debug_assert ! ( false ) ;
4324
+ valid_mpp = false ;
4325
+ break ;
4310
4326
}
4311
4327
}
4312
- mem:: drop ( channel_state_lock) ;
4313
- if !valid_mpp {
4314
- for htlc in sources. drain ( ..) {
4315
- let mut htlc_msat_height_data = htlc. value . to_be_bytes ( ) . to_vec ( ) ;
4316
- htlc_msat_height_data. extend_from_slice ( & self . best_block . read ( ) . unwrap ( ) . height ( ) . to_be_bytes ( ) ) ;
4317
- let source = HTLCSource :: PreviousHopData ( htlc. prev_hop ) ;
4318
- let reason = HTLCFailReason :: reason ( 0x4000 | 15 , htlc_msat_height_data) ;
4319
- let receiver = HTLCDestination :: FailedPayment { payment_hash } ;
4320
- self . fail_htlc_backwards_internal ( & source, & payment_hash, & reason, receiver) ;
4328
+
4329
+ claimable_amt_msat += htlc. value ;
4330
+ }
4331
+ if sources. is_empty ( ) || expected_amt_msat. is_none ( ) {
4332
+ self . claimable_payments . lock ( ) . unwrap ( ) . pending_claimed_payments . remove ( & payment_hash) ;
4333
+ log_info ! ( self . logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!" ) ;
4334
+ return ;
4335
+ }
4336
+ if claimable_amt_msat != expected_amt_msat. unwrap ( ) {
4337
+ self . claimable_payments . lock ( ) . unwrap ( ) . pending_claimed_payments . remove ( & payment_hash) ;
4338
+ log_info ! ( self . logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim." ,
4339
+ expected_amt_msat. unwrap( ) , claimable_amt_msat) ;
4340
+ return ;
4341
+ }
4342
+ if valid_mpp {
4343
+ for htlc in sources. drain ( ..) {
4344
+ match self . claim_funds_from_hop ( & mut channel_state_lock, htlc. prev_hop , payment_preimage) {
4345
+ ClaimFundsFromHop :: MonitorUpdateFail ( pk, err, _) => {
4346
+ if let msgs:: ErrorAction :: IgnoreError = err. err . action {
4347
+ // We got a temporary failure updating monitor, but will claim the
4348
+ // HTLC when the monitor updating is restored (or on chain).
4349
+ log_error ! ( self . logger, "Temporary failure claiming HTLC, treating as success: {}" , err. err. err) ;
4350
+ claimed_any_htlcs = true ;
4351
+ } else { errs. push ( ( pk, err) ) ; }
4352
+ } ,
4353
+ ClaimFundsFromHop :: PrevHopForceClosed => unreachable ! ( "We already checked for channel existence, we can't fail here!" ) ,
4354
+ ClaimFundsFromHop :: DuplicateClaim => {
4355
+ // While we should never get here in most cases, if we do, it likely
4356
+ // indicates that the HTLC was timed out some time ago and is no longer
4357
+ // available to be claimed. Thus, it does not make sense to set
4358
+ // `claimed_any_htlcs`.
4359
+ } ,
4360
+ ClaimFundsFromHop :: Success ( _) => claimed_any_htlcs = true ,
4321
4361
}
4322
4362
}
4323
-
4324
- if claimed_any_htlcs {
4325
- self . pending_events . lock ( ) . unwrap ( ) . push ( events:: Event :: PaymentClaimed {
4326
- receiver_node_id,
4327
- payment_hash,
4328
- purpose : payment_purpose,
4329
- amount_msat : claimable_amt_msat,
4330
- } ) ;
4363
+ }
4364
+ mem:: drop ( channel_state_lock) ;
4365
+ if !valid_mpp {
4366
+ for htlc in sources. drain ( ..) {
4367
+ let mut htlc_msat_height_data = htlc. value . to_be_bytes ( ) . to_vec ( ) ;
4368
+ htlc_msat_height_data. extend_from_slice ( & self . best_block . read ( ) . unwrap ( ) . height ( ) . to_be_bytes ( ) ) ;
4369
+ let source = HTLCSource :: PreviousHopData ( htlc. prev_hop ) ;
4370
+ let reason = HTLCFailReason :: reason ( 0x4000 | 15 , htlc_msat_height_data) ;
4371
+ let receiver = HTLCDestination :: FailedPayment { payment_hash } ;
4372
+ self . fail_htlc_backwards_internal ( & source, & payment_hash, & reason, receiver) ;
4331
4373
}
4374
+ }
4332
4375
4333
- // Now we can handle any errors which were generated.
4334
- for ( counterparty_node_id, err) in errs. drain ( ..) {
4335
- let res: Result < ( ) , _ > = Err ( err) ;
4336
- let _ = handle_error ! ( self , res, counterparty_node_id) ;
4337
- }
4376
+ let ClaimingPayment { amount_msat, payment_purpose : purpose, receiver_node_id } =
4377
+ self . claimable_payments . lock ( ) . unwrap ( ) . pending_claimed_payments . remove ( & payment_hash) . unwrap ( ) ;
4378
+ if claimed_any_htlcs {
4379
+ self . pending_events . lock ( ) . unwrap ( ) . push ( events:: Event :: PaymentClaimed {
4380
+ payment_hash, purpose, amount_msat, receiver_node_id : Some ( receiver_node_id) ,
4381
+ } ) ;
4382
+ }
4383
+
4384
+ // Now we can handle any errors which were generated.
4385
+ for ( counterparty_node_id, err) in errs. drain ( ..) {
4386
+ let res: Result < ( ) , _ > = Err ( err) ;
4387
+ let _ = handle_error ! ( self , res, counterparty_node_id) ;
4338
4388
}
4339
4389
}
4340
4390
@@ -7242,10 +7292,21 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable for ChannelMana
7242
7292
if our_pending_intercepts. len ( ) != 0 {
7243
7293
pending_intercepted_htlcs = Some ( our_pending_intercepts) ;
7244
7294
}
7295
+
7296
+ let mut pending_claimed_payments = Some ( & claimable_payments. pending_claimed_payments ) ;
7297
+ if pending_claimed_payments. as_ref ( ) . unwrap ( ) . is_empty ( ) {
7298
+ // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
7299
+ // map. Thus, if there are no entries we skip writing a TLV for it.
7300
+ pending_claimed_payments = None ;
7301
+ } else {
7302
+ debug_assert ! ( false , "While we have code to serialize pending_claimed_payments, the map should always be empty until a later PR" ) ;
7303
+ }
7304
+
7245
7305
write_tlv_fields ! ( writer, {
7246
7306
( 1 , pending_outbound_payments_no_retry, required) ,
7247
7307
( 2 , pending_intercepted_htlcs, option) ,
7248
7308
( 3 , pending_outbound_payments, required) ,
7309
+ ( 4 , pending_claimed_payments, option) ,
7249
7310
( 5 , self . our_network_pubkey, required) ,
7250
7311
( 7 , self . fake_scid_rand_bytes, required) ,
7251
7312
( 9 , htlc_purposes, vec_type) ,
@@ -7572,10 +7633,12 @@ impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
7572
7633
let mut fake_scid_rand_bytes: Option < [ u8 ; 32 ] > = None ;
7573
7634
let mut probing_cookie_secret: Option < [ u8 ; 32 ] > = None ;
7574
7635
let mut claimable_htlc_purposes = None ;
7636
+ let mut pending_claimed_payments = Some ( HashMap :: new ( ) ) ;
7575
7637
read_tlv_fields ! ( reader, {
7576
7638
( 1 , pending_outbound_payments_no_retry, option) ,
7577
7639
( 2 , pending_intercepted_htlcs, option) ,
7578
7640
( 3 , pending_outbound_payments, option) ,
7641
+ ( 4 , pending_claimed_payments, option) ,
7579
7642
( 5 , received_network_pubkey, option) ,
7580
7643
( 7 , fake_scid_rand_bytes, option) ,
7581
7644
( 9 , claimable_htlc_purposes, vec_type) ,
@@ -7834,7 +7897,7 @@ impl<'a, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
7834
7897
pending_intercepted_htlcs : Mutex :: new ( pending_intercepted_htlcs. unwrap ( ) ) ,
7835
7898
7836
7899
forward_htlcs : Mutex :: new ( forward_htlcs) ,
7837
- claimable_payments : Mutex :: new ( ClaimablePayments { claimable_htlcs } ) ,
7900
+ claimable_payments : Mutex :: new ( ClaimablePayments { claimable_htlcs, pending_claimed_payments : pending_claimed_payments . unwrap ( ) } ) ,
7838
7901
outbound_scid_aliases : Mutex :: new ( outbound_scid_aliases) ,
7839
7902
id_to_peer : Mutex :: new ( id_to_peer) ,
7840
7903
short_to_chan_info : FairRwLock :: new ( short_to_chan_info) ,
0 commit comments