Skip to content

Commit 501974d

Browse files
authored
Merge pull request #667 from valentinewallace/remove-channels-chanmon
Remove Channel's ChannelMonitor copy
2 parents 7de6cb8 + 28d9036 commit 501974d

File tree

7 files changed

+137
-144
lines changed

7 files changed

+137
-144
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use lightning::chain::transaction::OutPoint;
3434
use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil,ChainWatchInterface};
3535
use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
3636
use lightning::ln::channelmonitor;
37-
use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, HTLCUpdate};
37+
use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
3838
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret, ChannelManagerReadArgs};
3939
use lightning::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
4040
use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, UpdateAddHTLC, Init};
@@ -135,8 +135,8 @@ impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
135135
self.update_ret.lock().unwrap().clone()
136136
}
137137

138-
fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
139-
return self.simple_monitor.get_and_clear_pending_htlcs_updated();
138+
fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
139+
return self.simple_monitor.get_and_clear_pending_monitor_events();
140140
}
141141
}
142142

lightning/src/ln/channel.rs

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -386,9 +386,6 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
386386

387387
their_shutdown_scriptpubkey: Option<Script>,
388388

389-
/// Used exclusively to broadcast the latest local state, mostly a historical quirk that this
390-
/// is here:
391-
channel_monitor: Option<ChannelMonitor<ChanSigner>>,
392389
commitment_secrets: CounterpartyCommitmentSecrets,
393390

394391
network_sync: UpdateStatus,
@@ -557,7 +554,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
557554

558555
their_shutdown_scriptpubkey: None,
559556

560-
channel_monitor: None,
561557
commitment_secrets: CounterpartyCommitmentSecrets::new(),
562558

563559
network_sync: UpdateStatus::Fresh,
@@ -786,7 +782,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
786782

787783
their_shutdown_scriptpubkey,
788784

789-
channel_monitor: None,
790785
commitment_secrets: CounterpartyCommitmentSecrets::new(),
791786

792787
network_sync: UpdateStatus::Fresh,
@@ -1222,7 +1217,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
12221217
payment_preimage: payment_preimage_arg.clone(),
12231218
}],
12241219
};
1225-
self.channel_monitor.as_mut().unwrap().update_monitor_ooo(monitor_update.clone(), logger).unwrap();
12261220

12271221
if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32 | ChannelState::PeerDisconnected as u32 | ChannelState::MonitorUpdateFailed as u32)) != 0 {
12281222
for pending_update in self.holding_cell_htlc_updates.iter() {
@@ -1552,7 +1546,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
15521546
} }
15531547
}
15541548

1555-
self.channel_monitor = Some(create_monitor!());
15561549
let channel_monitor = create_monitor!();
15571550

15581551
self.channel_state = ChannelState::FundingSent as u32;
@@ -1618,7 +1611,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
16181611
} }
16191612
}
16201613

1621-
self.channel_monitor = Some(create_monitor!());
16221614
let channel_monitor = create_monitor!();
16231615

16241616
assert_eq!(self.channel_state & (ChannelState::MonitorUpdateFailed as u32), 0); // We have no had any monitor(s) yet to fail update!
@@ -2060,7 +2052,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
20602052
htlc_outputs: htlcs_and_sigs
20612053
}]
20622054
};
2063-
self.channel_monitor.as_mut().unwrap().update_monitor_ooo(monitor_update.clone(), logger).unwrap();
20642055

20652056
for htlc in self.pending_inbound_htlcs.iter_mut() {
20662057
let new_forward = if let &InboundHTLCState::RemoteAnnounced(ref forward_info) = &htlc.state {
@@ -2280,7 +2271,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
22802271
secret: msg.per_commitment_secret,
22812272
}],
22822273
};
2283-
self.channel_monitor.as_mut().unwrap().update_monitor_ooo(monitor_update.clone(), logger).unwrap();
22842274

22852275
// Update state now that we've passed all the can-fail calls...
22862276
// (note that we may still fail to generate the new commitment_signed message, but that's
@@ -3115,14 +3105,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
31153105
self.user_id
31163106
}
31173107

