Skip to content

Commit 726dd5c

Browse files
authored
Merge pull request #3429 from andrei-21/feature/channelmonitor-goodies
Clean channelmonitor.rs code
2 parents 1386bef + 8ebda06 commit 726dd5c

File tree

1 file changed

+53
-65
lines changed

1 file changed

+53
-65
lines changed

lightning/src/chain/channelmonitor.rs

+53-65
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ pub struct ChannelMonitorUpdate {
104104

105105
/// LDK prior to 0.1 used this constant as the [`ChannelMonitorUpdate::update_id`] for any
106106
/// [`ChannelMonitorUpdate`]s which were generated after the channel was closed.
107-
const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
107+
const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = u64::MAX;
108108

109109
impl Writeable for ChannelMonitorUpdate {
110110
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
@@ -285,7 +285,7 @@ impl_writeable_tlv_based!(HolderSignedTx, {
285285
(0, txid, required),
286286
// Note that this is filled in with data from OnchainTxHandler if it's missing.
287287
// For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
288-
(1, to_self_value_sat, (default_value, u64::max_value())),
288+
(1, to_self_value_sat, (default_value, u64::MAX)),
289289
(2, revocation_key, required),
290290
(4, a_htlc_key, required),
291291
(6, b_htlc_key, required),
@@ -298,7 +298,7 @@ impl_writeable_tlv_based!(HolderSignedTx, {
298298
impl HolderSignedTx {
299299
fn non_dust_htlcs(&self) -> Vec<HTLCOutputInCommitment> {
300300
self.htlc_outputs.iter().filter_map(|(htlc, _, _)| {
301-
if let Some(_) = htlc.transaction_output_index {
301+
if htlc.transaction_output_index.is_some() {
302302
Some(htlc.clone())
303303
} else {
304304
None
@@ -319,7 +319,7 @@ struct CounterpartyCommitmentParameters {
319319

320320
impl Writeable for CounterpartyCommitmentParameters {
321321
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
322-
w.write_all(&(0 as u64).to_be_bytes())?;
322+
w.write_all(&0u64.to_be_bytes())?;
323323
write_tlv_fields!(w, {
324324
(0, self.counterparty_delayed_payment_base_key, required),
325325
(2, self.counterparty_htlc_base_key, required),
@@ -334,7 +334,7 @@ impl Readable for CounterpartyCommitmentParameters {
334334
// Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
335335
// used. Read it for compatibility.
336336
let per_htlc_len: u64 = Readable::read(r)?;
337-
for _ in 0..per_htlc_len {
337+
for _ in 0..per_htlc_len {
338338
let _txid: Txid = Readable::read(r)?;
339339
let htlcs_count: u64 = Readable::read(r)?;
340340
for _ in 0..htlcs_count {
@@ -791,13 +791,13 @@ struct IrrevocablyResolvedHTLC {
791791
payment_preimage: Option<PaymentPreimage>,
792792
}
793793

794-
// In LDK versions prior to 0.0.111 commitment_tx_output_idx was not Option-al and
795-
// IrrevocablyResolvedHTLC objects only existed for non-dust HTLCs. This was a bug, but to maintain
796-
// backwards compatibility we must ensure we always write out a commitment_tx_output_idx field,
797-
// using `u32::max_value()` as a sentinal to indicate the HTLC was dust.
794+
/// In LDK versions prior to 0.0.111 commitment_tx_output_idx was not Option-al and
795+
/// IrrevocablyResolvedHTLC objects only existed for non-dust HTLCs. This was a bug, but to maintain
796+
/// backwards compatibility we must ensure we always write out a commitment_tx_output_idx field,
797+
/// using [`u32::MAX`] as a sentinal to indicate the HTLC was dust.
798798
impl Writeable for IrrevocablyResolvedHTLC {
799799
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
800-
let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::max_value());
800+
let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
801801
write_tlv_fields!(writer, {
802802
(0, mapped_commitment_tx_output_idx, required),
803803
(1, self.resolving_txid, option),
@@ -821,7 +821,7 @@ impl Readable for IrrevocablyResolvedHTLC {
821821
(3, resolving_tx, option),
822822
});
823823
Ok(Self {
824-
commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::max_value() { None } else { Some(mapped_commitment_tx_output_idx) },
824+
commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
825825
resolving_txid,
826826
payment_preimage,
827827
resolving_tx,
@@ -1581,7 +1581,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
15811581
filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
15821582
for (txid, outputs) in lock.get_outputs_to_watch().iter() {
15831583
for (index, script_pubkey) in outputs.iter() {
1584-
assert!(*index <= u16::max_value() as u32);
1584+
assert!(*index <= u16::MAX as u32);
15851585
let outpoint = OutPoint { txid: *txid, index: *index as u16 };
15861586
log_trace!(logger, "Registering outpoint {} with the filter for monitoring spends", outpoint);
15871587
filter.register_output(WatchedOutput {
@@ -2002,18 +2002,16 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
20022002
let current_height = self.current_best_block().height;
20032003
let mut inner = self.inner.lock().unwrap();
20042004

2005-
if is_all_funds_claimed {
2006-
if !inner.funding_spend_seen {
2007-
debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2008-
is_all_funds_claimed = false;
2009-
}
2005+
if is_all_funds_claimed && !inner.funding_spend_seen {
2006+
debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2007+
is_all_funds_claimed = false;
20102008
}
20112009

20122010
const BLOCKS_THRESHOLD: u32 = 4032; // ~four weeks
20132011
match (inner.balances_empty_height, is_all_funds_claimed) {
20142012
(Some(balances_empty_height), true) => {
20152013
// Claimed all funds, check if reached the blocks threshold.
2016-
return current_height >= balances_empty_height + BLOCKS_THRESHOLD;
2014+
current_height >= balances_empty_height + BLOCKS_THRESHOLD
20172015
},
20182016
(Some(_), false) => {
20192017
// previously assumed we claimed all funds, but we have new funds to claim.
@@ -2065,8 +2063,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
20652063
holder_commitment: bool, counterparty_revoked_commitment: bool,
20662064
confirmed_txid: Option<Txid>
20672065
) -> Option<Balance> {
2068-
let htlc_commitment_tx_output_idx =
2069-
if let Some(v) = htlc.transaction_output_index { v } else { return None; };
2066+
let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
20702067

20712068
let mut htlc_spend_txid_opt = None;
20722069
let mut htlc_spend_tx_opt = None;
@@ -2116,14 +2113,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
21162113
}
21172114
}
21182115
let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2119-
.find(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2116+
.any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
21202117
debug_assert!(htlc_spend_txid_opt.is_none());
21212118
htlc_spend_txid_opt = v.resolving_txid.as_ref();
21222119
debug_assert!(htlc_spend_tx_opt.is_none());
21232120
htlc_spend_tx_opt = v.resolving_tx.as_ref();
21242121
true
21252122
} else { false });
2126-
debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
2123+
debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
21272124

21282125
let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
21292126
let htlc_output_to_spend =
@@ -2154,31 +2151,31 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
21542151
confirmation_height: conf_thresh,
21552152
source: BalanceSource::Htlc,
21562153
});
2157-
} else if htlc_resolved.is_some() && !htlc_output_spend_pending {
2154+
} else if htlc_resolved && !htlc_output_spend_pending {
21582155
// Funding transaction spends should be fully confirmed by the time any
21592156
// HTLC transactions are resolved, unless we're talking about a holder
21602157
// commitment tx, whose resolution is delayed until the CSV timeout is
21612158
// reached, even though HTLCs may be resolved after only
21622159
// ANTI_REORG_DELAY confirmations.
21632160
debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
21642161
} else if counterparty_revoked_commitment {
2165-
let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2162+
let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
21662163
if let OnchainEvent::MaturingOutput {
21672164
descriptor: SpendableOutputDescriptor::StaticOutput { .. }
21682165
} = &event.event {
2169-
if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2166+
event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
21702167
if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
21712168
tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
21722169
} else {
21732170
Some(inp.previous_output.txid) == confirmed_txid &&
21742171
inp.previous_output.vout == htlc_commitment_tx_output_idx
21752172
}
2176-
})).unwrap_or(false) {
2177-
Some(())
2178-
} else { None }
2179-
} else { None }
2173+
})).unwrap_or(false)
2174+
} else {
2175+
false
2176+
}
21802177
});
2181-
if htlc_output_claim_pending.is_some() {
2178+
if htlc_output_claim_pending {
21822179
// We already push `Balance`s onto the `res` list for every
21832180
// `StaticOutput` in a `MaturingOutput` in the revoked
21842181
// counterparty commitment transaction case generally, so don't
@@ -2239,7 +2236,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
22392236
payment_preimage: *payment_preimage,
22402237
});
22412238
}
2242-
} else if htlc_resolved.is_none() {
2239+
} else if !htlc_resolved {
22432240
return Some(Balance::MaybePreimageClaimableHTLC {
22442241
amount_satoshis: htlc.amount_msat / 1000,
22452242
expiry_height: htlc.cltv_expiry,
@@ -3191,10 +3188,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
31913188
// confirmed (even with 1 confirmation) as it'll be rejected as
31923189
// duplicate/conflicting.
31933190
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
3194-
self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
3195-
OnchainEvent::FundingSpendConfirmation { .. } => true,
3196-
_ => false,
3197-
}).is_some();
3191+
self.onchain_events_awaiting_threshold_conf.iter().any(
3192+
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
31983193
if detected_funding_spend {
31993194
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
32003195
continue;
@@ -3268,7 +3263,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
32683263
// If we've detected a counterparty commitment tx on chain, we must include it in the set
32693264
// of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
32703265
// its trivial to do, double-check that here.
3271-
for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
3266+
for txid in self.counterparty_commitment_txn_on_chain.keys() {
32723267
self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
32733268
}
32743269
&self.outputs_to_watch
@@ -4118,16 +4113,10 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41184113
}
41194114

41204115
// Find which on-chain events have reached their confirmation threshold.
4121-
let onchain_events_awaiting_threshold_conf =
4122-
self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
4123-
let mut onchain_events_reaching_threshold_conf = Vec::new();
4124-
for entry in onchain_events_awaiting_threshold_conf {
4125-
if entry.has_reached_confirmation_threshold(&self.best_block) {
4126-
onchain_events_reaching_threshold_conf.push(entry);
4127-
} else {
4128-
self.onchain_events_awaiting_threshold_conf.push(entry);
4129-
}
4130-
}
4116+
let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
4117+
self.onchain_events_awaiting_threshold_conf.drain(..).partition(
4118+
|entry| entry.has_reached_confirmation_threshold(&self.best_block));
4119+
self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
41314120

41324121
// Used to check for duplicate HTLC resolutions.
41334122
#[cfg(debug_assertions)]
@@ -4142,19 +4131,19 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41424131
let mut matured_htlcs = Vec::new();
41434132

41444133
// Produce actionable events from on-chain events having reached their threshold.
4145-
for entry in onchain_events_reaching_threshold_conf.drain(..) {
4134+
for entry in onchain_events_reaching_threshold_conf {
41464135
match entry.event {
4147-
OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
4136+
OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
41484137
// Check for duplicate HTLC resolutions.
41494138
#[cfg(debug_assertions)]
41504139
{
41514140
debug_assert!(
4152-
unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
4141+
!unmatured_htlcs.contains(&&source),
41534142
"An unmature HTLC transaction conflicts with a maturing one; failed to \
41544143
call either transaction_unconfirmed for the conflicting transaction \
41554144
or block_disconnected for a block containing it.");
41564145
debug_assert!(
4157-
matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
4146+
!matured_htlcs.contains(&source),
41584147
"A matured HTLC transaction conflicts with a maturing one; failed to \
41594148
call either transaction_unconfirmed for the conflicting transaction \
41604149
or block_disconnected for a block containing it.");
@@ -4166,7 +4155,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
41664155
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
41674156
payment_hash,
41684157
payment_preimage: None,
4169-
source: source.clone(),
4158+
source,
41704159
htlc_value_satoshis,
41714160
}));
41724161
self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
@@ -4211,7 +4200,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
42114200
});
42124201
#[cfg(test)]
42134202
{
4214-
// If we see a transaction for which we registered outputs previously,
4203+
// If we see a transaction for which we registered outputs previously,
42154204
// make sure the registered scriptpubkey at the expected index match
42164205
// the actual transaction output one. We failed this case before #653.
42174206
for tx in &txn_matched {
@@ -4596,7 +4585,8 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
45964585
height,
45974586
block_hash: Some(*block_hash),
45984587
event: OnchainEvent::HTLCUpdate {
4599-
source, payment_hash,
4588+
source,
4589+
payment_hash,
46004590
htlc_value_satoshis: Some(amount_msat / 1000),
46014591
commitment_tx_output_idx: Some(input.previous_output.vout),
46024592
},
@@ -4808,7 +4798,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
48084798
for _ in 0..htlcs_count {
48094799
htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
48104800
}
4811-
if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
4801+
if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
48124802
return Err(DecodeError::InvalidValue);
48134803
}
48144804
}
@@ -4818,7 +4808,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
48184808
for _ in 0..counterparty_commitment_txn_on_chain_len {
48194809
let txid: Txid = Readable::read(reader)?;
48204810
let commitment_number = <U48 as Readable>::read(reader)?.0;
4821-
if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
4811+
if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
48224812
return Err(DecodeError::InvalidValue);
48234813
}
48244814
}
@@ -4828,17 +4818,15 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
48284818
for _ in 0..counterparty_hash_commitment_number_len {
48294819
let payment_hash: PaymentHash = Readable::read(reader)?;
48304820
let commitment_number = <U48 as Readable>::read(reader)?.0;
4831-
if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
4821+
if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
48324822
return Err(DecodeError::InvalidValue);
48334823
}
48344824
}
48354825

48364826
let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
48374827
match <u8 as Readable>::read(reader)? {
48384828
0 => None,
4839-
1 => {
4840-
Some(Readable::read(reader)?)
4841-
},
4829+
1 => Some(Readable::read(reader)?),
48424830
_ => return Err(DecodeError::InvalidValue),
48434831
};
48444832
let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
@@ -4851,7 +4839,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
48514839
for _ in 0..payment_preimages_len {
48524840
let preimage: PaymentPreimage = Readable::read(reader)?;
48534841
let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4854-
if let Some(_) = payment_preimages.insert(hash, (preimage, Vec::new())) {
4842+
if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
48554843
return Err(DecodeError::InvalidValue);
48564844
}
48574845
}
@@ -4895,7 +4883,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
48954883
for _ in 0..outputs_len {
48964884
outputs.push((Readable::read(reader)?, Readable::read(reader)?));
48974885
}
4898-
if let Some(_) = outputs_to_watch.insert(txid, outputs) {
4886+
if outputs_to_watch.insert(txid, outputs).is_some() {
48994887
return Err(DecodeError::InvalidValue);
49004888
}
49014889
}
@@ -4909,15 +4897,15 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
49094897
if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
49104898
let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
49114899
if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
4912-
if prev_commitment_tx.to_self_value_sat == u64::max_value() {
4900+
if prev_commitment_tx.to_self_value_sat == u64::MAX {
49134901
prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
49144902
} else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
49154903
return Err(DecodeError::InvalidValue);
49164904
}
49174905
}
49184906

49194907
let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
4920-
if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
4908+
if current_holder_commitment_tx.to_self_value_sat == u64::MAX {
49214909
current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
49224910
} else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
49234911
return Err(DecodeError::InvalidValue);
@@ -5259,7 +5247,7 @@ mod tests {
52595247
delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
52605248
htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
52615249
};
5262-
let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
5250+
let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
52635251
let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
52645252
let channel_parameters = ChannelTransactionParameters {
52655253
holder_pubkeys: keys.holder_channel_pubkeys.clone(),
@@ -5511,7 +5499,7 @@ mod tests {
55115499
delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
55125500
htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
55135501
};
5514-
let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
5502+
let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
55155503
let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
55165504
let channel_parameters = ChannelTransactionParameters {
55175505
holder_pubkeys: keys.holder_channel_pubkeys.clone(),

0 commit comments

Comments
 (0)