Skip to content

Commit b706480

Browse files
authored
Merge pull request #3268 from TheBlueMatt/2024-08-moar-feerate-categories
Split up `ConfirmationTarget` even more
2 parents 5e62df7 + cf97cef commit b706480

14 files changed

+203
-92
lines changed

fuzz/src/chanmon_consistency.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ impl FeeEstimator for FuzzEstimator {
9797
// always return a HighPriority feerate here which is >= the maximum Normal feerate and a
9898
// Background feerate which is <= the minimum Normal feerate.
9999
match conf_target {
100-
ConfirmationTarget::OnChainSweep => MAX_FEE,
100+
ConfirmationTarget::MaximumFeeEstimate | ConfirmationTarget::UrgentOnChainSweep => {
101+
MAX_FEE
102+
},
101103
ConfirmationTarget::ChannelCloseMinimum
102104
| ConfirmationTarget::AnchorChannelFee
103105
| ConfirmationTarget::MinAllowedAnchorChannelRemoteFee

lightning-background-processor/src/lib.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -1107,7 +1107,7 @@ mod tests {
11071107
use std::collections::VecDeque;
11081108
use std::path::PathBuf;
11091109
use std::sync::mpsc::SyncSender;
1110-
use std::sync::{Arc, Mutex};
1110+
use std::sync::Arc;
11111111
use std::time::Duration;
11121112
use std::{env, fs};
11131113

@@ -1126,7 +1126,7 @@ mod tests {
11261126
#[cfg(c_bindings)]
11271127
type LockingWrapper<T> = lightning::routing::scoring::MultiThreadedLockableScore<T>;
11281128
#[cfg(not(c_bindings))]
1129-
type LockingWrapper<T> = Mutex<T>;
1129+
type LockingWrapper<T> = std::sync::Mutex<T>;
11301130

11311131
type ChannelManager = channelmanager::ChannelManager<
11321132
Arc<ChainMonitor>,
@@ -1532,8 +1532,7 @@ mod tests {
15321532
let mut nodes = Vec::new();
15331533
for i in 0..num_nodes {
15341534
let tx_broadcaster = Arc::new(test_utils::TestBroadcaster::new(network));
1535-
let fee_estimator =
1536-
Arc::new(test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) });
1535+
let fee_estimator = Arc::new(test_utils::TestFeeEstimator::new(253));
15371536
let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
15381537
let genesis_block = genesis_block(network);
15391538
let network_graph = Arc::new(NetworkGraph::new(network, logger.clone()));

lightning/src/chain/chaininterface.rs

+18-6
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,19 @@ pub trait BroadcasterInterface {
4949
/// estimation.
5050
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
5151
pub enum ConfirmationTarget {
52+
/// The most aggressive (i.e. highest) feerate estimate available.
53+
///
54+
/// This is used to sanity-check our counterparty's feerates and should be as conservative as
55+
/// possible to ensure that we don't confuse a peer using a very conservative estimator for one
56+
/// trying to burn channel balance to dust.
57+
MaximumFeeEstimate,
5258
/// We have some funds available on chain which we need to spend prior to some expiry time at
53-
/// which point our counterparty may be able to steal them. Generally we have in the high tens
54-
/// to low hundreds of blocks to get our transaction on-chain, but we shouldn't risk too low a
55-
/// fee - this should be a relatively high priority feerate.
56-
OnChainSweep,
59+
/// which point our counterparty may be able to steal them.
60+
///
61+
/// Generally we have in the high tens to low hundreds of blocks to get our transaction
62+
/// on-chain (it doesn't have to happen in the next few blocks!), but we shouldn't risk too low
63+
/// a fee - this should be a relatively high priority feerate.
64+
UrgentOnChainSweep,
5765
/// This is the lowest feerate we will allow our channel counterparty to have in an anchor
5866
/// channel in order to close the channel if a channel party goes away.
5967
///
@@ -124,14 +132,18 @@ pub enum ConfirmationTarget {
124132
///
125133
/// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
126134
ChannelCloseMinimum,
127-
/// The feerate [`OutputSweeper`] will use on transactions spending
128-
/// [`SpendableOutputDescriptor`]s after a channel closure.
135+
/// The feerate used to claim on-chain funds when there is no particular urgency to do so.
136+
///
137+
/// It is used to get commitment transactions without any HTLCs confirmed in [`ChannelMonitor`]
138+
/// and by [`OutputSweeper`] on transactions spending [`SpendableOutputDescriptor`]s after a
139+
/// channel closure.
129140
///
130141
/// Generally spending these outputs is safe as long as they eventually confirm, so a value
131142
/// (slightly above) the mempool minimum should suffice. However, as this value will influence
132143
/// how long funds will be unavailable after channel closure, [`FeeEstimator`] implementors
133144
/// might want to choose a higher feerate to regain control over funds faster.
134145
///
146+
/// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
135147
/// [`OutputSweeper`]: crate::util::sweep::OutputSweeper
136148
/// [`SpendableOutputDescriptor`]: crate::sign::SpendableOutputDescriptor
137149
OutputSpendingFee,

lightning/src/chain/channelmonitor.rs

+46-13
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSe
4040
use crate::ln::channelmanager::{HTLCSource, SentHTLCId};
4141
use crate::chain;
4242
use crate::chain::{BestBlock, WatchedOutput};
43-
use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
43+
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
4444
use crate::chain::transaction::{OutPoint, TransactionData};
4545
use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::EcdsaChannelSigner, SignerProvider, EntropySource};
4646
use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler};
@@ -1902,8 +1902,9 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
19021902
let mut inner = self.inner.lock().unwrap();
19031903
let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
19041904
let current_height = inner.best_block.height;
1905+
let conf_target = inner.closure_conf_target();
19051906
inner.onchain_tx_handler.rebroadcast_pending_claims(
1906-
current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, &fee_estimator, &logger,
1907+
current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target, &fee_estimator, &logger,
19071908
);
19081909
}
19091910

@@ -1927,8 +1928,9 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
19271928
let mut inner = self.inner.lock().unwrap();
19281929
let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
19291930
let current_height = inner.best_block.height;
1931+
let conf_target = inner.closure_conf_target();
19301932
inner.onchain_tx_handler.rebroadcast_pending_claims(
1931-
current_height, FeerateStrategy::RetryPrevious, &broadcaster, &fee_estimator, &logger,
1933+
current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target, &fee_estimator, &logger,
19321934
);
19331935
}
19341936

@@ -2684,6 +2686,30 @@ pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
26842686
}
26852687

26862688
impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2689+
/// Gets the [`ConfirmationTarget`] we should use when selecting feerates for channel closure
2690+
/// transactions for this channel right now.
2691+
fn closure_conf_target(&self) -> ConfirmationTarget {
2692+
// Treat the sweep as urgent as long as there is at least one HTLC which is pending on a
2693+
// valid commitment transaction.
2694+
if !self.current_holder_commitment_tx.htlc_outputs.is_empty() {
2695+
return ConfirmationTarget::UrgentOnChainSweep;
2696+
}
2697+
if self.prev_holder_signed_commitment_tx.as_ref().map(|t| !t.htlc_outputs.is_empty()).unwrap_or(false) {
2698+
return ConfirmationTarget::UrgentOnChainSweep;
2699+
}
2700+
if let Some(txid) = self.current_counterparty_commitment_txid {
2701+
if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2702+
return ConfirmationTarget::UrgentOnChainSweep;
2703+
}
2704+
}
2705+
if let Some(txid) = self.prev_counterparty_commitment_txid {
2706+
if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2707+
return ConfirmationTarget::UrgentOnChainSweep;
2708+
}
2709+
}
2710+
ConfirmationTarget::OutputSpendingFee
2711+
}
2712+
26872713
/// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
26882714
/// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
26892715
/// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
@@ -2928,7 +2954,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
29282954
macro_rules! claim_htlcs {
29292955
($commitment_number: expr, $txid: expr, $htlcs: expr) => {
29302956
let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None, $htlcs);
2931-
self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
2957+
let conf_target = self.closure_conf_target();
2958+
self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
29322959
}
29332960
}
29342961
if let Some(txid) = self.current_counterparty_commitment_txid {
@@ -2976,7 +3003,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
29763003
// block. Even if not, its a reasonable metric for the bump criteria on the HTLC
29773004
// transactions.
29783005
let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
2979-
self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height, self.best_block.height, broadcaster, fee_estimator, logger);
3006+
let conf_target = self.closure_conf_target();
3007+
self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
29803008
}
29813009
}
29823010
}
@@ -3036,9 +3064,10 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
30363064
L::Target: Logger,
30373065
{
30383066
let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) });
3067+
let conf_target = self.closure_conf_target();
30393068
self.onchain_tx_handler.update_claims_view_from_requests(
30403069
claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
3041-
fee_estimator, logger
3070+
conf_target, fee_estimator, logger,
30423071
);
30433072
}
30443073

