Skip to content

Commit f98bbff

Browse files
committed
Move ChainMonitor to a separate module
1 parent a0e6a4b commit f98bbff

File tree

8 files changed

+234
-193
lines changed

8 files changed

+234
-193
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use bitcoin::hashes::sha256::Hash as Sha256;
2929
use bitcoin::hash_types::{BlockHash, WPubkeyHash};
3030

3131
use lightning::chain;
32+
use lightning::chain::chainmonitor;
3233
use lightning::chain::channelmonitor;
3334
use lightning::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
3435
use lightning::chain::transaction::OutPoint;
@@ -83,7 +84,7 @@ impl Writer for VecWriter {
8384

8485
struct TestChainMonitor {
8586
pub logger: Arc<dyn Logger>,
86-
pub chain_monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
87+
pub chain_monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
8788
pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
8889
// If we reload a node with an old copy of ChannelMonitors, the ChannelManager deserialization
8990
// logic will automatically force-close our channels for us (as we don't have an up-to-date
@@ -96,7 +97,7 @@ struct TestChainMonitor {
9697
impl TestChainMonitor {
9798
pub fn new(broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
9899
Self {
99-
chain_monitor: Arc::new(channelmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest)),
100+
chain_monitor: Arc::new(chainmonitor::ChainMonitor::new(None, broadcaster, logger.clone(), feeest)),
100101
logger,
101102
update_ret: Mutex::new(Ok(())),
102103
latest_monitors: Mutex::new(HashMap::new()),

fuzz/src/full_stack.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
2727

2828
use lightning::chain;
2929
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
30-
use lightning::chain::channelmonitor;
30+
use lightning::chain::chainmonitor;
3131
use lightning::chain::transaction::OutPoint;
3232
use lightning::chain::keysinterface::{InMemoryChannelKeys, KeysInterface};
3333
use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, PaymentSecret};
@@ -145,13 +145,13 @@ impl<'a> std::hash::Hash for Peer<'a> {
145145

146146
type ChannelMan = ChannelManager<
147147
EnforcingChannelKeys,
148-
Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
148+
Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
149149
Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>;
150150
type PeerMan<'a> = PeerManager<Peer<'a>, Arc<ChannelMan>, Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<dyn Logger>>>, Arc<dyn Logger>>;
151151

152152
struct MoneyLossDetector<'a> {
153153
manager: Arc<ChannelMan>,
154-
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
154+
monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
155155
handler: PeerMan<'a>,
156156

157157
peers: &'a RefCell<[bool; 256]>,
@@ -165,7 +165,7 @@ struct MoneyLossDetector<'a> {
165165
impl<'a> MoneyLossDetector<'a> {
166166
pub fn new(peers: &'a RefCell<[bool; 256]>,
167167
manager: Arc<ChannelMan>,
168-
monitor: Arc<channelmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
168+
monitor: Arc<chainmonitor::ChainMonitor<EnforcingChannelKeys, Arc<dyn chain::Filter>, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>>>,
169169
handler: PeerMan<'a>) -> Self {
170170
MoneyLossDetector {
171171
manager,
@@ -333,7 +333,7 @@ pub fn do_test(data: &[u8], logger: &Arc<dyn Logger>) {
333333
};
334334

335335
let broadcast = Arc::new(TestBroadcaster{});
336-
let monitor = Arc::new(channelmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone()));
336+
let monitor = Arc::new(chainmonitor::ChainMonitor::new(None, broadcast.clone(), Arc::clone(&logger), fee_est.clone()));
337337

338338
let keys_manager = Arc::new(KeyProvider { node_secret: our_network_key.clone(), counter: AtomicU64::new(0) });
339339
let mut config = UserConfig::default();

lightning-net-tokio/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
//! type Logger = dyn lightning::util::logger::Logger;
3737
//! type ChainAccess = dyn lightning::chain::Access;
3838
//! type ChainFilter = dyn lightning::chain::Filter;
39-
//! type ChainMonitor = lightning::chain::channelmonitor::ChainMonitor<lightning::chain::keysinterface::InMemoryChannelKeys, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
39+
//! type ChainMonitor = lightning::chain::chainmonitor::ChainMonitor<lightning::chain::keysinterface::InMemoryChannelKeys, Arc<ChainFilter>, Arc<TxBroadcaster>, Arc<FeeEstimator>, Arc<Logger>>;
4040
//! type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager<ChainMonitor, TxBroadcaster, FeeEstimator, Logger>;
4141
//! type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager<lightning_net_tokio::SocketDescriptor, ChainMonitor, TxBroadcaster, FeeEstimator, ChainAccess, Logger>;
4242
//!

lightning/src/chain/chainmonitor.rs

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
//! Logic to connect off-chain channel management with on-chain transaction monitoring.
11+
//!
12+
//! [`ChainMonitor`] is a simple implementation of [`chain::Watch`] used both to process blocks and
13+
//! to update on-chain [`ChannelMonitor`]s accordingly. If any on-chain events need further
14+
//! processing, it will make those available as [`MonitorEvent`]s to be consumed.
15+
//!
16+
//! `ChainMonitor` may be used directly to monitor channels locally or as a part of a distributed
17+
//! setup to monitor channels remotely. In the latter case, a custom `chain::Watch` implementation
18+
//! would be responsible for routing each update to a remote server and for retrieving monitor
19+
//! events. The remote server would make use of `ChainMonitor` for block processing and for
20+
//! servicing `ChannelMonitor` updates from the client.
21+
//!
22+
//! [`ChainMonitor`]: struct.ChainMonitor.html
23+
//! [`chain::Watch`]: ../trait.Watch.html
24+
//! [`ChannelMonitor`]: ../channelmonitor/struct.ChannelMonitor.html
25+
//! [`MonitorEvent`]: ../channelmonitor/enum.MonitorEvent.html
26+
27+
use bitcoin::blockdata::block::BlockHeader;
28+
29+
use chain;
30+
use chain::Filter;
31+
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
32+
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, MonitorUpdateError};
33+
use chain::transaction::{OutPoint, TransactionData};
34+
use chain::keysinterface::ChannelKeys;
35+
use util::logger::Logger;
36+
use util::events;
37+
use util::events::Event;
38+
39+
use std::collections::{HashMap, hash_map};
40+
use std::sync::Mutex;
41+
use std::ops::Deref;
42+
43+
/// An implementation of [`chain::Watch`] for monitoring channels.
44+
///
45+
/// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
46+
/// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
47+
/// or used independently to monitor channels remotely.
48+
///
49+
/// [`chain::Watch`]: ../trait.Watch.html
50+
/// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
51+
pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref>
52+
where C::Target: chain::Filter,
53+
T::Target: BroadcasterInterface,
54+
F::Target: FeeEstimator,
55+
L::Target: Logger,
56+
{
57+
/// The monitors
58+
pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
59+
chain_source: Option<C>,
60+
broadcaster: T,
61+
logger: L,
62+
fee_estimator: F
63+
}
64+
65+
impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, C, T, F, L>
66+
where C::Target: chain::Filter,
67+
T::Target: BroadcasterInterface,
68+
F::Target: FeeEstimator,
69+
L::Target: Logger,
70+
{
71+
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
72+
/// of a channel and reacting accordingly based on transactions in the connected block. See
73+
/// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
74+
/// be returned by [`chain::Watch::release_pending_monitor_events`].
75+
///
76+
/// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch, returning
77+
/// `true` if so. In this case, if providing pre-filtered blocks, the caller should re-fetch the
78+
/// block to obtain updated `txdata` and recall `block_connected`.
79+
///
80+
/// [`ChannelMonitor::block_connected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_connected
81+
/// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
82+
/// [`chain::Filter`]: ../trait.Filter.html
83+
pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) -> bool {
84+
let mut has_new_outputs_to_watch = false;
85+
{
86+
let mut monitors = self.monitors.lock().unwrap();
87+
for monitor in monitors.values_mut() {
88+
let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
89+
has_new_outputs_to_watch |= !txn_outputs.is_empty();
90+
91+
if let Some(ref chain_source) = self.chain_source {
92+
for (txid, outputs) in txn_outputs.drain(..) {
93+
for (idx, output) in outputs.iter().enumerate() {
94+
chain_source.register_output(&OutPoint { txid, index: idx as u16 }, &output.script_pubkey);
95+
}
96+
}
97+
}
98+
}
99+
}
100+
has_new_outputs_to_watch
101+
}
102+
103+
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
104+
/// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
105+
/// details.
106+
///
107+
/// [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
108+
pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
109+
let mut monitors = self.monitors.lock().unwrap();
110+
for monitor in monitors.values_mut() {
111+
monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
112+
}
113+
}
114+
115+
/// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
116+
///
117+
/// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
118+
/// will call back to it indicating transactions and outputs of interest. This allows clients to
119+
/// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
120+
/// always need to fetch full blocks absent another means for determining which blocks contain
121+
/// transactions relevant to the watched channels.
122+
///
123+
/// [`chain::Filter`]: ../trait.Filter.html
124+
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F) -> Self {
125+
Self {
126+
monitors: Mutex::new(HashMap::new()),
127+
chain_source,
128+
broadcaster,
129+
logger,
130+
fee_estimator: feeest,
131+
}
132+
}
133+
134+
/// Adds or updates the monitor which monitors the channel referred to by the given outpoint.
135+
///
136+
/// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
137+
///
138+
/// [`chain::Filter`]: ../trait.Filter.html
139+
fn add_monitor(&self, outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
140+
let mut monitors = self.monitors.lock().unwrap();
141+
let entry = match monitors.entry(outpoint) {
142+
hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given outpoint is already present")),
143+
hash_map::Entry::Vacant(e) => e,
144+
};
145+
{
146+
let funding_txo = monitor.get_funding_txo();
147+
log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
148+
149+
if let Some(ref chain_source) = self.chain_source {
150+
chain_source.register_tx(&funding_txo.0.txid, &funding_txo.1);
151+
for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
152+
for (idx, script_pubkey) in outputs.iter().enumerate() {
153+
chain_source.register_output(&OutPoint { txid: *txid, index: idx as u16 }, &script_pubkey);
154+
}
155+
}
156+
}
157+
}
158+
entry.insert(monitor);
159+
Ok(())
160+
}
161+
162+
/// Updates the monitor which monitors the channel referred to by the given outpoint.
163+
fn update_monitor(&self, outpoint: OutPoint, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
164+
let mut monitors = self.monitors.lock().unwrap();
165+
match monitors.get_mut(&outpoint) {
166+
Some(orig_monitor) => {
167+
log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
168+
orig_monitor.update_monitor(update, &self.broadcaster, &self.logger)
169+
},
170+
None => Err(MonitorUpdateError("No such monitor registered"))
171+
}
172+
}
173+
}
174+
175+
impl<ChanSigner: ChannelKeys, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, C, T, F, L>
176+
where C::Target: chain::Filter,
177+
T::Target: BroadcasterInterface,
178+
F::Target: FeeEstimator,
179+
L::Target: Logger,
180+
{
181+
type Keys = ChanSigner;
182+
183+
fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
184+
match self.add_monitor(funding_txo, monitor) {
185+
Ok(_) => Ok(()),
186+
Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
187+
}
188+
}
189+
190+
fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
191+
match self.update_monitor(funding_txo, update) {
192+
Ok(_) => Ok(()),
193+
Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
194+
}
195+
}
196+
197+
fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
198+
let mut pending_monitor_events = Vec::new();
199+
for chan in self.monitors.lock().unwrap().values_mut() {
200+
pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
201+
}
202+
pending_monitor_events
203+
}
204+
}
205+
206+
impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<ChanSigner, C, T, F, L>
207+
where C::Target: chain::Filter,
208+
T::Target: BroadcasterInterface,
209+
F::Target: FeeEstimator,
210+
L::Target: Logger,
211+
{
212+
fn get_and_clear_pending_events(&self) -> Vec<Event> {
213+
let mut pending_events = Vec::new();
214+
for chan in self.monitors.lock().unwrap().values_mut() {
215+
pending_events.append(&mut chan.get_and_clear_pending_events());
216+
}
217+
pending_events
218+
}
219+
}

0 commit comments

Comments
 (0)