3118-
/// May only be called after funding has been initiated (ie is_funding_initiated() is true)
3119-
pub fn channel_monitor(&mut self) -> &mut ChannelMonitor<ChanSigner> {
3120-
if self.channel_state < ChannelState::FundingSent as u32 {
3121-
panic!("Can't get a channel monitor until funding has been created");
3122-
}
3123-
self.channel_monitor.as_mut().unwrap()
3124-
}
3125-
31263108
/// Guaranteed to be Some after both FundingLocked messages have been exchanged (and, thus,
31273109
/// is_usable() returns true).
31283110
/// Allowed in any state (including after shutdown)
@@ -3397,9 +3379,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
33973379
if header.bitcoin_hash() != self.last_block_connected {
33983380
self.last_block_connected = header.bitcoin_hash();
33993381
self.update_time_counter = cmp::max(self.update_time_counter, header.time);
3400-
if let Some(channel_monitor) = self.channel_monitor.as_mut() {
3401-
channel_monitor.last_block_hash = self.last_block_connected;
3402-
}
34033382
if self.funding_tx_confirmations > 0 {
34043383
if self.funding_tx_confirmations == self.minimum_depth as u64 {
34053384
let need_commitment_update = if non_shutdown_state == ChannelState::FundingSent as u32 {
@@ -3458,9 +3437,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
34583437
self.funding_tx_confirmations = self.minimum_depth as u64 - 1;
34593438
}
34603439
self.last_block_connected = header.bitcoin_hash();
3461-
if let Some(channel_monitor) = self.channel_monitor.as_mut() {
3462-
channel_monitor.last_block_hash = self.last_block_connected;
3463-
}
34643440
false
34653441
}
34663442

@@ -3871,7 +3847,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
38713847
their_revocation_point: self.their_cur_commitment_point.unwrap()
38723848
}]
38733849
};
3874-
self.channel_monitor.as_mut().unwrap().update_monitor_ooo(monitor_update.clone(), logger).unwrap();
38753850
self.channel_state |= ChannelState::AwaitingRemoteRevoke as u32;
38763851
Ok((res, monitor_update))
38773852
}
@@ -4242,8 +4217,6 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
42424217
self.their_shutdown_scriptpubkey.write(writer)?;
42434218

42444219
self.commitment_secrets.write(writer)?;
4245-
4246-
self.channel_monitor.as_ref().unwrap().write_for_disk(writer)?;
42474220
Ok(())
42484221
}
42494222
}
@@ -4398,13 +4371,6 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
43984371
let their_shutdown_scriptpubkey = Readable::read(reader)?;
43994372
let commitment_secrets = Readable::read(reader)?;
44004373

4401-
let (monitor_last_block, channel_monitor) = Readable::read(reader)?;
4402-
// We drop the ChannelMonitor's last block connected hash cause we don't actually bother
4403-
// doing full block connection operations on the internal ChannelMonitor copies
4404-
if monitor_last_block != last_block_connected {
4405-
return Err(DecodeError::InvalidValue);
4406-
}
4407-
44084374
Ok(Channel {
44094375
user_id,
44104376

@@ -4476,7 +4442,6 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
44764442

44774443
their_shutdown_scriptpubkey,
44784444

4479-
channel_monitor: Some(channel_monitor),
44804445
commitment_secrets,
44814446

44824447
network_sync: UpdateStatus::Fresh,

lightning/src/ln/channelmanager.rs

Lines changed: 49 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ use bitcoin::secp256k1;
3838
use chain::chaininterface::{BroadcasterInterface,ChainListener,FeeEstimator};
3939
use chain::transaction::OutPoint;
4040
use ln::channel::{Channel, ChannelError};
41-
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
41+
use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, ManyChannelMonitor, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
4242
use ln::features::{InitFeatures, NodeFeatures};
4343
use routing::router::{Route, RouteHop};
4444
use ln::msgs;
@@ -2966,6 +2966,48 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
29662966
Err(e) => { Err(APIError::APIMisuseError { err: e.err })}
29672967
}
29682968
}
2969+
2970+
/// Process pending events from the ManyChannelMonitor.
2971+
fn process_pending_monitor_events(&self) {
2972+
let mut failed_channels = Vec::new();
2973+
{
2974+
for monitor_event in self.monitor.get_and_clear_pending_monitor_events() {
2975+
match monitor_event {
2976+
MonitorEvent::HTLCEvent(htlc_update) => {
2977+
if let Some(preimage) = htlc_update.payment_preimage {
2978+
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2979+
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2980+
} else {
2981+
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2982+
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2983+
}
2984+
},
2985+
MonitorEvent::CommitmentTxBroadcasted(funding_outpoint) => {
2986+
let mut channel_lock = self.channel_state.lock().unwrap();
2987+
let channel_state = &mut *channel_lock;
2988+
let by_id = &mut channel_state.by_id;
2989+
let short_to_id = &mut channel_state.short_to_id;
2990+
let pending_msg_events = &mut channel_state.pending_msg_events;
2991+
if let Some(mut chan) = by_id.remove(&funding_outpoint.to_channel_id()) {
2992+
if let Some(short_id) = chan.get_short_channel_id() {
2993+
short_to_id.remove(&short_id);
2994+
}
2995+
failed_channels.push(chan.force_shutdown(false));
2996+
if let Ok(update) = self.get_channel_update(&chan) {
2997+
pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2998+
msg: update
2999+
});
3000+
}
3001+
}
3002+
},
3003+
}
3004+
}
3005+
}
3006+
3007+
for failure in failed_channels.drain(..) {
3008+
self.finish_force_close_channel(failure);
3009+
}
3010+
}
29693011
}
29703012