@@ -3851,7 +3880,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
38513880
self.best_block = BestBlock::new(block_hash, height);
38523881
log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
38533882
self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3854-
self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
3883+
let conf_target = self.closure_conf_target();
3884+
self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, conf_target, fee_estimator, logger);
38553885
Vec::new()
38563886
} else { Vec::new() }
38573887
}
@@ -4116,8 +4146,9 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41164146
}
41174147
}
41184148

4119-
self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, fee_estimator, logger);
4120-
self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, fee_estimator, logger);
4149+
let conf_target = self.closure_conf_target();
4150+
self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4151+
self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
41214152

41224153
// Determine new outputs to watch by comparing against previously known outputs to watch,
41234154
// updating the latter in the process.
@@ -4156,7 +4187,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41564187
self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
41574188

41584189
let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4159-
self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
4190+
let conf_target = self.closure_conf_target();
4191+
self.onchain_tx_handler.block_disconnected(height, broadcaster, conf_target, &bounded_fee_estimator, logger);
41604192

41614193
self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
41624194
}
@@ -4190,7 +4222,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41904222

41914223
debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
41924224

4193-
self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
4225+
let conf_target = self.closure_conf_target();
4226+
self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, conf_target, fee_estimator, logger);
41944227
}
41954228

41964229
/// Filters a block's `txdata` for transactions spending watched outputs or for any child
@@ -4983,7 +5016,7 @@ mod tests {
49835016
use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
49845017
use crate::util::ser::{ReadableArgs, Writeable};
49855018
use crate::util::logger::Logger;
4986-
use crate::sync::{Arc, Mutex};
5019+
use crate::sync::Arc;
49875020
use crate::io;
49885021
use crate::ln::features::ChannelTypeFeatures;
49895022

@@ -5083,7 +5116,7 @@ mod tests {
50835116
let secp_ctx = Secp256k1::new();
50845117
let logger = Arc::new(TestLogger::new());
50855118
let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
5086-
let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
5119+
let fee_estimator = TestFeeEstimator::new(253);
50875120

50885121
let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
50895122

0 commit comments

Comments
 (0)