@@ -23,11 +23,12 @@ use bitcoin::secp256k1;
23
23
24
24
use ln:: msgs:: DecodeError ;
25
25
use ln:: PaymentPreimage ;
26
+ use ln:: chan_utils;
26
27
use ln:: chan_utils:: { ChannelTransactionParameters , HolderCommitmentTransaction } ;
27
- use chain:: chaininterface:: { FeeEstimator , BroadcasterInterface , LowerBoundedFeeEstimator } ;
28
+ use chain:: chaininterface:: { ConfirmationTarget , FeeEstimator , BroadcasterInterface , LowerBoundedFeeEstimator } ;
28
29
use chain:: channelmonitor:: { ANTI_REORG_DELAY , CLTV_SHARED_CLAIM_BUFFER } ;
29
30
use chain:: keysinterface:: { Sign , KeysInterface } ;
30
- use chain:: package:: PackageTemplate ;
31
+ use chain:: package:: { PackageSolvingData , PackageTemplate } ;
31
32
use util:: logger:: Logger ;
32
33
use util:: ser:: { Readable , ReadableArgs , MaybeReadable , Writer , Writeable , VecWriter } ;
33
34
use util:: byte_utils;
@@ -162,11 +163,27 @@ impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
162
163
}
163
164
}
164
165
166
+ // Represents the different types of claims for which events are yielded externally to satisfy said
167
+ // claims.
168
+ #[ allow( dead_code) ] // TODO: remove-on-anchors-release
169
+ pub ( crate ) enum ClaimEvent {
170
+ /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
171
+ /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
172
+ BumpCommitment {
173
+ package_target_feerate_sat_per_1000_weight : u32 ,
174
+ commitment_tx : Transaction ,
175
+ anchor_output_idx : u32 ,
176
+ } ,
177
+ }
178
+
165
179
/// Represents the different ways an output can be claimed (i.e., spent to an address under our
166
180
/// control) onchain.
167
181
pub ( crate ) enum OnchainClaim {
168
182
/// A finalized transaction pending confirmation spending the output to claim.
169
183
Tx ( Transaction ) ,
184
+ /// An event yielded externally to signal additional inputs must be added to a transaction
185
+ /// pending confirmation spending the output to claim.
186
+ Event ( ClaimEvent ) ,
170
187
}
171
188
172
189
/// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
@@ -199,6 +216,7 @@ pub struct OnchainTxHandler<ChannelSigner: Sign> {
199
216
pub ( crate ) pending_claim_requests : HashMap < Txid , PackageTemplate > ,
200
217
#[ cfg( not( test) ) ]
201
218
pending_claim_requests : HashMap < Txid , PackageTemplate > ,
219
+ pending_claim_events : HashMap < Txid , ClaimEvent > ,
202
220
203
221
// Used to link outpoints claimed in a connected block to a pending claim request.
204
222
// Key is outpoint than monitor parsing has detected we have keys/scripts to claim
@@ -348,6 +366,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
348
366
locktimed_packages,
349
367
pending_claim_requests,
350
368
onchain_events_awaiting_threshold_conf,
369
+ pending_claim_events : HashMap :: new ( ) ,
351
370
secp_ctx,
352
371
} )
353
372
}
@@ -367,6 +386,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
367
386
claimable_outpoints : HashMap :: new ( ) ,
368
387
locktimed_packages : BTreeMap :: new ( ) ,
369
388
onchain_events_awaiting_threshold_conf : Vec :: new ( ) ,
389
+ pending_claim_events : HashMap :: new ( ) ,
370
390
371
391
secp_ctx,
372
392
}
@@ -380,10 +400,14 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
380
400
self . holder_commitment . to_broadcaster_value_sat ( )
381
401
}
382
402
383
- /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration
384
- /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent.
385
- /// Panics if there are signing errors, because signing operations in reaction to on-chain events
386
- /// are not expected to fail, and if they do, we may lose funds.
403
+ /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
404
+ /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
405
+ /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
406
+ /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
407
+ /// Child-Pay-For-Parent.
408
+ ///
409
+ /// Panics if there are signing errors, because signing operations in reaction to on-chain
410
+ /// events are not expected to fail, and if they do, we may lose funds.
387
411
fn generate_claim < F : Deref , L : Deref > ( & mut self , cur_height : u32 , cached_request : & PackageTemplate , fee_estimator : & LowerBoundedFeeEstimator < F > , logger : & L ) -> Option < ( Option < u32 > , u64 , OnchainClaim ) >
388
412
where F :: Target : FeeEstimator ,
389
413
L :: Target : Logger ,
@@ -405,12 +429,60 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
405
429
return Some ( ( new_timer, new_feerate, OnchainClaim :: Tx ( transaction) ) )
406
430
}
407
431
} else {
408
- // Note: Currently, amounts of holder outputs spending witnesses aren't used
409
- // as we can't malleate spending package to increase their feerate. This
410
- // should change with the remaining anchor output patchset.
411
- if let Some ( transaction) = cached_request. finalize_untractable_package ( self , logger) {
412
- return Some ( ( None , 0 , OnchainClaim :: Tx ( transaction) ) ) ;
432
+ // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
433
+ // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
434
+ // which require external funding.
435
+ let inputs = cached_request. inputs ( ) ;
436
+ debug_assert_eq ! ( inputs. len( ) , 1 ) ;
437
+ let tx = match cached_request. finalize_untractable_package ( self , logger) {
438
+ Some ( tx) => tx,
439
+ None => return None ,
440
+ } ;
441
+ if !cached_request. requires_external_funding ( ) {
442
+ return Some ( ( None , 0 , OnchainClaim :: Tx ( tx) ) ) ;
413
443
}
444
+ return inputs. iter ( ) . find_map ( |input| match input {
445
+ // Commitment inputs with anchors support are the only untractable inputs supported
446
+ // thus far that require external funding.
447
+ PackageSolvingData :: HolderFundingOutput ( ..) => {
448
+ debug_assert_eq ! ( tx. txid( ) , self . holder_commitment. trust( ) . txid( ) ,
449
+ "Holder commitment transaction mismatch" ) ;
450
+ // We'll locate an anchor output we can spend within the commitment transaction.
451
+ let funding_pubkey = & self . channel_transaction_parameters . holder_pubkeys . funding_pubkey ;
452
+ match chan_utils:: get_anchor_output ( & tx, funding_pubkey) {
453
+ // An anchor output was found, so we should yield a funding event externally.
454
+ Some ( ( idx, _) ) => {
455
+ // Our target feerate will depend on whether we have any HTLCs present
456
+ // within our commitment.
457
+ let conf_target = if self . holder_commitment . trust ( ) . htlcs ( ) . is_empty ( ) {
458
+ ConfirmationTarget :: Background
459
+ } else {
460
+ ConfirmationTarget :: HighPriority
461
+ } ;
462
+ let package_target_feerate_sat_per_1000_weight = cached_request
463
+ . compute_package_feerate ( fee_estimator, conf_target) ;
464
+ Some ( (
465
+ new_timer,
466
+ package_target_feerate_sat_per_1000_weight as u64 ,
467
+ OnchainClaim :: Event ( ClaimEvent :: BumpCommitment {
468
+ package_target_feerate_sat_per_1000_weight,
469
+ commitment_tx : tx. clone ( ) ,
470
+ anchor_output_idx : idx,
471
+ } ) ,
472
+ ) )
473
+ } ,
474
+ // An anchor output was not found. There's nothing we can do other than
475
+ // attempt to broadcast the transaction with its current fee rate and hope
476
+ // it confirms. This is essentially the same behavior as a commitment
477
+ // transaction without anchor outputs.
478
+ None => Some ( ( None , 0 , OnchainClaim :: Tx ( tx. clone ( ) ) ) ) ,
479
+ }
480
+ } ,
481
+ _ => {
482
+ debug_assert ! ( false , "Only HolderFundingOutput inputs should be untractable and require external funding" ) ;
483
+ None
484
+ } ,
485
+ } ) ;
414
486
}
415
487
None
416
488
}
@@ -484,18 +556,26 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
484
556
if let Some ( ( new_timer, new_feerate, claim) ) = self . generate_claim ( cur_height, & req, & * fee_estimator, & * logger) {
485
557
req. set_timer ( new_timer) ;
486
558
req. set_feerate ( new_feerate) ;
487
- match claim {
559
+ let txid = match claim {
488
560
OnchainClaim :: Tx ( tx) => {
489
- let txid = tx. txid ( ) ;
490
- for k in req. outpoints ( ) {
491
- log_info ! ( logger, "Registering claiming request for {}:{}" , k. txid, k. vout) ;
492
- self . claimable_outpoints . insert ( k. clone ( ) , ( txid, conf_height) ) ;
493
- }
494
- self . pending_claim_requests . insert ( txid, req) ;
495
561
log_info ! ( logger, "Broadcasting onchain {}" , log_tx!( tx) ) ;
496
562
broadcaster. broadcast_transaction ( & tx) ;
563
+ tx. txid ( )
564
+ } ,
565
+ OnchainClaim :: Event ( claim_event) => {
566
+ log_info ! ( logger, "Yielding onchain event to spend inputs {:?}" , req. outpoints( ) ) ;
567
+ let txid = match claim_event {
568
+ ClaimEvent :: BumpCommitment { ref commitment_tx, .. } => commitment_tx. txid ( ) ,
569
+ } ;
570
+ self . pending_claim_events . insert ( txid, claim_event) ;
571
+ txid
497
572
} ,
573
+ } ;
574
+ for k in req. outpoints ( ) {
575
+ log_info ! ( logger, "Registering claiming request for {}:{}" , k. txid, k. vout) ;
576
+ self . claimable_outpoints . insert ( k. clone ( ) , ( txid, conf_height) ) ;
498
577
}
578
+ self . pending_claim_requests . insert ( txid, req) ;
499
579
}
500
580
}
501
581
@@ -587,6 +667,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
587
667
for outpoint in request. outpoints ( ) {
588
668
log_debug ! ( logger, "Removing claim tracking for {} due to maturation of claim tx {}." , outpoint, claim_request) ;
589
669
self . claimable_outpoints . remove ( & outpoint) ;
670
+ self . pending_claim_events . remove ( & claim_request) ;
590
671
}
591
672
}
592
673
} ,
@@ -619,6 +700,10 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
619
700
log_info ! ( logger, "Broadcasting RBF-bumped onchain {}" , log_tx!( bump_tx) ) ;
620
701
broadcaster. broadcast_transaction ( & bump_tx) ;
621
702
} ,
703
+ OnchainClaim :: Event ( claim_event) => {
704
+ log_info ! ( logger, "Yielding RBF-bumped onchain event to spend inputs {:?}" , request. outpoints( ) ) ;
705
+ self . pending_claim_events . insert ( * first_claim_txid, claim_event) ;
706
+ } ,
622
707
}
623
708
if let Some ( request) = self . pending_claim_requests . get_mut ( first_claim_txid) {
624
709
request. set_timer ( new_timer) ;
@@ -681,7 +766,7 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
681
766
self . onchain_events_awaiting_threshold_conf . push ( entry) ;
682
767
}
683
768
}
684
- for ( _ , request) in bump_candidates. iter_mut ( ) {
769
+ for ( first_claim_txid_height , request) in bump_candidates. iter_mut ( ) {
685
770
if let Some ( ( new_timer, new_feerate, bump_claim) ) = self . generate_claim ( height, & request, fee_estimator, & & * logger) {
686
771
request. set_timer ( new_timer) ;
687
772
request. set_feerate ( new_feerate) ;
@@ -690,6 +775,9 @@ impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
690
775
log_info ! ( logger, "Broadcasting onchain {}" , log_tx!( bump_tx) ) ;
691
776
broadcaster. broadcast_transaction ( & bump_tx) ;
692
777
} ,
778
+ OnchainClaim :: Event ( claim_event) => {
779
+ self . pending_claim_events . insert ( first_claim_txid_height. 0 , claim_event) ;
780
+ } ,
693
781
}
694
782
}
695
783
}
0 commit comments