29713013
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> events::MessageSendEventsProvider for ChannelManager<ChanSigner, M, T, K, F, L>
@@ -2976,21 +3018,9 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
29763018
L::Target: Logger,
29773019
{
29783020
fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
2979-
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
2980-
// user to serialize a ChannelManager with pending events in it and lose those events on
2981-
// restart. This is doubly true for the fail/fulfill-backs from monitor events!
2982-
{
2983-
//TODO: This behavior should be documented.
2984-
for htlc_update in self.monitor.get_and_clear_pending_htlcs_updated() {
2985-
if let Some(preimage) = htlc_update.payment_preimage {
2986-
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2987-
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
2988-
} else {
2989-
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
2990-
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
2991-
}
2992-
}
2993-
}
3021+
//TODO: This behavior should be documented. It's non-intuitive that we query
3022+
// ChannelMonitors when clearing other events.
3023+
self.process_pending_monitor_events();
29943024

29953025
let mut ret = Vec::new();
29963026
let mut channel_state = self.channel_state.lock().unwrap();
@@ -3007,21 +3037,9 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
30073037
L::Target: Logger,
30083038
{
30093039
fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
3010-
// TODO: Event release to users and serialization is currently race-y: it's very easy for a
3011-
// user to serialize a ChannelManager with pending events in it and lose those events on
3012-
// restart. This is doubly true for the fail/fulfill-backs from monitor events!
3013-
{
3014-
//TODO: This behavior should be documented.
3015-
for htlc_update in self.monitor.get_and_clear_pending_htlcs_updated() {
3016-
if let Some(preimage) = htlc_update.payment_preimage {
3017-
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
3018-
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3019-
} else {
3020-
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
3021-
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });
3022-
}
3023-
}
3024-
}
3040+
//TODO: This behavior should be documented. It's non-intuitive that we query
3041+
// ChannelMonitors when clearing other events.
3042+
self.process_pending_monitor_events();
30253043

30263044
let mut ret = Vec::new();
30273045
let mut pending_events = self.pending_events.lock().unwrap();
@@ -3104,21 +3122,6 @@ impl<ChanSigner: ChannelKeys, M: Deref + Sync + Send, T: Deref + Sync + Send, K:
31043122
}
31053123
}
31063124
}
3107-
if channel.is_funding_initiated() && channel.channel_monitor().would_broadcast_at_height(height, &self.logger) {
3108-
if let Some(short_id) = channel.get_short_channel_id() {
3109-
short_to_id.remove(&short_id);
3110-
}
3111-
// If would_broadcast_at_height() is true, the channel_monitor will broadcast
3112-
// the latest local tx for us, so we should skip that here (it doesn't really
3113-
// hurt anything, but does make tests a bit simpler).
3114-
failed_channels.push(channel.force_shutdown(false));
3115-
if let Ok(update) = self.get_channel_update(&channel) {
3116-
pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3117-
msg: update
3118-
});
3119-
}
3120-
return false;
3121-
}
31223125
true
31233126
});
31243127

0 commit comments

Comments
 (0)